code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def show_info_popup(self): <NEW_LINE> <INDENT> self.setWhatsThis(self.build_contents()) <NEW_LINE> QtGui.QWhatsThis.enterWhatsThisMode() <NEW_LINE> QtGui.QWhatsThis.showText(self.pos(), self.whatsThis(), self)
Show the information popup. This manually (programmatically) enters What's This? mode and spawns the tooltip at the location of trigger, the element that triggered this function.
625941f4eab8aa0e5d26e163
def insert_watched_instrument(self, market_id, timeframes): <NEW_LINE> <INDENT> if market_id not in self._watched_instruments: <NEW_LINE> <INDENT> self._watched_instruments.add(market_id) <NEW_LINE> <DEDENT> ltimeframes = set.union(set(self.STORED_TIMEFRAMES), set(timeframes)) <NEW_LINE> for timeframe in ltimeframes: <...
Must be called for each subscribed market to initialize the last price data structure.
625941f485dfad0860c3b466
def longestCommonPrefix(self, strs): <NEW_LINE> <INDENT> N = len(strs) <NEW_LINE> if N == 0: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> ret = strs[0] <NEW_LINE> for i in range(len(ret)): <NEW_LINE> <INDENT> for str in strs[1:]: <NEW_LINE> <INDENT> if len(str) == i or str[i] != ret[i]: <NEW_LINE> <INDENT> return ...
:type strs: List[str] :rtype: str
625941f4f7d966606f6aa614
def test_get_creation_date(self): <NEW_LINE> <INDENT> for torrent_file in TORRENTS_INFO: <NEW_LINE> <INDENT> tp = TorrentParser(os.path.join(test_data_dir, torrent_file)) <NEW_LINE> self.assertEqual(tp.get_creation_date(), datetime.utcfromtimestamp(TORRENTS_INFO[torrent_file]['creation_date']).isoformat())
Test getting creation date from a valid torrent file.
625941f401c39578d7e75444
def VerifyResults(Results): <NEW_LINE> <INDENT> n = 0 <NEW_LINE> tempRes = [] <NEW_LINE> for i in Results: <NEW_LINE> <INDENT> if calculate(i) == True: <NEW_LINE> <INDENT> correct = True <NEW_LINE> numberOfTests = 20 <NEW_LINE> while numberOfTests > 0: <NEW_LINE> <INDENT> if calculate(i) == False: <NEW_LINE> <INDENT> c...
verifyResults() iterates through the list of possible results and checks each one several times using calculate(). Returns the updated list of results.
625941f4aad79263cf391053
def AVG(src_column): <NEW_LINE> <INDENT> return ("__builtin__avg__", [src_column])
Builtin average aggregator for groupby. Synonym for gl.aggregate.MEAN. If src_column is of array type, and if array's do not match in length a NoneType is returned in the destination column. Example: Get the average rating of each user. >>> sf.groupby("user", {'rating_avg':gl.aggregate.AVG('rating')})
625941f426068e7796caf2f1
def none_to_mesh(value=None, me=None) -> "Mesh": <NEW_LINE> <INDENT> return me or bpy.data.meshes.new("none")
Transform nothing to Blender mesh.
625941f457b8e32f52483aa8
def optional_converter(kwargs_dict, convert_to_cls): <NEW_LINE> <INDENT> if kwargs_dict is not None and not isinstance(kwargs_dict, convert_to_cls): <NEW_LINE> <INDENT> return convert_to_cls(**kwargs_dict) <NEW_LINE> <DEDENT> return kwargs_dict
Instantiate a class instances from dict.
625941f44e696a04525c9a57
def func(self): <NEW_LINE> <INDENT> string = "-" * 50 <NEW_LINE> string += "\n|w%s|n - Command variables from evennia:\n" % self.key <NEW_LINE> string += "-" * 50 <NEW_LINE> string += "\nname of cmd (self.key): |w%s|n\n" % self.key <NEW_LINE> string += "cmd aliases (self.aliases): |w%s|n\n" % self.aliases <NEW_LINE> st...
This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
625941f4dc8b845886cb5b40
def get_population( tracts=None, communityareas=None, municipalities=None, wards=None, geoms=None): <NEW_LINE> <INDENT> if geoms is not None: <NEW_LINE> <INDENT> for g in iterable(geoms): <NEW_LINE> <INDENT> if isinstance(g,CensusTract): <NEW_LINE> <INDENT> if tracts==None: tracts=[g] <NEW_LINE> else: tracts.append(g)...
Get the population of a given geometry. If you want me to try to infer the geometry type, use the geoms argument.
625941f4f8510a7c17cf9d0a
def test_compute_fluxcalibration(self): <NEW_LINE> <INDENT> frame=get_frame_data() <NEW_LINE> modelwave,modelflux=get_models() <NEW_LINE> stdfibers=np.random.choice(9,3,replace=False) <NEW_LINE> frame.fibermap['OBJTYPE'][stdfibers] = 'STD' <NEW_LINE> input_model_wave=modelwave <NEW_LINE> input_model_flux=modelflux[0:3]...
Test compute_fluxcalibration interface
625941f4236d856c2ad44ded
def _get_update_rootps(self, shape, dx): <NEW_LINE> <INDENT> use_stored = False <NEW_LINE> for rootps_array, scale in self._rootps_store: <NEW_LINE> <INDENT> if shape == rootps_array.shape: <NEW_LINE> <INDENT> if ((dx <= 0. and scale == 1.) or (dx == scale)): <NEW_LINE> <INDENT> use_stored = True <NEW_LINE> rootps = ro...
Internal utility function for querying the rootps cache, used by applyTo and applyWhiteningTo methods.
625941f43eb6a72ae02ecaf8
def test_dump_unbound_typedef(SimpleTypeDef): <NEW_LINE> <INDENT> engine = TypeEngine.unique() <NEW_LINE> typedef = SimpleTypeDef() <NEW_LINE> ctx = {} <NEW_LINE> with pytest.raises(DeclareException): <NEW_LINE> <INDENT> engine.dump(typedef, "foo", context=ctx) <NEW_LINE> <DEDENT> engine.register(typedef) <NEW_LINE> wi...
engine.dump for an unbound typedef raises, even if registered
625941f4be383301e01b5a83
def optimize_SARIMA(parameters_list, d, D, s): <NEW_LINE> <INDENT> results = [] <NEW_LINE> best_aic = float('inf') <NEW_LINE> for param in tqdm_notebook(parameters_list): <NEW_LINE> <INDENT> try: model = sm.tsa.statespace.SARIMAX(data.CLOSE, order=(param[0], d, param[1]), seasonal_order=(param[2], D, param[3], s)).fit(...
Return dataframe with parameters and corresponding AIC parameters_list - list with (p, q, P, Q) tuples d - integration order D - seasonal integration order s - length of season
625941f4167d2b6e3121919d
def updateBatchStatus(self, jobinfo, batchId): <NEW_LINE> <INDENT> resp = self._bulkHttp( self.__join((self.JOB, self.runningJobId, self.BATCH, batchId)), None, self.__content_csv, 'GET') <NEW_LINE> dict_result = parseXMLResult(resp) <NEW_LINE> if self.__check_result(dict_result): <NEW_LINE> <INDENT> if dict_result['id...
Update individual batch status. @type: JobInfo @param jobinfo: job information @type: string @param batchId: batch id
625941f43cc13d1c6d3c7980
def get_stored_user(): <NEW_LINE> <INDENT> filename = '../username.json' <NEW_LINE> try: <NEW_LINE> <INDENT> with open(filename) as f: <NEW_LINE> <INDENT> user = json.load(f) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return user
Gets a stored user's name whether exists
625941f43539df3088e2e955
def parse_gpx(self,gpxstring): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> doc = parseString(gpxstring) <NEW_LINE> trkList = doc.getElementsByTagName('trk') <NEW_LINE> tracks = [] <NEW_LINE> for trkNode in trkList: <NEW_LINE> <INDENT> wpList = [] <NEW_LINE> tracks.append(Track(trkNode.getElementsByTagName('name')[0] ....
Processes gpx track and returns list of Track objects
625941f456ac1b37e62647cc
def Change(self, newtype, values): <NEW_LINE> <INDENT> if self.type != '': <NEW_LINE> <INDENT> self.cfg.Write('/BrowserSortKey/%s' % self.type, self.sortkey) <NEW_LINE> self.cfg.WriteInt('/BrowserSortOrder/%s' % self.type, self.sortorder) <NEW_LINE> <DEDENT> self.type = newtype <NEW_LINE> self.values = values <NEW_LINE...
Change type of browser component.
625941f4aad79263cf391054
def init_readline(self): <NEW_LINE> <INDENT> warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', DeprecationWarning, stacklevel=2) <NEW_LINE> self.set_custom_completer = no_op
DEPRECATED Moved to terminal subclass, here only to simplify the init logic.
625941f45166f23b2e1a5762
def ungroup(i, j, k): <NEW_LINE> <INDENT> l = j - 1 <NEW_LINE> m = j + 1 <NEW_LINE> while ((l != i) and (m != j)): <NEW_LINE> <INDENT> actions = [g.eye(1) for i in range(self.numQubits - 4)] <NEW_LINE> actions.insert(l-2, swap()) <NEW_LINE> actions.insert(m-2, swap()) <NEW_LINE> matrix = g.produceMatrix(actions) <NEW_L...
From the previously grouped position, swap each qubit back to its respective initial position, indices I, J, K.
625941f430bbd722463cc3d3
def info(msg): <NEW_LINE> <INDENT> print(color(msg, fg="#5DADE2"))
print styled INFO messages
625941f497e22403b379d5a5
def test_opt_in_email_notifs_without_profile(self): <NEW_LINE> <INDENT> response = self.client.post( '/api/users/login/', self.user3, format='json') <NEW_LINE> result = json.loads(response.content) <NEW_LINE> self.client.credentials( HTTP_AUTHORIZATION='Token ' + result["user"]["token"]) <NEW_LINE> response = self.clie...
Test user opting in for in-app notifications without creating a profile.
625941f4b545ff76a891441f
def imdb_proposals(net, imdb): <NEW_LINE> <INDENT> _t = Timer() <NEW_LINE> imdb_boxes = [[] for _ in range(imdb.num_images)] <NEW_LINE> for i in range(imdb.num_images): <NEW_LINE> <INDENT> im = cv2.imread(imdb.image_path_at(i)) <NEW_LINE> _t.tic() <NEW_LINE> imdb_boxes[i], scores = im_proposals(net, im) <NEW_LINE> _t.t...
Generate RPN proposals on all images in an imdb.
625941f4462c4b4f79d1dcd9
def to_internal_value(self, data): <NEW_LINE> <INDENT> if isinstance(data, int): <NEW_LINE> <INDENT> return get_object_or_404(Subject.objects.all(), pk=data) <NEW_LINE> <DEDENT> elif isinstance(data, dict) and data.get('id'): <NEW_LINE> <INDENT> return get_object_or_404(Subject.objects.all(), pk=data.get('id')) <NEW_LI...
Needed for PostSerializer create posts passing only the Subject id. Otherwise every time a Post is created a new Subject is alse created.
625941f40383005118ecfbea
def import_class(fullpath): <NEW_LINE> <INDENT> module_name, class_name = fullpath.rsplit('.', 1) <NEW_LINE> logger.debug('Importing {}.{}..'.format(module_name, class_name)) <NEW_LINE> module = import_module(module_name) <NEW_LINE> model_class = getattr(module, class_name) <NEW_LINE> return model_class
Import a class from a string based class path. 1. Import the module in fullpath 2. Load Class from the loaded module Args: fullpath: string based class path Returns: Class definition
625941f40a366e3fb873ee2a
def setup(hass, config): <NEW_LINE> <INDENT> conf = config[DOMAIN] <NEW_LINE> host = conf[CONF_HOST] <NEW_LINE> port = conf[CONF_PORT] <NEW_LINE> access_key = conf[CONF_ACCESS_KEY] <NEW_LINE> secret_key = conf[CONF_SECRET_KEY] <NEW_LINE> secure = conf[CONF_SECURE] <NEW_LINE> queue_listener = QueueListener(hass) <NEW_LI...
Set up MinioClient and event listeners.
625941f4bde94217f36833f5
def update_setting(fname, section, setting, value): <NEW_LINE> <INDENT> config = configparser.RawConfigParser() <NEW_LINE> config.read(fname) <NEW_LINE> config.set(section, setting, value) <NEW_LINE> with open(fname, 'w') as configfile: <NEW_LINE> <INDENT> config.write(configfile)
creates (if doesn't exist) or updates (if does exist) a setting in an existing section
625941f4ad47b63b2c50a589
def __init__(self, versionPredicateStr): <NEW_LINE> <INDENT> versionPredicateStr = versionPredicateStr.strip() <NEW_LINE> if not versionPredicateStr: <NEW_LINE> <INDENT> raise ValueError("empty package restriction") <NEW_LINE> <DEDENT> match = re_validPackage.match(versionPredicateStr) <NEW_LINE> if not match: <NEW_LIN...
Parse a version predicate string.
625941f467a9b606de4a84bf
def Is_Point_Inside(self,Point, Polynome): <NEW_LINE> <INDENT> if len(Polynome) > 10: <NEW_LINE> <INDENT> Polynome = [Polynome[i * 10] for i in range(int(len(Polynome) / 10) - 2)] <NEW_LINE> <DEDENT> num = len(Polynome) <NEW_LINE> i = 0 <NEW_LINE> j = num - 1 <NEW_LINE> c = False <NEW_LINE> for i in range(num): <NEW_LI...
###################################################### x, y -- x and y coordinates of point poly -- a list of tuples [(x, y), (x, y), ...] ######################################################
625941f423e79379d52eeb65
def upload_location(obj, filename): <NEW_LINE> <INDENT> return '%s/%s' %(obj.id, filename)
will upload the file to /media_cdn/<obj.id>/<filename.jpg>
625941f44f88993c3716c66a
@app.route('/student_add') <NEW_LINE> def student_add(): <NEW_LINE> <INDENT> return render_template('student_add.html')
Add a record for a new student
625941f4ec188e330fd5ad9b
def test_calcite(self): <NEW_LINE> <INDENT> calcite_structure = Structure.from_file('test_structures/calcite.cif', True, True) <NEW_LINE> cn_finder = EffectiveCoordFinder(calcite_structure) <NEW_LINE> cns = cn_finder.get_avg_cn(radius=2.5, anions=['O']) <NEW_LINE> for cation in cns: <NEW_LINE> <INDENT> self.assertTrue(...
Testing coordination and connectivity matrix for calcite structure CaCO3
625941f40fa83653e46575c1
def password_eval(s:str) -> None: <NEW_LINE> <INDENT> fragments, column_sums = decomp(s, True) <NEW_LINE> sys.exit(os.EX_OK)
Evaluate the string as a potential password, and then exit.
625941f4566aa707497f4b69
def missing_report(section, option): <NEW_LINE> <INDENT> raise Exception('Unable to read [%s]%s from configs:\n%s\n%s' % ( section, option, self.config_pathname, self.default_config_pathname, ))
Raise an informative exception
625941f4ad47b63b2c50a58a
def _get_cache_entry(self, key, retry=False): <NEW_LINE> <INDENT> with self.diskcache as dc: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> v = dc.get(key) <NEW_LINE> return 'None' == v, (v, None)['None' == v] <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> if not retry: <NEW_LINE> <INDENT> dc.close() <NE...
returns tuple of is_None and value :param key: :param retry:
625941f485dfad0860c3b467
@upgrade <NEW_LINE> @tier1 <NEW_LINE> def test_installer_options_and_flags(): <NEW_LINE> <INDENT> stdout = ssh.command('satellite-installer --full-help').stdout <NEW_LINE> current_installer_options = set(extract_params(stdout or [])) <NEW_LINE> removed_options = list( PREVIOUS_INSTALLER_OPTIONS - current_installer_opti...
Look for changes on installer options and flags :id: a51d3b9f-f347-4a96-a31a-770349db08c7 :Steps: 1. parse installer options and flags 2. compare with last options :expectedresults: Ideally options should not change on zstreams. Documentation must be updated accordingly when such changes occur. So wh...
625941f4627d3e7fe0d6945c
def fit(self, in_seq, out_seqs, createDyBM=True): <NEW_LINE> <INDENT> if not len(self.layers) == len(out_seqs): <NEW_LINE> <INDENT> raise ValueError("out_seqs and layers must have a common length") <NEW_LINE> <DEDENT> for i in xrange(len(self.layers)): <NEW_LINE> <INDENT> self.layers[i].learn_batch(in_seq, out_seqs[i])...
Fit LinearDyBM with in_seq and out_seqs and set FIFO and the eligibility trace Parameters ---------- in_seq: list of arraymath array each of shape(in_dim, ) input sequence out_seqs: list of numpy or arraymath array each of shape (out_dim, ) output sequence createDyBM: optional, boolean if True, return Mult...
625941f4e76e3b2f99f3ae0b
def followers_queryset(self, user_id, *fields): <NEW_LINE> <INDENT> key = cache_key('followers_queryset', user_id) <NEW_LINE> followers = cache.get(key) <NEW_LINE> if not followers: <NEW_LINE> <INDENT> qs = Follow.objects.filter(followee__pk=user_id).values("follower") <NEW_LINE> if(fields != None): <NEW_LINE> <INDENT>...
Return a list of all followers in queryset format
625941f455399d3f05588cc2
def test_with_branch(self): <NEW_LINE> <INDENT> self.block_header.git_ref_name = self.branch <NEW_LINE> self.block_header.render_git_ref_name_tab() <NEW_LINE> self.mock_construct.assert_called_with(self.branch)
Tests rendering with a branch
625941f429b78933be1e5cae
def calc_pure_python(desired_width, max_iterations): <NEW_LINE> <INDENT> x_step = (float(x2 - x1)) / float(desired_width) <NEW_LINE> y_step = (float(y1 - y2)) / float(desired_width) <NEW_LINE> x = [] <NEW_LINE> y = [] <NEW_LINE> ycoord = y2 <NEW_LINE> while ycoord > y1: <NEW_LINE> <INDENT> y.append(ycoord) <NEW_LINE> y...
:param desired_width: 像素 :param max_iterations: 最大迭代步数 :return: None
625941f49b70327d1c4e13e2
def setup_role_policy(account_number, name='default', external_id=None): <NEW_LINE> <INDENT> role_trust_document = {"Version": "2012-10-17", "Statement": [{ "Sid": "", "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::%s:root" % CLOUDHEALTH_AWS_ACCOUNT}, "Action": "sts:AssumeRole",...
create the role and policy in AWS
625941f4baa26c4b54cb1722
def recommend(dataMat, user, N=3, simMeas=cosSim, estMethod=standEst): <NEW_LINE> <INDENT> unratedItems = nonzero(dataMat[user, :].A == 0)[1] <NEW_LINE> if len(unratedItems) == 0: <NEW_LINE> <INDENT> return 'you rated everything' <NEW_LINE> <DEDENT> itemScores = [] <NEW_LINE> for item in unratedItems: <NEW_LINE> <INDEN...
:param dataMat: 数据集 :param user: 用户 :param N: 推荐个数 :param simMeas: 计算相似度的 :param estMethod: 计算方法, 默认是相似度计算 :return: 预测评分最高的前N个物品, 以及其评分
625941f44e696a04525c9a58
def repeat(phrase, num): <NEW_LINE> <INDENT> if num >= 1 : <NEW_LINE> <INDENT> return phrase * num <NEW_LINE> <DEDENT> if num == 0: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Return phrase, repeated num times. >>> repeat('*', 3) '***' >>> repeat('abc', 2) 'abcabc' >>> repeat('abc', 0) '' Ignore illegal values of num and return None: >>> repeat('abc', -1) is None True >>> repeat('abc', 'nope') is None True
625941f43c8af77a43ae3db2
def remove_hook(name, path): <NEW_LINE> <INDENT> logger = output.get_sub_logger('manager-remove', 'remove_hook') <NEW_LINE> logger.debug('Removing %s hook.', name) <NEW_LINE> if not path.exists(): <NEW_LINE> <INDENT> logger.debug('%s Hook doesn\'t exist.', name) <NEW_LINE> <DEDENT> elif click.confirm('Are you sure you ...
Remove a hook from path :type name: str :type path: Path
625941f44d74a7450ccd47cf
def get_random_state(): <NEW_LINE> <INDENT> random_state = int(input("Enter a random state size: ")) <NEW_LINE> while random_state <= 0: <NEW_LINE> <INDENT> random_state = int(input("Please enter a positive number.")) <NEW_LINE> <DEDENT> return random_state
prompt for a number to randomize the data :return: number
625941f44428ac0f6e5bae02
def check_character_name(player, name): <NEW_LINE> <INDENT> if len(name) < 4: <NEW_LINE> <INDENT> info(player, "Le nom du personnage doit contenir au moins quatre lettres.") <NEW_LINE> return False <NEW_LINE> <DEDENT> if player.game.db.has('character', name): <NEW_LINE> <INDENT> info(player, "Il existe déjà un personna...
Check if a name is valid.
625941f4fff4ab517eb2fa4a
def create_server_subprocess(target, args, logger): <NEW_LINE> <INDENT> server = multiprocessing.Process(target=target, args=args) <NEW_LINE> server.daemon = True <NEW_LINE> server.start() <NEW_LINE> logger.info("Created subprocess w/ PID %s", server.pid) <NEW_LINE> def sighandler(signum, frame): <NEW_LINE> <INDENT> pr...
Create the subprocess, set it as a daemon, setup a signal handler in case the parent process is killed, the child process should also be killed, then return the subprocess. :param target: Target function to run in a subprocess :param args: Args to pass to the function :return: `multiprocessing.Process`
625941f4baa26c4b54cb1723
def neighbours(self,index,order=1): <NEW_LINE> <INDENT> ndim=self.ndim <NEW_LINE> return [tuple((index[k]+j*l*(k==i) for k in range(ndim))) for i in range(ndim) for j in (-1,1) for l in range(1,order+1) if 0<=index[i]+j*l<self.shape[i]]
返回邻接节点的索引列表
625941f4cc40096d61595f58
def test_form_POST_saves_the_new_purchase(self): <NEW_LINE> <INDENT> item = Item.objects.create(name='test item #1') <NEW_LINE> self.client.post(self.uri, data={ 'item': str(item.id), 'quantity': '1', 'date': datetime.date.today().strftime('%Y-%m-%d'), }) <NEW_LINE> self.assertEqual(Purchase.objects.count(), 1) <NEW_LI...
Make sure we can create and save new item purchase by posting the form.
625941f4ab23a570cc250792
def map(arr): <NEW_LINE> <INDENT> for el in arr: <NEW_LINE> <INDENT> for i in range(len(el)): <NEW_LINE> <INDENT> if (len(el[i]) != 1): <NEW_LINE> <INDENT> el[i] = keymap.keymap[el[i]] <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return arr
Input -- arr: array of array of single elements Function -- Maps special keys to corresponding object Output -- Corrected array(To be directly used in key_events)
625941f4656771135c3ebe80
def display_instances(image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None): <NEW_LINE> <INDENT> N = boxes.shape[0] <NEW_LINE> if not N: <NEW_LINE> <INDENT> print("\n*** No instances to display *** \n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert boxes.shape[0] == masks...
boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box figsize: (optional) the size of the image.
625941f4bd1bec0571d90c39
def put(self): <NEW_LINE> <INDENT> token = str(request.form['token']) <NEW_LINE> if not os.path.exists("data/db/%s" % token): <NEW_LINE> <INDENT> return {"Message": "Wrong Token"}, bad_request <NEW_LINE> <DEDENT> directed = False <NEW_LINE> name = request.form['name'] <NEW_LINE> nets = json.load(open("resources/network...
@api {put} /api/Networks Load real graph @ApiDescription Create an ER graph compliant to the specified parameters and bind it to the provided token @apiVersion 0.4.0 @apiParam {String} token The token. @apiParam {String} name The network name. @apiName loadgraph @apiGroup Networks @apiExample [python request] Exa...
625941f4956e5f7376d71475
def get_object(self, request): <NEW_LINE> <INDENT> pk = request.GET.get('id') <NEW_LINE> try: <NEW_LINE> <INDENT> return models.Group.objects.get(pk=pk) <NEW_LINE> <DEDENT> except models.Group.DoesNotExist: <NEW_LINE> <INDENT> raise exceptions.AuthenticationFailed('必须指定一个对象id')
获取指定对象
625941f4b5575c28eb68e610
def _tailmatch(self, pattern, start, end, direction): <NEW_LINE> <INDENT> if isinstance(pattern, RDN): <NEW_LINE> <INDENT> pattern = DN(pattern) <NEW_LINE> <DEDENT> if isinstance(pattern, DN): <NEW_LINE> <INDENT> pat_len = len(pattern) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("expected DN or RDN bu...
Matches the end (direction >= 0) or start (direction < 0) of self against pattern (either a DN or RDN), using the start and end arguments. Returns 0 if not found and 1 if found.
625941f48da39b475bd65586
def validation_of_data(): <NEW_LINE> <INDENT> if len(list_of_numbers) == 30: <NEW_LINE> <INDENT> for i in list_of_numbers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> float(i) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> else: <NEW_...
проверяем данные на валидность: всего должно быть ровно 30 ЧИСЕЛ :return: True - данные корректны, False - нет
625941f4fb3f5b602dac3ca4
def fisher_z_to_r(fisher_samples): <NEW_LINE> <INDENT> new_cors = {"F": {}, "D": {}} <NEW_LINE> for pos in fisher_samples.keys(): <NEW_LINE> <INDENT> for sample in fisher_samples[pos].keys(): <NEW_LINE> <INDENT> new_cors[pos][sample] = {"num": fisher_samples[pos][sample]["num"]} <NEW_LINE> for stat in ["xg", "sh"]: <NE...
Convert the fisher z score for each group of sample to the r Need to average all of the score for that sample (ex: 25 shots) and then convert the avg to r with tanh (since arctanh was used to convert from r to z) :param fisher_samples: Samples for pos/sample_amount :return: dict of average r for each sample for F/D ...
625941f40c0af96317bb87f1
def __exit__( self, exctype: None | Type[BaseException] = None, excinst: None | BaseException = None, exctb: None | types.TracebackType = None, ) -> bool: <NEW_LINE> <INDENT> if exctype is not None and issubclass(exctype, self.exceptions): <NEW_LINE> <INDENT> self._caught_exceptions.append(cast(_ET, excinst)) <NEW_LINE...
Exit the context manager. Update :attr:`caught_exceptions` if an appropriate exception is encountered.
625941f4cc0a2c11143dd49c
@pytest.mark.forked <NEW_LINE> def test_simple_read_tensorflow_with_parquet_dataset(scalar_dataset): <NEW_LINE> <INDENT> with make_batch_reader(dataset_url=scalar_dataset.url) as reader: <NEW_LINE> <INDENT> row_tensors = tf_tensors(reader) <NEW_LINE> for column in row_tensors: <NEW_LINE> <INDENT> assert column.get_shap...
Read couple of rows. Make sure all tensors have static shape sizes assigned and the data matches reference data
625941f499cbb53fe67931ef
def p_Parametro(t): <NEW_LINE> <INDENT> t[0]=ParametroDefinicionFuncion(t[1],t[2],t.lineno(1),get_clomuna(entry,t.slice[2])) <NEW_LINE> asc.append(['PARAMETRO ','TIPO_VAR ID'])
PARAMETRO : TIPO_VAR ID
625941f49c8ee82313fbbd82
def enable_camera(): <NEW_LINE> <INDENT> global camera <NEW_LINE> if globals_.camera_running: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> camera = picamera.PiCamera() <NEW_LINE> globals_.camera_running = True <NEW_LINE> configure_camera() <NEW_LINE> main_app = main.App.get_running_app() <NEW...
Enables the picamera to display the preview window. The camera should only be called as a new thread by start_camera_thread().
625941f4a79ad161976cc750
def calculate_counter_values( data: ndarray, r2r_indices: ndarray, bin_reference_values: ndarray ) -> ndarray: <NEW_LINE> <INDENT> inds = np.zeros(data[r2r_indices, :].shape, dtype="uint16") <NEW_LINE> for row in range(4): <NEW_LINE> <INDENT> inds[row, :] = np.digitize( data[r2r_indices[row], :], bin_reference_values[r...
Determines the interferometer position from the (counter) values that the ADC collected from the R-2R-Network. The counter electronics from Zurich outputs the position via USB (on command) and also on a 16 line parallel port for every laser trigger. The results in a 16 digit binary number that is then converted into 4...
625941f450485f2cf553d3a6
def test_eap_teap_basic_password_auth_pac(dev, apdev): <NEW_LINE> <INDENT> check_eap_capa(dev[0], "TEAP") <NEW_LINE> params = int_teap_server_params(eap_teap_auth="1") <NEW_LINE> hapd = hostapd.add_ap(apdev[0], params) <NEW_LINE> eap_connect(dev[0], hapd, "TEAP", "user", anonymous_identity="TEAP", password="password", ...
EAP-TEAP with Basic-Password-Auth and PAC
625941f4656771135c3ebe81
def attr_value(self, target, index=0): <NEW_LINE> <INDENT> if not isinstance(target, basestring) or not isinstance(index, int): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> return capi.get_attr_value(self.ptr, target, index)
The attribute value for the given target node (e.g. 'PROJCS'). The index keyword specifies an index of the child node to return.
625941f41f5feb6acb0c5154
def extract_matches(sources, references, ranks, human_scores, measure_score): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> mismatches = [] <NEW_LINE> for source, reference, chain, human_chain, measure_chain, in zip(sources, references, iterate_chains(ranks), human_scores, measure_score): <NEW_LINE> <INDENT> last_measure...
returns a list of tuples of (source, references, first sentence, first measure, first human, second sentence, second measure_score, second human_score) where the measure rises together with the human score and another where it is not
625941f4cad5886f8bd275e2
def test_region_setting_serialization(self): <NEW_LINE> <INDENT> region_setting_model_json = {} <NEW_LINE> region_setting_model_json['enabled'] = True <NEW_LINE> region_setting_model_json['key'] = 'eu-de' <NEW_LINE> region_setting_model = RegionSetting.from_dict(region_setting_model_json) <NEW_LINE> assert region_setti...
Test serialization/deserialization for RegionSetting
625941f48a349b6b435e877d
def wait_inf_state(self, states, timeout, incorrect_states=None, vm_ids=None): <NEW_LINE> <INDENT> if not vm_ids: <NEW_LINE> <INDENT> before = time.time() <NEW_LINE> (success, vm_ids) = self.server.GetInfrastructureInfo( self.inf_id, self.auth_data) <NEW_LINE> resp_time = time.time() - before <NEW_LINE> self.__class__....
Wait for an infrastructure to have a specific state
625941f4287bf620b61d406a
def test_initialize_connection_of_fb_volume(self): <NEW_LINE> <INDENT> self.driver = FakeDS8KProxy(self.storage_info, self.logger, self.exception, self) <NEW_LINE> self.driver.setup(self.ctxt) <NEW_LINE> vol_type = volume_types.create(self.ctxt, 'VOL_TYPE', {}) <NEW_LINE> location = six.text_type({'vol_hex_id': TEST_VO...
attach a FB volume to host.
625941f430bbd722463cc3d4
def __init__(self, n_embedding=30, n_distance=100, n_hidden=60, init='glorot_uniform', activation='tanh', **kwargs): <NEW_LINE> <INDENT> self.n_embedding = n_embedding <NEW_LINE> self.n_distance = n_distance <NEW_LINE> self.n_hidden = n_hidden <NEW_LINE> self.init = initializations.get(init) <NEW_LINE> self.activation ...
Parameters ---------- n_embedding: int, optional Number of features for each atom n_distance: int, optional granularity of distance matrix n_hidden: int, optional Number of nodes in hidden layer init: str, optional Weight initialization for filters. activation: str, optional Activation function applied
625941f415fb5d323cde1124
def clean(self, data): <NEW_LINE> <INDENT> super(MultiFileField, self).clean(data) <NEW_LINE> if not self.required and data in EMPTY_VALUES: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> f = [UploadedFile(a['filename'], a['content']) for a in data] <NEW_LINE> <DEDENT> except TypeError: <N...
Cleans the data and makes sure that all the files had some content. Also checks whether a file was required.
625941f4a8370b7717052ea8
def MidiFile_writeVariableLength(*args): <NEW_LINE> <INDENT> return _CsoundAC.MidiFile_writeVariableLength(*args)
MidiFile_writeVariableLength(std::ostream & stream, int value)
625941f43eb6a72ae02ecaf9
def render_names_at_mouse_location(console, x, y, engine): <NEW_LINE> <INDENT> mouse_x, mouse_y = engine.mouse_location <NEW_LINE> mouse_y -= settings.msg_panel_height <NEW_LINE> names_at_mouse_location = engine.game_map.get_names_at( x=mouse_x, y=mouse_y, ) <NEW_LINE> console.print(x=x, y=y, string=f"({mouse_x},{mouse...
takes the console, x and y coordinates (the location to draw the names), and the engine. From the engine, it grabs the mouse’s current x and y positions, and passes them to get_names_at_location, which we can assume for the moment will return the list of entity names we want. Once we have these entity names as a string...
625941f4d53ae8145f87a86e
def plot_series(filename, plot_kwargs=None): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> if plot_kwargs is None: <NEW_LINE> <INDENT> plot_kwargs = {} <NEW_LINE> <DEDENT> data = np.genfromtxt(filename, dtype='i8,f4', names=['k', 'v']) <NEW_LINE> index = data['k'] <NEW_LINE> values = data['v'] <NEW_LIN...
Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required.
625941f430c21e258bdfaaaf
def mse(A,B): <NEW_LINE> <INDENT> mse = (np.square(A - B)).mean() <NEW_LINE> return mse
Calculates mean squared error
625941f456ac1b37e62647cd
def __init__(self, input, attributes=None, seq_len=0, preprocess=None, vocab=None, vocab_size=None, verbose=True): <NEW_LINE> <INDENT> self.input = input <NEW_LINE> self.attributes = attributes <NEW_LINE> if preprocess is not None: <NEW_LINE> <INDENT> self.preprocess = preprocess <NEW_LINE> <DEDENT> self.vocab, self.da...
Dataset for single corpus. Used for tasks like language modeling. Args: preprocess (callable): preprocessing callable, which takes as input a string and returns a list of tokens input (str, list): the path to the data file, or a list of samples. attributes (numpy.ndarray): list of attributes ...
625941f43317a56b8693a253
def acquire(data_stream: DataStream) -> None: <NEW_LINE> <INDENT> data_stream.prepare_stream(DataStreamArgs((slice(0, 1),), (1,))) <NEW_LINE> data_stream.start_stream(DataStreamArgs((slice(0, 1),), (1,))) <NEW_LINE> try: <NEW_LINE> <INDENT> last_progress = 0.0 <NEW_LINE> while not data_stream.is_finished and not data_s...
Perform an acquire. Performs consistency checks on progress and data.
625941f44f88993c3716c66b
def send_broadcast(cli_sock, data): <NEW_LINE> <INDENT> for conn in CONNECTIONLIST: <NEW_LINE> <INDENT> if conn != cli_sock: <NEW_LINE> <INDENT> conn.send(data)
Envia a mensagem em data para todos os usuários, exceto para o cli_sock
625941f4d164cc617578335a
def convert_to_attropl(self, attrib, cmd=MGR_CMD_SET, op=None): <NEW_LINE> <INDENT> if op is None: <NEW_LINE> <INDENT> op = self.command_to_op(cmd) <NEW_LINE> <DEDENT> if isinstance(attrib, (list, tuple)): <NEW_LINE> <INDENT> a = self.list_to_attropl(attrib, op) <NEW_LINE> <DEDENT> elif isinstance(attrib, (dict, Ordere...
Generic call to convert Python type to PBS attribute operation list :param attrib: Attributes to be converted :type attrib: List or tuple or dictionary or str :returns: PBS attribute operation list
625941f4e76e3b2f99f3ae0c
@multicast.command('logs') <NEW_LINE> @pass_context <NEW_LINE> def multicast_logs(ctx: Configuration): <NEW_LINE> <INDENT> _handle(ctx, 'multicast/logs')
Home Assistant DNS logs.
625941f4e5267d203edce2a0
def to_dict(self): <NEW_LINE> <INDENT> dict = {} <NEW_LINE> dict['id'] = self.id <NEW_LINE> dict['user_id'] = self.user_id <NEW_LINE> dict['username'] = self.username <NEW_LINE> dict['boat_type'] = self.boat_type <NEW_LINE> dict['timestamp'] = self.timestamp <NEW_LINE> dict['date_created'] = self.date_created <NEW_LINE...
Dictionary Representation of a scheduled boat request
625941f4be7bc26dc91cdbff
def download_picture(url, dest_filename, dest_folder='./', overwrite=False, verbose=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = urlopen(url) <NEW_LINE> document = response.read() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("Encountered an error on {}".format(url)) <NEW_LINE>...
download_picture(url, dest_filename, dest_folder, overwrite=False) note: dest_folder='./', overwrite=False, verbose=False if overwrite is True, it will overwrite an existing file if verbose, show user some information on console about progress. This is a synchronous process, so that could be problematic when image ser...
625941f4b5575c28eb68e611
def t2t(lines,name): <NEW_LINE> <INDENT> filename = join(website,'%s.t2t' % name) <NEW_LINE> temp=open(filename,'w') <NEW_LINE> temp.write( '\n'.join(lines)) <NEW_LINE> temp.close() <NEW_LINE> os.system('txt2tags --target html --style color.css --css-sugar %s' % filename)
create the HTML for a given t2t file.
625941f47d847024c06be8cc
def export_xy(self, min_rangespan=0.2, max_clipped=0.2): <NEW_LINE> <INDENT> if len(self.grouped_img["xy"]) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> rawfolder = self.outdir/"Images_xy"/"raw" <NEW_LINE> rawfolder.mkdir(parents=True, exist_ok=True) <NEW_LINE> compfolder = self.outdir/"Images_xy"/"compressed" ...
exports all xy image entries: - raw export: tif - compressed export (jpg, scaled to blackval/whiteval which was set during acquisition with burned in title + scale bar)
625941f4f7d966606f6aa616
def __repr__(self) -> str: <NEW_LINE> <INDENT> return str(self.handler)
Return the string names.
625941f4293b9510aa2c389b
def _trackMovement(self): <NEW_LINE> <INDENT> self.log.info("_trackMovement") <NEW_LINE> if self.settings['HUMANTRACKING']: <NEW_LINE> <INDENT> noMovementCount = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> print("Stopped",self._stopped) <NEW_LINE> if self.head.trackMovement(): <NEW_LINE> <INDENT> noMovementCount = 0 <...
Stop and check for movement. If movement detected, track it for a while
625941f48e71fb1e9831ddb1
def shell_logger(output): <NEW_LINE> <INDENT> if not os.environ.get('SHELL'): <NEW_LINE> <INDENT> logs.warn("Shell logger doesn't support your platform.") <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> fd = os.open(output, os.O_CREAT | os.O_TRUNC | os.O_RDWR) <NEW_LINE> os.write(fd, b'\x00' * const.LOG_SIZE_IN_BYTES) <NEW_...
Logs shell output to the `output`. Works like unix script command with `-f` flag.
625941f4236d856c2ad44def
def _save_completed_activities(activities_completed): <NEW_LINE> <INDENT> completed_activities_model = user_models.CompletedActivitiesModel( id=activities_completed.id, exploration_ids=( activities_completed.exploration_ids), collection_ids=activities_completed.collection_ids) <NEW_LINE> completed_activities_model.put(...
Save an activities completed domain object as a CompletedActivitiesModel instance in the datastore. Args: activities_completed: CompletedActivities. The activities completed domain object to be saved in the datastore.
625941f4f8510a7c17cf9d0c
def get_server_email_passw(self): <NEW_LINE> <INDENT> u <NEW_LINE> return self.server_email_passw or MAIL_PASSW
Вернет пароль серверного email.
625941f4cb5e8a47e48b80aa
def newFormat(self, *args, **kwargs): <NEW_LINE> <INDENT> exists = kwargs.pop("exists", False) <NEW_LINE> device_instance = kwargs.pop("device_instance", None) <NEW_LINE> fmt = getFormat(*args, **kwargs) <NEW_LINE> if isinstance(fmt, blivet.formats.disklabel.DiskLabel): <NEW_LINE> <INDENT> fmt._partedDevice = Mock() <N...
Return a new DeviceFormat instance suitable for testing. Keyword Arguments: device_instance - StorageDevice instance this format will be created on. This is needed for setup of resizable formats. All other arguments are passed directly to blivet.formats.getFormat.
625941f407f4c71912b11a90
def sort_payment_keys(keys): <NEW_LINE> <INDENT> def genkey(k): <NEW_LINE> <INDENT> if k in _payment_keys_order: <NEW_LINE> <INDENT> return (_payment_keys_order.index(k), None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (len(_payment_keys_order), k) <NEW_LINE> <DEDENT> <DEDENT> return sorted(keys, key=genkey)
Sort the given list in the most natural order of the keys of a payment object.
625941f4a934411ee3751ca0
def expand_target_wildcards(kwargs): <NEW_LINE> <INDENT> parms = get_all_parms(kwargs) <NEW_LINE> for parm in parms: <NEW_LINE> <INDENT> pnode = parm.node() <NEW_LINE> nodes = pnode.glob(parm.evalAsString()) <NEW_LINE> paths = " ".join( [ pnode.relativePathTo(n) for n in nodes ] ) <NEW_LINE> reset_parm(parm) <NEW_LINE>...
.
625941f463b5f9789fde76f1
def display(request): <NEW_LINE> <INDENT> context = { 'courses': Courses.objects.all(), 'form': add_course_form(), } <NEW_LINE> return render(request, 'course_table/index.html', context)
Show all courses, and form for adding new ones.
625941f48a43f66fc4b54669
def exit_application(self): <NEW_LINE> <INDENT> self.mpd.close_mpd() <NEW_LINE> LOGGER.debug("Exiting application.") <NEW_LINE> sys.exit(0)
Close the MPD connection and close the application
625941f40fa83653e46575c2
def LCDdrawPixel(x, y, update=True, outofbounds = False): <NEW_LINE> <INDENT> printDebug("In LCDdrawPixel, x is " + str(x) + ", y is " + str(y), DEBUG_INFO) <NEW_LINE> if outofbounds: <NEW_LINE> <INDENT> if x < 0 or x > 127 or y < 0 or y > 63: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <IN...
Draws a pixel on the LCD (which is 128x64; 0,0 is upper left; 127,63 is lower right) arguments: x - int x coordinate for the pixel, must be >= 0 and <= 127 y - int y coordinate for the pixel, must be >=0 and <= 63 update - True (default) if you want Sparki to update the display outofbounds - False (default) if you wan...
625941f430c21e258bdfaab0
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, RoommateGroupRequestItem): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941f41b99ca400220b0bf
def string_segmentation_tabulation(string, dictionary): <NEW_LINE> <INDENT> n = len(string) <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> cache = [False] * (n + 1) <NEW_LINE> matched_indices = deque([-1]) <NEW_LINE> for max_search_index in range(n): <NEW_LINE> <INDENT> for previously_matched...
A solution for the string segmentation problem that uses tabulation borrowed from: https://iq.opengenus.org/word-break-problem/
625941f4a79ad161976cc751
def _convertPositions(pos, units, func): <NEW_LINE> <INDENT> from .position import Position <NEW_LINE> from .angle import AngleUnit, arcsec <NEW_LINE> if isinstance(pos, Position): <NEW_LINE> <INDENT> pos = [ pos.x, pos.y ] <NEW_LINE> <DEDENT> elif len(pos) == 0: <NEW_LINE> <INDENT> raise TypeError("Unable to parse the...
Convert ``pos`` from the valid ways to input positions to two NumPy arrays This is used by the functions getShear(), getConvergence(), getMagnification(), and getLensing() for both PowerSpectrum and NFWHalo.
625941f450812a4eaa59c926
def request(self, url, method, headers=None, param=None, content_type=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if method == 'get': <NEW_LINE> <INDENT> result = requests.get(url=url, params=param, headers=headers).json() <NEW_LINE> return result <NEW_LINE> <DEDENT> elif method == 'post': <NEW_LINE> <INDENT> i...
通用请求工具类 :param url: :param method: :param headers: :param param: :param content_type: :return:
625941f40383005118ecfbeb
def register_touch_control_handlers(hass, config): <NEW_LINE> <INDENT> hass.services.register(DOMAIN, SERVICE_DIM, partial(service_light_dim, hass)) <NEW_LINE> hass.services.register(DOMAIN, SERVICE_BRIGHTEN, partial(service_light_brighten, hass)) <NEW_LINE> controllers = config[DOMAIN].get(CONF_TOUCH, None) <NEW_LINE>...
Registers handlers for touch scene controllers.
625941f4a219f33f34628f6c
def get_kids(thread_id_to_get_kids): <NEW_LINE> <INDENT> return requests.get(get_item_url(thread_id_to_get_kids)).json()["kids"]
get kids from story thread
625941f4a934411ee3751ca1
def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.__input_pins = [] <NEW_LINE> self.__width = 0 <NEW_LINE> self.__height = 0 <NEW_LINE> self._ref_avg = [[]]
Creates new instance of RawPressureSensorAdaptor
625941f4bde94217f36833f6