code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def inefficient_outer(x, y): <NEW_LINE> <INDENT> result = np.zeros((len(x), len(y))) <NEW_LINE> for i in range(len(x)): <NEW_LINE> <INDENT> for j in range(len(y)): <NEW_LINE> <INDENT> result[i, j] = x[i]*y[j] <NEW_LINE> <DEDENT> <DEDENT> return result
Inefficiently compute the outer product of two vectors. Parameters: x (numpy.ndarray): 1-dimensional numpy array. y (numpy.ndarray): 1-dimensional numpy array. Returns: numpy.ndarray: 2-dimensional numpy array.
625941ce71ff763f4b5497c8
def snapshot(self): <NEW_LINE> <INDENT> self.camera.raw_image(update_latest_frame=True)
Take a new snapshot and display it.
625941ce8da39b475bd650b0
def edit_subscription(request, **kwargs): <NEW_LINE> <INDENT> subscription_id = kwargs.pop('subscription_id', None) <NEW_LINE> subscription = get_object_or_404(Subscription, id=subscription_id) <NEW_LINE> if request.POST: <NEW_LINE> <INDENT> form = ManageSubscriptionForm(request.POST, instance=subscription) <NEW_LIN...
Change parameters of a subscription for current user.
625941ce462c4b4f79d1d80d
def generate_report(self, output_path): <NEW_LINE> <INDENT> dut_start_index = self.df_info['key'].tolist().index('<DUT>') <NEW_LINE> dut_end_index = self.df_info['key'].tolist().index('</DUT>') <NEW_LINE> port_start_index = self.df_info['key'].tolist().index('<PORT>') <NEW_LINE> port_end_index = self.df_info['key'].tol...
Generates a Report file :return:
625941ce090684286d50ee22
def number_of_graphlets(size): <NEW_LINE> <INDENT> if size == 2: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> if size == 3: <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> if size == 4: <NEW_LINE> <INDENT> return 11 <NEW_LINE> <DEDENT> if size == 5: <NEW_LINE> <INDENT> return 34
Number of all undirected graphlets of given size
625941cecc0a2c11143dcfcd
def index(request): <NEW_LINE> <INDENT> return HttpResponseRedirect('/calendar/')
REDIRECT to calendar view
625941ce8a349b6b435e82b0
def enable(self, cmd='', pattern='ssword', re_flags=re.IGNORECASE): <NEW_LINE> <INDENT> output = "" <NEW_LINE> if not self.check_enable_mode(): <NEW_LINE> <INDENT> self.write_channel(self.normalize_cmd(cmd)) <NEW_LINE> output += self.read_until_prompt_or_pattern(pattern=pattern, re_flags=re_flags) <NEW_LINE> self.write...
Enter enable mode.
625941ce7c178a314d6ef59d
def to_list_arr(l): <NEW_LINE> <INDENT> return [ np.array(e).reshape(len(e),1) for e in l ]
Turn [[]] into [np.array]
625941ced7e4931a7ee9e05a
def order_required(url_name='cart'): <NEW_LINE> <INDENT> if callable(url_name): <NEW_LINE> <INDENT> func = url_name <NEW_LINE> decorator = order_required() <NEW_LINE> return decorator(func) <NEW_LINE> <DEDENT> def decorator(func): <NEW_LINE> <INDENT> def inner(request, *args, **kwargs): <NEW_LINE> <INDENT> order = get_...
Ensures that an non-complete order exists before carrying out any additional functions that rely on one. If an order does not exist the browser will be redirected to another page supplied in the optional keyword argument `url_name`. Usage: @order_required def some_view(... OR: @order_required(url_name='cart') def so...
625941ce925a0f43d2549fb4
def make_copy_available(request_id): <NEW_LINE> <INDENT> barcode_requested = db.get_requested_barcode(request_id) <NEW_LINE> db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, barcode_requested) <NEW_LINE> update_requests_statuses(barcode_requested)
Change the status of a copy for CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF when an hold request was cancelled. @param request_id: identify the request: Primary key of crcLOANREQUEST @type request_id: int
625941ced4950a0f3b08c48b
def decoder(encoded_tensor, filters, is_training=True): <NEW_LINE> <INDENT> reversed_filters = np.flip(filters, axis=0) <NEW_LINE> net = encoded_tensor <NEW_LINE> with tf.variable_scope('decoder'): <NEW_LINE> <INDENT> for idx, num_filter in enumerate(reversed_filters[1:]): <NEW_LINE> <INDENT> net = base_conv_layer(net,...
:param encoded_tensor: :param filters: filters used in the relative encoder, therefore they will be reversed in the decoder :param is_training: :return:
625941ce31939e2706e4cfa6
def _call(self): <NEW_LINE> <INDENT> v = 0 <NEW_LINE> c, sigma, B = self._c, self._sigma, self.B <NEW_LINE> m = self.B.nrows() <NEW_LINE> for i in range(m - 1, -1, -1): <NEW_LINE> <INDENT> b_ = self._G[i] <NEW_LINE> c_ = c.dot_product(b_) / b_.dot_product(b_) <NEW_LINE> sigma_ = sigma / b_.norm() <NEW_LINE> assert(sigm...
Return a new sample. EXAMPLE:: sage: from sage.stats.distributions.discrete_gaussian_lattice import DiscreteGaussianDistributionLatticeSampler sage: D = DiscreteGaussianDistributionLatticeSampler(ZZ^3, 3.0, c=(1/2,0,0)) sage: L = [D._call() for _ in range(2^12)] # long time sage: mean(L).n() - D.c # l...
625941ced10714528d5ffe20
def repeating_key_xor_encrypt(plaintext, key): <NEW_LINE> <INDENT> keychargen = cycle(key) <NEW_LINE> result = "" <NEW_LINE> for plainchar in plaintext: <NEW_LINE> <INDENT> result = result + str(ord(plainchar) ^ ord(next(keychargen))) <NEW_LINE> <DEDENT> return result
Given plaintext and key, uses key to encrypt plaintext via repeating XOR and returns the result
625941ce9b70327d1c4e0f12
def test_normalized_axes_tuple_raise(): <NEW_LINE> <INDENT> with pytest.raises(TypeError): <NEW_LINE> <INDENT> normalized_axes_tuple(1.5, ndim=3) <NEW_LINE> <DEDENT> with pytest.raises(TypeError): <NEW_LINE> <INDENT> normalized_axes_tuple(None, ndim=3) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <IND...
Test if errors are raised for invalid input.
625941ce26238365f5f0efab
def get_other_roles(self, role, role_ids): <NEW_LINE> <INDENT> return [self.find_by_id(n) for n in role_ids if n != role['id']]
Get a list of role instances corresponding to the role ids, excluding the given role instance @type role: L{pulp.server.model.db.Role} instance @param role: role to exclude @type role_ids: list or tuple of str's @rtype: list of L{pulp.server.model.db.Role} instances @return: list of roles
625941ce009cb60464c634ee
def wordlist_to_freqdist(wordlist_file): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> corpus = open(wordlist_file) <NEW_LINE> close = True <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> corpus = wordlist_file <NEW_LINE> close = False <NEW_LINE> <DEDENT> types = next(corpus) <NEW_LINE> types = int(types[types...
Given a wordlist return a frequency distribution as well as the number of types and tokens :param wordlist_file: a .txt file generated from AntConc or freqdist_to_wordlistfile. Line 1 has the number of types, line 2 the number of tokens, and lines 4-end are in the format "rank word frequency". Can be a filena...
625941cebe383301e01b55c2
def siguiente_estado(estado, desplazamiento): <NEW_LINE> <INDENT> tabla_desp = {'W': (0, -1), 'N': (-1, 0), 'E': (0, 1), 'S': (1, 0)} <NEW_LINE> (fil, col) = estado <NEW_LINE> fil_ = fil + tabla_desp[desplazamiento][0] <NEW_LINE> col_ = col + tabla_desp[desplazamiento][1] <NEW_LINE> if (col_ > 3 or fil_ > 2 or col_ < 0...
Devuelve la celda en la que acabara el agente tras el desplazamiento desde estado. Los desplazamientos son deterministas. La componente estocastica se tuvo en cuenta en la funcion posibles_desplazamientos(accion). Hay que tener en cuenta el comportamiento ante los obstaculos y limites del laberinto. E.g. siguiente_est...
625941ce31939e2706e4cfa7
def get_formatting(self): <NEW_LINE> <INDENT> return self._colour_map
Returns a dict of
625941ce67a9b606de4a7ff6
def generatelockCondition(self): <NEW_LINE> <INDENT> if( self.__type.lower() == '') or ( self.__type.lower() == ''): <NEW_LINE> <INDENT> self.__lock_condition = random.choice(scaling.lock_condition) <NEW_LINE> if(self.__lock_condition == 'locked'): <NEW_LINE> <INDENT> self.__key_required = random.randint(1,5)
some housings are locked by default upon loading. This method generates this dependency upon first creation and sets a required amount of keys needed in order to open it up, if it gets locked. possible values are: #### locked #### opened - generates required keys if condition is 'locked' - if condition is 'opened' n...
625941cec4546d3d9de72b71
def print_commands(): <NEW_LINE> <INDENT> print('\nUsage: ' + sys.argv[0] + ' [option]', end='\n\n') <NEW_LINE> print(' --load-date'.ljust(40) + 'Loads the date stored in the filesystem and' + ' sets it as current date.') <NEW_LINE> print(' --save-date'.ljust(40) + 'Saves the date used by the operatingsy...
Prints the command line arguments avaible for this script
625941ce287bf620b61d3ba0
def euler_quaty(alpha): <NEW_LINE> <INDENT> alpha = np.asarray(alpha) <NEW_LINE> z = np.zeros_like(alpha) <NEW_LINE> c = np.cos(alpha * 0.5) <NEW_LINE> s = np.sin(alpha * 0.5) <NEW_LINE> return np.array([z, s, z, c]).T
Generate quaternion units along y axis Parameters ---------- alpha : float Polar angle in radian. Examples ---------- >>> euler_quaty(alpha=np.pi/2.) array([ 0. , 0.70710678, 0. , 0.70710678])
625941cef9cc0f698b140738
def _update_aliens(self): <NEW_LINE> <INDENT> self._check_fleet_edges() <NEW_LINE> self.aliens.update() <NEW_LINE> if pygame.sprite.spritecollideany(self.ship, self.aliens): <NEW_LINE> <INDENT> self._ship_hit() <NEW_LINE> <DEDENT> self._check_aliens_bottom()
Check if the fleet is at the edge, then update the position of all the fleets of the aliens.
625941ce4d74a7450ccd4300
def test_match(self): <NEW_LINE> <INDENT> jsmith = UniqueIdentity(uuid='jsmith') <NEW_LINE> jsmith.identities = [Identity(name='John Smith', email='jsmith@example.com', source='scm'), Identity(name='John Smith', source='scm'), Identity(username='jsmith', source='scm'), Identity(email='', source='scm')] <NEW_LINE> john_...
Test match method
625941ce76e4537e8c3517b0
def enable_vlan(self, mgr, vlanid, vlanname): <NEW_LINE> <INDENT> pass
Create a VLAN on Nexus Switch given the VLAN ID and Name.
625941ce30dc7b7665901aa3
@pytest.mark.uncollectif(lambda provider: provider.type != 'openstack') <NEW_LINE> def test_hard_reboot(setup_provider_funcscope, provider, testing_instance, soft_assert, verify_vm_running): <NEW_LINE> <INDENT> testing_instance.wait_for_instance_state_change(desired_state=testing_instance.STATE_ON) <NEW_LINE> navigate_...
Tests instance hard reboot Metadata: test_flag: power_control, provision
625941ce283ffb24f3c55a3e
def test_is_authorized_without_tokens(self): <NEW_LINE> <INDENT> hosting_account = self.create_hosting_account(data={ 'authorizations': {}, }) <NEW_LINE> self.assertFalse(hosting_account.is_authorized)
Testing GitHub.is_authorized with legacy authorization token
625941ce4527f215b584c593
def get_dummy_batch(self, num_tokens, max_positions, src_len=128, tgt_len=128): <NEW_LINE> <INDENT> src_len, tgt_len = utils.resolve_max_positions( (src_len, tgt_len), max_positions, (self.max_source_positions, self.max_target_positions), ) <NEW_LINE> return generate_dummy_batch(num_tokens, self.collater, self.src_dict...
Return a dummy batch with a given number of tokens.
625941cea4f1c619b28b0175
def test_unicode_only_file(self): <NEW_LINE> <INDENT> tree = self.make_branch_and_tree(".") <NEW_LINE> contents = [u"\u1234"] <NEW_LINE> self.build_tree(contents) <NEW_LINE> tree.add(contents) <NEW_LINE> tree.commit("Initial commit") <NEW_LINE> as_utf8 = u"\u1234".encode("UTF-8") <NEW_LINE> streams = self.run_bzr(["gre...
Test filename and contents that requires a unicode encoding
625941cee8904600ed9f206a
def HKMacauExitentrypermit(self, image, options=None): <NEW_LINE> <INDENT> options = options or {} <NEW_LINE> data = {} <NEW_LINE> data['image'] = base64.b64encode(image).decode() <NEW_LINE> data.update(options) <NEW_LINE> return self._request(self.__HKMacauExitentrypermitUrl, data)
港澳通行证识别
625941ce442bda511e8be555
def load_from_openraster(self, orazip, elem, cache_dir, progress, x=0, y=0, **kwargs): <NEW_LINE> <INDENT> if elem.tag != "stack": <NEW_LINE> <INDENT> raise lib.layer.error.LoadingFailed("<stack/> expected") <NEW_LINE> <DEDENT> if not progress: <NEW_LINE> <INDENT> progress = lib.feedback.Progress() <NEW_LINE> <DEDENT> ...
Load this layer from an open .ora file
625941ce26068e7796caee1d
def resolve_script_path(script: str) -> str: <NEW_LINE> <INDENT> from kivy.app import App <NEW_LINE> if script.startswith("/"): <NEW_LINE> <INDENT> path = Path(script) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> app = App.get_running_app() <NEW_LINE> path = Path(app.upload_dir) / script <NEW_LINE> <DEDENT> return str...
Resolve path against upload directory.
625941ce004d5f362079a470
def __init__( self, *, signature_record: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(TagAttributesTag, self).__init__(**kwargs) <NEW_LINE> self.signature_record = signature_record
:keyword signature_record: SignatureRecord value. :paramtype signature_record: str
625941cec4546d3d9de72b72
def maketankgroup(tank_id): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for i in range(tank_id): <NEW_LINE> <INDENT> ret.append(maketank(i, True)) <NEW_LINE> <DEDENT> ret.append(maketank(tank_id, False)) <NEW_LINE> return ret
Make all the tanks that should be on the field currently
625941cedc8b845886cb5672
def getActionCost(self, state, action, next_state): <NEW_LINE> <INDENT> util.raiseNotDefined()
state: Search state action: action taken at state. next_state: next Search state after taking action. For a given state, this should return the cost of the (s, a, s') transition.
625941ce7d43ff24873a2ddd
def test_last_name_field(self): <NEW_LINE> <INDENT> last_name = Signature.objects.get(last_name='Zbonack') <NEW_LINE> max_length = last_name._meta.get_field('last_name').max_length <NEW_LINE> self.assertEqual(max_length, 40)
Test last_name field
625941ce627d3e7fe0d68f8d
def get_head_sha(self): <NEW_LINE> <INDENT> return self.head_sha
Gets the SHA corresponding to the commit at HEAD. Returns: HEAD SHA
625941ce7d43ff24873a2dde
def test_init_dict(self): <NEW_LINE> <INDENT> x = adict({ 'z': 5, 'y': '0', 'a': 'x', 'B': [] }) <NEW_LINE> self.assertEqual([k for k in x.keys()], ['a', 'B', 'y', 'z']) <NEW_LINE> self.assertEqual([v for v in x.values()], ['x', [], '0', 5])
Test initialzation of alpha sorted dictionaries using a plain dictionary.
625941ce55399d3f055887f2
def expired(self, seconds=30, now=None): <NEW_LINE> <INDENT> if now is None: <NEW_LINE> <INDENT> now = datetime.datetime.utcnow() <NEW_LINE> <DEDENT> return (self.expires_at - now) < datetime.timedelta(seconds=seconds)
Check if the token has expired yet. :param seconds: the minimum number of seconds allowed before expiry.
625941ce57b8e32f524835d8
@pytest.fixture <NEW_LINE> def multisample_ann_vcf(): <NEW_LINE> <INDENT> with open(MULTISAMPLE_ANN) as f: <NEW_LINE> <INDENT> yield f
Open the multisample.vcf file with full annotation.
625941ce7b25080760e39597
def timestamp(dt): <NEW_LINE> <INDENT> return total_seconds(dt, BASE)
Return seconds since epoch of the time.
625941ce3539df3088e2e488
def test_time_explosion(self): <NEW_LINE> <INDENT> assert ( self.model.model_state.time_explosion.unit == self.model.time_explosion.unit ) <NEW_LINE> assert ( self.model.model_state.time_explosion == self.model.time_explosion )
Test if time_explosion stored in ModelState is the same as that stored in Model.
625941cee8904600ed9f206b
def update_tab(self): <NEW_LINE> <INDENT> self.tab_label.set_image(self.icon) <NEW_LINE> self.tab_label.set_text(self.text)
update the values of the tab
625941ce5166f23b2e1a5297
def rm_plugin(self, tag): <NEW_LINE> <INDENT> if tag in self._plugins: <NEW_LINE> <INDENT> del self._plugins[tag] <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Remove plugin from world. > *Input arguments* * `tag` (*type:* `str`): Local name identifier of the plugin to be removed. > *Returns* `bool`: `True`, if plugin could be removed, `False` if no plugin with name `tag` could be found in the world.
625941ce498bea3a759b9bed
def process_image(raw_rgb): <NEW_LINE> <INDENT> rgb = camera_cal.undistort_image(raw_rgb) <NEW_LINE> for match in match_vehicles(rgb): <NEW_LINE> <INDENT> veh.draw_vehicle_match(rgb, match) <NEW_LINE> <DEDENT> return rgb
Vehicle recognition pipeline. Input raw RGB images from camera.
625941ce5fdd1c0f98dc0371
def purple_account_set_remember_password(*args): <NEW_LINE> <INDENT> return _purple.purple_account_set_remember_password(*args)
purple_account_set_remember_password(PurpleAccount account, gboolean value)
625941ceb5575c28eb68e13e
def model(X, Y, layers_dims, optimizer, learning_rate=0.0007, mini_batch_size=64, beta=0.9, beta1=0.9, beta2=0.999, epsilon=1e-8, num_epochs=10000, print_cost=True): <NEW_LINE> <INDENT> L = len(layers_dims) <NEW_LINE> costs = [] <NEW_LINE> t = 0 <NEW_LINE> seed = 10 <NEW_LINE> parameters = initialize_parameters(layers_...
3-layer neural network model which can be run in different optimizer modes. Arguments: X -- input data, of shape (2, number of examples) Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples) layers_dims -- python list, containing the size of each layer learning_rate -- the learnin...
625941cec432627299f04d83
def setUp(self): <NEW_LINE> <INDENT> self.empty_atom = Atom() <NEW_LINE> self.trial_atom = Atom() <NEW_LINE> self.trial_atom.atomname = "C" <NEW_LINE> self.trial_atom.coordinates = Point(coords=np.array([1, 2, 3])) <NEW_LINE> self.trial_atom.charge = 0. <NEW_LINE> self.trial_atom.element = "C" <NEW_LINE> self.trial_ato...
Instantiates a pair of atom objects for tests.
625941ce3617ad0b5ed68035
def make_submask(master_mask, refpoint, shape, blemish=None): <NEW_LINE> <INDENT> x_master = np.arange(master_mask.shape[1]) - refpoint[1] <NEW_LINE> y_master = np.arange(master_mask.shape[0]) - refpoint[0] <NEW_LINE> interpolator = RegularGridInterpolator((y_master, x_master), master_mask, bounds_error=False, fill_val...
Make a submask from the master mask, knowing the master_cen center and the outgoing image shape and center subimg_cen. refpoint is in row,col format (y,x) This is the reference point that should register masks together # using interpolation for subpixel shifts NOTE : Internally, all reference points refer...
625941ce94891a1f4081bbe7
def firstname_field(self): <NEW_LINE> <INDENT> firstname_label = Label(self.root, text="First Name:") <NEW_LINE> self.firstname_entry = Entry() <NEW_LINE> firstname_label.grid(row=self.row, column=0) <NEW_LINE> self.row += 1 <NEW_LINE> self.firstname_entry.grid(row=self.row, column=0) <NEW_LINE> self.row += 1
Initialize firstname field
625941ce498bea3a759b9bec
def year_parser(year_str): <NEW_LINE> <INDENT> if re.match(re.compile(r'^s*(((18|19)\d\d)|((200\d)|(201[012])))\s*$'),year_str): <NEW_LINE> <INDENT> secured_input = int(re.search(re.compile(r'^(((18|19)\d\d)|((200\d)|(201[012])))$'),year_str).group()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise InvalidInputErro...
check if the input year string is legal
625941ce9f2886367277a9cb
def is_linear(self): <NEW_LINE> <INDENT> spine_item = self._get_spine_itemref_el() <NEW_LINE> if spine_item is not None: <NEW_LINE> <INDENT> linear_attr = spine_item.get("linear") <NEW_LINE> if linear_attr is not None and linear_attr == "no": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Looks to see if this item is marked as being linear in the spine
625941ce3c8af77a43ae38de
def get_unique_slug(self, slug): <NEW_LINE> <INDENT> orig_slug = slug <NEW_LINE> counter = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> projects = Project.objects.filter(slug=slug) <NEW_LINE> if not projects.exists(): <NEW_LINE> <INDENT> return slug <NEW_LINE> <DEDENT> slug = '%s-%s' % (orig_slug, counter) <NEW_LINE> c...
Iterate until a unique slug is found
625941cede87d2750b85fed1
def parameter_dict(dico, resource, special=None): <NEW_LINE> <INDENT> res = {} <NEW_LINE> for key in resource: <NEW_LINE> <INDENT> _logger.debug(' PARAMETER -> RESOURCE: %s' % key) <NEW_LINE> if key in 'xml_data': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> res['OERP_%s' % key.upper()] = ustr(resource[key]) <NEW_L...
Convert value to a parameter for SOAP query @type dico: dict @param dico: Contain parameter starts with OERP_ @type resource: dict @param resource: Contain parameter starts with WIZARD_ @rtype: dict @return: All keys in a dict
625941ce1f5feb6acb0c4c8e
def build_url(self, url, params): <NEW_LINE> <INDENT> return url + "?" + unquote(urlencode(params))
Due to `params` as kwarg being % escaped
625941cead47b63b2c50a0bd
def test_create_duplicated_game_category(self): <NEW_LINE> <INDENT> new_game_category_name = "New Game Category" <NEW_LINE> response1 = self.create_game_category(new_game_category_name) <NEW_LINE> self.assertEqual(response1.status_code, status.HTTP_201_CREATED) <NEW_LINE> response2 = self.create_game_category(new_game_...
Test we cannot create duplicate game category
625941ce4527f215b584c594
def _entity_func(self) -> Callable[[str, str], bool]: <NEW_LINE> <INDENT> raise NotImplementedError
Return a function that can test entity access.
625941cefbf16365ca6f6303
def pull_single_msg(self, queuename): <NEW_LINE> <INDENT> return self.ch.basic_get(queue=queuename, auto_ack=True)
return (method, properties, body)
625941ce50812a4eaa59c45f
def test_basic_multivariate(network=ShapeletForestClassifier()): <NEW_LINE> <INDENT> print("Start test_multivariate()") <NEW_LINE> X_train, y_train = load_basic_motions(split='train', return_X_y=True) <NEW_LINE> X_test, y_test = load_basic_motions(split='test', return_X_y=True) <NEW_LINE> hist = network.fit(X_train[:10...
just a super basic test with basicmotions, load data, construct classifier, fit, score
625941ce99cbb53fe6792d24
def summoner_get_names_for_ids(self, region, summoner_ids): <NEW_LINE> <INDENT> url = '{0}/{1}/{2}/summoner/{3}/name?api_key={4}'.format( self.base_url, region, SUMMONER_VERSION, summoner_ids, self.api_key) <NEW_LINE> response = requests.get(url) <NEW_LINE> response.raise_for_status() <NEW_LINE> content = response.json...
Get summoner names for list of summoner ids region: Region where to retrieve the data. Use the constants included in this package. summoner_ids: Comma separted string of summoner IDs. returns dictionary of summoner ids to names id long Summoner ID. name string Summoner name throws HTTPError
625941cea4f1c619b28b0176
def update(self): <NEW_LINE> <INDENT> self.rect.x += Ball.ball_speed_x <NEW_LINE> self.rect.y += Ball.ball_speed_y
Function that updates the ball's state.
625941ce099cdd3c635f0d99
def _set_headers(self): <NEW_LINE> <INDENT> self.send_response(200) <NEW_LINE> self.send_header('content-type', 'text/html') <NEW_LINE> self.end_headers()
sets headers
625941ceaad79263cf390b7f
def index_starters(rule_tokens, gaps, _ngram_length=NGRAM_LENGTH): <NEW_LINE> <INDENT> rule_tokens = list(rule_tokens) <NEW_LINE> len_tokens = len(rule_tokens) <NEW_LINE> if not gaps: <NEW_LINE> <INDENT> if len_tokens >= _ngram_length: <NEW_LINE> <INDENT> yield tuple(rule_tokens[:_ngram_length]), 0 <NEW_LINE> <DEDENT> ...
Given an sequence of rule tokens and a set of gaps for that rule, return a sequence of tuples of (starter ngram, start,) computed from the tokens, gaps and ngram len. start is the starting position of the ngram.
625941ce30bbd722463cbf04
def compute_spectrograms(self, waveforms, labels=None): <NEW_LINE> <INDENT> s = self.settings <NEW_LINE> waveforms = tf.cast(waveforms, tf.float32) <NEW_LINE> stfts = tf.signal.stft( waveforms, self.window_size, self.hop_size, fft_length=self.dft_size, window_fn=self.window_fn) <NEW_LINE> stfts = stfts[..., self.freq_s...
Computes spectrograms for a batch of waveforms.
625941ce566aa707497f46a6
def begin_final_file(self, resulting_file): <NEW_LINE> <INDENT> print("[", file=resulting_file)
Hook executes at the beginning of writing a resulting file. (After BOM is written)
625941ce23849d37ff7b31cd
def o_rundzie(self, gra): <NEW_LINE> <INDENT> bazowa_dl_separatora = 120 <NEW_LINE> korekta = round((gra.plansza.kolumny - 8) * 13) <NEW_LINE> dl_separatora = bazowa_dl_separatora + korekta <NEW_LINE> komunikat = gra.podaj_info_o_rundzie().title() <NEW_LINE> komunikat = " ".join([" ", self.GWIAZDKA, komunikat, self.G...
Wyświetl komunikat o nowej rundzie.
625941cefb3f5b602dac37d1
def build_query( self, sketch_id, query_string, query_filter, query_dsl, aggregations=None): <NEW_LINE> <INDENT> if not query_dsl: <NEW_LINE> <INDENT> if query_filter.get(u'star', None): <NEW_LINE> <INDENT> query_dsl = self._build_label_query(sketch_id, u'__ts_star') <NEW_LINE> <DEDENT> if query_filter.get(u'events', N...
Build Elasticsearch DSL query. Args: sketch_id: Integer of sketch primary key query_string: Query string query_filter: Dictionary containing filters to apply query_dsl: Dictionary containing Elasticsearch DSL query aggregations: Dict of Elasticsearch aggregations Returns: Elasticsearch DSL que...
625941ce3317a56b86939d95
def get_client(service, event, region=None): <NEW_LINE> <INDENT> if not ASSUME_ROLE_MODE: <NEW_LINE> <INDENT> return boto3.client(service, region) <NEW_LINE> <DEDENT> credentials = get_assume_role_credentials(event["executionRoleArn"], region) <NEW_LINE> return boto3.client(service, aws_access_key_id=credentials['Acces...
Return the service boto client. It should be used instead of directly calling the client. Keyword arguments: service -- the service name used for calling the boto.client() event -- the event variable given in the lambda handler region -- the region where the client is called (default: None)
625941cea8370b77170529dd
def setController(self, controller): <NEW_LINE> <INDENT> self.controller = controller
Set a controller. Argument(s): controller (Controller): Controller of the view
625941ced53ae8145f87a3ad
def test_get_current_ticket_amount_no_comp_active(self): <NEW_LINE> <INDENT> comp = Competition.objects.create(is_active=False) <NEW_LINE> comp.save() <NEW_LINE> ticket_amount = self.client.get('/competition/get_current/') <NEW_LINE> self.assertEqual(ticket_amount.content, b'No Competition Active')
Test reponse of view that returns the current ticket amount of the homepage if theres no competition active
625941ceb7558d58953c5051
def getSignalPos(self): <NEW_LINE> <INDENT> return self.signalPos
获取信号仓位
625941ce0383005118ecf720
def __init__( self, *, disable_password_authentication: Optional[bool] = None, ssh: Optional["SshConfiguration"] = None, provision_vm_agent: Optional[bool] = None, patch_settings: Optional["LinuxPatchSettings"] = None, **kwargs ): <NEW_LINE> <INDENT> super(LinuxConfiguration, self).__init__(**kwargs) <NEW_LINE> self.di...
:keyword disable_password_authentication: Specifies whether password authentication should be disabled. :paramtype disable_password_authentication: bool :keyword ssh: Specifies the ssh key configuration for a Linux OS. :paramtype ssh: ~azure.mgmt.compute.v2021_04_01.models.SshConfiguration :keyword provision_vm_agent:...
625941ced268445f265b4fac
def get_total_matches(self): <NEW_LINE> <INDENT> return self.db_instance.get_num_documents(self.match_collection)
Get total matches to be analyzed. :return: num matches in db collection
625941ce711fe17d825424a9
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserMembershipListResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941ce3317a56b86939d96
def set_positioning(pos_mode): <NEW_LINE> <INDENT> return Code(POSITIONING_MODES[pos_mode], comment=f"set pos_mode positioning mode")
G90/G91: Change positioning mode to absolute/relative
625941ce377c676e912722e7
def update(grid): <NEW_LINE> <INDENT> new_grid = {} <NEW_LINE> for location, cell in grid.items(): <NEW_LINE> <INDENT> new_grid.update({location:(cell[1], False)}) <NEW_LINE> <DEDENT> return new_grid
Changes status of each cell to alive (True) or dead (False) depending on the second boolean in each cell. :type: grid: dict
625941ce8c0ade5d55d3eaf9
def kurtosis(signal): <NEW_LINE> <INDENT> return scipy.stats.kurtosis(signal)
Obtains the kurtosis of a signal fragment. We use this value as an indicator of the signal quality.
625941ce3eb6a72ae02ec61c
def test_get_user_credentials_when_authenticated(self): <NEW_LINE> <INDENT> self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token) <NEW_LINE> response = self.client.get(self.url) <NEW_LINE> self.assertEqual(response.data['username'], user3['username']) <NEW_LINE> self.assertEqual(response.status_code, statu...
Test api can get user if user is authenticated
625941ce462c4b4f79d1d80f
def test_init(self): <NEW_LINE> <INDENT> test_classname = 'test_classname' <NEW_LINE> test_name = 'test_name' <NEW_LINE> test_parent_mock = Mock(spec=['full_path']) <NEW_LINE> test_parent_mock.full_path.return_value = 'test_parent' <NEW_LINE> idl_node = node.IDLNode(test_classname, test_name, test_parent_mock) <NEW_LIN...
test for init
625941ce4c3428357757c466
def get_framesets(self, url): <NEW_LINE> <INDENT> page_content = self.previous_results['page_content'][url] <NEW_LINE> assert 'content' in page_content <NEW_LINE> if page_content['content'] is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> result = { 'frameset': None, } <NEW_LINE> soup = BeautifulSoup(page_conten...
Expects page_content_dict['content'] to carry the HTML content
625941cefff4ab517eb2f57a
def user_exit(path): <NEW_LINE> <INDENT> with open(path, 'wt') as fhandler: <NEW_LINE> <INDENT> fhandler.write(json.dumps(users))
退出系统
625941ce15baa723493c40b4
def on_failure_cobranca_aberto(self, req,result): <NEW_LINE> <INDENT> print(result)
retorno da função get_cobranca_aberto() caso haja o request falhe
625941ce046cf37aa974ce86
def test___init___array(self): <NEW_LINE> <INDENT> comp = TestImplCompArray() <NEW_LINE> prob = Problem(comp).setup(check=False) <NEW_LINE> prob['rhs'] = np.ones(2) <NEW_LINE> prob.run_model() <NEW_LINE> assert_rel_error(self, prob['x'], np.ones(2))
Test an implicit component with array inputs/outputs.
625941ce187af65679ca525d
def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): <NEW_LINE> <INDENT> new_values = self.values if inplace else self.values.copy() <NEW_LINE> new_values[mask] = new <NEW_LINE> return [self.make_block_same_class(values=new_values, placement=self.mgr_locs)]
putmask the data to the block; it is possible that we may create a new dtype of block return the resulting block(s) Parameters ---------- mask : the condition to respect new : a ndarray/object align : boolean, perform alignment on other/cond, default is True inplace : perform inplace modification, default is False ...
625941ce23849d37ff7b31ce
def get_bytes(self, key, *args): <NEW_LINE> <INDENT> raise NotImplementedError('Method must be implemented by subclass')
Return a byte string representation or raise a KeyError.
625941ce7d847024c06be3fb
def format_log_filename(logfile): <NEW_LINE> <INDENT> date = datetime.date.today() <NEW_LINE> logfile = logfile.format(date=date) <NEW_LINE> return logfile
Adds the date to the log file name.
625941cea219f33f34628aa8
def evaluate_model(self, features_name, model): <NEW_LINE> <INDENT> logger.debug('Model {} predicting from features {}'.format(model.name, features_name)) <NEW_LINE> _features = self.features[features_name] <NEW_LINE> predictions = model.predict(_features.values) <NEW_LINE> prediction = self.Prediction('{}__{}'.format(...
Predict from features.
625941ce99cbb53fe6792d25
def add_random_edges(self, total_edges): <NEW_LINE> <INDENT> while len(self._edges) < total_edges: <NEW_LINE> <INDENT> self.add_edge(self.make_random_edge())
Add random edges until the number of desired edges is reached.
625941cf379a373c97cfac83
def superimpose(self): <NEW_LINE> <INDENT> if not self.superimposed_: <NEW_LINE> <INDENT> self.traj_.superpose(self.ref_, frame=0, atom_indices=self.superpose_atom_indices_) <NEW_LINE> self.superimposed_ = True <NEW_LINE> <DEDENT> return self
Superimpose the trajectory to a reference structure. Returns ------- self : return an instance of self.
625941ce21bff66bcd684a91
def export_raw(self, params, time_delta=600): <NEW_LINE> <INDENT> signed = self._sign_params(params, time_delta) <NEW_LINE> content = self.execute(RAW_ENDPOINT, VERSION, ['export'], signed) <NEW_LINE> return [json.loads(obj) for obj in content.splitlines()]
Generate a Mixpanel Raw Export request. A signature will automatically attached. :param params: extra parameters associated with method :param time_delta: amount of time request is live (TTL)
625941cf4f6381625f114b79
def print_memory_usage(sorted_cmds, shareds, count, total, swaps, total_swap, show_swap): <NEW_LINE> <INDENT> for cmd in sorted_cmds: <NEW_LINE> <INDENT> output_string = "%9s + %9s = %9s" <NEW_LINE> output_data = (human(cmd[1]-shareds[cmd[0]]), human(shareds[cmd[0]]), human(cmd[1])) <NEW_LINE> if show_swap: <NEW_LINE> ...
Print memory usage
625941cebde94217f3682f2f
def get_info(self): <NEW_LINE> <INDENT> output = "# pointer variables are : " <NEW_LINE> output += ", ".join('{0}={1}' .format(key, val) for key, val in sorted(self.variables.items())) <NEW_LINE> output += "\n# next pointers are : " <NEW_LINE> output += ", ".join('{0}={1}' .format(key, val) for key, val in sorted(self....
Return string to be written into header of program.py.
625941ce63f4b57ef0001257
def get_file_ext(f): <NEW_LINE> <INDENT> delim = f.rfind('.') + 1 <NEW_LINE> filetype = f[delim:] <NEW_LINE> return filetype
takes in a filename.ext, finds extension by looking for the last . delimiter, and returns the filetype as str :param f: str, required; filename with extension :return: file extension
625941cfc4546d3d9de72b73
def get_failure_reason(block_id, block_dict, extra_args=None): <NEW_LINE> <INDENT> function_name = runner_utils.get_param_for_module(block_id, block_dict, "function") <NEW_LINE> return "Executing function {0}".format(function_name)
The function is used to find the action that was performed during the audit check :param block_id: id of the block :param block_dict: parameter for this module :param extra_args: Extra argument dictionary, (If any) Example: {'chaining_args': {'result': "/some/path/file.txt", 'status': True}, ...
625941cf96565a6dacc8f80a
def _guess_from_label_text(self, label_lines): <NEW_LINE> <INDENT> names = self._get_names() <NEW_LINE> best_ratio = 0 <NEW_LINE> best_name = None <NEW_LINE> for line in label_lines: <NEW_LINE> <INDENT> matcher = SequenceMatcher() <NEW_LINE> matcher.set_seq2(line) <NEW_LINE> for name in names: <NEW_LINE> <INDENT> match...
Looks through all of the lines, and compares each line to the list of names. Returns the objects with the name that is the closest match to any line in `label_lines`
625941cf63f4b57ef0001258
def toHTML(self, formatted=False, *args, **kwargs): <NEW_LINE> <INDENT> if self.childElements: <NEW_LINE> <INDENT> for child in self: <NEW_LINE> <INDENT> child.removeClass("WVisible") <NEW_LINE> <DEDENT> self.visibleElement().addClass("WVisible") <NEW_LINE> <DEDENT> return Base.Node.toHTML(self, formatted=formatted, *a...
Changes toHTML behavior to only generate the html for the visible element
625941cf435de62698dfdd8c
def store_msg_to_db(text_msg_dict, xml): <NEW_LINE> <INDENT> logging.info("writing msg details to db") <NEW_LINE> if service_prop.DatabaseProperty.isLocalDBHost: <NEW_LINE> <INDENT> host = service_prop.DatabaseProperty.local_host <NEW_LINE> user = service_prop.DatabaseProperty.local_user <NEW_LINE> pwd = service_prop.D...
:rtype : object :param text_msg_dict: dictionary contains parsed info :param xml: posted XML from WeChat server :return:
625941cf507cdc57c6306e1a
def from_node(self, node: "Node") -> list: <NEW_LINE> <INDENT> pass
Queries all Edge configurations which is from the given node entry. @rtype: list[Edge]
625941cf3c8af77a43ae38df
def analyse_all(microscopy_collection, output_dir, threshold, min_voxel, max_voxel): <NEW_LINE> <INDENT> for s in microscopy_collection.series: <NEW_LINE> <INDENT> sub_dir = os.path.join(output_dir, str(s)) <NEW_LINE> if not os.path.isdir(sub_dir): <NEW_LINE> <INDENT> os.mkdir(sub_dir) <NEW_LINE> <DEDENT> AutoName.dire...
Analyse all series in input microscopy file.
625941cf4e4d5625662d4516
def bump(self, pkg, version): <NEW_LINE> <INDENT> if not self.has_package(pkg): <NEW_LINE> <INDENT> msg = "Unable to find package {} in file {}".format( pkg, self.filename ) <NEW_LINE> raise KeyError(msg) <NEW_LINE> <DEDENT> if self.operators.get(pkg) is not None: <NEW_LINE> <INDENT> replacer = re.compile("^[\s]*({pkg}...
bump the version of package in the requirements file
625941cfa934411ee37517d2
def __len__(self): <NEW_LINE> <INDENT> return self.size
Returns the number of nodes in the list.
625941cf4d74a7450ccd4302