code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def filter_line(self, blob): <NEW_LINE> <INDENT> if 'osxcollector_vthash' in blob: <NEW_LINE> <INDENT> self._vthash.append(blob) <NEW_LINE> <DEDENT> if 'osxcollector_vtdomain' in blob: <NEW_LINE> <INDENT> self._vtdomain.append(blob) <NEW_LINE> <DEDENT> if 'osxcollector_opendns' in blob: <NEW_LINE> <INDENT> self._opendn... | Each Line of OSXCollector output will be passed to filter_line.
The OutputFilter should return the line, either modified or unmodified.
The OutputFilter can also choose to return nothing, effectively swallowing the line.
Args:
output_line: A dict
Returns:
A dict or None | 625941d66fb2d068a760f2dd |
def test_cli_display(): <NEW_LINE> <INDENT> q = queue.Queue() <NEW_LINE> display = CLIDisplay(q) <NEW_LINE> display.start() <NEW_LINE> d = DumpIntoQueue(q) <NEW_LINE> d.run() <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> test = TestObj() <NEW_LINE> test.payload = f"Number {i}" <NEW_LINE> q.put(test) <NEW_LINE> <DED... | Tests CLI display functionality | 625941d66e29344779a6284e |
def calculate_sub_index_no2(no2): <NEW_LINE> <INDENT> if no2 <= 40: <NEW_LINE> <INDENT> return no2 <NEW_LINE> <DEDENT> elif no2 > 40 and no2 <= 80: <NEW_LINE> <INDENT> return 50 + (no2 - 40) <NEW_LINE> <DEDENT> elif no2 > 80 and no2 <= 180: <NEW_LINE> <INDENT> return 100 + (no2 - 80) <NEW_LINE> <DEDENT> elif no2 > 180 ... | Function to calculate the sub-index of the pollutant no2 | 625941d6283ffb24f3c55b3c |
def get_data(self, environment_title_or_num=-1, frequency=None): <NEW_LINE> <INDENT> if isinstance(environment_title_or_num, int): <NEW_LINE> <INDENT> if len(self._environments_by_title) < (environment_title_or_num + 1): <NEW_LINE> <INDENT> raise ValueError( f"Environment number {environment_title_or_num} does not exis... | Get eso data as a pandas data frame.
Parameters
----------
environment_title_or_num: str or int
title or number of the simulated environment. If empty, last environment will be used.
frequency: {'timestep', 'hourly', 'daily', 'monthly', 'annual', 'run_period', None}
If None, will look for the smallest frequenc... | 625941d6851cf427c661a74a |
def get_cached_zone_variable(self, zone_id, variable, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._retrieve_cached_zone_variable(zone_id, variable) <NEW_LINE> <DEDENT> except UncachedVariable: <NEW_LINE> <INDENT> return default | Retrieve the current value of a zone variable from the cache or
return the default value if the variable is not present. | 625941d6711fe17d825425a5 |
def _check_project(self, was, willbe): <NEW_LINE> <INDENT> self.BibTerm = os.path.normpath( os.environ['HomeDrive'] + os.environ['HomePath'] + '\\BibTerm') <NEW_LINE> if willbe in self.list_projects: <NEW_LINE> <INDENT> self.ddnCurProject.set(willbe) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW... | verify project is in list | 625941d650812a4eaa59c55d |
def save_embedding(self, path): <NEW_LINE> <INDENT> embeddings = self.get_embedding_dictionnary() <NEW_LINE> for key in embeddings: <NEW_LINE> <INDENT> embeddings[key] = embeddings[key].tolist() <NEW_LINE> <DEDENT> with open(path, 'w') as file: <NEW_LINE> <INDENT> json.dumps(embeddings) <NEW_LINE> <DEDENT> pass | saves the embedding in a JSON file | 625941d6711fe17d825425a6 |
def mae(self, X, Y): <NEW_LINE> <INDENT> Yhat = self.predict(X) <NEW_LINE> return np.mean(np.absolute(Y - Yhat.reshape(Y.shape)), axis=0) | Computes the mean absolute error
Computes
(1/M) \sum_i | f(x^{(i)}) - y^{(i)} |
of a regression model f(.) on test data X and Y.
Args:
X (arr): M x N array that contains M data points with N features
Y (arr): M x 1 array of target values for each data point
Returns:
float: mean absolute error | 625941d68da39b475bd651b2 |
def p_c_vn(self): <NEW_LINE> <INDENT> p_c_vn = (self.p_c * self.p_vc[self.ys_v, :] * self.p_nc[self.ys_n, :]).T <NEW_LINE> p_vn = np.sum(p_c_vn, axis=0) <NEW_LINE> p_c_vn /= p_vn <NEW_LINE> return p_c_vn, p_vn | P(c|v, n)
:return: | 625941d61d351010ab855d59 |
def setStatus(self, status): <NEW_LINE> <INDENT> return _DataModel.MomentTensor_setStatus(self, status) | setStatus(MomentTensor self, Seiscomp::Core::Optional< Seiscomp::DataModel::MomentTensorStatus >::Impl const & status) | 625941d64c3428357757c564 |
def playerStandings(): <NEW_LINE> <INDENT> conn = connect() <NEW_LINE> cursor = conn.cursor() <NEW_LINE> cursor.execute("select id,name,win,matches from players order by win") <NEW_LINE> result = cursor.fetchall() <NEW_LINE> conn.close() <NEW_LINE> return result | Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by... | 625941d610dbd63aa1bd2ddf |
def _find_classes(self, dir, subset): <NEW_LINE> <INDENT> if subset in [0, 1, 2, 3]: <NEW_LINE> <INDENT> with open(os.path.join(dir, f'wnids_{subset}.txt')) as f: <NEW_LINE> <INDENT> classes = [line[:-1] for line in f.readlines()] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with open(os.path.join(dir, f'wnid... | Finds the class folders in a dataset.
Args:
dir (string): Root directory path.
Returns:
tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.
Ensures:
No class is a subdirectory of another. | 625941d67cff6e4e81117bc2 |
def select_best(population, cost_func, num_to_keep): <NEW_LINE> <INDENT> scored_population = [(i, cost_func(i)) for i in population] <NEW_LINE> scored_population.sort(key=lambda x: x[1]) <NEW_LINE> return [i[0] for i in scored_population[:num_to_keep]] | Select a given number of paths with the lowest cost (the best paths)
Arguments received:
population -- an array of lists of coordinates representing paths
cost_func -- function to calculate cost of a path
num_to_keep -- number of paths to select
Arguments returned:
[i[0] for i in scored_population[:num_to_keep]] -- a... | 625941d691af0d3eaac9bc58 |
def log_configure(): <NEW_LINE> <INDENT> for key, value in settings.LOGGING.items(): <NEW_LINE> <INDENT> if isinstance(cfg[key], dict): <NEW_LINE> <INDENT> cfg[key].update(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cfg[key] = value <NEW_LINE> <DEDENT> <DEDENT> USE_SYSLOG = settings.HAS_SYSLOG and not settings... | You have to explicitly call this to configure logging. | 625941d68e71fb1e9831d9e6 |
def create_ordering(self) -> SortedList: <NEW_LINE> <INDENT> unique_complexes = set() <NEW_LINE> for rule in self.rules: <NEW_LINE> <INDENT> unique_complexes |= rule.create_all_compatible(self.atomic_signature, self.structure_signature) <NEW_LINE> <DEDENT> unique_complexes |= set(self.init) <NEW_LINE> return SortedList... | Extracts all possible unique agents from the model and gives them fixed order using SortedList.
:return: SortedList of unique agents | 625941d6f8510a7c17cf993a |
def partitionLabels(self, S): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> while S: <NEW_LINE> <INDENT> cur = self.find_first_word(S) <NEW_LINE> S = S[cur+1:] <NEW_LINE> ans.append(cur+1) <NEW_LINE> <DEDENT> return ans | :type S: str
:rtype: List[int] | 625941d6091ae35668667198 |
def _get_reconstructed_input(self, hidden): <NEW_LINE> <INDENT> a = T.dot(hidden, self.W_prime) + self.b_prime <NEW_LINE> return T.nnet.sigmoid(a) | Computes the reconstructed input given the values of the hidden units | 625941d6a4f1c619b28b0273 |
def _check_call(ret): <NEW_LINE> <INDENT> if ret != 0: <NEW_LINE> <INDENT> raise XGBoostError(py_str(_LIB.XGBGetLastError())) | Check the return value of C API call
This function will raise exception when error occurs.
Wrap every API call with this function
Parameters
----------
ret : int
return value from API calls | 625941d63cc13d1c6d3c75b7 |
def __init__(self, location): <NEW_LINE> <INDENT> if not location in self.__LOCATIONS: <NEW_LINE> <INDENT> raise AttributeError("Invalid Navigator name '%s'" % (location,)) <NEW_LINE> <DEDENT> self._id = location <NEW_LINE> self._state = None <NEW_LINE> self.button0_changed = baxter_dataflow.Signal() <NEW_LINE> self.bu... | Constructor.
@type location: str
@param location: body location (prefix) of Navigator to control.
Valid locations are in L{Navigator.__LOCATIONS}::
left, right, torso_left, torso_right | 625941d6d486a94d0b98e384 |
def delete(self, name, **kwargs): <NEW_LINE> <INDENT> return Collection.delete(self, name.lower(), **kwargs) | Deletes the user and returns the resulting collection of users.
:param name: The name of the user to delete.
:type name: ``string``
:return:
:rtype: :class:`Users` | 625941d64e4d5625662d4613 |
def _normalize_old_style_args(self, thing, action): <NEW_LINE> <INDENT> if isinstance(thing, dict): <NEW_LINE> <INDENT> args = thing <NEW_LINE> <DEDENT> elif isinstance(thing, string_types): <NEW_LINE> <INDENT> check_raw = action in ('command', 'shell', 'script') <NEW_LINE> args = parse_kv(thing, check_raw=check_raw) <... | deals with fuzziness in old-style (action/local_action) module invocations
returns tuple of (module_name, dictionary_args)
possible example inputs:
{ 'local_action' : 'shell echo hi' }
{ 'action' : 'shell echo hi' }
{ 'local_action' : { 'module' : 'ec2', 'x' : 1, 'y': 2 }}
standardized outputs like:
... | 625941d6462c4b4f79d1d90d |
def to_base16(n, visualize=False): <NEW_LINE> <INDENT> _list = [] <NEW_LINE> while n != 0: <NEW_LINE> <INDENT> if visualize: <NEW_LINE> <INDENT> print("{} % 16 = {} -> hex = {}".format( str(n), str(n % 16), HEX_VALUES[n % 16] )) <NEW_LINE> <DEDENT> _list.append(HEX_VALUES[n % 16]) <NEW_LINE> n = int(n / 16) <NEW_LINE> ... | Convert decimal number to hexadecimal
Divide the number by 16 and add the remainder
to a list, round down the value after division
and repeat till our value is 0
Reverse the results list, get each values respective
hex value using HEX_VALUES map
:param n: decimal number
:param visualize: Show process
:return: hexade... | 625941d60fa83653e46571f7 |
def read(self, count): <NEW_LINE> <INDENT> self._assert_rlock() <NEW_LINE> if count > self._rstream.available(): <NEW_LINE> <INDENT> raise EOFError("request to read more than available") <NEW_LINE> <DEDENT> self.logger.info("read(%r)", count) <NEW_LINE> data = self._rstream.read(count) <NEW_LINE> self.logger.info(" ... | reads up to `count` bytes from the ongoing read transaction.
begin_read() must have been called prior to this | 625941d6ff9c53063f47c430 |
def _init_fona(self): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> timeout = 7000 <NEW_LINE> while timeout > 0: <NEW_LINE> <INDENT> if self._send_check_reply(CMD_AT, reply=REPLY_OK): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if self._send_check_reply(CMD_AT, reply=REPLY_AT): <NEW_LINE> <INDENT> break <NEW_LINE> <DED... | Initializes FONA module. | 625941d6ec188e330fd5a9d9 |
def play_one(self) -> None: <NEW_LINE> <INDENT> print("\nSTART: Let's play the match case number " + str(self.page) + ".") <NEW_LINE> self.actual_page_info = self.involved_pages(self.page) <NEW_LINE> print("\n\n The case title is: ", self.actual_page_info['actual_page']['msg_pre']) <NEW_LINE> initial_check = input( "Pl... | Match develpment based on a specific case | 625941d6091ae35668667199 |
def output_multiple(self): <NEW_LINE> <INDENT> return _ieee802_11_swig.moving_average_ff_sptr_output_multiple(self) | output_multiple(moving_average_ff_sptr self) -> int | 625941d67cff6e4e81117bc3 |
def getNeighbors(self): <NEW_LINE> <INDENT> r, c = self <NEW_LINE> yield self.__class__( (r-1, c) ) <NEW_LINE> yield self.__class__( (r+1, c) ) <NEW_LINE> yield self.__class__( (r, c-1) ) <NEW_LINE> yield self.__class__( (r, c+1) ) | Yields self's neighbors in up, down, left, right order. | 625941d6be383301e01b56c1 |
def select_uuid(uuid): <NEW_LINE> <INDENT> success = None <NEW_LINE> mongo = Mongo() <NEW_LINE> try: <NEW_LINE> <INDENT> result = mongo.company.find_one({"uuid": uuid}) <NEW_LINE> success = result <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> <DEDENT> finally: <NEW_LINE... | 通过uuid查询
:param uuid: str
:return: None or dict | 625941d666656f66f7cbc3ea |
@app.route("/users", methods = ('GET', 'POST')) <NEW_LINE> def user(): <NEW_LINE> <INDENT> if session.get("nombre"): <NEW_LINE> <INDENT> users = archivo.leer("archivos_csv/passws.csv") <NEW_LINE> return render_template('users.html', users = users) <NEW_LINE> <DEDENT> flash('Debe estar logueado para acceder') <NEW_LINE>... | listado de usuarios creados, solo se puede ver si el usuario que ingreso a la sesion es admin | 625941d6283ffb24f3c55b3d |
def __init__(self, app, config, mount, frontpage, roots, substitutions=None, embeddings=None, instances=None, preamble=None, debug_mode=None): <NEW_LINE> <INDENT> for origin, info in roots.iteritems(): <NEW_LINE> <INDENT> if not re.match(r"^[-a-z0-9]+$", origin): <NEW_LINE> <INDENT> raise ValueError("invalid root label... | .. rubric:: Constructor
:arg app: Reference to the :class:`~.RESTMain` application.
:arg config: :class:`~.WMCore.ConfigSection` for me.
:arg str mount: URL tree mount point for this object.
:arg str frontpage: Name of the front-page file, which must exist in
... | 625941d6925a0f43d254a0b6 |
def predict_lstm(self, feats, no_softmax = False): <NEW_LINE> <INDENT> batch_size = self.batch_size <NEW_LINE> feats_packed, seq_length, post_pick = self.pack_utterance(feats, max_length = self.max_length) <NEW_LINE> posts = [] <NEW_LINE> assert len(feats_packed) % batch_size == 0 <NEW_LINE> num_batches = len(feats_pac... | we need a sliding window to generate frame posteriors
args:
feats: np 2-d array of size[num_frames, feat_dim]
output:
posts: np 2-d array of size[num_frames, num_targets] | 625941d682261d6c526ab6df |
def test_RemoveBook(self): <NEW_LINE> <INDENT> book1 = self.setUp() <NEW_LINE> shelf1 = shelf.Shelf() <NEW_LINE> shelf1.AddBook(book1) <NEW_LINE> shelf1.RemoveBook("Catcher in the Rye") <NEW_LINE> self.assertEqual(shelf1.GetBookCount(), 0) <NEW_LINE> pass | Tests that a book is successfully removed from a shelf. | 625941d6d164cc6175782f8c |
def findCalendarListAll(self, with_item=False, with_count_hatena_bookmark=False): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for page in range(1, self.max_calendar_page + 1): <NEW_LINE> <INDENT> rows = self.findCalendarList(page) <NEW_LINE> result.extend(rows) <NEW_LINE> if len(rows) < self.max_calendar_per_page: <NEW_... | 全 カレンダー 情報 取得
| 625941d607d97122c4178acd |
def buildRequests(trainStations): <NEW_LINE> <INDENT> stations = trainStations.keys() <NEW_LINE> reqURLs = [] <NEW_LINE> for ii in range(0, len(stations)/MAXREQ): <NEW_LINE> <INDENT> idx = ii*MAXREQ <NEW_LINE> reqURLs.append(baseURL + "".join(["&mapid=" + str(x) for x in stations[idx:idx+MAXREQ]])) <NEW_LINE> <DEDENT> ... | Constructs all the API requests that will be used by this program. | 625941d6287bf620b61d3ca0 |
def maybe_close(log_fh): <NEW_LINE> <INDENT> if log_fh is not sys.stdout: <NEW_LINE> <INDENT> log_fh.close() | Close if log_fh is not STDOUT | 625941d663d6d428bbe4472e |
def _on_access_token(self, future, response): <NEW_LINE> <INDENT> if response.error: <NEW_LINE> <INDENT> future.set_exception(AuthError('FullContact auth error: %s' % str(response))) <NEW_LINE> return <NEW_LINE> <DEDENT> args = escape.json_decode(response.body) <NEW_LINE> future.set_result(args) | Callback function for the exchange to the access token. | 625941d67b25080760e39696 |
def details(self, network_id): <NEW_LINE> <INDENT> return AsObj(**self._call(self._urls["details"] % str(network_id), "")) | Get a networks details by id.
:param network_id: int
:return: | 625941d6e76e3b2f99f3aa46 |
@app.route("/") <NEW_LINE> def welcome(): <NEW_LINE> <INDENT> return ( "<b>Hawaii Climate App</b><br><br/>" "Available Routes:<br/>" "<br>" "/api/v1.0/precipitation<br/>" "/api/v1.0/stations<br/>" "/api/v1.0/tobs<br/>" "/api/v1.0/start<br/>" "/api/v1.0/start/end<br/>" ) | List all available api routes. | 625941d65fc7496912cc3bbc |
def getParameterInfo(self): <NEW_LINE> <INDENT> param0 = arcpy.Parameter( displayName="Lines of Sight", name="in_los", datatype="GPFeatureLayer", parameterType="Required", direction="Input") <NEW_LINE> param0.filter.list = ["Polyline"] <NEW_LINE> param1 = arcpy.Parameter( displayName="Line of Sight ID", name="in_id", d... | Define parameter definitions | 625941d6dc8b845886cb5774 |
def GetEccentricity(self, *args): <NEW_LINE> <INDENT> return _itkLabelGeometryImageFilterPython.itkLabelGeometryImageFilterIUS2IF2_GetEccentricity(self, *args) | GetEccentricity(self, unsigned short label) -> double | 625941d694891a1f4081bce8 |
def __init__(self, title=None, hash=None): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.hash = hash | Initialize a ShortDoc object.
:param str title: (optional) The title of the input document, if identified.
:param str hash: (optional) The MD5 hash of the input document. | 625941d6d4950a0f3b08c58b |
def islink(self, path): <NEW_LINE> <INDENT> path = str(path) <NEW_LINE> try: <NEW_LINE> <INDENT> lstat_result = self._host.lstat( path, _exception_for_missing_path=False) <NEW_LINE> if lstat_result is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return stat.S_ISLNK(lstat_result.s... | Return true if the `path` exists and is a link.
A non-existing path does _not_ cause a `PermanentError`. | 625941d663f4b57ef0001352 |
def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr in self.SCALES and self.scale is not None: <NEW_LINE> <INDENT> cache = self.cache['scale'] <NEW_LINE> if attr not in cache: <NEW_LINE> <INDENT> if attr == self.scale: <NEW_LINE> <INDENT> tm = self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tm = self.replicate(... | Get dynamic attributes to output format or do timescale conversion. | 625941d616aa5153ce3626b6 |
def test_no_subpaths(self): <NEW_LINE> <INDENT> resource = IModelResource() <NEW_LINE> resource.model = MagicMock() <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> resource['foobar'] | If resource already contains model, further paths raise KeyError | 625941d62c8b7c6e89b359fe |
def dont_record(): <NEW_LINE> <INDENT> recorder_proxy.clear_for_current_request() | API to prevent recording of the current request. Used by ui.py. | 625941d6c4546d3d9de72c73 |
def preorderTraversal(self, root): <NEW_LINE> <INDENT> return self.iteration_preorder(root) | :type root: TreeNode
:rtype: List[int] | 625941d6e1aae11d1e749ef7 |
def __eq__(self, *args): <NEW_LINE> <INDENT> return _ilwisobjects.Size___eq__(self, *args) | __eq__(Size self, Size sz) -> bool | 625941d69c8ee82313fbb9b4 |
def load(self): <NEW_LINE> <INDENT> print('loading', self.filename) <NEW_LINE> self.filename = self.filename.replace(".db", "") <NEW_LINE> self.db = shelve.open(self.filename, writeback=True) | load the cloudmesh_job | 625941d64d74a7450ccd4401 |
def combinationSum2(self, candidates, target): <NEW_LINE> <INDENT> if candidates == []: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> candidates = sorted(candidates, reverse=True) <NEW_LINE> results = [] <NEW_LINE> lenth = len(candidates) <NEW_LINE> def helper(res, idx): <NEW_LINE> <INDENT> if idx >= lenth: <NEW_L... | :type candidates: List[int]
:type target: int
:rtype: List[List[int]] | 625941d630bbd722463cc006 |
def load_klein(): <NEW_LINE> <INDENT> datadir = Path(__file__).parent.joinpath('data/klein') <NEW_LINE> profile = pd.read_csv(datadir.joinpath('profile.txt'), index_col=0) <NEW_LINE> with open(str(datadir.joinpath('labels.txt').resolve()), 'r') as f: <NEW_LINE> <INDENT> labels = f.read().split() <NEW_LINE> <DEDENT> ret... | Klein AM, Mazutis L, Akartuna I, Tallapragada N et al.
Droplet barcoding for single-cell transcriptomics applied to embryonic
stem cells. Cell 2015 May 21;161(5):1187-1201. PMID: 26000487
GSE65525
note: this data is modified from its origin. | 625941d6fbf16365ca6f6404 |
def _eintr_test_fail(self): <NEW_LINE> <INDENT> self.poller.stop() <NEW_LINE> self.fail('Eintr-test timed out') | This function gets called when eintr-test failed to get
_eintr_read_handler called. | 625941d65f7d997b87174cd7 |
def dev_step(x_batch, y_batch, writer=None): <NEW_LINE> <INDENT> feed_dict = { cnn.input_x: x_batch, cnn.input_y: y_batch, cnn.dropout_keep_prob: 1.0 } <NEW_LINE> step, summaries, loss, accuracy = sess.run( [global_step, dev_summary_op, cnn.loss, cnn.accuracy], feed_dict) <NEW_LINE> time_str = datetime.datetime.now().i... | Evaluates model on a dev set | 625941d68c0ade5d55d3ebfa |
def _apply_to_all(func, paths: 'Iterable[PathLike]'): <NEW_LINE> <INDENT> for path in paths: <NEW_LINE> <INDENT> path = os.fspath(path) <NEW_LINE> if os.path.isdir(path): <NEW_LINE> <INDENT> _apply_to_dir(func, path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func(path) | Call a function on files and directories. | 625941d607f4c71912b116c2 |
def __init__(self, contact_id=None, list_id=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._contact_id = None <NEW_L... | ContactSearchResponse - a model defined in OpenAPI | 625941d65fdd1c0f98dc0472 |
def calculate_mag(raw_val): <NEW_LINE> <INDENT> result = raw_val * 2 / ((2**15) - 1) <NEW_LINE> return result | Converts the raw value read from the magnetometer.
Currently does not take calibration into consideration. | 625941d660cbc95b062c6782 |
def process_client_run(self): <NEW_LINE> <INDENT> error = [] <NEW_LINE> hemlock.raw_input = lambda _: 'y' <NEW_LINE> a = hemlock.Hemlock() <NEW_LINE> m_server = self.connect_mysql(0, "localhost", "travis", "password", "hemlock_test") <NEW_LINE> c, error2 = a.process_action(0, "tenant-create", {'--name':'tenant1'}, m_se... | Tests client-run action.
:return: returns any data and a list of any errors | 625941d644b2445a339322d3 |
def __init__(self, force_constant, indexes, icfn): <NEW_LINE> <INDENT> self.force_constant = force_constant <NEW_LINE> self.indexes = indexes <NEW_LINE> self.icfn = icfn | Arguments:
| ``force_constant`` -- The force constant in atomic units.
| ``indexes`` -- The indexes of the atoms in the internal
coordinate. The order must be the same as the order
of the mandatory arguments of icfn.
| ``icfn`` -- a function from molmod.ic that can compute the
... | 625941d62eb69b55b151caf0 |
def application(self): <NEW_LINE> <INDENT> return self.conn.application() | Return admin Application object.
| 625941d68a43f66fc4b542a2 |
def linear(input, weight, bias=None): <NEW_LINE> <INDENT> if input.dim() == 2 and bias is not None: <NEW_LINE> <INDENT> ret = torch.addmm(bias, input, weight.t()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output = input.matmul(weight.t()) <NEW_LINE> if bias is not None: <NEW_LINE> <INDENT> output += bias <NEW_LINE>... | Applies a linear transformation to the incoming data: :math:`y = xA^T + b`.
Shape:
- Input: :math:`(N, *, in\_features)` where `*` means any number of
additional dimensions
- Weight: :math:`(out\_features, in\_features)`
- Bias: :math:`(out\_features)`
- Output: :math:`(N, *, out\_features)` | 625941d6b7558d58953c5150 |
def __init__(self, session, cwd = None): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> self.client = session.client('ec2') <NEW_LINE> if cwd == None: <NEW_LINE> <INDENT> self.cwd = os.getcwd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cwd = cwd <NEW_LINE> <DEDENT> self.tf = Terraform(working_dir=self.c... | Initilize the class with the boto3 client and terraform wrapper
session: boto3 session variabled. Required
cwd: Current working directory of the script. Optional.
If cwd is not specified, the current working directory
of the script is used instead. | 625941d6956e5f7376d710aa |
def forward(self, hidden, encoder_outputs): <NEW_LINE> <INDENT> seq_len = len(encoder_outputs) <NEW_LINE> batch_size = encoder_outputs.shape[1] <NEW_LINE> attn_energies = Variable(torch.zeros(seq_len, batch_size)) <NEW_LINE> if self.USE_CUDA: attn_energies = attn_energies.cuda() <NEW_LINE> for i in range(seq_len): <NEW... | hidden: (BS, hidden_size)
encoder_outputs(seq_len, BS, encoder_hidden_size) | 625941d6aad79263cf390c82 |
def SetNeighborhoodRadius(self, *args): <NEW_LINE> <INDENT> return _itkStochasticFractalDimensionImageFilterPython.itkStochasticFractalDimensionImageFilterIUC2IUS2_SetNeighborhoodRadius(self, *args) | SetNeighborhoodRadius(self, itkSize2 _arg) | 625941d6956e5f7376d710ab |
def server_get_role(self, server_id: str) -> Optional[str]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.servers[server_id].role <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return uita.server.database.get_server_role(server_id) | Get the role required to use bot commands.
Args:
server_id: Server to get required role from.
Returns:
ID of required role. Can be ``None`` for no requirement. | 625941d6796e427e537b0806 |
def __extractSkosConcepts(self): <NEW_LINE> <INDENT> self.skosConcepts = [] <NEW_LINE> qres = self.queryHelper.getSKOSInstances() <NEW_LINE> for candidate in qres: <NEW_LINE> <INDENT> test_existing_cl = self.getSkosConcept(uri=candidate[0]) <NEW_LINE> if not test_existing_cl: <NEW_LINE> <INDENT> self.skosConcepts += [O... | 2015-08-19: first draft | 625941d696565a6dacc8f909 |
def _grammar_injection(self, string_a, string, switch): <NEW_LINE> <INDENT> if switch.lower() not in str(string).split(" ", 1)[0].lower(): <NEW_LINE> <INDENT> if len(str(string).split(" ", 1)) > 1: <NEW_LINE> <INDENT> return f"{str(string).split(' ', 1)[0]}{string_a} {str(string).split(' ', 1)[1]}" <NEW_LINE> <DEDENT> ... | if the first word of input does not contains switch this will return input
else it will return the first word of input input + string_a + rest of input
:param string_a: a string to inject into input
:param string: the string being concatonated
:param switch_string: the set of strings to look for in the first word of i... | 625941d6cc40096d61595b8f |
def test_auth_object(unauth_client): <NEW_LINE> <INDENT> unauth_client.add_credentials('joe', '1234') <NEW_LINE> assert isinstance(unauth_client.auth, HTTPBasicAuth) | Test auth is HTTPBasicAuth object. | 625941d676e4537e8c3518b3 |
def prediction(file): <NEW_LINE> <INDENT> x = load_img(file, target_size=(longitud,altura)) <NEW_LINE> x = img_to_array(x) <NEW_LINE> x = np.expand_dims(x, axis = 0) <NEW_LINE> arreglo = cnn.predict(x) <NEW_LINE> resultado = arreglo[0] <NEW_LINE> respuesta = np.argmax(resultado) <NEW_LINE> if respuesta == 0: <NEW_LINE>... | path = cv2.imread(file)
image = cv2.resize(path,(100,100))
cv2.imwrite('data/validation/prueba.jpg', image) | 625941d615fb5d323cde0d51 |
def Rstar20(filter_id=2, altitude=90., aperture_cut=True, absorb=True): <NEW_LINE> <INDENT> filter_id = np.atleast_1d(filter_id) <NEW_LINE> altitude = np.atleast_1d(altitude) <NEW_LINE> if len(altitude) == 1: <NEW_LINE> <INDENT> altitude = np.ones(len(filter_id)) * altitude <NEW_LINE> <DEDENT> assert (len(filter_id) ==... | Compute electrons per second for a 20th mag source. | 625941d6fbf16365ca6f6405 |
def add_row(self, test, denied=False): <NEW_LINE> <INDENT> self.file.write("<li>" + 'denied' if denied else '' + test['test'] + "</li><ul>") <NEW_LINE> if test['output_valid']: <NEW_LINE> <INDENT> self.file.write('<li class="ok">output</li>') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.file.write('<li class="err... | Creates a new bullet point for a test containing the validated outputs.
| 625941d63cc13d1c6d3c75b8 |
def print_classpath(): <NEW_LINE> <INDENT> print(get_classpath([])) | Syntax: [storm classpath]
Prints the classpath used by the storm client when running commands. | 625941d696565a6dacc8f90a |
def get_label_row(self, uid: str, get_signed_url: bool = True): <NEW_LINE> <INDENT> payload = {"get_signed_url": get_signed_url} <NEW_LINE> return self._querier.basic_getter(LabelRow, uid, payload=payload) | Retrieve label row.
Args:
uid: A label_hash (uid) string.
get_signed_url: By default the operation returns a signed URL for the underlying data asset. This can be
expensive so it can optionally be turned off
Returns:
LabelRow: A label row instance.
Raises:
AuthenticationError: If the project API ... | 625941d67b180e01f3dc4a39 |
def getSquareValue(self, tup): <NEW_LINE> <INDENT> squareX = tup[0] <NEW_LINE> squareY = tup[1] <NEW_LINE> return self.squares[squareX][squareY].getTroop() | Accepts a tuple of form (x,y).
Returns the Troop Object of the square at that location. | 625941d6435de62698dfde8c |
def test_create_recipe_with_ingredients(self): <NEW_LINE> <INDENT> ingredient1 = sample_ingredient(user=self.user, name='Prawns') <NEW_LINE> ingredient2 = sample_ingredient(user=self.user, name='Ginger') <NEW_LINE> payload = { 'title': 'Thai prawn red curry', 'ingredients': [ingredient1.id, ingredient2.id], 'time_minut... | Test creating a recipe with ingredients | 625941d6460517430c3943c0 |
def where(predicate): <NEW_LINE> <INDENT> matching_idx = predicate.nonzero() <NEW_LINE> n_match = len(matching_idx) <NEW_LINE> if n_match != 0: <NEW_LINE> <INDENT> matching_idx = matching_idx.t().squeeze(0) <NEW_LINE> <DEDENT> return matching_idx | Returns indices which match given predicate | 625941d6d18da76e23532717 |
def test_dwca_get_data_set_names(self): <NEW_LINE> <INDENT> pass | Test case for dwca_get_data_set_names | 625941d64a966d76dd551250 |
def setUp(self): <NEW_LINE> <INDENT> self.keep_ADC = self.force_env('TEAL_ALERT_DUPLICATE_CHECK', 'No') <NEW_LINE> self.teal = Teal('data/alert_delivery_test/listener_failure/test.conf', "stderr", msgLevel=self.msglevel, commit_alerts=False, commit_checkpoints=False) <NEW_LINE> return | Setup Teal | 625941d6097d151d1a223097 |
def _get_timestamp(global_configs, statuses=('SUCCESS', 'PARTIAL_SUCCESS')): <NEW_LINE> <INDENT> latest_timestamp = None <NEW_LINE> try: <NEW_LINE> <INDENT> latest_timestamp = ( dao.Dao(global_configs).get_latest_snapshot_timestamp(statuses)) <NEW_LINE> <DEDENT> except db_errors.MySQLError as err: <NEW_LINE> <INDENT> L... | Get latest snapshot timestamp.
Args:
global_configs (dict): Global configurations.
statuses (tuple): The snapshot statuses to search for latest timestamp.
Returns:
str: The latest snapshot timestamp. | 625941d699fddb7c1c9de5d0 |
def set_ydata(self, y): <NEW_LINE> <INDENT> segments = np.array(self.collection.get_segments()) <NEW_LINE> segments[:,0,1] = y[:-1] <NEW_LINE> segments[:,1,1] = y[1:] <NEW_LINE> self.collection.set_segments(segments) | Set new y (must be same size as current x data)
y[N] ydata | 625941d6b830903b967e9b48 |
def _find_magic_number(self): <NEW_LINE> <INDENT> string = self.rpmfile.read(1) <NEW_LINE> while True: <NEW_LINE> <INDENT> match = HeaderBase.MAGIC_NUMBER_MATCHER.search(string) <NEW_LINE> if match: <NEW_LINE> <INDENT> self.rpmfile.seek(-3, 1) <NEW_LINE> return True <NEW_LINE> <DEDENT> byte = self.rpmfile.read(1) <NEW_... | find a magic number in a buffer
| 625941d691af0d3eaac9bc5a |
def run_in_event_loop(coroutine): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> loop = asyncio.get_event_loop() <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> loop = asyncio.new_event_loop() <NEW_LINE> asyncio.set_event_loop(loop) <NEW_LINE> <DEDENT> loop.set_default_executor(ThreadPoolExecutor(max_workers... | Wrap and run coroutine in event loop.
:param coroutine: coroutine to run in the event loop | 625941d68e71fb1e9831d9e8 |
def forbid_multi_line_headers(name, val, encoding): <NEW_LINE> <INDENT> encoding = encoding or "utf8" <NEW_LINE> val = unicode(val) <NEW_LINE> if '\n' in val or '\r' in val: <NEW_LINE> <INDENT> raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name)) <NEW_LINE> <DEDENT> try: <NE... | Forbids multi-line headers, to prevent header injection. | 625941d6dc8b845886cb5775 |
def test_can_edit_field_with_patch(self): <NEW_LINE> <INDENT> expected = 'Field1 modified' <NEW_LINE> field1 = FieldType.objects.create(name='Field1') <NEW_LINE> url = reverse('fieldtype-detail', kwargs={'pk': field1.id}) <NEW_LINE> response = self.client.patch(url, data={'name': 'Field1 modified'}) <NEW_LINE> self.ass... | Should be able to edit a field type with a PATCH method. | 625941d6a4f1c619b28b0275 |
def is_future(term, request): <NEW_LINE> <INDENT> return term.get_bod_first_day() > get_comparison_datetime(request) | return true if the given term is in the future | 625941d69b70327d1c4e1015 |
def _parse_bytes(self, raw): <NEW_LINE> <INDENT> data = Raw(raw, self.NAME, self.LEN) <NEW_LINE> isd_as = cast(int, struct.unpack("!I", data.pop())[0]) <NEW_LINE> self._parse_int(isd_as) | :param bytes raw:
a byte string containing ISD ID, AS ID. ISD and AS are respectively
represented as 12 and 20 most significant bits. | 625941d6009cb60464c635ef |
def log2(x): <NEW_LINE> <INDENT> return log(x, 2) | logarithm base 2 | 625941d6091ae3566866719a |
def test_part1() -> None: <NEW_LINE> <INDENT> example = {8: 0, 7: 0, 6: 0, 5: 0, 4: 1, 3: 2, 2: 1, 1: 1, 0: 0} <NEW_LINE> assert read_fish("3,4,3,1,2") == example <NEW_LINE> assert progress(example, 1) == { 8: 0, 7: 0, 6: 0, 5: 0, 4: 0, 3: 1, 2: 2, 1: 1, 0: 1, } <NEW_LINE> assert progress(example, 2) == { 8: 1, 7: 0, 6... | Examples for Part 1. | 625941d6293b9510aa2c34d3 |
def check_and_update_periodic_info(pbc_info, box_x, xleft_current, xright_current): <NEW_LINE> <INDENT> def get_pbc_edge_multiplier_addition(x_current, box_x): <NEW_LINE> <INDENT> if x_current % box_x > abs(box_x - x_current % box_x): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return +1... | Detect whether an edge has crossed a boundary and update the multipliers.
If a PBC boundary has been crossed by one edge (assuming that the time
difference between maps is small enough to not allow both edges to cross
at once), the edge that crossed should be the one which is furthest from
its previous position.
The ... | 625941d629b78933be1e58e8 |
def update_service_account(self, etag, name='', project_id='', unique_id='', email='', display_name='', oauth2_client_id='', options=None): <NEW_LINE> <INDENT> request = iam_pb2.ServiceAccount( etag=etag, name=name, project_id=project_id, unique_id=unique_id, email=email, display_name=display_name, oauth2_client_id=oau... | Updates a ``ServiceAccount``.
Currently, only the following fields are updatable:
``display_name`` .
The ``etag`` is mandatory.
Example:
>>> from google.cloud.gapic.iam_admin.v1 import iam_api
>>> api = iam_api.IAMApi()
>>> etag = ''
>>> response = api.update_service_account(etag)
Args:
name (string): The r... | 625941d60fa83653e46571f9 |
def avg(cluster): <NEW_LINE> <INDENT> samples = cluster.samples <NEW_LINE> C = len(samples) <NEW_LINE> if C <= 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> a = np.array([x.vector for x in samples]).reshape(C, -1).T <NEW_LINE> a = np.expand_dims(a, axis=-1) <NEW_LINE> a = a.repeat(C, axis=-1) <NEW_LINE> cos = (np... | 求簇cluster的样本间的平均距离
:param cluster: Cluster
:return: 平均距离 | 625941d6d268445f265b50ad |
def test_doctests(): <NEW_LINE> <INDENT> local('python -m doctest `find shareclip -name \'*.py\'` -v') | Search for and run all docstring doctests. | 625941d6ec188e330fd5a9db |
def __init__(self, *args): <NEW_LINE> <INDENT> self.settings = args | Resolves slug paths into corresponding views or raises Http404 exception if resolution fails.
Args - 2-items tuples: (queryset, view).
CleanURLHandler subsequently tries to match captured `slug` among querysets' objects, and calls corresponding view on success. The view will also receive matched object as an `instance... | 625941d6adb09d7d5db6c9ce |
@pytest.fixture <NEW_LINE> def gaebed(gae, gae_sdk_path, gae_probability, mocker): <NEW_LINE> <INDENT> if gae: <NEW_LINE> <INDENT> if gae_sdk_path not in sys.path: <NEW_LINE> <INDENT> sys.path.insert(0, gae_sdk_path) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> import appengine_config <NEW_LINE> <DEDENT> except ImportE... | Prepare GAE testbed environment if necessary | 625941d66fece00bbac2d980 |
def test_get_formatted_contents_calls_colorize_if_use_color(): <NEW_LINE> <INDENT> starting_contents = 'this is where we start' <NEW_LINE> colorized_contents = 'COLORIZED: this is where we start' <NEW_LINE> _helper_assert_formatted_contents( starting_contents=starting_contents, use_color=True, color_config='some color ... | Colorize the contents if use_color = True. | 625941d6dd821e528d63b3e7 |
def output_signature(self): <NEW_LINE> <INDENT> return _PHY_swig.conv_decode_tag_sptr_output_signature(self) | output_signature(conv_decode_tag_sptr self) -> io_signature_sptr | 625941d6925a0f43d254a0b8 |
def remove_process(self, name): <NEW_LINE> <INDENT> self.request("delete", "/processes/%s" % name) <NEW_LINE> return True | Stop a process and remove it from the managed processes | 625941d68c3a8732951585fc |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedom.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. | 625941d6eab8aa0e5d26dd98 |
def get_service(self, service, decrypt_blind=False): <NEW_LINE> <INDENT> ret = {'result': False} <NEW_LINE> try: <NEW_LINE> <INDENT> response = self._execute_request( 'get', '{0}/v1/services/{1}'.format(self.config['url'], service), expected_return_codes=[200, 404] ) <NEW_LINE> <DEDENT> except RequestExecutionError: <N... | Get a service's metadata and secrets. | 625941d6566aa707497f47a6 |
def initialize(self, es): <NEW_LINE> <INDENT> r = es.sp.weights.mueff / es.popsize <NEW_LINE> self.index_to_compare = 0.5 * (r**0.5 + 2.0 * (1 - r**0.5) / np.log(es.N + 9)**2) * (es.popsize) <NEW_LINE> self.index_to_compare = 0.30 * es.popsize <NEW_LINE> self.damp = 2 - 2 / es.N <NEW_LINE> self.c = 0.3 <NEW_LINE> self.... | late initialization using attributes ``N`` and ``popsize`` | 625941d6baa26c4b54cb135d |
def stop(self): <NEW_LINE> <INDENT> self.logger.info('Stopping crawler %s' % self.name) <NEW_LINE> self.stopped = True <NEW_LINE> while not self.network._request_queue.empty(): <NEW_LINE> <INDENT> self.network._request_queue.get() | 停止爬虫。
| 625941d632920d7e50b28412 |
def convert(infile, h5file, mode="w-", create_dataset_args=None): <NEW_LINE> <INDENT> if mode not in ["w", "w-"]: <NEW_LINE> <INDENT> raise IOError("File mode must be 'w' or 'w-'. Use write_to_h5" + " to append data to an existing HDF5 file.") <NEW_LINE> <DEDENT> write_to_h5(infile, h5file, h5path='/', mode=mode, creat... | Convert a supported file into an HDF5 file, write scans into the
root group (``/``).
This is a convenience shortcut to call::
write_to_h5(h5like, h5file, h5path='/',
mode="w-", link_type="soft")
:param infile: Path of input file or :class:`commonh5.File` object
or :class:`commonh5.Group` obje... | 625941d6a79ad161976cc385 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.