code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@weak_script <NEW_LINE> def multi_margin_loss(input, target, p=1, margin=1., weight=None, size_average=None, reduce=None, reduction='mean'): <NEW_LINE> <INDENT> if size_average is not None or reduce is not None: <NEW_LINE> <INDENT> reduction_enum = _Reduction.legacy_get_enum(size_average, reduce) <NEW_LINE> <DEDENT> el... | multi_margin_loss(input, target, p=1, margin=1, weight=None, size_average=None,
reduce=None, reduction='mean') -> Tensor
See :class:`~torch.nn.MultiMarginLoss` for details. | 625941f407f4c71912b11aad |
def getRandomCapture(self, board): <NEW_LINE> <INDENT> enemylist = self.opponent.getpieces(board) <NEW_LINE> potentialCaptures = [] <NEW_LINE> for enemy in enemylist: <NEW_LINE> <INDENT> for move in self.validmoves: <NEW_LINE> <INDENT> if enemy in move: <NEW_LINE> <INDENT> potentialCaptures.append([move[0],enemy]) <NEW... | Of possible captures, return a random one | 625941f429b78933be1e5ccc |
def get_end_time_metric(result, namespace, name): <NEW_LINE> <INDENT> distributions = result.metrics().query( MetricsFilter().with_namespace(namespace).with_name( name))['distributions'] <NEW_LINE> max_list = list(map(lambda m: m.result.max, distributions)) <NEW_LINE> return max(max_list) if len(max_list) > 0 else -1 | get the end time out of all times recorded by the specified distribution
metric
Args:
result: the PipelineResult which metrics are read from
namespace: a string representing the namespace of wanted metric
name: a string representing the name of the wanted metric
Returns:
the largest time in the metric or -1 ... | 625941f4462c4b4f79d1dcf7 |
def encode_eternal_jwt_token(self, user): <NEW_LINE> <INDENT> return self.encode_jwt_token( user, override_access_lifespan=VITAM_AETERNUM, override_refresh_lifespan=VITAM_AETERNUM, ) | This utility function encodes a jwt token that never expires
.. note:: This should be used sparingly since the token could become
a security concern if it is ever lost. If you use this
method, you should be sure that your application also
implements a blacklist so that a given token can b... | 625941f4283ffb24f3c55f22 |
def test_product_not_spotted(test_client): <NEW_LINE> <INDENT> quiz.new(test_client) <NEW_LINE> quiz.answer_correct(test_client, *([3]*3)) <NEW_LINE> resp = quiz.answer_correct(test_client, *([1]*3)) <NEW_LINE> patterns = quiz.get_patterns(test_client) <NEW_LINE> correct = patterns.index(CORRECT_PRODUCT_PATTERN) <NEW_L... | Test for when a user answers first two questions correct but
fails to spot the pattern correctly. | 625941f4656771135c3ebe9e |
def get_classpath_for_group(self, group_key): <NEW_LINE> <INDENT> if group_key not in self._group_classpaths: <NEW_LINE> <INDENT> self._group_classpaths[group_key] = OrderedSet() <NEW_LINE> <DEDENT> return list(reversed(self._group_classpaths[group_key])) | Get the classpath to use for jvm compilations of a group.
Each exclusives group requires a distinct classpath. We maintain
them here as a map from the exclusives key to a classpath. The
classpath is updated during compilations to add the results of
compiling a group to the classpaths of other groups that could depend ... | 625941f48e05c05ec3eea9a2 |
def display_temp(hass: HomeAssistant, temperature: float, unit: str, precision: float) -> float: <NEW_LINE> <INDENT> temperature_unit = unit <NEW_LINE> ha_unit = hass.config.units.temperature_unit <NEW_LINE> if temperature is None: <NEW_LINE> <INDENT> return temperature <NEW_LINE> <DEDENT> if not isinstance(temperature... | Convert temperature into preferred units for display purposes. | 625941f460cbc95b062c6b6b |
def CheckSynchronizedWithUpstream(self): <NEW_LINE> <INDENT> exit_code, _, _ = self.RunCommand('git fetch upstream') <NEW_LINE> if exit_code != 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> exit_code, output, _ = self.RunCommand( 'git log HEAD..upstream/main --oneline') <NEW_LINE> return exit_code == 0 and no... | Checks if the git repo is synchronized with upstream.
Returns:
bool: True if the git repo is synchronized with upstream. | 625941f4377c676e912727ce |
def mono(r, lam, a, b, lmax=None): <NEW_LINE> <INDENT> return _mono(lam, a, b, r, lmax) | Return the SSA for mono-disperse spheres | 625941f42c8b7c6e89b35de3 |
def _synchDoor(self): <NEW_LINE> <INDENT> if not self.__door: <NEW_LINE> <INDENT> self.__door = self.state.door <NEW_LINE> <DEDENT> elif not self.state.isDoorFromMacroServer(self.__door): <NEW_LINE> <INDENT> replay = Qt.QMessageBox.question( self.ui.preferences, "NXSelector: The New Measurement Group" "was created for ... | synchronize the current door name with macroserver
| 625941f4566aa707497f4b88 |
def by_median_home_value( self, lower: int = -1, upper: int = 2 ** 31, zipcode_type: ZipcodeTypeEnum = ZipcodeTypeEnum.Standard, sort_by: str = SimpleZipcode.median_home_value.name, ascending: bool = False, returns: int = DEFAULT_LIMIT, ): <NEW_LINE> <INDENT> return self.query( median_home_value_lower=lower, median_hom... | Search zipcode information by median home value. | 625941f4be7bc26dc91cdc1c |
def fill_motion(self): <NEW_LINE> <INDENT> while len(self.x_values) < self.num_points: <NEW_LINE> <INDENT> x_direction = choice([1, -1]) <NEW_LINE> x_distance = choice([0, 1, 2, 3, 4]) <NEW_LINE> x_movement = x_direction * x_distance <NEW_LINE> y_direction = choice([1, -1]) <NEW_LINE> y_distance = choice([0, 1, 2, 3, 4... | Calculate all points of the motion. | 625941f4bf627c535bc137f7 |
def merge_ts(dataframe): <NEW_LINE> <INDENT> max_series_name = np.argmax(dataframe.notnull().sum().to_frame()[0]) <NEW_LINE> quick_corr = dataframe.corr().sort(max_series_name, ascending=False).index.values[1:] <NEW_LINE> DF_other_series = pd.DataFrame() <NEW_LINE> for other_series_name in dataframe[quick_corr]: <NEW_L... | Merge temporally coinciding timeseries via interpolation from
bivariate linear regression.
Input: Dataframe of temporally coinciding timeseries.
-Find TS with most values. Use a reference to enhance.
-Enhance missing values in reference via linear regression from other TS.
Only use correlating (R>0.8) TS for interp... | 625941f4ab23a570cc2507b0 |
def getFileProps(file_path): <NEW_LINE> <INDENT> propNames = ('Comments', 'InternalName', 'ProductName', 'CompanyName', 'LegalCopyright', 'ProductVersion', 'FileDescription', 'LegalTrademarks', 'PrivateBuild', 'FileVersion', 'OriginalFilename', 'SpecialBuild') <NEW_LINE> props = {'FixedFileInfo': None, 'StringFileInfo'... | Read all properties of the given file return them as a dictionary. | 625941f4090684286d50f318 |
def OnDemandPointer(offsetfunc, subcon, force_build = True): <NEW_LINE> <INDENT> return OnDemand(Pointer(offsetfunc, subcon), advance_stream = False, force_build = force_build ) | An on-demand pointer.
:param offsetfunc: a function taking the context as an argument and returning
the absolute stream position
:param subcon: the subcon that will be parsed from the `offsetfunc()` stream position on demand
:param force_build: see OnDemand. by default True. | 625941f48e71fb1e9831ddce |
def set_reserved(self, reserved): <NEW_LINE> <INDENT> self.__reserved = reserved | Method that sets the reserved to reserved. | 625941f55fc7496912cc3fa5 |
def get_inter_layer_edges(self): <NEW_LINE> <INDENT> return self.inter_layer_edges | Return a list with the inter-layer edges | 625941f53eb6a72ae02ecb17 |
def get_match(self, year=None, month=None, station_slug=None): <NEW_LINE> <INDENT> match = { "$match": {} } <NEW_LINE> if year is not None and year != '': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> year_int = int(year) <NEW_LINE> match["$match"]["data.viti"] = year_int <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE... | Build and return the match object .
:param year: the sampling year.
:param month: the sampling month.
:param station_slug: the station name slug. | 625941f5be8e80087fb2125f |
def new_url(module): <NEW_LINE> <INDENT> url_base = "/axapi/v3/ipv6/neighbor/static/{ipv6-addr}+{vlan}" <NEW_LINE> f_dict = {} <NEW_LINE> f_dict["ipv6-addr"] = "" <NEW_LINE> f_dict["vlan"] = "" <NEW_LINE> return url_base.format(**f_dict) | Return the URL for creating a resource | 625941f5e5267d203edce2bd |
def to_categorical(y, nb_classes=None): <NEW_LINE> <INDENT> y = np.asarray(y, dtype='int32') <NEW_LINE> if not nb_classes: <NEW_LINE> <INDENT> nb_classes = np.max(y)+1 <NEW_LINE> <DEDENT> Y = np.zeros((len(y), nb_classes), dtype='bool') <NEW_LINE> for i in range(len(y)): <NEW_LINE> <INDENT> Y[i, y[i]] = 1 <NEW_LINE> <D... | Convert class vector (integers from 0 to nb_classes)
to binary class matrix, for use with categorical_crossentropy. | 625941f59c8ee82313fbbda0 |
def verify_data(self, data: bytes, signature: bytes) -> bool: <NEW_LINE> <INDENT> pub_key = self.__ca_cert.public_key() <NEW_LINE> return self.verify_data_with_publickey(public_key=pub_key, data=data, signature=signature) | CA 개인키로 서명한 DATA 검증
:param data: 서명 대상 원문
:param signature: 서명 데이터
:return: 검증 결과(True/False) | 625941f5ec188e330fd5adba |
def fit(self, T, y, sample_weight=None): <NEW_LINE> <INDENT> T = column_or_1d(T) <NEW_LINE> assert sample_weight is None <NEW_LINE> t0 = T[y == 0] <NEW_LINE> t1 = T[y == 1] <NEW_LINE> self.calibrator0 = KernelDensity(bandwidth=self.bandwidth) <NEW_LINE> self.calibrator1 = KernelDensity(bandwidth=self.bandwidth) <NEW_LI... | Fit using `T`, `y` as training data.
Parameters
----------
* `T` [array-like, shape=(n_samples,)]:
Training data.
* `y` [array-like, shape=(n_samples,)]:
Training target.
Returns
-------
* `self` [object]:
`self`. | 625941f5004d5f362079a956 |
def Calcula_Relativo_IPC_subitem(peso_atual, peso_anterior): <NEW_LINE> <INDENT> return peso_atual/peso_anterior | este metodo calculara a razao entre o peso atual do subitem e o peso anterior do subitem | 625941f5377c676e912727cf |
def _SendBlockRequest(self, node_id, section, offset): <NEW_LINE> <INDENT> request = pack_avionics_messages.ParamRequestMessage() <NEW_LINE> request.node_id = node_id <NEW_LINE> request.section = section <NEW_LINE> request.offset = offset <NEW_LINE> self.aio_client.Send(request, 'kMessageTypeParamRequest', 'kAioNodeOpe... | Fill out and send a ParamRequestMessage. | 625941f58e7ae83300e4b5f7 |
def config_native(native): <NEW_LINE> <INDENT> definition = native.vrf.Definition() <NEW_LINE> definition.name = "VRF1" <NEW_LINE> definition.rd = "65000:1" <NEW_LINE> definition.description = "IPv4 VRF with Route Target" <NEW_LINE> ipv4 = definition.address_family.Ipv4() <NEW_LINE> ipv4.parent = definition.address_fam... | Add config data to native object. | 625941f5cc0a2c11143dd4ba |
def nombre(jugador): <NEW_LINE> <INDENT> return jugador['nombre'] | Devuelve el nombre del jugador pasado como argumento. | 625941f521a7993f00bc8324 |
def __le__(self, other): <NEW_LINE> <INDENT> return self._radius <= other.radius | Return `True` if this circle's radius is less than or equal to
the other circle's radius. | 625941f596565a6dacc8fcf1 |
def evaluate(self, expr, g): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parsed = Expression.fromstring(expr) <NEW_LINE> return self.satisfy(parsed, g) <NEW_LINE> <DEDENT> except Undefined: <NEW_LINE> <INDENT> return 'Undefined' | Read input expressions, and provide a handler for ``satisfy``
that blocks further propagation of the ``Undefined`` error.
:param expr: An ``Expression`` of ``logic``.
:param g: Assignment | 625941f5d164cc6175783377 |
@contextmanager <NEW_LINE> def ignore_unique_violation(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> except IntegrityError as error: <NEW_LINE> <INDENT> if not is_unique_violation(error): <NEW_LINE> <INDENT> raise | Context manager for gobbling unique violations.
NOTE: If a unique violation is raised, the existing psql connection will
not accept new commands. This just silences the python-level error. If
you need emit another command after possibly ignoring a unique violation,
you should explicitly use savepoints. | 625941f58a349b6b435e879b |
def contact(request, *args, **kwargs): <NEW_LINE> <INDENT> initParam = {} <NEW_LINE> page = request.GET.get('page', 1) <NEW_LINE> apps = appModels.App.objects.filter(status=2) <NEW_LINE> initParam['apps'] = queryAppsWithPaginator(request, page=page, apps=apps) <NEW_LINE> return render_to_response('help/contact.html', i... | Query the apps info in home page. | 625941f57b180e01f3dc4e18 |
def export_font(self, file, new_filename=None, colors=1): <NEW_LINE> <INDENT> if colors not in [1, 16]: <NEW_LINE> <INDENT> raise Exception <NEW_LINE> <DEDENT> filename = os.path.basename(file) <NEW_LINE> if new_filename is None: <NEW_LINE> <INDENT> new_filename = os.path.splitext(filename)[0] + ".png" <NEW_LINE> <DEDE... | Exports the provided font's charmap rendered as a PNG | 625941f566673b3332b926b9 |
def possible_change_to_four(self) -> None: <NEW_LINE> <INDENT> if random() < 0.1: <NEW_LINE> <INDENT> self._number: int = 4 | Change the square to initialize wit the number 4 with a slight chance | 625941f57cff6e4e81117fae |
def __len__(self): <NEW_LINE> <INDENT> return self._num_sub_spaces | Return the number of sub functions | 625941f5236d856c2ad44e0c |
def delete_port(port_id): <NEW_LINE> <INDENT> return neutron().delete_port(port_id) | Delete the port.
Args:
port_id (str): The port ID. | 625941f5498bea3a759ba0d6 |
def get_vote_form(self, **kwargs): <NEW_LINE> <INDENT> from openslides.poll.forms import OptionForm <NEW_LINE> return OptionForm(extra=self.get_vote_objects_with_values(kwargs['formid']), **kwargs) | Returns the form for one option of the poll. | 625941f53346ee7daa2b339a |
def sieve(indices, bits, base_list = None): <NEW_LINE> <INDENT> new_indices = [] <NEW_LINE> for k in range(len(indices)): <NEW_LINE> <INDENT> starts = indices[k] <NEW_LINE> p = starts[0] <NEW_LINE> for i in range(1, 3): <NEW_LINE> <INDENT> start = starts[i] <NEW_LINE> if start >= I: <NEW_LINE> <INDENT> print('start ind... | Run over bits, sequentially adding factor base bits using information from indices | 625941f5d6c5a10208144678 |
def _send_to_hipchat(self): <NEW_LINE> <INDENT> msg = ('Weekly snippets are ready!' ' http://weekly-snippets.appspot.com/weekly') <NEW_LINE> hipchatlib.send_to_hipchat_room('Khan Academy', msg) | Sends a note to the main hipchat room. | 625941f5851cf427c661ab32 |
def _collect_nodes(limit, sender, method_name, cacheable, params=None): <NEW_LINE> <INDENT> if not limit: limit = sys.maxint <NEW_LINE> if not params: params = sender._get_params() <NEW_LINE> nodes = [] <NEW_LINE> page = 1 <NEW_LINE> end_of_pages = False <NEW_LINE> while len(nodes) < limit and not end_of_pages: <NEW_LI... | Returns a sequqnce of dom.Node objects about as close to
limit as possible | 625941f5a17c0f6771cbe677 |
def __enter__(self): <NEW_LINE> <INDENT> if not self.connect(): <NEW_LINE> <INDENT> raise ConnectionException( 'Failed to connect[{0}]'.format(self.__str__()) ) <NEW_LINE> <DEDENT> return self | Implement the client with enter block
:returns: The current instance of the client | 625941f5cad5886f8bd27600 |
def get_topics(self): <NEW_LINE> <INDENT> topics = [ topic for topic in [ self.csv_data["LCSH_Topic_1"], self.csv_data["LCSH_Topic_2"], self.csv_data["LCSH_Topic_3"], ] if topic != "" ] <NEW_LINE> return {"label": {"en": ["Topics"]}, "value": {"en": topics}} | Use values in topic fields to get topics to metadata section of a IIIF v3 metadata profile | 625941f563f4b57ef000172f |
def set_dac(self, channels=[0,1]): <NEW_LINE> <INDENT> @command(classname='Modulation') <NEW_LINE> def set_dac_buffer(self, channel, arr): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for channel in channels: <NEW_LINE> <INDENT> data = np.int16(16384 * (self.dac[channel,:])) <NEW_LINE> set_dac_buffer(self, channel, np.... | Write the BRAM corresponding on the selected channels
(dac0 or dac1) with the array stored in self.dac[channel,:].
ex: self.set_dac(channel=[0]) | 625941f576e4537e8c351ca1 |
def test_failing_fit(self): <NEW_LINE> <INDENT> n = array([0, 1, 1]) <NEW_LINE> bins = array([0, 10, 20]) <NEW_LINE> fmpv = find_mpv.FindMostProbableValueInSpectrum(n, bins) <NEW_LINE> first_guess = fmpv.find_first_guess_mpv() <NEW_LINE> with self.assertRaises(RuntimeError) as cm: <NEW_LINE> <INDENT> fmpv.fit_mpv(first... | Check for correct warnings/errors for failing fit | 625941f5009cb60464c639d5 |
@pytest.mark.parametrize( "spec, expected_name, expected_columns", [ ({"columns": ["column 1"]}, None, ["column 1"]), ({"name": "name 1", "columns": ["column 1"]}, "name 1", ["column 1"]), ({"columns": ["column 1", "column 2"]}, None, ["column 1", "column 2"]), ], ids=["single", "single name", "multiple"], ) <NEW_LINE>... | GIVEN spec, expected name and columns
WHEN _construct_unique is called
THEN a unique constraint with the expected name and columns is returned. | 625941f566656f66f7cbc7d6 |
def upload(self, trans, history_id, provider, bucket, objects, credentials, input_args=None): <NEW_LINE> <INDENT> if CloudProviderFactory is None: <NEW_LINE> <INDENT> raise Exception(NO_CLOUDBRIDGE_ERROR_MESSAGE) <NEW_LINE> <DEDENT> if input_args is None: <NEW_LINE> <INDENT> input_args = {} <NEW_LINE> <DEDENT> connecti... | Implements the logic of uploading a file from a cloud-based storage (e.g., Amazon S3)
and persisting it as a Galaxy dataset.
:type trans: galaxy.web.framework.webapp.GalaxyWebTransaction
:param trans: Galaxy web transaction
:type history_id: string
:param history_id: the (decoded) id of history to whi... | 625941f5f7d966606f6aa634 |
def test_add_key_pair(self, name=None): <NEW_LINE> <INDENT> keypair = { 'user_id': self.user_id, 'name': name or 'test-keypair', 'fingerprint': '15:b0:f8:b3:f9:48:63:71:cf:7b:5b:38:6d:44:2d:4a', 'private_key': 'private_key_value', 'public_key': 'public_key_value' } <NEW_LINE> result_key = db.key_pair_create(context.get... | Check if keypair creation work as expected. | 625941f5d4950a0f3b08c96e |
def mobilenetv3_large(pretrained_path=None,**kwargs): <NEW_LINE> <INDENT> cfgs = [ [3, 1, 16, 0, 0, 1], [3, 4, 24, 0, 0, 2], [3, 3, 24, 0, 0, 1], [5, 3, 40, 1, 0, 2], [5, 3, 40, 1, 0, 1], [5, 3, 40, 1, 0, 1], [3, 6, 80, 0, 1, 2], [3, 2.5, 80, 0, 1, 1], [3, 2.3, 80, 0, 1, 1], [3, 2.3, 80, 0, 1, 1... | Constructs a MobileNetV3-Large models | 625941f5f548e778e58cdba9 |
def batch_to_time(inputs, dilation, crop_left=0): <NEW_LINE> <INDENT> with tf.variable_scope('batch_to_time'): <NEW_LINE> <INDENT> shape = tf.shape(inputs) <NEW_LINE> batch_size = shape[0] / dilation <NEW_LINE> width = shape[1] <NEW_LINE> out_width = tf.to_int32(width * dilation) <NEW_LINE> _, _, num_channels = inputs.... | Reshape to 1d signal, and remove excess zero-padding | 625941f566673b3332b926ba |
def clear(self): <NEW_LINE> <INDENT> self.connection.execute("DELETE FROM filelist") | Delete all nodes from the database. | 625941f5d6c5a10208144679 |
def add(s): <NEW_LINE> <INDENT> simultons.add(s) | add simulton s to the simulation | 625941f55510c4643540f9fc |
def put_dataset_testcases(self, args): <NEW_LINE> <INDENT> args["testcases"] = [] <NEW_LINE> for (subtask_index, subtask) in enumerate(self.subtasks): <NEW_LINE> <INDENT> for (testcase_index, testcase) in enumerate(subtask["testcases"]): <NEW_LINE> <INDENT> input_path = testcase["input"] <NEW_LINE> output_path = testca... | Put the task's testcases in the given args. | 625941f51d351010ab856143 |
def get_qso_bundle_size(self): <NEW_LINE> <INDENT> opt_qso_bundle_size = 'qso_bundle_size' <NEW_LINE> return self.config_parser.getint(self.section_performance, opt_qso_bundle_size) | size of QSO bundle to match against all other QSOs. | 625941f51f037a2d8b946825 |
def do_all(self, args): <NEW_LINE> <INDENT> list_ar = split(args) <NEW_LINE> if len(list_ar) == 0: <NEW_LINE> <INDENT> l = [str(v) for v in storage.all().values()] <NEW_LINE> print(l) <NEW_LINE> <DEDENT> elif len(list_ar) > 0 and list_ar[0] not in self.__Models: <NEW_LINE> <INDENT> print("** class doesn't exist **") <N... | ->Use:(hbnb)all or: (hbnb)all <class name>
Method that prints all string representation of all
instances based or not on the class name. | 625941f53539df3088e2e974 |
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkElasticBodyReciprocalSplineKernelTransformD2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj | New() -> itkElasticBodyReciprocalSplineKernelTransformD2
Create a new object of the class itkElasticBodyReciprocalSplineKernelTransformD2 and set the input and the parameters if some
named or non-named arguments are passed to that method.
New() tries to assign all the non named parameters to the input of the new obje... | 625941f56fb2d068a760f6d0 |
def test_lizmap_getserversettings(client): <NEW_LINE> <INDENT> projectfile = "france_parts.qgs" <NEW_LINE> qs = "?SERVICE=LIZMAP&REQUEST=GetServerSettings&MAP=france_parts.qgs" <NEW_LINE> rv = client.get(qs, projectfile) <NEW_LINE> assert rv.status_code == 200 <NEW_LINE> assert rv.headers.get('Content-Type', '').find('... | Test getserversettings response
| 625941f5cdde0d52a9e53662 |
def write_enum(self, writers_schema, datum, encoder): <NEW_LINE> <INDENT> index_of_datum = writers_schema.symbols.index(datum) <NEW_LINE> encoder.write_int(index_of_datum) | An enum is encoded by a int, representing the zero-based position
of the symbol in the schema. | 625941f5d99f1b3c44c67bab |
def run(self): <NEW_LINE> <INDENT> self._prepare() <NEW_LINE> for commandName in self.get_sub_commands(): <NEW_LINE> <INDENT> self.run_command(commandName) <NEW_LINE> <DEDENT> from distutils import dist <NEW_LINE> distutilDistributionClass = dist.Distribution <NEW_LINE> startScripts = [(scriptName, False) for scriptNam... | Perform command actions. | 625941f526238365f5f0f49f |
def _info(message, *args): <NEW_LINE> <INDENT> sys.stdout.write(message % args + "\n") | Prints a message on the console. | 625941f5236d856c2ad44e0d |
def cluster_seq_support(seq_dict,ident_thresh=0.90): <NEW_LINE> <INDENT> matrix = matlist.blosum62 <NEW_LINE> items=seq_dict.items() <NEW_LINE> ident_matrix=np.identity(len(items)) <NEW_LINE> msa=muscle_aln([SeqRecord(v.seq,id=str(k)) for k,v in seq_dict.iteritems()]) <NEW_LINE> seq_dict={int(sr.id):sr.seq for sr in ms... | This function for a set of sequences - returns a dictionary,
where for every sequence there is a number - corresponding to the number
of similar sequences in this sequence set. | 625941f54e696a04525c9a77 |
def check_isbn_validity( self, isbn ): <NEW_LINE> <INDENT> validity = False <NEW_LINE> try: <NEW_LINE> <INDENT> self.canonical_isbn = isbnlib.get_canonical_isbn( isbn, output='isbn13' ) <NEW_LINE> validity = isbnlib.is_isbn13( self.canonical_isbn ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.warn... | Returns boolean.
Called by views.alternates() and views.filtered_alternates() | 625941f5379a373c97cfb170 |
def message_at_a_time(fileobj): <NEW_LINE> <INDENT> field_sep = '|^~\&|' <NEW_LINE> segment_id_len = len('MSH') <NEW_LINE> input = fileobj.read() <NEW_LINE> msg_start = 0 <NEW_LINE> while msg_start < len(input): <NEW_LINE> <INDENT> start_search = msg_start + len(field_sep) + segment_id_len <NEW_LINE> next_sep = input.f... | Generator to yield a complete HL/7 message at a time till exhausted
:param fileobj: open filelike obj ready to read and yield a line at a time | 625941f5eab8aa0e5d26e183 |
def _effective_gaussian_noise_multiplier( event: dp_event.DpEvent) -> Optional[float]: <NEW_LINE> <INDENT> if isinstance(event, dp_event.GaussianDpEvent): <NEW_LINE> <INDENT> return event.noise_multiplier <NEW_LINE> <DEDENT> elif isinstance(event, dp_event.ComposedDpEvent): <NEW_LINE> <INDENT> sum_sigma_inv_sq = 0 <NEW... | Determines the effective noise multiplier of nested structure of Gaussians.
A series of Gaussian queries on the same data can be reexpressed as a single
query with pre- and post- processing. For details, see section 3 of
https://arxiv.org/pdf/1812.06210.pdf.
Args:
event: A `dp_event.DpEvent`. In order for conversio... | 625941f5adb09d7d5db6cdb5 |
def _schedule_ha_routers_to_additional_agent(self, plugin, context, agent): <NEW_LINE> <INDENT> routers_agents = self.get_ha_routers_l3_agents_counts(context, plugin, agent) <NEW_LINE> scheduled = False <NEW_LINE> admin_ctx = context.elevated() <NEW_LINE> underscheduled_routers = [router for router, agents in routers_a... | Bind already scheduled routers to the agent.
Retrieve the number of agents per router and check if the router has
to be scheduled on the given agent if max_l3_agents_per_router
is not yet reached. | 625941f556b00c62f0f14c87 |
def filter(names: Iterable[AnyStr], pat: AnyStr) -> List[AnyStr]: <NEW_LINE> <INDENT> result = List[AnyStr]() <NEW_LINE> pat = os.path.normcase(pat) <NEW_LINE> match = _compile_pattern(pat, isinstance(pat, bytes)) <NEW_LINE> if os.path is posixpath: <NEW_LINE> <INDENT> for name in names: <NEW_LINE> <INDENT> if match(na... | Return the subset of the list NAMES that match PAT. | 625941f50a366e3fb873ee49 |
def apply_transpose(self, transpose_dict): <NEW_LINE> <INDENT> encrypted_message = '' <NEW_LINE> message = SubMessage.get_message_text(self) <NEW_LINE> for letter in message: <NEW_LINE> <INDENT> if letter in transpose_dict: <NEW_LINE> <INDENT> encrypted_message += transpose_dict[letter] <NEW_LINE> <DEDENT> else: <NEW_L... | transpose_dict (dict): a transpose dictionary
Returns: an encrypted version of the message text, based
on the dictionary | 625941f57047854f462a1a2b |
def __init__(self, page, cid, node_list=None, height=None, hide_list=None, show_search=None, show_pagination=None, search_placeholder=None, search_focus=None, visible_pages_limit=None, reset_row_offset_on_search_change=None, search_focus_after_search=None, search_timeout=None, infinite_scroll_debounce_delay=None, show_... | Paginated list using the PrettyListLayout based on bootstrap. Offers search bar above and pagination below
using the EPFL theming mechanism. Links given as parameters are checked against the existing routes
automatically showing or hiding them based on the users permissions.
:param node_list: List of child components.... | 625941f510dbd63aa1bd31cb |
def bestAlignedDest(self, dests): <NEW_LINE> <INDENT> my = self.brain.my <NEW_LINE> ball = self.brain.ball <NEW_LINE> bestHeading = -1. <NEW_LINE> bestDest = None <NEW_LINE> for dest in dests: <NEW_LINE> <INDENT> heading = (fabs(((ball.headingTo(dest) - my.headingTo(ball)) % 90) - 45)) <NEW_LINE> if heading > bestHeadi... | We get our relative heading to the ball based on a 0 heading to each
of the aim points. We adjust these values to put them in a range from
0 to 45 degrees, with 45 being aligned just right with the ball to
execute one of our kicks. We find out which one later, we just want
to know where to shoot. This conversion lets u... | 625941f5be7bc26dc91cdc1d |
def test_edit(self): <NEW_LINE> <INDENT> self.token_login() <NEW_LINE> cassette_name = self.cassette_name("edit") <NEW_LINE> with self.recorder.use_cassette(cassette_name): <NEW_LINE> <INDENT> repository = self.gh.repository("github3py", "github3.py") <NEW_LINE> assert repository.edit("github3py") is True | Test the ability to edit a repository. | 625941f573bcbd0ca4b2c69f |
def getstringlist(self, section, option, **kwargs): <NEW_LINE> <INDENT> value = self.get(section, option, **kwargs) <NEW_LINE> return [s.strip() for s in value.split(',') if s.strip()] | directly parses a config value into a list of strings | 625941f58c0ade5d55d3efea |
def __init__(self, name, kind, system, root_vector=None, alloc_complex=False, ncol=1): <NEW_LINE> <INDENT> super().__init__(name, kind, system, root_vector=root_vector, alloc_complex=alloc_complex, ncol=ncol) <NEW_LINE> self._dup_inds = None | Initialize all attributes.
Parameters
----------
name : str
The name of the vector: 'nonlinear', 'linear', or right-hand side name.
kind : str
The kind of vector, 'input', 'output', or 'residual'.
system : <System>
Pointer to the owning system.
root_vector : <Vector>
Pointer to the vector owned by the ... | 625941f56aa9bd52df0373d1 |
def test_no_upstream_array(): <NEW_LINE> <INDENT> mg = RasterModelGrid((30, 70)) <NEW_LINE> mg.add_ones("topographic__elevation", at="node") <NEW_LINE> mg.add_ones("drainage_area", at="node") <NEW_LINE> fd = FlowDirectorSteepest(mg) <NEW_LINE> fd.run_one_step() <NEW_LINE> with pytest.raises(FieldError): <NEW_LINE> <IND... | Test that correct error is raised when no flow__upstream_node_order. | 625941f5eab8aa0e5d26e184 |
def warn(self, msg): <NEW_LINE> <INDENT> self._logmsg(DAQLog.WARN, msg) | Log a warning | 625941f5ac7a0e7691ed46e9 |
def complete(self): <NEW_LINE> <INDENT> logging.info("Packaging: {}".format(self.path)) <NEW_LINE> ret = 0 <NEW_LINE> for i in [ self.destdir_chmod, self.destdir_filelist, self.destdir_verify_paths_correctness, self.destdir_verify_paths_correctness2, self.destdir_verify_paths_correctness3, self.destdir_verify_paths_cor... | Do all specter of pack operations on building site | 625941f5a79ad161976cc76f |
def padding_3d(sents, max_2d, max_3d): <NEW_LINE> <INDENT> padded_sents = np.zeros(shape= [len(sents), max_2d, max_3d]) <NEW_LINE> for i_s, sent in enumerate(sents): <NEW_LINE> <INDENT> padded_sent = np.zeros(shape=[max_2d, max_3d]) <NEW_LINE> for i_w, word in enumerate(sent): <NEW_LINE> <INDENT> if i_w < max_2d: <NEW_... | :param sents: given sents with shape (,,)
:param max_2d: max_word
:param max_3d: max_ch
:return: | 625941f50383005118ecfc09 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'flash.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure i... | Run administrative tasks. | 625941f5046cf37aa974d36a |
def render(self, answers): <NEW_LINE> <INDENT> chart = self.get_chart(answers) <NEW_LINE> return self.page(question=self.question, chart_url=chart.get_url()) | Render statistics as HTML code | 625941f5009cb60464c639d6 |
def sent_to_wos(self, code_title=None): <NEW_LINE> <INDENT> fltr = {'sent_wos': 'True'} <NEW_LINE> if code_title: <NEW_LINE> <INDENT> fltr.update({'code_title': code_title}) <NEW_LINE> <DEDENT> documents = [] <NEW_LINE> total = 0 <NEW_LINE> for document in self._articles_coll.find(fltr, {'code': 1}): <NEW_LINE> <INDENT... | Implements an iterable article PID list cotaining docs already sent to wos.
sent_wos = True | 625941f515fb5d323cde1143 |
def test_invalid_json_returns_400(client: FlaskClient): <NEW_LINE> <INDENT> assert client.post('/', data="asd").status_code == 400 | When a request with invalid JSON is sent, a 400 error should be returned. | 625941f51d351010ab856144 |
def load_oof(results_dir: str, model_name: str, fold: int, epoch_num: int) -> np.ndarray: <NEW_LINE> <INDENT> predictions_dir = f"{results_dir}/oof/{model_name}_fold_{fold}" <NEW_LINE> fn = f"{predictions_dir}/{epoch_num:03}.pkl" <NEW_LINE> print(f"Loading preds from {fn}") <NEW_LINE> oof = pickle.load(open(fn, "rb")) ... | Helper,
Loads oot-of-fold predictions from pickle | 625941f54428ac0f6e5bae22 |
def my_account(self): <NEW_LINE> <INDENT> c.active = 'profile' <NEW_LINE> self.__load_data() <NEW_LINE> c.perm_user = AuthUser(user_id=self.authuser.user_id) <NEW_LINE> c.ip_addr = self.ip_addr <NEW_LINE> managed_fields = auth_modules.get_managed_fields(c.user) <NEW_LINE> def_user_perms = User.get_default_user().AuthUs... | GET /_admin/my_account Displays info about my account | 625941f5d18da76e23532b08 |
def generate_image(self, out_name, tex, tmp_dir, size_name): <NEW_LINE> <INDENT> tmp_filename = '{0}/{1}'.format(tmp_dir, 'tmp.png') <NEW_LINE> fig_index = abs(hash(tmp_filename)) % 100 <NEW_LINE> self._fig = plt.figure(fig_index) <NEW_LINE> self._fig.text(0, 0, r"$%s$" % tex, fontsize=DPI[size_name]) <NEW_LINE> self._... | Generates an image with the give filename(out_name) for the
given tex string
@type out_name: string
@param out_name: string containing the filename of the
resulting image
@type tex: string
@param tex: string containing the tex used to generate the
image
@type tmp_dir: string
@param tmp_d... | 625941f5bde94217f3683414 |
def update(self, work): <NEW_LINE> <INDENT> if work > self.total_work: <NEW_LINE> <INDENT> self.total_work = work <NEW_LINE> <DEDENT> t = _time() <NEW_LINE> history_entry = (work, t) <NEW_LINE> replace = (len(self.history) > 0 and t == self.history[-1][1]) or (len(self.history) > 1 and self.history[-1][1] - ... | Updates the work completed to 'work'. | 625941f591f36d47f21acb23 |
def __init__(self, integrand, abs_tol=.05, alpha=.01, rmse_tol=None, n_init=256., n_max=1e10, replications=32., levels_min=2, levels_max=10, n_tols=10, tol_mult=100**(1/9), theta_init=0.5): <NEW_LINE> <INDENT> self.parameters = ['rmse_tol','n_init','n_max','replications','levels_min', 'levels_max','n_tols','tol_mult','... | Args:
integrand (Integrand): integrand with multi-level g method
abs_tol (float): absolute tolerance
alpha (float): uncertaintly level.
If rmse_tol not supplied, then rmse_tol = abs_tol/norm.ppf(1-alpha/2)
rmse_tol (float): root mean squared error
If supplied (not None), then absolute to... | 625941f530dc7b7665901f88 |
def get_sender(self) -> str: <NEW_LINE> <INDENT> return self.sender | returns sender address | 625941f597e22403b379d5c6 |
def build(self, input_shape): <NEW_LINE> <INDENT> self.hidden_kernel = self.add_weight(name='hidden_kernel', shape=[self.input_size, self.hidden_size], initializer='random_normal', trainable=True) <NEW_LINE> self.hidden_bias= self.add_weight(name='hidden_bias', shape=(1, self.hidden_size), initializer='random_normal', ... | :param input_shape: [batch, <=input_size]
:return: | 625941f5d8ef3951e3243b67 |
def extractTmpVarAssignExprs(self, func: obj.Func) -> None: <NEW_LINE> <INDENT> tmpExprMap = self._funcTmpExprMap <NEW_LINE> if func.instrSeq: <NEW_LINE> <INDENT> for insn in func.instrSeq: <NEW_LINE> <INDENT> if insn.instrCode == instr.ASSIGN_INSTR_IC: <NEW_LINE> <INDENT> insn: instr.AssignI = insn <NEW_LINE> lhs: exp... | Extract temporary variables and the unique expressions they hold the value of.
It caches the result in a global map. | 625941f582261d6c526abad3 |
def _get_comment_lines(self): <NEW_LINE> <INDENT> with open(self.path, 'r') as test_file: <NEW_LINE> <INDENT> return (line for line in test_file.readlines() if re.match(r'^\s*;.*$', line) is not None) | Return an iterator over comment lines, ;'s included | 625941f55e10d32532c5f54e |
def sendkeys(self, keys, key_box, byid='xpath', tsleep=0.5): <NEW_LINE> <INDENT> time.sleep(tsleep) <NEW_LINE> info = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> keybox = self.driver.find_element(byid, key_box) <NEW_LINE> keybox.clear() <NEW_LINE> keybox.sendkeys(keys) <NEW_LINE> time.sleep(tsleep) <NEW_LINE> <DEDENT> except... | send keys
keys: keywords needed to be sent
key_box: the box in which keywords put | 625941f515baa723493c45a4 |
def predict(theta, X): <NEW_LINE> <INDENT> m = X.shape[0] <NEW_LINE> p = np.zeros(m) <NEW_LINE> hypothesis = sigmoid(np.dot(X, theta)) <NEW_LINE> p = [] <NEW_LINE> for z in hypothesis: <NEW_LINE> <INDENT> if (z > 0.5): <NEW_LINE> <INDENT> p.append(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p.append(0) <NEW_LINE> ... | Predict whether the label is 0 or 1 using learned logistic regression.
Computes the predictions for X using a threshold at 0.5
(i.e., if sigmoid(theta.T*x) >= 0.5, predict 1)
Parameters
----------
theta : array_like
Parameters for logistic regression. A vecotor of shape (n+1, ).
X : array_like
The data to us... | 625941f50383005118ecfc0a |
def me(self, channel, message): <NEW_LINE> <INDENT> logger.debug('[-->] %s - /me %s', channel, message) <NEW_LINE> return self._send_message(channel, message, subtype='me_message') | Send a "/me" message over Slack to the specified channel.
Note that this must be a plaintext message (no attachments).
:param channel: The Slack channel to send the message to (eg
"general").
:type channel: ``str``
:param message: The message to send (string)
:type message: ``str`` | 625941f5283ffb24f3c55f24 |
def Dijkstra(self,Node1,Short): <NEW_LINE> <INDENT> Node1.Distance=0 <NEW_LINE> VisitedNodes=[] <NEW_LINE> UnvisitedNodes=[Node1] <NEW_LINE> while len(UnvisitedNodes)!=0: <NEW_LINE> <INDENT> currentNode=self.LowBigDistance(UnvisitedNodes,Short) <NEW_LINE> UnvisitedNodes.remove(currentNode) <NEW_LINE> for key in current... | Función que contiene el algoritmo de Dijkstra con una variante para el camino más largo
Autor: Marcelo Truque
Entrada: Nodo fuente y booleano sobre camino más corto o largo
| 625941f567a9b606de4a84df |
def load_data(path, nr_rows=None, batch_size=16, train_ratio=0.8, transform=None): <NEW_LINE> <INDENT> hands_set = HandsDataset(path, rows=nr_rows, transform=transform) <NEW_LINE> train_len = int(train_ratio * len(hands_set)) <NEW_LINE> train_set, test_set = random_split(hands_set, [train_len, len(hands_set) - train_le... | :param path:path for csv file
:param nr_rows:get nr_rows from csv file
None = get all from file
:param batch_size:size of batch for data loader
:param train_ratio:ratio to split data into train and test
:param transform:tranformation for image
:return:Loader for train_set and test_set | 625941f5f9cc0f698b140c1f |
def __contains__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Test if a statement exists whose identifier is `key`.
Return :obj:`True` if it exists, and :obj:`False` otherwise.
Parameters
- `key` (:obj:`str`)
The identifier of the statement. `key` is case-insensitive. | 625941f53317a56b8693a272 |
def countPrimes(self, n): <NEW_LINE> <INDENT> if n < 3: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if n < 4: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if n < 10: <NEW_LINE> <INDENT> return n/2 <NEW_LINE> <DEDENT> isPrime = [True] * n <NEW_LINE> i = 3 <NEW_LINE> while i * i < n: <NEW_LINE> <INDENT> if isPri... | :type n: int
:rtype: int | 625941f567a9b606de4a84e0 |
def render(self, provides_own_theme_data=False): <NEW_LINE> <INDENT> log.debug('Render called') <NEW_LINE> self._display_frames = [] <NEW_LINE> self.bg_image_bytes = None <NEW_LINE> if not provides_own_theme_data: <NEW_LINE> <INDENT> self.renderer.set_item_theme(self.theme) <NEW_LINE> self.themedata, self.main, self.fo... | The render method is what generates the frames for the screen and
obtains the display information from the renderer. At this point all
slides are built for the given display size.
``provides_own_theme_data``
This switch disables the usage of the item's theme. However, this is
disabled by default. If this is us... | 625941f54f6381625f115065 |
def pc_work_time_var(self): <NEW_LINE> <INDENT> return _blocks_swig4.packed_to_unpacked_ii_sptr_pc_work_time_var(self) | pc_work_time_var(packed_to_unpacked_ii_sptr self) -> float | 625941f55fdd1c0f98dc085f |
def test_square_sum1(): <NEW_LINE> <INDENT> from squared_sum import square_sum <NEW_LINE> assert square_sum([1, 2]) == 5 | Test that squared_sum returns sum of every squared number in list. | 625941f5377c676e912727d0 |
def get(id): <NEW_LINE> <INDENT> marketplaceModel = marketplace.get_marketplace() <NEW_LINE> product = ndb.Key('ProductModel', int( id), parent=marketplaceModel.key).get() <NEW_LINE> if product is None: <NEW_LINE> <INDENT> raise NotFoundEntityException(message='messages.product.notfound') <NEW_LINE> <DEDENT> return pro... | Get product by id.
| 625941f5cb5e8a47e48b80c9 |
def import_trusted_keys(self, signing_keys): <NEW_LINE> <INDENT> raise NotImplementedError | Imports trusted keys into the image
Implementation in specialized repository class
:param list signing_keys: list of the key files to import | 625941f5bde94217f3683415 |
def test_m2o_encode_invalid_nonstrict(self): <NEW_LINE> <INDENT> self.assertTrue(self.m2o_codec.encode(self.invalid_c_sequence).eq( IntTensor([3, 4, 1, 4, 4, 3])).all()) | Test correct handling of noisy character sequences (many-to-one encoder) | 625941f5566aa707497f4b89 |
def setupDetectors(self): <NEW_LINE> <INDENT> seq = None <NEW_LINE> actions = [] <NEW_LINE> logger.info('+++ Setting up sensitive detectors:') <NEW_LINE> for i in self.description.detectors(): <NEW_LINE> <INDENT> o = DetElement(i.second.ptr()) <NEW_LINE> sd = self.description.sensitiveDetector(str(o.name())) <NEW_LINE... | Scan the list of detectors and assign the proper sensitive actions
uthor M.Frank | 625941f5566aa707497f4b8a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.