code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_init_with_data(self): <NEW_LINE> <INDENT> one_attr = Attr.new_u16(TYPE_U16, 4881) <NEW_LINE> attr_parser = AttrParser(one_attr) <NEW_LINE> self.assertTrue(isinstance(attr_parser, AttrParser)) | Test AttrParser object creation with data.
| 625941c08e05c05ec3eea2c9 |
def print_graph(self): <NEW_LINE> <INDENT> for i in self.graph: <NEW_LINE> <INDENT> print(i, '->', ' -> '.join([str(j) for j in self.graph[i]])) | for printing the contents of the graph | 625941c07d847024c06be210 |
def test_ultrasound_distance() -> None: <NEW_LINE> <INDENT> backend = SBArduinoConsoleBackend( "TestBoard", console_class=MockConsole, ) <NEW_LINE> backend._console.next_input = "1.23" <NEW_LINE> metres = backend.get_ultrasound_distance(3, 4) <NEW_LINE> assert metres is not None <NEW_LINE> assert isclose(metres, 1.23) <NEW_LINE> assert backend.get_gpio_pin_mode(3) is GPIOPinMode.DIGITAL_OUTPUT <NEW_LINE> assert backend.get_gpio_pin_digital_state(3) is False <NEW_LINE> assert backend.get_gpio_pin_mode(4) is GPIOPinMode.DIGITAL_INPUT | Test that we can read an ultrasound distance. | 625941c06e29344779a6256b |
def within(self,residue,xyz,cutoff) : <NEW_LINE> <INDENT> return self.distance2(residue,xyz) <= cutoff*cutoff | Return whether this residues is within a cutoff of another residue | 625941c00a366e3fb873e76f |
def test_handle_qpack_encoder_duplicate(self): <NEW_LINE> <INDENT> quic_client = FakeQuicConnection( configuration=QuicConfiguration(is_client=True) ) <NEW_LINE> h3_client = H3Connection(quic_client) <NEW_LINE> h3_client.handle_event( StreamDataReceived( stream_id=11, data=encode_uint_var(StreamType.QPACK_ENCODER), end_stream=False, ) ) <NEW_LINE> h3_client.handle_event( StreamDataReceived( stream_id=15, data=encode_uint_var(StreamType.QPACK_ENCODER), end_stream=False, ) ) <NEW_LINE> self.assertEqual( quic_client.closed, ( ErrorCode.H3_STREAM_CREATION_ERROR, "Only one QPACK encoder stream is allowed", ), ) | We must only receive a single QPACK encoder stream. | 625941c0187af65679ca5075 |
def convert(self, direction): <NEW_LINE> <INDENT> print("Converting corpus..") <NEW_LINE> data = [] <NEW_LINE> for sent in self.sentences: <NEW_LINE> <INDENT> for i in range(len(sent)): <NEW_LINE> <INDENT> center, contexts = self.skipgram(sent, i, direction) <NEW_LINE> data.append((self.word2idx[center], np.array([self.word2idx[context] for context in contexts]))) <NEW_LINE> <DEDENT> <DEDENT> self.data = data <NEW_LINE> print("Done") | Class method for converting amino acid into indexes.
Parameters
----------
direction: str
specifies which direction you are looking in at the data (backward, forward or both) | 625941c0d8ef3951e3243494 |
def judgeSquareSum(self, c): <NEW_LINE> <INDENT> j = int(math.sqrt(c)) <NEW_LINE> i = 0 <NEW_LINE> while i <= j: <NEW_LINE> <INDENT> total = i * i + j * j <NEW_LINE> if total > c: <NEW_LINE> <INDENT> j = j - 1 <NEW_LINE> <DEDENT> elif total < c: <NEW_LINE> <INDENT> i = i + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | :type c: int
:rtype: bool | 625941c06fb2d068a760eff2 |
def game(player_1, player_2, filetype='txt'): <NEW_LINE> <INDENT> if filetype == 'txt': <NEW_LINE> <INDENT> skill_player_1 = init_txt(player_1) <NEW_LINE> skill_player_2 = init_txt(player_2) <NEW_LINE> <DEDENT> elif filetype == 'bin': <NEW_LINE> <INDENT> skill_player_1 = init_bin(player_1) <NEW_LINE> skill_player_2 = init_bin(player_2) <NEW_LINE> <DEDENT> round_battle = 1 <NEW_LINE> while skill_player_1['health'] >= 0 and skill_player_2['health'] >= 0: <NEW_LINE> <INDENT> print(f'Раунд {round_battle}') <NEW_LINE> print(f'Атака {skill_player_1["name"]} на {skill_player_2["name"]}!') <NEW_LINE> print(battle(skill_player_1, skill_player_2)) <NEW_LINE> skill_player_1['health'] -= battle(skill_player_1, skill_player_2) <NEW_LINE> print( f'У игрока {skill_player_2["name"]} ', f'осталось {skill_player_2["health"]:.0f} единиц здоровья.' ) <NEW_LINE> print(f'Атака {skill_player_2["name"]} на {skill_player_1["name"]}!') <NEW_LINE> skill_player_2['health'] -= battle(skill_player_2, skill_player_1) <NEW_LINE> print( f'У игрока {skill_player_1["name"]} ', f'осталось {skill_player_1["health"]:.0f} единиц здоровья.' ) <NEW_LINE> round_battle += 1 <NEW_LINE> <DEDENT> if skill_player_2['health'] <= 0 < skill_player_1['health']: <NEW_LINE> <INDENT> print(f'Выиграл игрок {skill_player_1["name"]}!') <NEW_LINE> <DEDENT> elif skill_player_1['health'] <= 0 < skill_player_2['health']: <NEW_LINE> <INDENT> print(f'Выиграл игрок {skill_player_2["name"]}!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Ничья') <NEW_LINE> <DEDENT> return 1 | Игра.
fileformat тип файла для хранения сущности: txt - текстовой,
bin - бинарный
string --> return 1 | 625941c045492302aab5e218 |
def get_error_control(self): <NEW_LINE> <INDENT> return self.control.text | Returns the editor's control for indicating error status.
| 625941c0b830903b967e9864 |
def asaic(): <NEW_LINE> <INDENT> global verifoka <NEW_LINE> global choix <NEW_LINE> if verifoka: <NEW_LINE> <INDENT> global header, image , final, choix <NEW_LINE> k=0 <NEW_LINE> couleurmodif='' <NEW_LINE> longueurimage=len(image) <NEW_LINE> if choix==2: <NEW_LINE> <INDENT> while k!=longueurimage: <NEW_LINE> <INDENT> newcoul=int(image[k:k+2], 16) <NEW_LINE> if newcoul<128: <NEW_LINE> <INDENT> newcoul='00' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newcoul=hex(newcoul)[2:] <NEW_LINE> <DEDENT> couleurmodif += newcoul <NEW_LINE> k+=2 <NEW_LINE> <DEDENT> <DEDENT> elif choix==1: <NEW_LINE> <INDENT> while k!=longueurimage: <NEW_LINE> <INDENT> newcoul=int(image[k:k+2], 16) <NEW_LINE> if newcoul>=128: <NEW_LINE> <INDENT> newcoul='FF' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if newcoul<=15: <NEW_LINE> <INDENT> newcoul='0'+(hex(newcoul)[2:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newcoul=hex(newcoul)[2:] <NEW_LINE> <DEDENT> <DEDENT> couleurmodif+=newcoul <NEW_LINE> k+=2 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> tkinter.messagebox.showerror('Erreur !', "Erreur dans durant l'execution du logiciels") <NEW_LINE> <DEDENT> final.write(header+bytes.fromhex(couleurmodif)) <NEW_LINE> final.close() <NEW_LINE> tkinter.messagebox.showinfo("Fait !", "Success !") <NEW_LINE> end() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tkinter.messagebox.showerror('Erreur !', "Vous n'avez pas spécifié de fichier (Code 4)") | Fonction de saturation, parametres : header de l'image, corps de l'image
et nom du fichier final | 625941c063d6d428bbe44446 |
def create(**kwargs): <NEW_LINE> <INDENT> policy = RotationPolicy(**kwargs) <NEW_LINE> database.create(policy) <NEW_LINE> return policy | Creates a new rotation policy.
:param kwargs:
:return: | 625941c0b5575c28eb68df56 |
@login_required <NEW_LINE> def chat(req): <NEW_LINE> <INDENT> username=req.session.get('username') <NEW_LINE> try: <NEW_LINE> <INDENT> room, created=Room.objects.get_or_create(label='default') <NEW_LINE> messages=reversed(room.messages.order_by('-timestamp')[:50]) <NEW_LINE> return render_to_response('group_chat.html', {'username': SafeString(username), 'room':room, 'messages':messages}) <NEW_LINE> <DEDENT> except Room.DoesNotExist: <NEW_LINE> <INDENT> return HttpResponseRedirect('/logout/') | 聊天室入口
:param req: 请求
:param label: 房间名称
:return: | 625941c015fb5d323cde0a63 |
def update_defaults(self, defaults): <NEW_LINE> <INDENT> config = {} <NEW_LINE> config.update(dict(self.get_config_section('virtualenv'))) <NEW_LINE> config.update(dict(self.get_environ_vars())) <NEW_LINE> for key, val in config.items(): <NEW_LINE> <INDENT> key = key.replace('_', '-') <NEW_LINE> if not key.startswith('--'): <NEW_LINE> <INDENT> key = '--%s' % key <NEW_LINE> <DEDENT> option = self.get_option(key) <NEW_LINE> if option is not None: <NEW_LINE> <INDENT> if not val: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if option.action == 'append': <NEW_LINE> <INDENT> val = val.split() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> option.nargs = 1 <NEW_LINE> <DEDENT> if option.action == 'store_false': <NEW_LINE> <INDENT> val = not strtobool(val) <NEW_LINE> <DEDENT> elif option.action in ('store_true', 'count'): <NEW_LINE> <INDENT> val = strtobool(val) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> val = option.convert_value(key, val) <NEW_LINE> <DEDENT> except optparse.OptionValueError: <NEW_LINE> <INDENT> e = sys.exc_info()[1] <NEW_LINE> print("An error occurred during configuration: %s" % e) <NEW_LINE> sys.exit(3) <NEW_LINE> <DEDENT> defaults[option.dest] = val <NEW_LINE> <DEDENT> <DEDENT> return defaults | Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists). | 625941c01f037a2d8b946155 |
def typevalue(self, key, value): <NEW_LINE> <INDENT> def listconvert(value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ast.literal_eval(value) <NEW_LINE> <DEDENT> except (SyntaxError, ValueError): <NEW_LINE> <INDENT> if "," in value: <NEW_LINE> <INDENT> return [x.strip() for x in value.split(",")] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> default = self.get(key) <NEW_LINE> if inspect.isclass(default): <NEW_LINE> <INDENT> t = default <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t = type(default) <NEW_LINE> <DEDENT> if t == bool: <NEW_LINE> <INDENT> t = LayeredConfig.boolconvert <NEW_LINE> <DEDENT> elif t == list: <NEW_LINE> <INDENT> t = listconvert <NEW_LINE> <DEDENT> elif t == date: <NEW_LINE> <INDENT> t = LayeredConfig.dateconvert <NEW_LINE> <DEDENT> elif t == datetime: <NEW_LINE> <INDENT> t = LayeredConfig.datetimeconvert <NEW_LINE> <DEDENT> return t(value) | Given a parameter identified by ``key`` and an untyped string,
convert that string to the type that our version of key has. | 625941c09b70327d1c4e0d2b |
def run(self, niter, burnin=0, step=1, init_state=None): <NEW_LINE> <INDENT> assert burnin < niter <NEW_LINE> variables = self.vs.keys() <NEW_LINE> samples = {v: [] for v in variables} <NEW_LINE> state = {v: npr.choice(vnode.domain) for v, vnode in self.vs.items()} <NEW_LINE> if init_state is not None: <NEW_LINE> <INDENT> state.update(init_state) <NEW_LINE> <DEDENT> n_iterations = niter + burnin <NEW_LINE> variable = npr.choice(variables) <NEW_LINE> for it in range(n_iterations): <NEW_LINE> <INDENT> variable = npr.choice(variables) <NEW_LINE> state[variable] = self.sample_var(variable, state) <NEW_LINE> if it >= burnin and (it - burnin) % step == 0: <NEW_LINE> <INDENT> for v in variables: <NEW_LINE> <INDENT> samples[v].append(state[v]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> marginals = self.get_marginals(samples) <NEW_LINE> domains = {v.name: v.orig_domain for v in self.vs.values()} <NEW_LINE> return (marginals, domains, self.fgraph.vobs) | Run a Gibbs sampler to estimate marginals using ``niter`` samples.
Optionally, use a burn-in period during which samples are discarded,
and specify (part of) the starting state.
Arguments
---------
niter : int
Number of samples to be returned.
burnin : int
Length of burn-in period.
step : int
Every ``step``-th point will be considered in the average.
For example, if ``step=5``, then the following samples will be
averaged: 0, 5, 10, 15, ...
init_state : dict
Starting state. Can be specified partially by only providing
initial values for a subset of all variables.
Returns
-------
A tuple of computed marginals, variable domains, and observations,
same as that returned by ``bprob.FactorGraph.run_bp``. | 625941c0bd1bec0571d90586 |
def get_HEMCO_output(wd=None, files=None, filename=None, vars=None, use_netCDF=True): <NEW_LINE> <INDENT> logging.info("Called get hemco output.") <NEW_LINE> if isinstance(vars, str): <NEW_LINE> <INDENT> vars = [vars] <NEW_LINE> <DEDENT> if isinstance(files, str): <NEW_LINE> <INDENT> filename = files <NEW_LINE> files = [files] <NEW_LINE> <DEDENT> if not wd == None: <NEW_LINE> <INDENT> fname = os.path.join(wd, "hemco.nc") <NEW_LINE> if not os.path.isfile(fname): <NEW_LINE> <INDENT> from .bpch2netCDF import hemco_to_netCDF <NEW_LINE> hemco_to_netCDF(wd, hemco_file_list=files) <NEW_LINE> pass <NEW_LINE> <DEDENT> logging.debug("Looking for hemco data in {wd}".format(wd=wd)) <NEW_LINE> try: <NEW_LINE> <INDENT> HEMCO_data = Dataset(fname, 'r') <NEW_LINE> arr = [] <NEW_LINE> for var in vars: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> arr.append(HEMCO_data.variables[var][:]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.warning("Could not find {var} in {fname}" .format(var=var, fname=fname)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> logging.error("Could not open hemco data from {fn}" .format(fn=fname)) <NEW_LINE> <DEDENT> <DEDENT> elif not filename == None: <NEW_LINE> <INDENT> logging.debug("Looking for hemco data in {file}".format(file=filename)) <NEW_LINE> HEMCO_data = Dataset(filename, 'r') <NEW_LINE> arr = [] <NEW_LINE> for var in vars: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> arr.append(HEMCO_data.variables[var][:]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.warning("Could not find {var} in {fname}" .format(var=var, fname=filename)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logging.error("No wd of filename given to get_hemco_output!") <NEW_LINE> return <NEW_LINE> <DEDENT> if len(arr) == 1: <NEW_LINE> <INDENT> arr = arr[0] <NEW_LINE> <DEDENT> return arr | Data extractor for hemco files and folders. You can specify either a
working dir or a file to get the data from.
Parameters
-------
wd (str): the directory to search for files in
vars (None): hemco_file or file list
files (None): hemco_file or file list
Returns
-------
(list) of numpy arrays the size of the input vars list.
Notes
----- | 625941c0435de62698dfdba3 |
def test_211_keystone_neutron_api_identity_relation(self): <NEW_LINE> <INDENT> u.log.debug('Checking keystone:neutron-api id relation data...') <NEW_LINE> unit = self.keystone_sentry <NEW_LINE> relation = ['identity-service', 'neutron-api:identity-service'] <NEW_LINE> rel_ks_id = unit.relation('identity-service', 'neutron-api:identity-service') <NEW_LINE> id_ip = rel_ks_id['private-address'] <NEW_LINE> expected = { 'admin_token': 'ubuntutesting', 'auth_host': id_ip, 'auth_port': "35357", 'auth_protocol': 'http', 'private-address': id_ip, 'service_host': id_ip, } <NEW_LINE> ret = u.validate_relation_data(unit, relation, expected) <NEW_LINE> if ret: <NEW_LINE> <INDENT> message = u.relation_error('neutron-api identity-service', ret) <NEW_LINE> amulet.raise_status(amulet.FAIL, msg=message) | Verify the keystone to neutron-api identity-service relation data | 625941c0cb5e8a47e48b7a04 |
def filna_dict(mes): <NEW_LINE> <INDENT> key = [f'pdf_{count+1}'for count in range(mes)] <NEW_LINE> value = ['stans.pdf'for count in range(mes)] <NEW_LINE> filna_tobe_inserted = dict(zip(key,value)) <NEW_LINE> return filna_tobe_inserted | "werkt. maar ga een dict comprehension proberen. | 625941c029b78933be1e5607 |
def test_create_user_valid(self): <NEW_LINE> <INDENT> user_http = { 'email': 'test@elguerodev.com', 'password': 'test123', 'name': 'guero' } <NEW_LINE> res = self.client.post(CREATE_USER_URL, user_http) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_201_CREATED) <NEW_LINE> self.assertNotIn('password', res.data) <NEW_LINE> user = get_user_model().objects.get(**res.data) <NEW_LINE> self.assertTrue(user.check_password(user_http['password'])) | Test creating user is successfull | 625941c07d43ff24873a2bf6 |
def _updateTemperatureVA(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = self.GetIO(1, 0) <NEW_LINE> v = val * 10 / 4095 <NEW_LINE> t0 = v / 10e-3 <NEW_LINE> val = self.GetIO(1, 4) <NEW_LINE> v = val * 10 / 4095 <NEW_LINE> t1 = v / 10e-3 <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logging.exception("Failed to read the temperature") <NEW_LINE> return <NEW_LINE> <DEDENT> logging.info("Temperature 0 = %g °C, temperature 1 = %g °C", t0, t1) <NEW_LINE> self.temperature._value = t0 <NEW_LINE> self.temperature.notify(t0) <NEW_LINE> self.temperature1._value = t1 <NEW_LINE> self.temperature1.notify(t1) | Update the temperature VAs, assuming that the 2 analogue inputs are
connected to a temperature sensor with mapping 10 mV <-> 1 °C. That's
conveniently what is in the Delphi. | 625941c0d4950a0f3b08c2a8 |
def fit_cov(self, X): <NEW_LINE> <INDENT> self.cov.fit(X) | Fit the model to a dataset
Parameters
----------
X : array, sample features to train the covariance estimator on (usually 'safe' dataset)
Returns
-------
None | 625941c0a17c0f6771cbdfaa |
def go_to_storage_tab(self): <NEW_LINE> <INDENT> self._model.storage_link.click() | Select Storage tab. | 625941c067a9b606de4a7e12 |
def _save_model(self, avg_acc): <NEW_LINE> <INDENT> epoch_save_path = os.path.join(self.opt.ckpt_path, 'epoch_' + str(self.epoch) + '_learn_xstar_tower_' + 'model.pth') <NEW_LINE> torch.save({'state': self.dlupi_model.state_dict(), 'acc': avg_acc}, epoch_save_path) <NEW_LINE> if avg_acc > self.best_val_acc: <NEW_LINE> <INDENT> self.best_val_acc = avg_acc | Save every single epoch's progress in Phase 1 of curriculum learning. s | 625941c01f037a2d8b946156 |
def combine(self, value): <NEW_LINE> <INDENT> self.__value = value <NEW_LINE> return True | Combine the return value of a slot.
Return True to continue processing slots or False to stop. | 625941c021a7993f00bc7c43 |
def test_relative_path(self): <NEW_LINE> <INDENT> url = '../file/path' <NEW_LINE> scheme, netloc, path, params, query, fragment, is_url, is_absolute = util.parse_url(url) <NEW_LINE> self.assertEqual(scheme, '') <NEW_LINE> self.assertEqual(path, '../file/path') <NEW_LINE> self.assertEqual(is_url, False) <NEW_LINE> self.assertEqual(is_absolute, False) | Test relative path. | 625941c04527f215b584c3b1 |
def log_score(sess, summary_writer, filename, data, scoring, epoch, x, y_): <NEW_LINE> <INDENT> with open(filename, "a") as myfile: <NEW_LINE> <INDENT> train = eval_network(sess, summary_writer, data.train, scoring, epoch, "train", x, y_) <NEW_LINE> test = eval_network(sess, summary_writer, data.test, scoring, epoch, "test", x, y_) <NEW_LINE> myfile.write("%i;%0.6f;%0.6f\n" % (epoch, train, test)) | Write the score to in CSV format to a file. | 625941c015fb5d323cde0a64 |
def fourier_make_response_real(response): <NEW_LINE> <INDENT> def real_response(freq): <NEW_LINE> <INDENT> abs_response=response(abs(freq)) <NEW_LINE> return abs_response*(freq>0)+abs_response.conjugate()*(freq<0)+abs_response.real*(freq==0) <NEW_LINE> <DEDENT> return real_response | Turn a frequency filter function into a real one (in the time domain).
Done by reflecting and complex conjugating positive frequency part to negative frequencies.
`response` is a function with a single argument (frequency), return value is a modified function. | 625941c03617ad0b5ed67e50 |
def GetChain(whole_name): <NEW_LINE> <INDENT> return whole_name[-1:] | Gets the chain name of a protein ID (chain name will be of the format "A").
Arguments:
whole_name: name of the protein of format "abc_A" | 625941c0cdde0d52a9e52f88 |
def bitsPerPixel2(self): <NEW_LINE> <INDENT> if self == type(self).TEXELED: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 | Return the number of bits per pixel that this format requires in
a texture's second data region.
This is useful for calculating the expected amount of data some
texture will have, given its width, height and format. | 625941c010dbd63aa1bd2afd |
def __init__(self, board): <NEW_LINE> <INDENT> self.board = board <NEW_LINE> self.players = {} | @param board: Board | 625941c0d99f1b3c44c674ec |
def _verify_encrypted_datum_repository_interactions(self): <NEW_LINE> <INDENT> self.assertEqual( 1, self.datum_repo.create_from.call_count) <NEW_LINE> args, kwargs = self.datum_repo.create_from.call_args <NEW_LINE> test_datum_model = args[0] <NEW_LINE> self.assertIsInstance(test_datum_model, models.EncryptedDatum) <NEW_LINE> self.assertEqual( self.content_type, test_datum_model.content_type) <NEW_LINE> self.assertEqual( base64.encodestring(self.cypher_text).rstrip(b'\n'), test_datum_model.cypher_text) <NEW_LINE> self.assertEqual( self.response_dto.kek_meta_extended, test_datum_model.kek_meta_extended) | Verify the encrypted datum repository interactions. | 625941c03eb6a72ae02ec42e |
def getCompressorNotConnectedFault(self): <NEW_LINE> <INDENT> return hal.getCompressorNotConnectedFault(self.compressorHandle) | :returns: True if PCM is in fault state : Compressor does not appear
to be wired, i.e. compressor is not drawing enough current. | 625941c0cb5e8a47e48b7a05 |
def setup(self): <NEW_LINE> <INDENT> self.points = helpers.load_sample_data()['geometry'].values <NEW_LINE> self.k = 40 <NEW_LINE> self.traversal = farthest_first_traversal.FarthestFirstTraversal(k=self.k) <NEW_LINE> self.traversal.fit(self.points) | Initialize and fit algorithm. | 625941c04c3428357757c281 |
def clear_auv_path(self): <NEW_LINE> <INDENT> self.auv_path_obj.pop(0).remove() | Clears the AUV path | 625941c04c3428357757c282 |
def has_loop(self, color): <NEW_LINE> <INDENT> if self.is_legal() == False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> connected_tile = 0 <NEW_LINE> for tile in self._tile_value: <NEW_LINE> <INDENT> code = self.get_code(tile) <NEW_LINE> direction1 = code.find(color) <NEW_LINE> direction2 = code.rfind(color) <NEW_LINE> neighbor1 = self.get_neighbor(tile, direction1) <NEW_LINE> if neighbor1 not in self._tile_value: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> neighbor1_code = self.get_code(neighbor1) <NEW_LINE> neighbor2 = self.get_neighbor(tile, direction2) <NEW_LINE> if neighbor2 not in self._tile_value: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> neighbor2_code = self.get_code(neighbor2) <NEW_LINE> if code[direction1] == neighbor1_code[reverse_direction(direction1)]: <NEW_LINE> <INDENT> if code[direction2] == neighbor2_code[reverse_direction(direction2)]: <NEW_LINE> <INDENT> connected_tile += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if connected_tile == len(SOLITAIRE_CODES): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Check whether a tile configuration has a loop of size 10 of given color | 625941c0167d2b6e31218aee |
def Postfija(cadena): <NEW_LINE> <INDENT> if evaluarP(cadena) and evaluarO(cadena) and evaluarA(cadena): <NEW_LINE> <INDENT> l = len(cadena) <NEW_LINE> i = 0 <NEW_LINE> pila = [] <NEW_LINE> postfija = [] <NEW_LINE> while(i < l): <NEW_LINE> <INDENT> if cadena[i] == "(": <NEW_LINE> <INDENT> pila.append(cadena[i]) <NEW_LINE> <DEDENT> elif isNumber(cadena[i]): <NEW_LINE> <INDENT> num = cadena[i] <NEW_LINE> if i + 1 < l: <NEW_LINE> <INDENT> while isNumber(cadena[i+1]): <NEW_LINE> <INDENT> num = num + cadena[i+1] <NEW_LINE> i += 1 <NEW_LINE> if i >= l-1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> postfija.append(num) <NEW_LINE> <DEDENT> elif esOperador(cadena[i]): <NEW_LINE> <INDENT> if pilaEmpty(pila): <NEW_LINE> <INDENT> pila.append(cadena[i]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> j = len(pila)- 1 <NEW_LINE> if esOperador(pila[j]) and jerarquia(pila[j]) > jerarquia(cadena[i]): <NEW_LINE> <INDENT> postfija.append(pila.pop()) <NEW_LINE> pila.append(cadena[i]) <NEW_LINE> <DEDENT> elif esOperador(pila[j]) and jerarquia(pila[j]) < jerarquia(cadena[i]): <NEW_LINE> <INDENT> pila.append(cadena[i]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pila.append(cadena[i]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif cadena[i] == ")": <NEW_LINE> <INDENT> lp = len(pila) -1 <NEW_LINE> while(pila[lp] != "("): <NEW_LINE> <INDENT> postfija.append(pila.pop()) <NEW_LINE> lp -= 1 <NEW_LINE> <DEDENT> pila.pop() <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> if not pilaEmpty(pila): <NEW_LINE> <INDENT> while(not pilaEmpty(pila)): <NEW_LINE> <INDENT> postfija.append(pila.pop()) <NEW_LINE> <DEDENT> <DEDENT> return postfija <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("error, expresion no valida!") <NEW_LINE> return None | Esta funcion realiza la conversion de notacion Infija a
Postfija | 625941c04a966d76dd550f65 |
def node_iter(self, path): <NEW_LINE> <INDENT> for n in self.layout_iter(path): <NEW_LINE> <INDENT> yield n[0] | An iterator over every node in the layout. Will throw AttributeError
on an invalid path at the point in iteration where the path is invalid. | 625941c03317a56b86939bb6 |
def threshold(self, frame, threshmin, threshmax): <NEW_LINE> <INDENT> assert frame.getColorSpace() == ColorSpace.HSV, "Image must be HSV!" <NEW_LINE> iplframe = frame.getBitmap() <NEW_LINE> if (self._blur > 0 and not self._displayBlur): <NEW_LINE> <INDENT> cv.Smooth(iplframe, iplframe, cv.CV_BLUR, self._blur) <NEW_LINE> <DEDENT> if (self._normalize): <NEW_LINE> <INDENT> avg = self.get_average_val(iplframe) <NEW_LINE> self._normalDiff = int(avg - self._normalVal) <NEW_LINE> self._normalize = False <NEW_LINE> <DEDENT> crossover = False <NEW_LINE> if threshmin[0] > threshmax[0]: <NEW_LINE> <INDENT> hMax = threshmin[0] <NEW_LINE> hMin = threshmax[0] <NEW_LINE> crossover = True <NEW_LINE> threshmax2 = [hMin, threshmax[1], threshmax[2]] <NEW_LINE> threshmin = [hMax, threshmin[1], threshmin[2]] <NEW_LINE> threshmax = [255, threshmax[1], threshmax[2]] <NEW_LINE> threshmin2 = [0, threshmin[1], threshmin[2]] <NEW_LINE> <DEDENT> iplresult = cv.CreateImage(cv.GetSize(iplframe), frame.depth, 1) <NEW_LINE> cv.InRangeS(iplframe, threshmin, threshmax, iplresult) <NEW_LINE> result = Image(iplresult) <NEW_LINE> if crossover: <NEW_LINE> <INDENT> iplresult2 = cv.CreateImage(cv.GetSize(iplframe), frame.depth, 1) <NEW_LINE> cv.InRangeS(iplframe, threshmin2, threshmax2, iplresult2) <NEW_LINE> result = result + Image(iplresult2) <NEW_LINE> <DEDENT> return result | Performs thresholding on a frame.
The image must be in the HSV colorspace! | 625941c00c0af96317bb8140 |
def convert_chgperiods_for_gens_to_dictionary(chgperiods_for_gens): <NEW_LINE> <INDENT> n_gens = len(chgperiods_for_gens) <NEW_LINE> gens_of_chgperiods = {0: [0]} <NEW_LINE> if n_gens > 1: <NEW_LINE> <INDENT> change_nr = 0 <NEW_LINE> for i in range(1, len(chgperiods_for_gens)): <NEW_LINE> <INDENT> if chgperiods_for_gens[i - 1] == chgperiods_for_gens[i]: <NEW_LINE> <INDENT> gens_of_chgperiods[change_nr].append(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> change_nr += 1 <NEW_LINE> gens_of_chgperiods[change_nr] = [i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> assert len(gens_of_chgperiods) == len(np.unique(chgperiods_for_gens)) <NEW_LINE> return gens_of_chgperiods | @param chgperiods_for_gens: 1d numpy array containing for each generation the
change period number it belongs to
@return dictionary: for each change period (even if the EA did not detect
it) a list of the corresponding generations | 625941c0bde94217f3682d4b |
def get_integration_weights(order,nodes=None): <NEW_LINE> <INDENT> if np.all(nodes == False): <NEW_LINE> <INDENT> nodes=get_quadrature_points(order) <NEW_LINE> <DEDENT> if poly == polynomial.chebyshev.Chebyshev: <NEW_LINE> <INDENT> weights = np.empty((order+1)) <NEW_LINE> weights[1:-1] = np.pi/order <NEW_LINE> weights[0] = np.pi/(2*order) <NEW_LINE> weights[-1] = weights[0] <NEW_LINE> return weights <NEW_LINE> <DEDENT> elif poly == polynomial.legendre.Legendre: <NEW_LINE> <INDENT> interior_weights = 2/((order+1)*order*poly.basis(order)(nodes[1:-1])**2) <NEW_LINE> boundary_weights = np.array([1-0.5*np.sum(interior_weights)]) <NEW_LINE> weights = np.concatenate((boundary_weights, interior_weights, boundary_weights)) <NEW_LINE> return weights <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Not a known polynomial type.") <NEW_LINE> return False | Returns the integration weights for Gauss-Lobatto quadrature
as a function of the order of the polynomial we want to
represent.
See: https://en.wikipedia.org/wiki/Gaussian_quadrature
See: arXive:gr-qc/0609020v1 | 625941c071ff763f4b5495df |
def compute_vehicle_emissions(veh_id): <NEW_LINE> <INDENT> co2 = traci.vehicle.getCO2Emission(veh_id) <NEW_LINE> co = traci.vehicle.getCOEmission(veh_id) <NEW_LINE> nox = traci.vehicle.getNOxEmission(veh_id) <NEW_LINE> hc = traci.vehicle.getHCEmission(veh_id) <NEW_LINE> pmx = traci.vehicle.getPMxEmission(veh_id) <NEW_LINE> return Emission(co2, co, nox, hc, pmx) | Recover the emissions of different pollutants from a vehicle and create an Emission instance
:param veh_id: The vehicle ID
:return: A new Emission instance | 625941c04e696a04525c93a4 |
def det(mat): <NEW_LINE> <INDENT> n = len(mat) <NEW_LINE> lower, upper = lu(mat) <NEW_LINE> product = 1 <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> product *= upper[i][i] <NEW_LINE> <DEDENT> return product | Input: An N x N matrix
Output: The determinant of the input matrix
Procedure:
The input matrix is decomposed into L and U using lu()
The determinant is the product of the diagonal entries of upper
triangular matrix, U. | 625941c0d164cc6175782ca5 |
def get_name(self): <NEW_LINE> <INDENT> return _sphinxbase.JsgfRule_get_name(self) | get_name(JsgfRule self) -> char const * | 625941c0baa26c4b54cb107a |
def readToken(self, _sFileToken, _bPasswordShow = False ): <NEW_LINE> <INDENT> oToken = TokenReader() <NEW_LINE> oToken.config(self._sFileKeyPrivate, self._sFileKeyPublic) <NEW_LINE> iReturn = oToken.readToken(_sFileToken) <NEW_LINE> if iReturn: <NEW_LINE> <INDENT> return iReturn <NEW_LINE> <DEDENT> dToken = oToken.getData() <NEW_LINE> for sField in list(dToken.keys()): <NEW_LINE> <INDENT> if not _bPasswordShow and sField[0:8]=='password': <NEW_LINE> <INDENT> dToken.pop(sField) <NEW_LINE> <DEDENT> <DEDENT> sys.stdout.write('%s\n' % JSON.dumps(dToken, indent=4, sort_keys=True)) <NEW_LINE> return 0 | Read token; returns a non-zero exit code in case of failure. | 625941c010dbd63aa1bd2afe |
def __str__(self): <NEW_LINE> <INDENT> result = ('White to move\n' if self.white_to_move else 'Black to move\n') <NEW_LINE> for rank in reversed(self.pieces.get_board_layout()): <NEW_LINE> <INDENT> for piece in rank: <NEW_LINE> <INDENT> if piece is None: <NEW_LINE> <INDENT> result += ' ' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result += piece + ' ' <NEW_LINE> <DEDENT> <DEDENT> result += '\n' <NEW_LINE> <DEDENT> return result | Return an ascii representation of current position. | 625941c096565a6dacc8f624 |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> if self.__locked: <NEW_LINE> <INDENT> raise AttributeError( SET_ERROR % (self.__class__.__name__, key, value) ) <NEW_LINE> <DEDENT> check_name(key) <NEW_LINE> if key in self.__d: <NEW_LINE> <INDENT> raise AttributeError(OVERRIDE_ERROR % (self.__class__.__name__, key, self.__d[key], value) ) <NEW_LINE> <DEDENT> assert not hasattr(self, key) <NEW_LINE> if isinstance(value, basestring): <NEW_LINE> <INDENT> value = value.strip() <NEW_LINE> if isinstance(value, str): <NEW_LINE> <INDENT> value = value.decode('utf-8') <NEW_LINE> <DEDENT> m = { 'True': True, 'False': False, 'None': None, '': None, } <NEW_LINE> if value in m: <NEW_LINE> <INDENT> value = m[value] <NEW_LINE> <DEDENT> elif value.isdigit(): <NEW_LINE> <INDENT> value = int(value) <NEW_LINE> <DEDENT> elif key in ('basedn'): <NEW_LINE> <INDENT> value = DN(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = float(value) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> assert type(value) in (unicode, int, float, bool, NoneType, DN) <NEW_LINE> object.__setattr__(self, key, value) <NEW_LINE> self.__d[key] = value | Set ``key`` to ``value``. | 625941c0b57a9660fec337d9 |
def test_read_dataset_challenge(self): <NEW_LINE> <INDENT> test_dataset = dataset_reader.ReadDataset('../tests/testdata/test_file.txt', challenge=True) <NEW_LINE> self.assertIsInstance(test_dataset, dataset_reader.ReadDataset) <NEW_LINE> self.assertEqual(test_dataset.challenge, True) | Test main class ReadDataset, result should be an instance of that class
Challenge flag is True | 625941c057b8e32f524833f1 |
def getNodeByClientId(self,dynamicId): <NEW_LINE> <INDENT> vcharacter = self.getVCharacterByClientId(dynamicId) <NEW_LINE> if vcharacter: <NEW_LINE> <INDENT> return vcharacter.getNode() <NEW_LINE> <DEDENT> return -1 | 根据客户端的ID获取服务节点的id
@param dynamicId: int 客户端的id | 625941c03346ee7daa2b2cc2 |
def subtract_vx_minus_vy(self): <NEW_LINE> <INDENT> self.registers['v'][0xf] = numpy.uint8(0) <NEW_LINE> vx_register = (self.opcode & 0x0F00) >> 8 <NEW_LINE> vy_register = (self.opcode & 0x00F0) >> 4 <NEW_LINE> resultado = numpy.subtract(self.registers['v'][vx_register], self.registers['v'][vy_register]) <NEW_LINE> if (int(self.registers['v'][vx_register]) - int(self.registers['v'][vy_register])) < 0: <NEW_LINE> <INDENT> self.registers['v'][0xf] = numpy.uint8(1) <NEW_LINE> <DEDENT> self.registers['v'][vx_register] = resultado <NEW_LINE> mnemonic = "SUB V" + str(vx_register) + ", V" + str(vy_register) <NEW_LINE> human = "V" + str(vx_register) + " <= V" + str(vx_register) + " - V" + str(vy_register) <NEW_LINE> result = "V" + str(vx_register) + " = " + str(self.registers['v'][vx_register]) <NEW_LINE> return (mnemonic, human, result) | Resta Vy a Vx. Si llevamos un bit establecemos la bandera a 1 | 625941c08da39b475bd64ec9 |
def test_content_type_content_type_mismatch(self): <NEW_LINE> <INDENT> test_request = DummyRequest() <NEW_LINE> test_request.setHeader("Content-Type", "image/jpeg; charset=utf-8") <NEW_LINE> outer_wrap = webapi.url_arguments(["arg1"], content_type="application/json") <NEW_LINE> inner_wrap = outer_wrap(self.dummy_render_func) <NEW_LINE> self.assertEqual(str(webapi.ContentTypeError(test_request)), inner_wrap(self, test_request)) | Request Content-Type doesn't match expected type. | 625941c0f7d966606f6a9f5a |
def _find_nn_pos_before_site(self, siteindex): <NEW_LINE> <INDENT> alldist = [(self._mol.get_distance(siteindex, i), i) for i in range(siteindex)] <NEW_LINE> alldist = sorted(alldist, key=lambda x: x[0]) <NEW_LINE> return [d[1] for d in alldist] | Returns index of nearest neighbor atoms. | 625941c0fb3f5b602dac35e9 |
def test___init__min_eq_max(self): <NEW_LINE> <INDENT> n = 1 <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> IntHyperParam(min=n, max=n) | Test instantiation with ``min=n`` and ``max=n`` | 625941c04527f215b584c3b2 |
def _raw(self, msg): <NEW_LINE> <INDENT> if isinstance(msg, str): <NEW_LINE> <INDENT> self.device.send(msg.encode()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.device.send(msg) | Print any command sent in raw format | 625941c063d6d428bbe44447 |
def is_dunder(s: str) -> bool: <NEW_LINE> <INDENT> if len(s) < 5 or s[:2] != '__' or s[-2:] != '__': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return NO_DOUBLE_US_RE.match(s[2:-2]) is not None | Examples:
>>> is_dunder('__dunder__')
True
>>> is_dunder('')
False
>>> is_dunder('__not_')
False
>>> is_dunder('_not__')
False
>>> is_dunder('__another_dunder__')
True
>>> is_dunder('___not_a_dunder__')
False
>>> is_dunder('__also_not_a_dunder___')
False
>>> is_dunder('__a_tricky__case__')
False
>>> is_dunder('__an___even_tricker___case__')
False
>>> is_dunder('___')
False
>>> is_dunder('____')
False
>>> is_dunder('_____')
False
>>> is_dunder('__2__')
True
>>> is_dunder('__HTTPResponseCode__')
True | 625941c0627d3e7fe0d68da7 |
def setInstanceProperty(self, part_instance: ObjectInstance, key: str, value: Any): <NEW_LINE> <INDENT> part_instance.setProperty(key, value) | Set an instance property
Args:
part_instance (ObjectInstance):
key (str):
value (object): | 625941c0cc40096d615958a9 |
def get_sam_input(transactions, key_func=None): <NEW_LINE> <INDENT> if key_func is None: <NEW_LINE> <INDENT> def key_func(e): <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> <DEDENT> (asorted_seqs, _) = _sort_transactions_by_freq(transactions, key_func) <NEW_LINE> sam_input = deque() <NEW_LINE> visited = {} <NEW_LINE> current = 0 <NEW_LINE> for seq in asorted_seqs: <NEW_LINE> <INDENT> if seq not in visited: <NEW_LINE> <INDENT> sam_input.append((1, seq)) <NEW_LINE> visited[seq] = current <NEW_LINE> current += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = visited[seq] <NEW_LINE> (count, oldseq) = sam_input[i] <NEW_LINE> sam_input[i] = (count + 1, oldseq) <NEW_LINE> <DEDENT> <DEDENT> return sam_input | Given a list of transactions and a key function, returns a data
structure used as the input of the sam algorithm.
:param transactions: a sequence of sequences. [ [transaction items...]]
:param key_func: a function that returns a comparable key for a
transaction item. | 625941c0a934411ee37515eb |
def _getuie(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value, newpos = self._readuie(0) <NEW_LINE> if value is None or newpos != self.len: <NEW_LINE> <INDENT> raise bitstring.ReadError <NEW_LINE> <DEDENT> <DEDENT> except bitstring.ReadError: <NEW_LINE> <INDENT> raise bitstring.InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") <NEW_LINE> <DEDENT> return value | Return data as unsigned interleaved exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code. | 625941c06aa9bd52df036cfb |
def get_iobuf_from_core(self, x, y, p): <NEW_LINE> <INDENT> warn_once(logger, "The get_iobuf_from_core method is deprecated and " "likely to be removed.") <NEW_LINE> core_subsets = CoreSubsets() <NEW_LINE> core_subsets.add_processor(x, y, p) <NEW_LINE> return next(self.get_iobuf(core_subsets)) | Get the contents of IOBUF for a given core
This method is currently deprecated and likely to be removed.
:param int x: The x-coordinate of the chip containing the processor
:param int y: The y-coordinate of the chip containing the processor
:param int p: The ID of the processor to get the IOBUF for
:return: An IOBUF buffer
:rtype: IOBuffer
:raise SpinnmanIOException:
If there is an error communicating with the board
:raise SpinnmanInvalidPacketException:
If a packet is received that is not in the valid format
:raise SpinnmanInvalidParameterException:
* If chip_and_cores contains invalid items
* If a packet is received that has invalid parameters
:raise SpinnmanUnexpectedResponseCodeException:
If a response indicates an error during the exchange | 625941c032920d7e50b28126 |
@app.route('/api/results') <NEW_LINE> def api_results(): <NEW_LINE> <INDENT> x = db.DbOps(db_u, db_p, db_h, db_db) <NEW_LINE> res, pg, qnum = x.display_results_api() <NEW_LINE> results = process_results(res, pg, qnum) <NEW_LINE> resp = Response(results, status=200, mimetype='application/json') <NEW_LINE> return resp | Get most recent 100 results of Search Results | 625941c07c178a314d6ef3b4 |
def __init__(self, size, pixels, variable_name=b'picture', transparent_colour=None): <NEW_LINE> <INDENT> self.xsize, self.ysize = size <NEW_LINE> self.variable_name = variable_name <NEW_LINE> self.pixels = pixels <NEW_LINE> self.transparent_colour = transparent_colour <NEW_LINE> colour_counts = collections.Counter( self.pixels[x, y] for x in range(self.xsize) for y in range(self.ysize)) <NEW_LINE> self.colours = [x for x, _ in sorted( colour_counts.items(), key=lambda x: -x[1])] <NEW_LINE> self.colour_width = int( math.log(len(self.colours)) // math.log(len(COLOUR_DIGITS))) + 1 <NEW_LINE> self.colour_table = dict( zip( self.colours, enumerate_colours(self.colour_width))) <NEW_LINE> self.add_pretty_colour_names() | Pixels is a dictionary mapping x,y coordinates to rgba tuples | 625941c021bff66bcd6848ad |
def _notify_remove(self, slice_): <NEW_LINE> <INDENT> change = RemoveChange(self, slice_) <NEW_LINE> self.notify_observers(change) | Notify about a RemoveChange. | 625941c076d4e153a657ea88 |
def update(self, datastream_id, **kwargs): <NEW_LINE> <INDENT> url = self.url(datastream_id) <NEW_LINE> with wrap_exceptions: <NEW_LINE> <INDENT> response = self.client.put(url, data=kwargs) <NEW_LINE> response.raise_for_status() | Updates a feeds datastream by id.
:param datastream_id: The ID of the datastream to update
:param kwargs: The datastream fields to be updated | 625941c03617ad0b5ed67e51 |
def add_to_cart(cart, all_items): <NEW_LINE> <INDENT> n = len(all_items) <NEW_LINE> show_all_items(all_items) <NEW_LINE> valid_num = False <NEW_LINE> while not valid_num: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> item_num = int(input('Enter the item you want to add: ')) <NEW_LINE> if item_num not in range(n): <NEW_LINE> <INDENT> print('Invalid input. Please enter the item number!') <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> valid_num = True <NEW_LINE> cart.append(all_items[item_num]) <NEW_LINE> print('Item {} added.'.format(item_num)) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print('Invalid input. Please enter the item number!') | name: item name to be added
price: item price
cart: a list storing (name, price) tuples | 625941c03d592f4c4ed1cfcc |
def entity_analysis(self): <NEW_LINE> <INDENT> entity_num = len(self.g.nodes()) <NEW_LINE> self.get_net_density() <NEW_LINE> self.get_cluster_coefficient() <NEW_LINE> self.analysis_summary = { "country": self.g.graph["country"], "date": self.g.graph["date"], "entity_num": entity_num, "density": self.density, "cluster_coefficient": self.cluster_coefficient, } | number of node, network density, number of connected
components, cluster coefficient | 625941c0ad47b63b2c509ed8 |
def leer_fichero(self, nombre_fichero): <NEW_LINE> <INDENT> with open (nombre_fichero, "r") as f: <NEW_LINE> <INDENT> lineas=f.readlines() <NEW_LINE> <DEDENT> texto="" <NEW_LINE> for l in lineas: <NEW_LINE> <INDENT> texto+=l <NEW_LINE> <DEDENT> return texto | Leer todo un fichero
Argumentos:
nombre_fichero -- nombre del fichero a leer
Devuelve:
cadena -- una cadena con todo el fichero completo | 625941c05e10d32532c5ee80 |
def save(self): <NEW_LINE> <INDENT> for table in self.tables.values(): <NEW_LINE> <INDENT> table.save() <NEW_LINE> <DEDENT> if self.dbName is not None: <NEW_LINE> <INDENT> dbDir = "./" + self.dbName + "/" <NEW_LINE> tableFiles = [tbl.fileName for tbl in self.tables.values()] <NEW_LINE> diskFiles = os.listdir(dbDir) <NEW_LINE> for filename in diskFiles: <NEW_LINE> <INDENT> if filename not in tableFiles: <NEW_LINE> <INDENT> os.remove(dbDir + filename) | Purpose: Saves the Database and all member tables currently in
memory to the disk.
Parameters: None
Returns: None | 625941c0e5267d203edcdbf8 |
def load_words(): <NEW_LINE> <INDENT> pass | Load dictionary into a list and return list | 625941c0046cf37aa974cca2 |
def union(x, y): <NEW_LINE> <INDENT> link(find_set(x), find_set(y)) | Join two elements in fact their corresponding set
:param x: a node
:param y: a second node | 625941c07b25080760e393b2 |
def run(self): <NEW_LINE> <INDENT> list_after_schedule = self.apply_sheduling() <NEW_LINE> for agent in list_after_schedule: <NEW_LINE> <INDENT> agent.decide() <NEW_LINE> <DEDENT> self.set_changed() <NEW_LINE> self.notify_observers(self.environnement) <NEW_LINE> if self.prop.trace(): <NEW_LINE> <INDENT> self.print_tick() <NEW_LINE> <DEDENT> self.tick += 1 | effectue le tour de parole
:return: | 625941c0283ffb24f3c5585c |
def create_release(self, package, release_file): <NEW_LINE> <INDENT> package_path = os.path.join( self.packages_root, package.name ) <NEW_LINE> if not os.path.isdir(package_path): <NEW_LINE> <INDENT> if not self.create_package(package): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> release_path = os.path.join(package_path, release_file.filename) <NEW_LINE> release_file.save(release_path) <NEW_LINE> return True | Copy release file inside package directory
If package directory does not exists, it will create it before | 625941c08e7ae83300e4af24 |
def test_filter_collection(self, stream1, stream2): <NEW_LINE> <INDENT> streams = StreamSet([stream1, stream2]) <NEW_LINE> other = streams.filter(collection="fruits") <NEW_LINE> assert other._streams == [] <NEW_LINE> other = streams.filter(collection="fruits/apple") <NEW_LINE> assert other._streams == [stream1] <NEW_LINE> other = streams.filter(collection="FRUITS/APPLE") <NEW_LINE> assert other._streams == [stream1] <NEW_LINE> other = streams.filter(collection="fruits*") <NEW_LINE> assert other._streams == [] <NEW_LINE> other = streams.filter(collection=re.compile("fruits")) <NEW_LINE> assert other._streams == [stream1, stream2] <NEW_LINE> other = streams.filter(collection=re.compile("fruits.*")) <NEW_LINE> assert other._streams == [stream1, stream2] <NEW_LINE> type(stream1).collection = PropertyMock(return_value="foo/region-north") <NEW_LINE> other = streams.filter(collection=re.compile("region-")) <NEW_LINE> assert other._streams == [stream1] <NEW_LINE> other = streams.filter(collection=re.compile("^region-")) <NEW_LINE> assert other._streams == [] <NEW_LINE> other = streams.filter(collection=re.compile("foo/")) <NEW_LINE> assert other._streams == [stream1] <NEW_LINE> other = streams.filter(collection=re.compile("foo/z")) <NEW_LINE> assert other._streams == [] <NEW_LINE> type(stream1).collection = PropertyMock(return_value="region.north/foo") <NEW_LINE> other = streams.filter(collection=re.compile(r"region\.")) <NEW_LINE> assert other._streams == [stream1] | Assert filter collection works as intended | 625941c0f8510a7c17cf9654 |
def sublattice(self, *args, **kwds): <NEW_LINE> <INDENT> if "_sublattice" not in self.__dict__: <NEW_LINE> <INDENT> self._split_ambient_lattice() <NEW_LINE> <DEDENT> if args or kwds: <NEW_LINE> <INDENT> return self._sublattice(*args, **kwds) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._sublattice | The sublattice spanned by the cone.
Let `\sigma` be the given cone and `N=` ``self.lattice()`` the
ambient lattice. Then, in the notation of [Fulton]_, this
method returns the sublattice
.. MATH::
N_\sigma \stackrel{\text{def}}{=} \mathop{span}( N\cap \sigma )
INPUT:
- either nothing or something that can be turned into an element of
this lattice.
OUTPUT:
- if no arguments were given, a :class:`toric sublattice
<sage.geometry.toric_lattice.ToricLattice_sublattice_with_basis>`,
otherwise the corresponding element of it.
.. NOTE::
* The sublattice spanned by the cone is the saturation of
the sublattice generated by the rays of the cone.
* See
:meth:`sage.geometry.cone.IntegralRayCollection.ray_basis`
if you only need a `\QQ`-basis.
* The returned lattice points are usually not rays of the
cone. In fact, for a non-smooth cone the rays do not
generate the sublattice `N_\sigma`, but only a finite
index sublattice.
EXAMPLES::
sage: cone = Cone([(1, 1, 1), (1, -1, 1), (-1, -1, 1), (-1, 1, 1)])
sage: cone.rays().basis()
N( 1, 1, 1),
N( 1, -1, 1),
N(-1, -1, 1)
in 3-d lattice N
sage: cone.rays().basis().matrix().det()
-4
sage: cone.sublattice()
Sublattice <N(-1, -1, 1), N(1, 0, 0), N(1, 1, 0)>
sage: matrix( cone.sublattice().gens() ).det()
1
Another example::
sage: c = Cone([(1,2,3), (4,-5,1)])
sage: c
2-d cone in 3-d lattice N
sage: c.rays()
N(1, 2, 3),
N(4, -5, 1)
in 3-d lattice N
sage: c.sublattice()
Sublattice <N(1, 2, 3), N(4, -5, 1)>
sage: c.sublattice(5, -3, 4)
N(5, -3, 4)
sage: c.sublattice(1, 0, 0)
Traceback (most recent call last):
...
TypeError: element (= [1, 0, 0]) is not in free module | 625941c0be8e80087fb20b9f |
def search_ALL(self, query, id, msg): <NEW_LINE> <INDENT> return True | Returns C{True} if the message matches the ALL search key (always).
@type query: A L{list} of L{str}
@param query: A list representing the parsed query string.
@type id: L{int}
@param id: The sequence number of the message being checked.
@type msg: Provider of L{imap4.IMessage} | 625941c0462c4b4f79d1d629 |
@login_required() <NEW_LINE> def proposal(request): <NEW_LINE> <INDENT> context = { } <NEW_LINE> return render(request, 'pawneerangers_trenchcalculator/proposal.html', context) | Controller for the app home page. | 625941c0507cdc57c6306c2e |
def test_get_templates_dict(self): <NEW_LINE> <INDENT> self.assertDictContainsSubset( {'network.test_network_name.forward_mode': 'None'}, self.network_conf.get_templates_dict()) | ConfigurationNetwork.get_templates_dict() should return a dict
with all parameters of the network | 625941c0a4f1c619b28aff97 |
def evento_edit(request, id): <NEW_LINE> <INDENT> pass | modulo = get_object_or_404(Modulo, pk=id)
form = Modulo_Form(instance=modulo)
if request.method == 'POST':
form = Modulo_Form(request.POST, instance=modulo)
if form.is_valid():
form.save()
return HttpResponseRedirect('/modulo')
return render(request, 'modulo/modulo_edit.html', {'form': form, 'id': id}) | 625941c0091ae35668666ebb |
def _cache_tab_headers(self, tab): <NEW_LINE> <INDENT> tab_data = self._get_tab_data(tab + "!2:2") <NEW_LINE> if 'values' not in tab_data: <NEW_LINE> <INDENT> raise Exception('No header values found in tab "' + tab + '"') <NEW_LINE> <DEDENT> header_values = tab_data['values'][0] <NEW_LINE> header_map = {} <NEW_LINE> for index in range(len(header_values)): <NEW_LINE> <INDENT> header_map[header_values[index]] = index <NEW_LINE> <DEDENT> inverse_header_map = {} <NEW_LINE> for key in header_map.keys(): <NEW_LINE> <INDENT> inverse_header_map[header_map[key]] = key <NEW_LINE> <DEDENT> self._tab_headers[tab] = header_map <NEW_LINE> self._inverse_tab_headers[tab] = inverse_header_map | Cache the headers (and locations) in a tab
returns a map that maps headers to column indexes | 625941c0a219f33f346288c5 |
def update(self, instance, validated_data): <NEW_LINE> <INDENT> print(validated_data,'==========') <NEW_LINE> instance.selected_row = validated_data.get('selectedRow', instance.selected_row) <NEW_LINE> instance.can_write = validated_data.get('canWrite', instance.can_write) <NEW_LINE> instance.can_write_on_parent = validated_data.get('canWriteOnParent', instance.can_write_on_parent) <NEW_LINE> instance.save() <NEW_LINE> return instance | Update and return an existing `Schedule` instance, given the validated data. | 625941c0f548e778e58cd4d5 |
def set_name(self, PersonName): <NEW_LINE> <INDENT> self.name = PersonName | takes a string PersonName and sets the person's name | 625941c07d847024c06be212 |
def append_target(self, item): <NEW_LINE> <INDENT> self.targets.add_item( JSONEntry( item.uuid, comment=item.target_name, suffix=',')) | Append a PBXNative target | 625941c024f1403a92600ac1 |
def database_query(operation): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = psycopg2.connect(conn_string) <NEW_LINE> cursor = conn.cursor() <NEW_LINE> cursor.execute(operation) <NEW_LINE> query = cursor.fetchall() <NEW_LINE> logging.info('queried information') <NEW_LINE> return query <NEW_LINE> <DEDENT> except (Exception, psycopg2.Error) as error: <NEW_LINE> <INDENT> logging.error("Error while fetching data from PostgreSQL", error) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if (conn): <NEW_LINE> <INDENT> cursor.close() <NEW_LINE> conn.close() <NEW_LINE> logging.info("PostgreSQL connection is closed") | Performs operations depending on input passed in discord server
Parameters:
operation (str): The PostgreSQL operation
Returns:
tuple: a tuples full of lists that contain rows of the table | 625941c05f7d997b871749ee |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> ProcessingNode.__init__(self, name = 'median filter', mode = 'editable', category = 'time domain filter', tags = ['filter', 'median', 'time domain', 'de-spike', 'spike'], **kwargs ) <NEW_LINE> item = IntegerSpinPrefItem(name = 'samples', value = 3, limit = (3, 100) ) <NEW_LINE> self.pref_manager.add_item(item = item) | The constructor
| 625941c03539df3088e2e2a4 |
def is_available(self, relation: Relation = None): <NEW_LINE> <INDENT> if relation is None: <NEW_LINE> <INDENT> return any(self.is_available(relation) for relation in self.relations) <NEW_LINE> <DEDENT> with self.remote_context(relation): <NEW_LINE> <INDENT> return super().is_available(relation) | Same as EndpointWrapper.is_available, but with the remote context. | 625941c09f2886367277a7e8 |
def DeviceHandler(*args, **kwargs): <NEW_LINE> <INDENT> if kwargs['ios_type'] not in platforms: <NEW_LINE> <INDENT> raise ValueError('Unsupported ios_type: currently supported platforms are: {}'.format(platforms_str)) <NEW_LINE> <DEDENT> DeviceClass = device_dispatcher(kwargs['ios_type']) <NEW_LINE> return DeviceClass(*args, **kwargs) | Select the proper class and creates object based on ios_type. | 625941c007d97122c41787df |
def test_findDisplaynamesByKeyword_keyword_not_found(self): <NEW_LINE> <INDENT> keyword = "noun" <NEW_LINE> future = go(self.client.get, f'/repository/findDisplaynamesByKeyword/{keyword}', headers=dict(Authorization='Bearer valid', LoginType='sso') ) <NEW_LINE> request = self.server.receives() <NEW_LINE> request.ok(cursor={'id': None, 'firstBatch': []}) <NEW_LINE> http_response = future() <NEW_LINE> data = json.loads(http_response.data.decode()) <NEW_LINE> self.assertEqual(http_response.status_code, 404) <NEW_LINE> self.assertEqual(f'There is no keyword({keyword}).', data['message']) <NEW_LINE> self.assertIn('Fail', data['status']) | Ensure error is thrown if the keyword is not exist. | 625941c08a43f66fc4b53fc0 |
def patch(self, request: Request, meetup_id: str, question_id: str) -> Response: <NEW_LINE> <INDENT> vote_value = 1 <NEW_LINE> return give_vote( request=request, meetup_id=meetup_id, question_id=question_id, vote_value=vote_value ) | upvote view function | 625941c015fb5d323cde0a65 |
def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.sub_minion_process.terminate() <NEW_LINE> self.minion_process.terminate() <NEW_LINE> self.master_process.terminate() <NEW_LINE> try: <NEW_LINE> <INDENT> self.syndic_process.terminate() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.smaster_process.terminate() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.log_server.server_close() <NEW_LINE> self.log_server.shutdown() <NEW_LINE> self._exit_mockbin() <NEW_LINE> self._exit_ssh() <NEW_LINE> self.log_server_process.join() <NEW_LINE> salt_log_setup.shutdown_multiprocessing_logging() <NEW_LINE> salt_log_setup.shutdown_multiprocessing_logging_listener(daemonizing=True) | Kill the minion and master processes | 625941c02ae34c7f2600d08b |
def sizeHint(self): <NEW_LINE> <INDENT> return self.minimumSize() | In most cases the size is set externally, but we prefer at least the minimum size | 625941c0dc8b845886cb548d |
def _get_firewall_rules(self): <NEW_LINE> <INDENT> return firewall_rule_dao.FirewallRuleDao(self.global_configs). get_firewall_rules(self.snapshot_timestamp) | Retrieves firewall rules.
Returns:
list: FirewallRule | 625941c04f6381625f114996 |
def get_portgroup(self, portgroup_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> LOG.info('Getting port group %s details', portgroup_name) <NEW_LINE> return self.provisioning.get_port_group(portgroup_name) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> LOG.error('Got error %s while getting details of port group %s', str(e), portgroup_name) <NEW_LINE> return None | Get details of a given port group | 625941c082261d6c526ab3f5 |
def slh_associate(a_features, b_features, max_sigma=5): <NEW_LINE> <INDENT> proximity = _weighted_proximity(a_features, b_features) <NEW_LINE> association_matrix = _proximity_to_association(proximity) <NEW_LINE> associations = [] <NEW_LINE> if association_matrix.shape[0] == 0: <NEW_LINE> <INDENT> return np.zeros((0, 2)) <NEW_LINE> <DEDENT> col_max_idxs = np.argmax(association_matrix, axis=0) <NEW_LINE> prox_threshold = np.exp(-0.5*max_sigma*max_sigma) <NEW_LINE> for row_idx, row in enumerate(association_matrix): <NEW_LINE> <INDENT> if row.shape[0] == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> col_idx = np.argmax(row) <NEW_LINE> if col_max_idxs[col_idx] == row_idx: <NEW_LINE> <INDENT> prox = proximity[row_idx, col_idx] <NEW_LINE> if prox > prox_threshold: <NEW_LINE> <INDENT> associations.append((row_idx, col_idx)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len(associations) == 0: <NEW_LINE> <INDENT> return np.zeros((0, 2)) <NEW_LINE> <DEDENT> return np.vstack(associations) | An implementation of the Scott and Longuet-Higgins algorithm for feature
association.
This function takes two lists of features. Each feature is a
:py:class:`MultivariateNormal` instance representing a feature
location and its associated uncertainty.
Args:
a_features (list of MultivariateNormal)
b_features (list of MultivariateNormal)
max_sigma (float or int): maximum number of standard deviations two
features can be separated and still considered "associated".
Returns:
(array): A Nx2 array of feature associations. Column 0 is the index into
the a_features list, column 1 is the index into the b_features list. | 625941c0ac7a0e7691ed402a |
def beacon(config): <NEW_LINE> <INDENT> log.debug('Executing napalm beacon with config:') <NEW_LINE> log.debug(config) <NEW_LINE> ret = [] <NEW_LINE> for mod in config: <NEW_LINE> <INDENT> if not mod: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> event = {} <NEW_LINE> fun = mod.keys()[0] <NEW_LINE> fun_cfg = mod.values()[0] <NEW_LINE> args = fun_cfg.pop('_args', []) <NEW_LINE> kwargs = fun_cfg.pop('_kwargs', {}) <NEW_LINE> log.debug('Executing {fun} with {args} and {kwargs}'.format( fun=fun, args=args, kwargs=kwargs )) <NEW_LINE> fun_ret = __salt__[fun](*args, **kwargs) <NEW_LINE> log.debug('Got the reply from the minion:') <NEW_LINE> log.debug(fun_ret) <NEW_LINE> if not fun_ret.get('result', False): <NEW_LINE> <INDENT> log.error('Error whilst executing {}'.format(fun)) <NEW_LINE> log.error(fun_ret) <NEW_LINE> continue <NEW_LINE> <DEDENT> fun_ret_out = fun_ret['out'] <NEW_LINE> log.debug('Comparing to:') <NEW_LINE> log.debug(fun_cfg) <NEW_LINE> try: <NEW_LINE> <INDENT> fun_cmp_result = _compare(fun_cfg, fun_ret_out) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> log.error(err, exc_info=True) <NEW_LINE> continue <NEW_LINE> <DEDENT> log.debug('Result of comparison: {res}'.format(res=fun_cmp_result)) <NEW_LINE> if fun_cmp_result: <NEW_LINE> <INDENT> log.info('Matched {fun} with {cfg}'.format( fun=fun, cfg=fun_cfg )) <NEW_LINE> event['tag'] = '{os}/{fun}'.format(os=__grains__['os'], fun=fun) <NEW_LINE> event['fun'] = fun <NEW_LINE> event['args'] = args <NEW_LINE> event['kwargs'] = kwargs <NEW_LINE> event['data'] = fun_ret <NEW_LINE> event['match'] = fun_cfg <NEW_LINE> log.debug('Queueing event:') <NEW_LINE> log.debug(event) <NEW_LINE> ret.append(event) <NEW_LINE> <DEDENT> <DEDENT> log.debug('NAPALM beacon generated the events:') <NEW_LINE> log.debug(ret) <NEW_LINE> return ret | Watch napalm function and fire events. | 625941c076d4e153a657ea89 |
def get_dict_by_index(self, index): <NEW_LINE> <INDENT> word, offset, size = self._dict_index.get_index_by_num(index) <NEW_LINE> self._offset = offset <NEW_LINE> sametypesequence = self._dict_ifo.get_ifo("sametypesequence") <NEW_LINE> if sametypesequence: <NEW_LINE> <INDENT> return self._get_entry_sametypesequence(size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._get_entry(size) | Get the word's dictionary data by it's index infomation.
Arguments:
- `index`: index of a word entrt in .idx file.'
Return:
The specified word's dictionary data, in form of dict as below:
{type_identifier: infomation, ...}
in which type_identifier can be any character in "mlgtxykwhnrWP". | 625941c0435de62698dfdba5 |
def common_grid(wavelist): <NEW_LINE> <INDENT> wavelist = sorted(wavelist, key = lambda w: w[0]) <NEW_LINE> we = wavelist[0] <NEW_LINE> for wei in wavelist[1:]: <NEW_LINE> <INDENT> if we[-1] < wei[0]: <NEW_LINE> <INDENT> we = np.append(we,wei) <NEW_LINE> continue <NEW_LINE> <DEDENT> if we[0] > wei[-1]: <NEW_LINE> <INDENT> we = np.append(wei,we) <NEW_LINE> continue <NEW_LINE> <DEDENT> i0,i1 = np.searchsorted(we, wei[[0,-1]]) <NEW_LINE> j0,j1 = np.searchsorted(wei, we[[0,-1]]) <NEW_LINE> Nwe, Nwei = i1-i0, j1-j0 <NEW_LINE> if Nwe < Nwei: <NEW_LINE> <INDENT> wei_pre, _, wei_app = np.split(wei, [j0,j1]) <NEW_LINE> we = np.hstack([wei_pre[:-1], we, wei_app[1:]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> we_pre, _, we_app = np.split(we, [i0,i1]) <NEW_LINE> we = np.hstack([we_pre[:-1], wei, we_app[1:]]) <NEW_LINE> <DEDENT> <DEDENT> return we | Generates a common wavelength grid from any number of provided grids
by using the lowest resolution grid wherever there is overlap.
This is not a great method. Oversampling is still possible. It is fast
though. | 625941c0097d151d1a222db5 |
@pytest.fixture <NEW_LINE> def mock_venv(): <NEW_LINE> <INDENT> with patch('homeassistant.util.package.running_under_virtualenv') as mock: <NEW_LINE> <INDENT> mock.return_value = True <NEW_LINE> yield mock | Mock homeassistant.util.package.running_under_virtualenv. | 625941c08e05c05ec3eea2cc |
def setup_layout (self): <NEW_LINE> <INDENT> self.layout = gtk.VBox (spacing=12) <NEW_LINE> self.layout.show () <NEW_LINE> self.pack_start (self.layout) | Setup the layout of the container | 625941c029b78933be1e5609 |
def __init__(self, model): <NEW_LINE> <INDENT> self._model = model <NEW_LINE> self._detection_scene = DetectionScene(model.getDetectionModel()) <NEW_LINE> self._marker_scene = MarkerScene(model.getMarkerModel()) <NEW_LINE> self._setupVisualisation() | Constructor | 625941c07d43ff24873a2bf8 |
def columnHeight(self, j): <NEW_LINE> <INDENT> i = self.height + 1 <NEW_LINE> while i >= 0 and self.isCellEmpty(i, j): <NEW_LINE> <INDENT> i -= 1 <NEW_LINE> <DEDENT> return i + 1 | Renvoie la hauteur de la colonne j
Attention, cette fonction renvoie la hauteur et non l'indice de la dernière pièce | 625941c0c4546d3d9de7298b |
def get_status(self): <NEW_LINE> <INDENT> status = False <NEW_LINE> attr_path = self.__psu_presence_attr <NEW_LINE> attr_rv = self.__get_attr_value(attr_path) <NEW_LINE> if (attr_rv != 'ERR'): <NEW_LINE> <INDENT> if (attr_rv == PsuConst.PSU_TYPE_LIST[1]): <NEW_LINE> <INDENT> status = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise SyntaxError <NEW_LINE> <DEDENT> return status | Retrieves the operational status of the device
Returns:
A boolean value, True if device is operating properly, False if not | 625941c07b180e01f3dc475b |
def createGaussianKernel(self, textureRadius, softness=1.5): <NEW_LINE> <INDENT> stepRadius = min(10, int(textureRadius * self.majorAxis + 1)) <NEW_LINE> t = [] <NEW_LINE> s = 0 <NEW_LINE> z = softness / stepRadius <NEW_LINE> for i in xrange(stepRadius): <NEW_LINE> <INDENT> x = (1.0 + i) * z <NEW_LINE> y = math.exp(-x*x) <NEW_LINE> t.append(y) <NEW_LINE> s += y <NEW_LINE> <DEDENT> a = 1.0 / (1 + 2*s) <NEW_LINE> kernel = [(0, a)] <NEW_LINE> z = textureRadius / stepRadius <NEW_LINE> x = 0 <NEW_LINE> for y in t: <NEW_LINE> <INDENT> x += z <NEW_LINE> kernel.append((x, y*a)) <NEW_LINE> kernel.append((-x, y*a)) <NEW_LINE> <DEDENT> return kernel | Create a kernel sequence for a gaussian blur. The
radius is specified in texture space (0 to 1),
the number of quantization steps is determined
automatically. 'softness' determines how far out
we evaluate the gaussian distribution. | 625941c0796e427e537b051d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.