code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def forward(self, x, pad_mask): <NEW_LINE> <INDENT> b = x.shape[0] <NEW_LINE> T = x.shape[1] <NEW_LINE> subseq_mask = utils.get_subseq_mask(x) <NEW_LINE> x = torch.transpose(x,1,2) <NEW_LINE> G_ = [] <NEW_LINE> for l in range(self._hparams['n_layers']): <NEW_LINE> <INDENT> ki = self.layers['k_conv_%d'%l](x) <NEW_LINE> ... | x: [x_1...x_T] input, shape (b, T, d)
return: G, shape (b, L, T, T) | 625941ea4e696a04525c991f |
def _check_date_time_args( year: int = None, month: int = None, day: int = None, hour: int = None): <NEW_LINE> <INDENT> if year is not None and year > datetime.now().year: <NEW_LINE> <INDENT> raise ValueError("Provided year is larger than current year") <NEW_LINE> <DEDENT> arg_constraints = [('month', month, (1, 12)), ... | Provides type and value checking for date and time arguments
This function provides argument type and value checking for the functions
`measured_pwv` and `modeled_pwv`.
Args:
year: An integer value less than or equal to the current year
month: An integer value between 1 and 12 (inclusive)
day: An integer ... | 625941eaa219f33f34628e34 |
def do_add_blank_frame(self, data): <NEW_LINE> <INDENT> if selected_run == -1: <NEW_LINE> <INDENT> print("ERROR: No run is selected!\n") <NEW_LINE> return <NEW_LINE> <DEDENT> print("Note this is automatically offset for dummy frame count and headers, it is not offset for other blank frames") <NEW_LINE> print("This Cann... | Add a blank frame at a particular offset in the current run | 625941ea23e79379d52eea2f |
def query(self, v, n): <NEW_LINE> <INDENT> v = numpy.ascontiguousarray(v, dtype=self._precision) <NEW_LINE> if self._metric == 'angular': <NEW_LINE> <INDENT> dists = -numpy.dot(self.index, v) <NEW_LINE> <DEDENT> elif self._metric == 'euclidean': <NEW_LINE> <INDENT> dists = self.lengths - 2 * numpy.dot(self.index, v) <N... | Find indices of `n` most similar vectors from the index to query vector `v`. | 625941ea82261d6c526ab978 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Crawler): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941ea711fe17d82542832 |
def _calculate_pos_trs(self, site): <NEW_LINE> <INDENT> station_info = self.data[site] <NEW_LINE> ref_epoch = Time(station_info["ref_epoch"], scale="utc", fmt="datetime") <NEW_LINE> pos = np.zeros((self.time.size, 3)) <NEW_LINE> for pv in station_info["pos_vel"].values(): <NEW_LINE> <INDENT> idx = np.logical_and(self.t... | Calculate positions for the given time epochs
The positions are calculated as simple linear offsets based on the reference epoch. If there is a post-seismic
deformations model for a station the motion due to that model is added to the linear velocity model. Makes sure
to pick out the correct time interval to use.
Arg... | 625941eaaad79263cf390f1a |
def add_link(self, parent_id, child_id): <NEW_LINE> <INDENT> url = self.__url + '/rest/parts/' + self.get_ice_number(parent_id) + '/links' <NEW_LINE> data = {'id': self.get_ice_number(child_id)} <NEW_LINE> return _read_resp(net_utils.post(url, data=json.dumps(data), headers=self.__headers)) | Adds a link between a parent and child. | 625941eaac7a0e7691ed4594 |
def _q(self, number, precision='.00001'): <NEW_LINE> <INDENT> if np.isinf(number): <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return D(D(number).quantize(D(precision))) | quantiztion of BSSEval values | 625941ea167d2b6e31219066 |
def _populate(self): <NEW_LINE> <INDENT> f = open('bastard.sql', 'r') <NEW_LINE> sql = f.read() <NEW_LINE> self.cursor.executescript(sql) <NEW_LINE> f.close() | Populates bastard.db using bastard.sql | 625941eae5267d203edce168 |
def log_error(message: str) -> None: <NEW_LINE> <INDENT> print(message) | Log error message. | 625941ea7c178a314d6ef939 |
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> None.some_method_none_does_not_know_about() <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> ex2 = ex <NEW_LINE> <DEDENT> self.assertEqual('AttributeError', ex2.__class__.__name__) <NEW... | What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later | 625941ea090684286d50f1bf |
def schedule_query(self, name: str, query_string: str) -> types.TransferConfig: <NEW_LINE> <INDENT> data_transfer_config = self._get_existing_transfer('scheduled_query', name=name) <NEW_LINE> parameters = struct_pb2.Struct() <NEW_LINE> parameters['query'] = query_string <NEW_LINE> if data_transfer_config: <NEW_LINE> <I... | Schedules query to run every day.
Args:
name: Name of the scheduled query.
query_string: The query to be run. | 625941ea45492302aab5e79a |
def centroid_stats(self, train=False, valid=False, xval=False): <NEW_LINE> <INDENT> return {model.model_id: model.centroid_stats(train, valid, xval) for model in self.models} | Get the centroid statistics for each cluster.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where
the keys are "train", "valid", and "xval".
:param bool train: If True, then return the centroid statistics for the trainin... | 625941eabaa26c4b54cb15ec |
def test1_login(self): <NEW_LINE> <INDENT> url = myunit.MyTest.base_url + "login" <NEW_LINE> payload = {"username":"nn.chen@yuneec.com","password":"1234567890a"} <NEW_LINE> payload = json.dumps(payload) <NEW_LINE> r = requests.post(url,data=payload) <NEW_LINE> self.result = r.json() <NEW_LINE> self.assertEqual(self.res... | 先登录 获取token | 625941ea377c676e91272678 |
def GetExpectedCR(s): <NEW_LINE> <INDENT> weight = s.totalMass * AC['g'] <NEW_LINE> drag = 0.5 * Density(s.x2[s.n]) * AC['S'] * GetCd(s.alpha[s.n], s.x2[s.n]) * s.V() ** 2 <NEW_LINE> CR = s.V() * (s.thrust[s.n] - drag) / weight <NEW_LINE> return CR | This is the excess power estimate for climb rate, returns in m/s | 625941ea7b25080760e39928 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ProcessorRunStatusDetailsEntity): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941ea442bda511e8be8e3 |
def __nonzero__(self): <NEW_LINE> <INDENT> return self.root.__nonzero__() | Returns false if the Heap is empty, therefore return True | 625941ea82261d6c526ab979 |
def testSetContentTypeFromFile(self): <NEW_LINE> <INDENT> if system_util.IS_WINDOWS: <NEW_LINE> <INDENT> return unittest.skip('use_magicfile features not available on Windows') <NEW_LINE> <DEDENT> surprise_html = '<html><body>And you thought I was just text!</body></html>' <NEW_LINE> temp_dir_path = self.CreateTempDir(... | Tests that content type is correctly determined for symlinks. | 625941ea1b99ca400220af85 |
def haversine(lat1, lon1, lat2, lon2): <NEW_LINE> <INDENT> lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) <NEW_LINE> dlon = lon2 - lon1 <NEW_LINE> dlat = lat2 - lat1 <NEW_LINE> a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 <NEW_LINE> c = 2 * asin(sqrt(a)) <NEW_LINE> r = 6371 <NEW_LINE> re... | Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points | 625941ea71ff763f4b549b66 |
def priority(self): <NEW_LINE> <INDENT> return self._priority | Get the priority of this rule | 625941eac432627299f0511b |
def build_collate_fn(batch_first=False, parallel=True, sort=False): <NEW_LINE> <INDENT> def collate_seq(seq): <NEW_LINE> <INDENT> lengths = [len(s) for s in seq] <NEW_LINE> batch_length = max(lengths) <NEW_LINE> shape = (batch_length, len(seq)) <NEW_LINE> seq_tensor = torch.full(shape, config.PAD, dtype=torch.int64) <N... | Factor for collate_fn functions.
:param batch_first: if True returns batches in (batch, seq) format, if not
returns in (seq, batch) format
:param parallel: if True builds batches from parallel corpus (src, tgt)
:param sort: if True sorts by src sequence length within each batch | 625941eac432627299f0511c |
def _prepare_allocation_pools(self, allocation_pools, cidr, gateway_ip): <NEW_LINE> <INDENT> if not attributes.is_attr_set(allocation_pools): <NEW_LINE> <INDENT> return self.generate_pools(cidr, gateway_ip) <NEW_LINE> <DEDENT> ip_range_pools = self.pools_to_ip_range(allocation_pools) <NEW_LINE> self._validate_allocatio... | Returns allocation pools represented as list of IPRanges | 625941eaadb09d7d5db6cc5e |
def transfer_knowledge(self, previous_agent, new_agent, previous_supervisor): <NEW_LINE> <INDENT> new_agent.H_j = self.semantic_mapping(previous_agent.H_j, new_agent.n, new_agent.m, new_agent.p) <NEW_LINE> new_agent.policy_parameters = new_agent.improve_policy() <NEW_LINE> H_vector = new_agent.H_to_H_1D() <NEW_LINE> ne... | :param SS_dimensions: The state space dimensions
:param H_source: The source kernel matrix which is to be mapped
:return: H_target, the mapped kernel matrix | 625941ea566aa707497f4a34 |
def get_mongodb_conf(): <NEW_LINE> <INDENT> return Configuration(ConsulConf.CONF_SYSTEM_FILENAME).get("mongodb") | 获取mongo数据库配置 | 625941ea6fb2d068a760f577 |
def sanity_check(self): <NEW_LINE> <INDENT> errMsg = "" <NEW_LINE> if self.ice_opts.quiver is True: <NEW_LINE> <INDENT> if self.bas_fofn is None: <NEW_LINE> <INDENT> errMsg = "A fofn of bas/bax.h5 files, e.g., input.fofn, " + "is required in order to polish consensus " + ... | Do sanity check before stat to run. | 625941eae64d504609d74d12 |
def bench(sExpr, neval=1, units = "ms", ndigits = 5): <NEW_LINE> <INDENT> times = np.ndarray(shape=(neval,), dtype = np.float64) <NEW_LINE> expr = compile(sExpr, "<string>", "eval") <NEW_LINE> for i in np.arange(neval): <NEW_LINE> <INDENT> start = tt.time() <NEW_LINE> out = eval(expr) <NEW_LINE> end = tt.time() <NEW_LI... | :param expr: string expression to be evaluated
:param neval: number of evaluations that the statistics will be calculated from
:param units: string the units of time: "ms": (milliseconds), "us": (microseconds),
"ns": nanoseconds, "s": time in seconds, "raw": raw time in seconds
:param ndigits: number of... | 625941eafb3f5b602dac3b6a |
def DoTestSpliceOperations(self, trie_factory): <NEW_LINE> <INDENT> d = dict.fromkeys((self._SHORT_KEY, self._LONG_KEY), 42) <NEW_LINE> t = trie_factory(self._TRIE_CLS, d) <NEW_LINE> self.assertEquals([42, 42], list(t[self._SHORT_KEY:])) <NEW_LINE> self.assertEquals([42], list(t[self._LONG_PREFIXES[0]:])) <NEW_LINE> t[... | Splice trie operations tests. | 625941ea5fdd1c0f98dc0707 |
def get_unaired_episodes(self, seriesid): <NEW_LINE> <INDENT> next_episodes = [] <NEW_LINE> seriesinfo = self.get_series(seriesid) <NEW_LINE> if seriesinfo and seriesinfo.get("status", "") == "Continuing": <NEW_LINE> <INDENT> highest_season = self.get_last_season_for_series(seriesid) <NEW_LINE> episodes = self.get_seri... | Returns the unaired episodes for the specified seriesid
Usage: specify the series ID: TheTvDb().get_unaired_episodes(seriesid) | 625941ea8c3a873295158893 |
def read_data(path): <NEW_LINE> <INDENT> with open(path) as csvfile: <NEW_LINE> <INDENT> reader = csv.DictReader(csvfile) <NEW_LINE> sentences = [] <NEW_LINE> labels = [] <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> score = float(row["score"]) <NEW_LINE> sentences.append((row["sentence1"], row["sentence2"])) <NEW_... | Reads csv dataset and returns in the correct format.
:param path: Path of file.
:type path: str
:rtype: tuple | 625941ea56b00c62f0f14b2f |
def get_callbacks(self): <NEW_LINE> <INDENT> callbacks = ["on_connect", "on_disconnect", "on_ready", "on_message"] <NEW_LINE> return { c: self.callbacks.get(c, self.default_callback).__name__ for c in callbacks } | get all of the current callbacks because reasons | 625941ea91f36d47f21ac9ca |
def vec2txt(self, vector, delimiter=' '): <NEW_LINE> <INDENT> text = delimiter.join(self[int(idx)] for idx in vector) <NEW_LINE> if self.tokenizer == 'bpe' and not self.opt.get('bpe_debug', False): <NEW_LINE> <INDENT> text = text.replace('@@ ', '') <NEW_LINE> if text.endswith('@@'): <NEW_LINE> <INDENT> text = text[:-2]... | Converts a vector (iterable of ints) into a string, with each token
separated by the delimiter (default ``' '``). | 625941ea99fddb7c1c9de860 |
def checkOpenBet(self, betbtc_bet_id) : <NEW_LINE> <INDENT> response = requests.get("http://www.betbtc.co/api/bet/",headers=self.header).json() <NEW_LINE> matched_sum = 0 <NEW_LINE> unmatched_sum = 0 <NEW_LINE> for line in response : <NEW_LINE> <INDENT> if betbtc_bet_id == line[0] : <NEW_LINE> <INDENT> if line[2] == '... | Check for open bet (matched and unmatched)
Args:
betbtc_bet_id : betbtc id of the bet
Returns:
status : 1 = matched
2 = unmatched
lien : additional information about the bet
| 625941ea5fcc89381b1e1b95 |
def set_etablissement(self, etablissement): <NEW_LINE> <INDENT> self.etablissement = etablissement | Set the prescription's etablissement | 625941ea0383005118ecfab3 |
def calc_lens_array(self, radius, n): <NEW_LINE> <INDENT> T_dl = self._calc_T_dl(self.dl_lens) <NEW_LINE> T_fs = self._calc_T_fs(radius) <NEW_LINE> T_fs_accum = self._dot(self._matrix_power(self._dot(T_fs, T_dl), n - 1), T_fs) <NEW_LINE> return T_fs_accum | Calculate accumulated T_fs for one cartridge with fixed radius.
:param radius: radius.
:param n: number of lenses in one cartridge.
:return T_fs_accum: accumulated T_fs. | 625941ea99fddb7c1c9de861 |
def p_CDLANGOPT_performer(p): <NEW_LINE> <INDENT> p[0] = ('performer', p[2]) | CDLANGOPT : PERFORMER TEXT | 625941eaadb09d7d5db6cc5f |
def filter_commands(self): <NEW_LINE> <INDENT> fcmds = {} <NEW_LINE> for m in dir(self): <NEW_LINE> <INDENT> if m.startswith("docmd_"): <NEW_LINE> <INDENT> key = m.replace("docmd_", "") <NEW_LINE> fcmds[key] = getattr(self, m) <NEW_LINE> <DEDENT> <DEDENT> return fcmds | Return dictionary of filter command canonical names and method objects. | 625941ea5f7d997b87174f6e |
def create(self, build_ele): <NEW_LINE> <INDENT> height = build_ele.Height.value <NEW_LINE> OD = build_ele.OD.value <NEW_LINE> thickness = build_ele.Thickness.value <NEW_LINE> radFillet = build_ele.RadFillet.value <NEW_LINE> self.create_extrude_box_steel(height, OD, thickness, radFillet) <NEW_LINE> return (self.model_e... | Create the elements
Args:
build_ele: the building element.
Returns:
tuple with created elements and handles.
=> Trả về 1 tuple chứa danh sách các elements và các handles được tạo ra | 625941ea38b623060ff0b2bf |
def on_mnu_close_activate(self, widget, data=None): <NEW_LINE> <INDENT> self.destroy() | Signal handler for closing the RmspyWindow. | 625941ea1f5feb6acb0c501b |
def agendar_tarefa(self): <NEW_LINE> <INDENT> hash_f = random.getrandbits(28) <NEW_LINE> data_agenda = self.dateEdit.text() <NEW_LINE> data_agenda = data_agenda.replace('/','-') <NEW_LINE> hora_agenda = self.timeEdit.text() <NEW_LINE> hora_agenda = hora_agenda.replace(':','_') <NEW_LINE> path_oblivion = os.path.dirname... | Creates the scheduled scan/Cria análise agendada. | 625941eaf7d966606f6aa4dc |
def decrypt(self, data): <NEW_LINE> <INDENT> aes_key, hmac_key = self.keys <NEW_LINE> sig = data[-self.SIG_SIZE:] <NEW_LINE> data = data[:-self.SIG_SIZE] <NEW_LINE> mac_bytes = hmac.new(hmac_key, data, hashlib.sha256).digest() <NEW_LINE> if len(mac_bytes) != len(sig): <NEW_LINE> <INDENT> log.debug('Failed to authentica... | verify HMAC-SHA256 signature and decrypt data with AES-CBC | 625941ea99cbb53fe67930b7 |
def set_file_id(self, tree_edition = None, env_variable = None, location_path = None, file_name = None ): <NEW_LINE> <INDENT> self.file_id = None <NEW_LINE> if self.ready: <NEW_LINE> <INDENT> if tree_edition and env_variable and file_name: <NEW_LINE> <INDENT> self.set_location_id(tree_edition = tree_edition, env... | Get file_id. | 625941eae5267d203edce169 |
def create_bin_regions(self): <NEW_LINE> <INDENT> start = 0 <NEW_LINE> regions = [] <NEW_LINE> for bound in self.bounds: <NEW_LINE> <INDENT> regions.append(self._create_bin_region(start, bound - start)) <NEW_LINE> start = bound <NEW_LINE> <DEDENT> self.regions = regions <NEW_LINE> self.update_region_map() | Call `dmstats` to create regions on the bound device that
correspond to the configured bin boundaries for this
`IOScope`.
Returns nothing on success and raises `DmStatsException` on
error. | 625941ead7e4931a7ee9e3f1 |
def emit(self, event): <NEW_LINE> <INDENT> for observer in self.__observers[event.event]: <NEW_LINE> <INDENT> logger.debug( msg="Notifying event: %s to %s" % (event.name, observer.name) ) <NEW_LINE> observer.notify(event) | Emit event notification to observer. | 625941ea55399d3f05588b8a |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941ea8da39b475bd6544c |
def __init__ (self): <NEW_LINE> <INDENT> EDPluginControl.__init__(self) <NEW_LINE> self.setXSDataInputClass(XSDataInputMXCuBE) <NEW_LINE> self.strPluginMXWaitFileName = "EDPluginMXWaitFilev1_1" <NEW_LINE> self.strPluginControlInterface = "EDPluginControlInterfacev1_2" <NEW_LINE> self.edPluginControlInterface = None <NE... | Initialisation of EDPluginControlInterfaceToMXCuBEv1_4:
- Input data type class : XSDataInputMXCuBE
- Name of default characterisation plugin : EDPluginControlCharacterisationv1_1 | 625941ea10dbd63aa1bd3074 |
def get_info(self): <NEW_LINE> <INDENT> for line in sys.stdin: <NEW_LINE> <INDENT> if(DEBUG): <NEW_LINE> <INDENT> os.system("echo \"{}\" >> /Users/$USER/.config/pianobar/test3.txt\n".format(line)) <NEW_LINE> <DEDENT> key, delimiter, value = str(line).strip().partition(u'=') <NEW_LINE> if value.isdigit(): <NEW_LINE> <IN... | The pianobar app just dumps all the info into stdin
This parses the pile of stuff in stdin into a dictionary | 625941ea3346ee7daa2b3242 |
def clean_slug(self): <NEW_LINE> <INDENT> cleaned_data = super().clean() <NEW_LINE> slug = cleaned_data['slug'] <NEW_LINE> if not slug: <NEW_LINE> <INDENT> title = cleaned_data['slug'] <NEW_LINE> slug = slugify(title)[:100] <NEW_LINE> <DEDENT> if Task.objects.filter(slug=slug).exists(): <NEW_LINE> <INDENT> raise Valida... | Обрабатывает случай, если slug не уникален. | 625941ea56ac1b37e6264698 |
def set_value(self, label, value, takeable=False): <NEW_LINE> <INDENT> warnings.warn("set_value is deprecated and will be removed " "in a future release. Please use " ".at[] or .iat[] accessors instead", FutureWarning, stacklevel=2) <NEW_LINE> return self._set_value(label, value, takeable=takeable) | Quickly set single value at passed label. If label is not contained, a
new object is created with the label placed at the end of the result
index
.. deprecated:: 0.21.0
Please use .at[] or .iat[] accessors.
Parameters
----------
label : object
Partial indexing with MultiIndex not allowed
value : object
Scala... | 625941ea63d6d428bbe449c3 |
def test_misdetected_no_headers(self, mocker): <NEW_LINE> <INDENT> no_data_stream = io.StringIO(self.NO_DATA_STRING) <NEW_LINE> mocker.patch("comma.helpers.open_stream", return_value=no_data_stream) <NEW_LINE> mocker.patch("csv.reader", return_value=self.NO_DATA_LIST) <NEW_LINE> mocker.patch("comma.extras.detect_csv_ty... | Checks whether the `comma.helpers.open_csv()` is able to detect when
headers are missing. | 625941ead7e4931a7ee9e3f2 |
def create(self, header=None): <NEW_LINE> <INDENT> self.directory.prepare() <NEW_LINE> header = self.header if header is None else header <NEW_LINE> if isinstance(header, basestring): <NEW_LINE> <INDENT> self.write(header) <NEW_LINE> <DEDENT> elif hasattr(header, "__call__"): <NEW_LINE> <INDENT> self.write(header()) <N... | create the file with all the directory tree if necessary
!! Twhis will erase file contant !!
A file header can be specified and will be writen in the file if
this one does not exists.
The fpath object can also have a header attribute taken by default
Header can also callable method which return a string.
... | 625941ea30dc7b7665901e33 |
def process(self, data, mask): <NEW_LINE> <INDENT> data.redistribute("freq") <NEW_LINE> mask.redistribute("freq") <NEW_LINE> flag = ~mask.mask[:].view(np.ndarray) <NEW_LINE> data.weight[:] *= flag.astype(np.float32) <NEW_LINE> return data | Mask outlier beamformed visibilities.
Parameters
----------
data : FormedBeam, FormedBeamHA, or RingMap
Beamformed visibilities.
mask : FormedBeamMask, FormedBeamHAMask, or RingMapMask
Container with a boolean mask where True indicates
a beamformed visibility that should be ignored.
Returns
-------
data ... | 625941ea3317a56b8693a11f |
def _retrieve(self): <NEW_LINE> <INDENT> model_manager = self.service_config.model_manager <NEW_LINE> scoped_session, data_access = model_manager.get(self.model_name) <NEW_LINE> with scoped_session as session: <NEW_LINE> <INDENT> policy_data = [] <NEW_LINE> resource_counts = {iam_type: 0 for iam_type in IAM_TYPE_RESOUR... | Retrieves the data for scanner.
Returns:
list: List of (gcp_type, forseti_data_model_resource) tuples.
dict: A dict of resource counts.
Raises:
NoDataError: If no policies are found. | 625941eabaa26c4b54cb15ed |
def get_duration(days=0, hours=0, minutes=0, seconds=0, millis=0): <NEW_LINE> <INDENT> duration = 0.0 <NEW_LINE> duration += float(days) * 24 * 60 * 60 <NEW_LINE> duration += float(hours) * 60 * 60 <NEW_LINE> duration += float(minutes) * 60 <NEW_LINE> duration += float(seconds) <NEW_LINE> duration += millis / 1000.0 <N... | Get the given duration in seconds
:param float|int days:
:param float|int hours:
:param float|int minutes:
:param float|int seconds:
:param float|int millis:
:return float: Number of seconds in the duration, incl. fractions | 625941eac4546d3d9de72f0b |
def test_packages_present(self): <NEW_LINE> <INDENT> self.assertTrue(os.path.isdir(self.actions_dir)) <NEW_LINE> self.assertTrue(os.path.isdir(self.stt_dir)) <NEW_LINE> self.assertTrue(os.path.isdir(self.tts_dir)) <NEW_LINE> self.assertTrue(os.path.isdir(self.wakeon_dir)) | Check that the actions folder exist in the root of the project | 625941eabde94217f36832bf |
def apply_force(self, force_vector): <NEW_LINE> <INDENT> self.acceleration += force_vector / self.mass | Uses F=MA to update acceleration based on force applied. | 625941ea66656f66f7cbc67f |
def _get_jpg_dimensions( fin ): <NEW_LINE> <INDENT> M_SOF0 = b'\xC0' <NEW_LINE> M_SOF1 = b'\xC1' <NEW_LINE> M_SOF2 = b'\xC2' <NEW_LINE> M_SOF3 = b'\xC3' <NEW_LINE> M_SOF5 = b'\xC5' <NEW_LINE> M_SOF6 = b'\xC6' <NEW_LINE> M_SOF7 = b'\xC7' <NEW_LINE> M_SOF9 = b'\xC9' <NEW_LINE> M_SOF10 = b'\xCA' <NEW_LINE... | converted from: http://dev.w3.org/cvsweb/Amaya/libjpeg/rdjpgcom.c?rev=1.2 | 625941ea4c3428357757c7f8 |
def map_f(f, mapping, n_new): <NEW_LINE> <INDENT> mapping_new = -np.ones([n_new], dtype=int) <NEW_LINE> for j in range(n_new): <NEW_LINE> <INDENT> if j in mapping: <NEW_LINE> <INDENT> mapping_new[j] = np.argwhere(mapping == j) <NEW_LINE> <DEDENT> <DEDENT> f_mapped = _map_f(f, mapping_new, n_new) <NEW_LINE> return f_map... | Obtain suitable mapping for function _map_f and call it. | 625941ea6fb2d068a760f578 |
def plot(self, axs=None, vmin=None, vmax=None, ylim=None): <NEW_LINE> <INDENT> check_is_fitted(self, 'time_average_') <NEW_LINE> if axs is None: <NEW_LINE> <INDENT> fig, axs = plt.subplots(2, 1, sharex=True, figsize=(8, 8)) <NEW_LINE> axs = axs.ravel() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fig = axs[0].figure <... | Returns
-------
fig : matplotlib.figure.Figure
Figure instance containing the plot. | 625941ea091ae35668667428 |
def _setReviewStatus(self, report_id, status, message, session): <NEW_LINE> <INDENT> self.__require_permission([permissions.PRODUCT_ACCESS, permissions.PRODUCT_STORE]) <NEW_LINE> report = session.query(Report).get(report_id) <NEW_LINE> if report: <NEW_LINE> <INDENT> review_status = session.query(ReviewStatus).get(repor... | This function sets the review status of the given report. This is the
implementation of changeReviewStatus(), but it is also extended with
a session parameter which represents a database transaction. This is
needed because during storage a specific session object has to be used. | 625941ea92d797404e30465f |
def __call__(self, predicted, target): <NEW_LINE> <INDENT> return np.mean( predicted != target ) | Both 'predicted' and 'target' can be either scalars or sequences,
but have to be of the same length. | 625941ea099cdd3c635f112b |
def test_create_index(self): <NEW_LINE> <INDENT> url = reverse('admin:create_index') <NEW_LINE> self.client.login(username='test_admin', password='testadminpassword') <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 200) | 일반적인 URL을 이용한 AdminManager 테스트. | 625941ea796e427e537b0a9d |
def webpush(subscription_info, data=None, vapid_private_key=None, vapid_claims=None, content_encoding="aesgcm", curl=False, timeout=None): <NEW_LINE> <INDENT> vapid_headers = None <NEW_LINE> if vapid_claims: <NEW_LINE> <INDENT> if not vapid_claims.get('aud'): <NEW_LINE> <INDENT> url = urlparse(subscription_info.get('en... | One call solution to endcode and send `data` to the endpoint
contained in `subscription_info` using optional VAPID auth headers.
in example:
.. code-block:: python
from pywebpush import python
webpush(
subscription_info={
"endpoint": "https://push.example.com/v1/abcd",
... | 625941eaa8370b7717052d70 |
def __del__(self): <NEW_LINE> <INDENT> self._done = True <NEW_LINE> if getattr(self, "_f_objs"): <NEW_LINE> <INDENT> for file_obj in self._f_objs: <NEW_LINE> <INDENT> file_obj.close() <NEW_LINE> <DEDENT> self._f_objs = None <NEW_LINE> <DEDENT> if getattr(self, "_rthread"): <NEW_LINE> <INDENT> self._rthread.join() <NEW_... | The class destructor which closes opened files. | 625941ea66656f66f7cbc680 |
def check_admin(): <NEW_LINE> <INDENT> if not current_user.is_admin: <NEW_LINE> <INDENT> abort(403) | Prevent non_admins from accessing the page | 625941ea596a897236089f8d |
def interp_locked (self, *args, **kwargs): <NEW_LINE> <INDENT> return self._interp_locked(self.interp, *args, **kwargs) | Generate a :meth:`interp` wrapper that allows only one running
interpolation.
With each successive call, the current interpolation is aborted and a new one
started.
The wrapper is partially applied using the positional and keyword arguments
passed to this function. Typical usage is as follows::
# create the wra... | 625941ea3eb6a72ae02ec9bd |
def clean_lines(self, hdu_list): <NEW_LINE> <INDENT> if not isinstance(hdu_list, _pyfits.HDUList): <NEW_LINE> <INDENT> raise TypeError('Please, use a HDUList as input') <NEW_LINE> <DEDENT> if len(hdu_list) != 5: <NEW_LINE> <INDENT> raise ValueError( "HDUList is expected to have 1 + 4 elements. Found {}".format( len(hdu... | Clean the known bad lines that exists in most of SAMI's, SOI's or
SIFS's data. This method is meant to be overwritten via inheritance.
Args:
hdu_list (astropy.io.fits.HDUList)
See also:
Reducer.clean_column
Reducer.clean_line
Reducer.clean_lines | 625941ea16aa5153ce36294b |
def get_change_event(self, timeout=0): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> port_dict = {} <NEW_LINE> ret_dict = {"sfp": port_dict} <NEW_LINE> port = self.PORT_START <NEW_LINE> forever = False <NEW_LINE> if timeout == 0: <NEW_LINE> <INDENT> forever = True <NEW_LINE> <DEDENT> elif timeout > 0: <NEW_LI... | Returns a nested dictionary containing all devices which have
experienced a change at chassis level
Args:
timeout: Timeout in milliseconds (optional). If timeout == 0,
this method will block until a change is detected.
Returns:
(bool, dict):
- True if call successful, False if not;
- A... | 625941eaa219f33f34628e35 |
def countrySearch(name): <NEW_LINE> <INDENT> max = 0 <NEW_LINE> most_likely = "" <NEW_LINE> if is_tag(name): <NEW_LINE> <INDENT> return trigger_search(name) <NEW_LINE> <DEDENT> for country in countryTagLib: <NEW_LINE> <INDENT> f = fuzz.ratio(country, name.lower()) <NEW_LINE> if f > max: <NEW_LINE> <INDENT> max = f <NEW... | find the closest match to the name is looking for. | 625941ea2eb69b55b151cd89 |
def wait_for_image_resp_code(self, image_id, code): <NEW_LINE> <INDENT> resp, body = self.get("images/%s" % str(image_id)) <NEW_LINE> start = int(time.time()) <NEW_LINE> while resp.status != code: <NEW_LINE> <INDENT> time.sleep(self.build_interval) <NEW_LINE> resp, body = self.get("images/%s" % str(image_id)) <NEW_LINE... | Waits until the HTTP response code for the request matches the
expected value | 625941ea8e05c05ec3eea84c |
def can_create_objectives(self): <NEW_LINE> <INDENT> return | Tests if this user can create ``Objectives``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known creating an Objective
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer create
operations to an unauthoriz... | 625941eabf627c535bc136a2 |
def train(self, dataset): <NEW_LINE> <INDENT> if self.accuracy == 0.: <NEW_LINE> <INDENT> self.accuracy = train_and_score(self.network, dataset) | Train the network and record the accuracy.
Args:
dataset (str): Name of dataset to use. | 625941eaf7d966606f6aa4dd |
def __init__(self, data_source=None, drug_group=None, input_type=None, query_type=None, data=None, num_predictions=None, browser_type=None, job_id=None, filename=None): <NEW_LINE> <INDENT> self._chemData = None <NEW_LINE> self._filterDict = None <NEW_LINE> self.data_source = data_source <NEW_LINE> self.drug_group = dru... | Instantiate a QuartataChemicalRecord object instance.
Inputs are the same as QuartataWebBrowser. | 625941eaec188e330fd5ac68 |
def queryset(self, request): <NEW_LINE> <INDENT> return super(SampleAdmin,self).queryset(request) | Revert modification made by SampleAdmin | 625941eae8904600ed9f2408 |
def check_update_domain_contacts(self, contact_set, epp, domain, user): <NEW_LINE> <INDENT> current_contacts = domain.contacts.filter( active=True ) <NEW_LINE> self.check_add_contacts(contact_set, current_contacts, epp, user) <NEW_LINE> self.check_remove_contacts(contact_set, current_contacts, epp, user) | Compare submitted contacts with current set attached to domain.
:contact_set: list of dict objects with new contact handlers
:epp: dict EPP request structure
:domain: RegisteredDomain object
:user: HTTP request user | 625941eab5575c28eb68e4d8 |
def fillna(train: pd.DataFrame, test: pd.DataFrame, col_definition: dict, option: dict): <NEW_LINE> <INDENT> for f in col_definition['encode_col']: <NEW_LINE> <INDENT> if option['how'] == 'median': <NEW_LINE> <INDENT> train[f].fillna(train[f].median(), inplace=True) <NEW_LINE> test[f].fillna(train[f].median(), inplace=... | col_definition: encode_col
option: how={'median', 'mean'} | 625941ea009cb60464c63880 |
def getMappingMetaTags(self): <NEW_LINE> <INDENT> metadata_name = SortedDict() <NEW_LINE> if self.gseo: <NEW_LINE> <INDENT> for mt in self.gseo.metatags_order: <NEW_LINE> <INDENT> if METADATA_MAPS.has_key(mt): <NEW_LINE> <INDENT> metadata_name[mt] = METADATA_MAPS[mt] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return metadat... | See interface.
| 625941ea7c178a314d6ef93a |
def get(self, id_activity): <NEW_LINE> <INDENT> if isinstance(id_activity, int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif isinstance(id_activity, Activity): <NEW_LINE> <INDENT> id_activity = id_activity.id <NEW_LINE> <DEDENT> elif isinstance(id_activity, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> id_ac... | Get activity. | 625941ea7b180e01f3dc4cc6 |
@betterdebug <NEW_LINE> def do_stuff_v3(*args, **kwargs): <NEW_LINE> <INDENT> print(args, kwargs) | Do your stuff v3 | 625941ea73bcbd0ca4b2c548 |
def reconfigure(self, control, newconf): <NEW_LINE> <INDENT> uniques_conf = None <NEW_LINE> old_preserve_n = self.preserve_n <NEW_LINE> new_preserve_n = old_preserve_n <NEW_LINE> if newconf.has_key(CONF_UNIQUE): <NEW_LINE> <INDENT> uniques_conf = newconf[CONF_UNIQUE] <NEW_LINE> <DEDENT> if newconf.has_key(CONF_PRESERVE... | Give the engine a new configuration.
@note There must not be a decide call in progress when this is called,
and there must not be a new decide call while this is in progress.
@param control instance of Control, used to request changes to system
@param newconf None or dict of key/value pairs
@exception Exception if en... | 625941ea4f6381625f114f0f |
def p_id_list(p): <NEW_LINE> <INDENT> if len(p) == 4: <NEW_LINE> <INDENT> p[0] = Node('id_list', children=[p[1], p[3]], leaf=',', line=p.lineno(1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = Node('id_list', children=p[1], leaf='id', line=p.lineno(1)) | id_list : ID VIRGULA id_list
| ID | 625941ea442bda511e8be8e4 |
def mobile_videodetail(request,new_id,**kwargs): <NEW_LINE> <INDENT> ret = {'news': '', 'username': '', 'category': '', 'nowuser': '', 'NewType':'', 'course_list':''} <NEW_LINE> news = models.News.objects.get(id=new_id) <NEW_LINE> BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) <NEW_LINE> categor... | 页面详细渲染
:param request:
:param new_id:
:param kwargs:
:return: | 625941ea0fa83653e465748b |
def has_mute_role(): <NEW_LINE> <INDENT> async def predicate(ctx): <NEW_LINE> <INDENT> if ('administrator', True) in ctx.message.author.permissions_in(ctx.channel): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> guild = get_guild_config(ctx.guild.id) <NEW_LINE> author_roles = ctx.message.author.roles <NEW_LINE> au... | Check if a user has the role specified in the guild config to use mute and un-mute commands | 625941ea0a366e3fb873ecf2 |
def rebuild(self, context, instance, image_meta, injected_files, admin_password, bdms, detach_block_devices, attach_block_devices, network_info=None, recreate=False, block_device_info=None, preserve_ephemeral=False): <NEW_LINE> <INDENT> raise NotImplementedError() | Destroy and re-make this instance.
A 'rebuild' effectively purges all existing data from the system and
remakes the VM with given 'metadata' and 'personalities'.
This base class method shuts down the VM, detaches all block devices,
then spins up the new VM afterwards. It may be overridden by
hypervisors that need to ... | 625941ea8c3a873295158894 |
def parse_genotypes_from_file(genotypeFile): <NEW_LINE> <INDENT> rawGenos = [] <NEW_LINE> with open(genotypeFile) as f: <NEW_LINE> <INDENT> genoReader = csv.reader(f, delimiter='\t') <NEW_LINE> for item in genoReader: <NEW_LINE> <INDENT> item.pop(0) <NEW_LINE> for i in range(len(item)): <NEW_LINE> <INDENT> item[i] = in... | Converts a newline-delimited file of genotypes (for a given chromosome) to a list of allele calls
:param genotypeFile: file path for genotype information on allele calls, ignoring the first column since it is an index term
:type genotypeFile: string
:return: list of allele calls (integers)
:rtype: list | 625941ea23e79379d52eea31 |
def test_parse_remark_465(self): <NEW_LINE> <INDENT> info = _parse_remark_465("GLU B 276") <NEW_LINE> self.assertEqual(info, {"model": None, "res_name": "GLU", "chain": "B", "ssseq": 276, "insertion": None}) <NEW_LINE> info = _parse_remark_465("2 GLU B 276B") <NEW_LINE> self.assertEqual(info, {"model": 2, "res_name... | A UNIT-test for the private function _parse_remark_465. | 625941ea29b78933be1e5b79 |
@open_file(0, mode="rb") <NEW_LINE> def read_graph6(path): <NEW_LINE> <INDENT> glist = [] <NEW_LINE> for line in path: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not len(line): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> glist.append(from_graph6_bytes(line)) <NEW_LINE> <DEDENT> if len(glist) == 1: <NEW_... | Read simple undirected graphs in graph6 format from path.
Parameters
----------
path : file or string
File or filename to write.
Returns
-------
G : Graph or list of Graphs
If the file contains multiple lines then a list of graphs is returned
Raises
------
NetworkXError
If the string is unable to be parsed... | 625941ea507cdc57c63071ba |
def spatial_groupnorm_backward(dout, cache): <NEW_LINE> <INDENT> dx, dgamma, dbeta = None, None, None <NEW_LINE> G = cache[0] <NEW_LINE> N, C, H, W = dout.shape <NEW_LINE> dout = dout.transpose(0, 2, 3, 1).reshape(N, H, W, G, int(C / G)) <NEW_LINE> dout_group = dout.reshape(N * H * W, G, int(C / G)) <NEW_LINE> dx = np.... | Computes the backward pass for spatial group normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, C, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, C, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (C,)
- dbeta: Grad... | 625941ead58c6744b4258131 |
def test_get_all_empty(self): <NEW_LINE> <INDENT> inquiry_count = 0 <NEW_LINE> get_all_resp = self._do_get_all() <NEW_LINE> inquiries = get_all_resp.json <NEW_LINE> self.assertIsInstance(inquiries, list) <NEW_LINE> self.assertEqual(len(inquiries), inquiry_count) | Test retrieval of a list of Inquiries when there are none | 625941eaa17c0f6771cbe523 |
def calculate_loops_length_two(self, dfg_matrix, freq_triples_matrix, loops_length_two_thresh=default_parameters[LOOP_LENGTH_TWO_THRESH]): <NEW_LINE> <INDENT> if self.nodes_dictionary is not None and self.node_name in freq_triples_matrix: <NEW_LINE> <INDENT> n1 = self.node_name <NEW_LINE> for n2 in freq_triples_matrix[... | get loops of length two
:param dfg_matrix:
:param freq_triples_matrix:
:param loops_length_two_thresh:
:return: | 625941ea711fe17d82542834 |
def onProxyConnectionError(self, err): <NEW_LINE> <INDENT> pass | Function to reimplement
@param err: error message
@type err: string | 625941ea63d6d428bbe449c4 |
def fit(self, x): <NEW_LINE> <INDENT> if self.p == 0: <NEW_LINE> <INDENT> self.identifyP(x) <NEW_LINE> <DEDENT> X = np.zeros([len(x)-self.p, self.p+1]) <NEW_LINE> Y = np.zeros([len(x)-self.p, 1]) <NEW_LINE> for i in range(len(x)-self.p): <NEW_LINE> <INDENT> Y[i, 0] = x[i+self.p] <NEW_LINE> X[i, 0] = 1 <NEW_LINE> X[i, 1... | Just a linear regression using least square. | 625941eaa934411ee3751b68 |
def test_sync_partner(self): <NEW_LINE> <INDENT> partner = self.new_partner() <NEW_LINE> fields = 'phone', 'mobile', 'fax' <NEW_LINE> phones = [] <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> expect = 'new %s' % field <NEW_LINE> phones.append(self.new_phone(partner, field)) <NEW_LINE> phones[-1].write({'phone': e... | It should set proper attributes on partner when updated | 625941eae5267d203edce16a |
def clone(self): <NEW_LINE> <INDENT> return Polygon(self.vertices, self.normal, self.color) | Clones the polygon and returns the clone | 625941ea91af0d3eaac9bef1 |
def open_decrypt(): <NEW_LINE> <INDENT> key = input('What is the Vigenere key you want to use? ') <NEW_LINE> txt_file = input('What is the name of the file to be decrypted? ') <NEW_LINE> txt_file = open(txt_file, 'r') <NEW_LINE> decrypt(txt_file, key) | Asks for the Vigenere key to be used. Asks for the file that is to be opened and
decrypts the file. | 625941ea5e10d32532c5f3f8 |
def detect_uniqueness_error(self, exc): <NEW_LINE> <INDENT> raise NotImplementedError() | Should parse error message and collect any that describe violations
of a uniqueness constraint.
return the curresponding fields, else None
Arguments:
- exc: exception instance
Returns:
- list: list of fields
- None: if no uniqueness errors | 625941eaa8370b7717052d71 |
def save_objs(workspace_name): <NEW_LINE> <INDENT> order = ['Host', 'Interface', 'Service', 'Vulnerability'] <NEW_LINE> saved_ids = set() <NEW_LINE> tmp = created_objs <NEW_LINE> iterable = tmp.items() <NEW_LINE> for type in order: <NEW_LINE> <INDENT> for key, objs in iterable: <NEW_LINE> <INDENT> if key == type: <NEW_... | This function uses a set to avoid hitting too much couchdb.
Wifi packets usually are repeated, for example for beacons.
:param workspace_name:
:return: | 625941ea91f36d47f21ac9cb |
def func_cleanup_schema(): <NEW_LINE> <INDENT> return func.sim_pkg.cleanup_schema().execution_options( autocommit = True ) | Define function call to clean-up schema. | 625941ea5fcc89381b1e1b96 |
def setUp(self): <NEW_LINE> <INDENT> self.name = "Masuk sekolah pagi " <NEW_LINE> self.day = "0" <NEW_LINE> self.time = "0700" <NEW_LINE> self.sound = "0" <NEW_LINE> self.schedule = Schedule(name=self.name, day=self.day, time=self.time, sound=self.sound) | Define the test client and other test variables. | 625941ea21bff66bcd684e21 |
def put(self, key, value): <NEW_LINE> <INDENT> if self.get(key) != -1: <NEW_LINE> <INDENT> self._table[key].val = value <NEW_LINE> return <NEW_LINE> <DEDENT> if self._size == self._cap: <NEW_LINE> <INDENT> victim = self._head.next <NEW_LINE> del self._table[victim.key] <NEW_LINE> self._head.next = victim.next <NEW_LINE... | :type key: int
:type value: int
:rtype: None | 625941ea9f2886367277ad5d |
def default_get(self, cr, uid, fields, context=None): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> stream = [] <NEW_LINE> res = super(copy_product_ldm, self).default_get(cr, uid, fields, context=context) <NEW_LINE> ldm_ids = self.pool.get('mrp.bom').search(cr, uid, [('pro... | To get default values for the object.
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param fields: List of fields for which we want default values
@param context: A standard dictionary
@return: A dictionary which of fields with values. | 625941ea7b25080760e3992a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.