code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def first(it): <NEW_LINE> <INDENT> return next(it) | Return first element in iterable. | 625941ed7047854f462a1933 |
def master_srcmdl_xml(self, **kwargs): <NEW_LINE> <INDENT> kwargs_copy = self.base_dict.copy() <NEW_LINE> kwargs_copy.update(**kwargs) <NEW_LINE> self._replace_none(kwargs_copy) <NEW_LINE> localpath = NameFactory.master_srcmdl_xml_format.format(**kwargs_copy) <NEW_LINE> if kwargs.get('fullpath', False): <NEW_LINE> <IND... | return the name of a source model file
| 625941ed8c3a8732951588f0 |
def test_seq_unequal_hit_query_len(self): <NEW_LINE> <INDENT> for seq_type in ('hit', 'query'): <NEW_LINE> <INDENT> opp_type = 'query' if seq_type == 'hit' else 'hit' <NEW_LINE> fragment = HSPFragment('hit_id', 'query_id') <NEW_LINE> setattr(fragment, seq_type, 'ATGCACAACAGGA') <NEW_LINE> self.assertRaises(ValueError, ... | Test HSPFragment sequence setter with unequal hit and query lengths | 625941ed4f6381625f114f6b |
def keys(self, data, *args, **kwargs): <NEW_LINE> <INDENT> for e in self.elems(*args, **kwargs): <NEW_LINE> <INDENT> e.send_keys(data) | Types the specified data into the queried elements. | 625941edde87d2750b8602c8 |
@pytest.mark.sanity <NEW_LINE> def test_state_refresh_disable_cache(): <NEW_LINE> <INDENT> foldered_name = sdk_utils.get_foldered_name(config.SERVICE_NAME) <NEW_LINE> config.check_running(foldered_name) <NEW_LINE> task_ids = sdk_tasks.get_task_ids(foldered_name, '') <NEW_LINE> stdout = sdk_cmd.svc_cli(config.PACKAGE_NA... | Disables caching via a scheduler envvar | 625941ed85dfad0860c3b38c |
def test_04(self): <NEW_LINE> <INDENT> Pop = ("xpath",".//*[@id='inner-container']/div[2]/ng-switch/div/div/div/div[1]/div/div/div/button[2]") <NEW_LINE> self.P.pop_out(Pop) <NEW_LINE> self.assertEqual(2,len(Pop)) | 测试弹出报表 | 625941ed30c21e258bdfa9d3 |
def similarity(self, word1, word2): <NEW_LINE> <INDENT> aa = self.dot(self.distributional_sims.get(word1, {}), self.distributional_sims.get(word1, {})) <NEW_LINE> ab = self.dot(self.distributional_sims.get(word1, {}), self.distributional_sims.get(word2, {})) <NEW_LINE> bb = self.dot(self.distributional_sims.get(word2, ... | Uses the dot() method to calculate dot products needed for cosine similarity between word1 and word2
:param word1: First word
:param word2: Second word
:return: The dot product | 625941ed5f7d997b87174fcc |
def __iter__(self): <NEW_LINE> <INDENT> return iter(self.root) | Depth first search as the iterator | 625941edcdde0d52a9e53567 |
def pathCount(*args, **kwargs): <NEW_LINE> <INDENT> pass | Returns the number of sub-paths which make up this path. | 625941ed2c8b7c6e89b35cec |
def _clean_identifier_quotes(identifier): <NEW_LINE> <INDENT> clean_identifier = _remove_quote(identifier, '`') <NEW_LINE> if clean_identifier == identifier: <NEW_LINE> <INDENT> clean_identifier = _remove_quote(clean_identifier, '"') <NEW_LINE> <DEDENT> return clean_identifier | Clean the quotes for identifiers.
| 625941ed3346ee7daa2b32a0 |
def test_pos_operate_ordered_increment_nonexistent_key(self): <NEW_LINE> <INDENT> key = ('test', 'demo', "non_existentkey") <NEW_LINE> llist = [{"op": aerospike.OPERATOR_INCR, "bin": "age", "val": 5}] <NEW_LINE> key, _, bins = self.as_connection.operate_ordered(key, llist) <NEW_LINE> assert bins == [None] <NEW_LINE> (k... | Invoke operate_ordered() with increment with nonexistent_key | 625941edd18da76e23532a0d |
def _degrees_to_direction(self, degrees): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> degrees = float(degrees) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if degrees < 0 or degrees > 360: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if degrees <= 11.25 or degrees >... | Convert wind direction from degrees to compass direction. | 625941edfff4ab517eb2f96f |
def getLogViewerContent(self): <NEW_LINE> <INDENT> return self.logViewer.getText() | Provides the log viewer window content as a plain text | 625941ed091ae35668667485 |
def test_thread_required_fields(self): <NEW_LINE> <INDENT> with self.assertRaisesMessage( TypeError, "create_thread() missing 1 required positional argument: 'author_name'", ): <NEW_LINE> <INDENT> _ = self.topic.create_thread(title="Foo") <NEW_LINE> <DEDENT> with self.assertRaisesMessage( TypeError, "create_thread() mi... | Threads require the 'author_name' and 'title' fields. | 625941edcc0a2c11143dd3c1 |
def attr(*args, **kwargs): <NEW_LINE> <INDENT> def decorator(f): <NEW_LINE> <INDENT> if 'type' in kwargs and isinstance(kwargs['type'], str): <NEW_LINE> <INDENT> f = testtools.testcase.attr(kwargs['type'])(f) <NEW_LINE> <DEDENT> elif 'type' in kwargs and isinstance(kwargs['type'], list): <NEW_LINE> <INDENT> for attr in... | A decorator which applies the testtools attr decorator
This decorator applies the testtools.testcase.attr if it is in the list of
attributes to testtools we want to apply. | 625941ed1b99ca400220afe3 |
@decorators.DefineVersions <NEW_LINE> def GetInitialStatus(SplitLine): <NEW_LINE> <INDENT> return int(SplitLine[3]), SplitLine[4] | Function to get ddrescue's initial status. Works with ddrescue versions: 1.14,1.15,1.16,1.17,1.18,1.19,1.20,1.21,1.22 | 625941ed31939e2706e4d392 |
def plot_series( df: pd.DataFrame, sku_dict: dict, fcp_dict: dict, x: str = None, y: str = None ) -> None: <NEW_LINE> <INDENT> groupby = ["SKUID", "ForecastGroupID"] <NEW_LINE> for index in pandas_helpers.get_time_series_combinations(df, groupby): <NEW_LINE> <INDENT> data = pandas_helpers.get_series(df, index) <NEW_LIN... | Creates an individual plot for every time series.
Args:
df (pd.DataFrame): DataFrame to plot
sku_dict (dict): Dictionary with the SKUID as key and the name as value
fcp_dict (dict): Dictionary with the FCP as key and the name as value
x (str): column name of x axis
y (str): column name of y axis | 625941ed4e4d5625662d4900 |
def _check_array(self, array, symbol): <NEW_LINE> <INDENT> for i in array: <NEW_LINE> <INDENT> if i != symbol: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Return True if every element of the array == symbol
False otherwise | 625941edac7a0e7691ed45f2 |
def variances(t, modes, **kwargs): <NEW_LINE> <INDENT> return moments(t, modes, order=2, centered=True, normalized=False, **kwargs) | Convenience function for the second centered unnormalized moment (see :func: `moments`) | 625941ed5fc7496912cc3ead |
def get_fields(model, name_filter_list=None, attr_func=lambda x: x, filt_func=lambda x: x.verbose_name): <NEW_LINE> <INDENT> if name_filter_list is None: <NEW_LINE> <INDENT> return [attr_func(f) for f in model._meta.fields] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [attr_func(f) for f in get_fields(model) if... | helper function to return model fields | 625941ed01c39578d7e7536b |
@click.command() <NEW_LINE> @click.option('--dry-run', is_flag=True) <NEW_LINE> @click.option('--flavor', default=None, help='The flavor to use') <NEW_LINE> @click.option('--interactive', is_flag=True) <NEW_LINE> @click.option('--debug', is_flag=True, help='Do not use multiprocessing (which breaks pdb).') <NEW_LINE> de... | Pull down tasks from forges and add them to your taskwarrior tasks.
Relies on configuration in bugwarriorrc | 625941ed71ff763f4b549bc5 |
def create_dock_panes(self): <NEW_LINE> <INDENT> browser = PythonScriptBrowserPane() <NEW_LINE> handler = lambda _: self._open_file(browser.selected_file) <NEW_LINE> browser.observe(handler, "activated") <NEW_LINE> return [browser] | Create the file browser and connect to its double click event.
| 625941ede76e3b2f99f3ad32 |
def rangeGen(data, std=1): <NEW_LINE> <INDENT> dataStd = np.std(data) <NEW_LINE> if dataStd==0: <NEW_LINE> <INDENT> dataStd=1 <NEW_LINE> <DEDENT> minval = np.min(data) - std * dataStd <NEW_LINE> maxval = np.max(data) + std * dataStd <NEW_LINE> return minval, maxval | Return reasonable min/max values to use given the data. | 625941ed711fe17d8254288f |
def run_problem(sudoku: Board, algorithm_class: module_problem_base_class, seed: int, difficulty: difficulties, printing: bool, log_name=None): <NEW_LINE> <INDENT> if log_name is None: <NEW_LINE> <INDENT> log_name = get_log_file_name(algorithm_class.__name__) <NEW_LINE> <DEDENT> algorithm = algorithm_class(sudoku, seed... | Runs the given algorithm and returns the sudoku problem.
:param log_name: log file name
:param seed: seed value
:param sudoku: the sudoku board
:param printing: Bool value if the pages should be printed
:param algorithm_class: the class of the algorithm to use
:param difficulty: the difficulty of the problem specified ... | 625941ed4e696a04525c997d |
def test_update_comment(self): <NEW_LINE> <INDENT> pass | Test case for update_comment
Updates a Comment of a Requirement | 625941ed92d797404e3046bd |
def check_jboss_status(self): <NEW_LINE> <INDENT> processes = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE).communicate()[0].split("\n") <NEW_LINE> for process in processes: <NEW_LINE> <INDENT> if self.ps in process: <NEW_LINE> <INDENT> return process | Check ps -ef for jboss
return result
:return String: | 625941ed5fdd1c0f98dc0765 |
def convert_exchange_objects(elements: List[int]) -> List[int]: <NEW_LINE> <INDENT> pass | Convert exchange objects to cadwork elements
Args:
elements (List[int]): element IDs
Returns:
List[int]: converted elements | 625941edbe383301e01b59ab |
def to_legacy_filter_properties_dict(self): <NEW_LINE> <INDENT> filt_props = {} <NEW_LINE> if self.obj_attr_is_set('ignore_hosts') and self.ignore_hosts: <NEW_LINE> <INDENT> filt_props['ignore_hosts'] = self.ignore_hosts <NEW_LINE> <DEDENT> if self.obj_attr_is_set('force_hosts') and self.force_hosts: <NEW_LINE> <INDENT... | Returns a legacy filter_properties dict from the RequestSpec object.
Since we need to manage backwards compatibility and rolling upgrades
within our RPC API, we need to accept to provide an helper for
primitiving the right RequestSpec object into a legacy dict until we
drop support for old Scheduler RPC API versions.
... | 625941ed91af0d3eaac9bf4e |
@app.route('/api/login/', methods=['POST']) <NEW_LINE> def login(): <NEW_LINE> <INDENT> user_to_login = json.loads(request.data) <NEW_LINE> username = user_to_login.get("login") <NEW_LINE> password = user_to_login.get("password") <NEW_LINE> user = api.get_user(username, password) <NEW_LINE> if user: <NEW_LINE> <INDENT>... | Login the current user. | 625941edec188e330fd5acc4 |
def square(x): <NEW_LINE> <INDENT> return x * x | Returns the square of a number
>>> square(5)
25
>>> square(10)
100
>>> square(-7)
49
>>> square(0)
0 | 625941ed851cf427c661aa3a |
def test_cmfs(self): <NEW_LINE> <INDENT> self.assertIs(self._tree.cmfs, self._cmfs) | Test :attr:`colour.recovery.otsu2018.Tree_Otsu2018.cmfs` property. | 625941ed7b25080760e39986 |
def _get_next_acq(self): <NEW_LINE> <INDENT> if self.options.acq_probs == 'adaptive': <NEW_LINE> <INDENT> self.acq_probs = self._get_adaptive_ensemble_acq_probs() <NEW_LINE> <DEDENT> ret = np.random.choice(self.acqs_to_use, p=self.acq_probs) <NEW_LINE> return ret | Gets the acquisition to use in the current iteration. | 625941edab23a570cc2506b7 |
def print_clue_scrolls(author): <NEW_LINE> <INDENT> out = f'{CLUE_HEADER}' <NEW_LINE> for clue in author.clue_counts: <NEW_LINE> <INDENT> out += f'**{clue[0].title()}**: {clue[1]}\n' <NEW_LINE> <DEDENT> return out | Prints the number of clues a user has completed. | 625941edcc0a2c11143dd3c2 |
def form_valid(self, form): <NEW_LINE> <INDENT> messages.success(self.request, 'Your new account has been created.') <NEW_LINE> return super().form_valid(form) | Display a flash message that the account has been created. | 625941edb830903b967e9e35 |
def bisim2(a, b, normalized=True): <NEW_LINE> <INDENT> pad_symbol = "-" <NEW_LINE> n = 2 <NEW_LINE> m = [] <NEW_LINE> la = len(a) + 1 <NEW_LINE> lb = len(b) + 1 <NEW_LINE> s_a = it.chain((pad_symbol,) * (n - 1), a) <NEW_LINE> s_a = it.chain(s_a, (pad_symbol,) * (n - 1)) <NEW_LINE> s_a = list(s_a) <NEW_LINE> count = max... | Computes bigram similarity "the comprehensive version".
Notes
-----
Computes the
number of common 1-grams between two n-grams. | 625941ed1b99ca400220afe4 |
def test_company_details_resolved(self): <NEW_LINE> <INDENT> url = reverse('vendor:company_details', kwargs={'pk': 1}) <NEW_LINE> self.assertEquals( resolve(url).func.view_class, views.CompanyDetails) | Test company details url | 625941ed5f7d997b87174fcd |
@hydra.main(config_path="conf", config_name="simulate") <NEW_LINE> def simulate(cfg): <NEW_LINE> <INDENT> from mocasin.tasks.simulate import simulate <NEW_LINE> simulate(cfg) | Replay traces to simulate the execution of a dataflow application on a
given platform | 625941ed9b70327d1c4e1308 |
def check_fonts(app_configs=None, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> render_size("DejaVu Sans", Pango.Weight.NORMAL, 11, 0, "test") <NEW_LINE> return [] <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> return [ Critical( "Failed to use Pango: {}".format(error), hint=get_doc_url("a... | Checks font rendering. | 625941ede64d504609d74d70 |
def red(s): <NEW_LINE> <INDENT> return '\033[91m{}\033[0m'.format(s) | Decorates the specified string with character codes for red text.
:param s: Text to decorate with color codes.
:return: String containing original text wrapped with color character codes. | 625941ed23e79379d52eea8d |
def __init__(self): <NEW_LINE> <INDENT> super(EventsQueue, self).__init__() <NEW_LINE> self.count = 0 | Initialize parameters of the events queue. | 625941ed97e22403b379d4cc |
def supports_srcrev(self): <NEW_LINE> <INDENT> return False | The fetcher supports auto source revisions (SRCREV) | 625941ed55399d3f05588be8 |
def convierte_ascii(c): <NEW_LINE> <INDENT> return (unicodedata.normalize('NFD', c.decode('utf8')) .encode('ascii', 'ignore')) | Convierte c a una cadena que únicamente contiene
caracteres ASCII.
Convierte caracteres con acento, diéresis o tilde al
carácter simple correspondiente. Elimina cualquier otro
carácter que no sea ASCII. | 625941ed3539df3088e2e87c |
def frequency(gene_seq): <NEW_LINE> <INDENT> from collections import Counter <NEW_LINE> assert validate_seq(gene_seq), 'Invalid gene sequence' <NEW_LINE> gene_counts = Counter(gene_seq) <NEW_LINE> gene_counts = {i:j for i,j in sorted(gene_counts.items(), key=lambda x: x[0])} <NEW_LINE> return gene_counts | This counts the number of AGTC in the gene_seq
| 625941ed94891a1f4081bfdc |
def bootstrap(self): <NEW_LINE> <INDENT> pass | Implement this method in order to manipulate the configuration
paths, e.g.. | 625941ed3c8af77a43ae3cd7 |
@click.command() <NEW_LINE> @click.argument('file_path', type=click.Path(dir_okay=False, file_okay=True, exists=True, path_type=pathlib.Path)) <NEW_LINE> @click.argument('save_path', type=click.Path(dir_okay=True, file_okay=False, path_type=pathlib.Path)) <NEW_LINE> def parse_shakespeare_cmd( file_path: pathlib.Path, s... | Read the Project Gutenberg "The Complete Works of William Shakespeare"
text and save it into the desired directory structure for testing.
This program will not overwrite existing data in SAVE_PATH--generally,
you should delete the contents before running this program.
FILE_PATH: path to the "The Complete Works of Will... | 625941ed4d74a7450ccd46f5 |
def date_from_string(s): <NEW_LINE> <INDENT> return datetime.datetime.strptime(s, '%Y-%m-%d') | Get datetime from string.
:param s: String in format YYYY-mm-dd
:returns: Datetime | 625941ed01c39578d7e7536c |
def test_log_send_empty(self): <NEW_LINE> <INDENT> self.logger.open_test_case( self.some_test_case_id, name=self.some_test_case_name, index=self.some_test_case_index ) <NEW_LINE> self.logger.log_send(b"") <NEW_LINE> self.virtual_file.seek(0) <NEW_LINE> six.assertRegex( self, self.virtual_file.readline(), LOGGER_PREAMBL... | Given: FuzzLoggerCsv with a virtual file handle.
When: Calling open_test_case with some test_case_id.
and: Calling log_send with an empty buffer.
Then: log_send logs with zero-length data. | 625941ed24f1403a92601092 |
def rewrite_links (self, f): <NEW_LINE> <INDENT> for chunk in self.chunks: <NEW_LINE> <INDENT> for link in xpath (chunk['chunk'], '//xhtml:*[@href]'): <NEW_LINE> <INDENT> url = link.get ('href') <NEW_LINE> if not url.startswith('http://') and not url.startswith('https://'): <NEW_LINE> <INDENT> link.set ('href', f (url)... | Rewrite all href and src using f (). | 625941edf548e778e58cdab0 |
def testFilesystemAssetstore(self): <NEW_LINE> <INDENT> self.assetstore = self.model('assetstore').getCurrent() <NEW_LINE> root = self.assetstore['root'] <NEW_LINE> shutil.rmtree(root) <NEW_LINE> tmpdir = os.path.join(root, 'temp') <NEW_LINE> if os.path.isdir(tmpdir): <NEW_LINE> <INDENT> for tempname in os.listdir(tmpd... | Test usage of the Filesystem assetstore type. | 625941ed44b2445a339325c2 |
def all(self): <NEW_LINE> <INDENT> request_url = build_url_endpoint(self.ENDPOINT, self.context) <NEW_LINE> request_params = dict(self.request_params) <NEW_LINE> result = self.do_http_request( "get", request_url, data=request_params, custom_header=self.custom_header, timeout=self.timeout, ) <NEW_LINE> if result.status_... | This method retrieve an iterator with all the available types.
return: iterator of crossref document types
Example:
>>> from crossref.restful import Types
>>> types = Types()
>>> [i for i in types.all()]
[{'label': 'Book Section', 'id': 'book-section'},
{'label': 'Monograph', 'id': 'monograph'},
... | 625941ed9c8ee82313fbbca8 |
def addFileAnnot(self, point, buffer, filename, ufilename=None, desc=None, icon=None): <NEW_LINE> <INDENT> CheckParent(self) <NEW_LINE> if not self.parent.isPDF: <NEW_LINE> <INDENT> raise ValueError("not a PDF") <NEW_LINE> <DEDENT> val = _fitz.Page_addFileAnnot(self, point, buffer, filename, ufilename, desc, icon) <NEW... | Add a 'FileAttachment' annotation at location 'point'. | 625941edd10714528d60021a |
def connection(status): <NEW_LINE> <INDENT> if status not in ['init', 'established', 'off']: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> return {u'action': 'connection', u'status': status} | Possible 'status' values:
init
established
off | 625941ede5267d203edce1c6 |
def supportsTilting(self): <NEW_LINE> <INDENT> return self._supportsTilting | Return whether tilting is supported by this engine.
@rtype: bool | 625941edc4546d3d9de72f69 |
def write_train_files2(src, dest, g): <NEW_LINE> <INDENT> g = float(g) <NEW_LINE> if os.path.isdir(dest): <NEW_LINE> <INDENT> print('removing dir: %s... ' % (dest), end='') <NEW_LINE> shutil.rmtree(dest) <NEW_LINE> print('done') <NEW_LINE> <DEDENT> print('creating dir: %s... ' % (dest), end='') <NEW_LINE> os.makedirs('... | Write training files mixing positive and negative
examples according to the g ratio.
Positive examples will be draw not only from the pool of positives
examples retrieved for the specified class, but also from positive
examples appearin gin the train set of the other classes.
Keyword arguments:
src -- the src dir
des... | 625941edd8ef3951e3243a6e |
def set_data(self, data): <NEW_LINE> <INDENT> assert data.shape == self.shape, "data should be an array of the same shape as Mask" <NEW_LINE> assert data.dtype == bool, "data should be an array of data type bool" <NEW_LINE> self.data = data | User callable method to set "custom" Mask.data
Yes, the burden is on the user to set the data, but, be creative!
:param data: 2D numpy.array of the same size as Mask.data, and of data type bool;
The Boolean matrix that will define the mask | 625941ed5166f23b2e1a568a |
def init_axes(self): <NEW_LINE> <INDENT> axes = vtk.vtkAxesActor() <NEW_LINE> axes.SetTotalLength(50, 50, 50) <NEW_LINE> widget = vtk.vtkOrientationMarkerWidget() <NEW_LINE> widget.SetOutlineColor(0.9300, 0.5700, 0.1300) <NEW_LINE> widget.SetOrientationMarker(axes) <NEW_LINE> widget.SetInteractor(self.renderWindowInter... | Initialize a small axes widget | 625941ede5267d203edce1c7 |
def mock_purge_orphaned_health_monitor( self, target=None, call_cnt=1, static=None, expected_args=None, **kwargs): <NEW_LINE> <INDENT> if not target: <NEW_LINE> <INDENT> target = self.new_fully_mocked_target() <NEW_LINE> <DEDENT> self._mockfactory(target, 'purge_orphaned_health_monitor', static, call_cnt, expected_args... | Mocks iControlDriver.purge_orphaned_health_monitor | 625941edf9cc0f698b140b27 |
def _construct_project_name(self): <NEW_LINE> <INDENT> if self.signup_type == "organisation": <NEW_LINE> <INDENT> project_name = str(slugify(self.company_name)) <NEW_LINE> <DEDENT> elif self.signup_type == "individual": <NEW_LINE> <INDENT> project_name = str(slugify(self.name)) <NEW_LINE> <DEDENT> return project_name | Construct Name to match our convention.
The name needs to be a lowercase slug "[^0-9a-z_-]" | 625941ed45492302aab5e7f9 |
def polyDuplicateAndConnect(removeOriginalFromShaders=bool, renameChildren=bool): <NEW_LINE> <INDENT> pass | polyDuplicateAndConnect is undoable, NOT queryable, and NOT editable.
This command duplicates the input polygonal object, connects up the outMesh attribute of the original polygonal shape to the inMesh attribute of the newly created duplicate shape and copies over the shader assignments from the original... | 625941ed8e7ae83300e4b4ff |
def setUp(self): <NEW_LINE> <INDENT> num_samples = 10 <NEW_LINE> self.lam_domain = np.array([[.0, .1]]) <NEW_LINE> edges = np.linspace(self.lam_domain[:, 0], self.lam_domain[:, 1], num_samples + 1) <NEW_LINE> self.samples = (edges[1:] + edges[:-1]) * .5 <NEW_LINE> np.random.shuffle(self.samples) <NEW_LINE> self.volume_... | Test dimension, number of samples, and that all the samples are within
lambda_domain. | 625941ed851cf427c661aa3b |
def create_admin_api_client(access_token): <NEW_LINE> <INDENT> api_client = ApiClient( host=DS_CONFIG["admin_api_client_host"], header_name="Authorization", header_value=f"Bearer {access_token}" ) <NEW_LINE> return api_client | Create API client and construct API headers | 625941edd7e4931a7ee9e450 |
def main(): <NEW_LINE> <INDENT> if 'dump' in os.listdir(): <NEW_LINE> <INDENT> print("dump folder is already defined. Files in it will be overwritten.\n") <NEW_LINE> answer = input("Do you wish to delete dump folder? [Y/N]\n") <NEW_LINE> while answer is not "Y" or "N": <NEW_LINE> <INDENT> answer = input("Input is not v... | TODO: Docstring for main.
:returns: TODO | 625941ed56ac1b37e62646f5 |
def show_transaction_history(*args): <NEW_LINE> <INDENT> account_id = args[0] if len(args) else None <NEW_LINE> history = list() <NEW_LINE> if account_id is None: <NEW_LINE> <INDENT> history = bank.history <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> check_context() <NEW_LINE> history = context.get_account_history(acc... | [account_id:str]
Show transaction history for bank/account | 625941ed44b2445a339325c3 |
def parse_value(self, key, value): <NEW_LINE> <INDENT> if super(Inventory, self).parse_value(key, value): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif key == 'index.count': <NEW_LINE> <INDENT> self.index_count = int(value) <NEW_LINE> return <NEW_LINE> <DEDENT> parts = key.split('.') <NEW_LINE> if parts[0][:5] ==... | Parse values
Parses inventory file values | 625941ed596a897236089fea |
def load_config(): <NEW_LINE> <INDENT> with open('config.json') as f: <NEW_LINE> <INDENT> return json.load(f) | Load and return the config from file. | 625941ed56b00c62f0f14b8d |
def test_string(self): <NEW_LINE> <INDENT> message = 'hello' <NEW_LINE> self.assertEqual(util.pack(message), struct.pack('>l5s', 5, message)) | Give it a low-ball test | 625941ed5510c4643540f907 |
def setup_axes2(fig, rect): <NEW_LINE> <INDENT> tr = PolarAxes.PolarTransform() <NEW_LINE> pi = np.pi <NEW_LINE> angle_ticks = [(0, r"0"), (.25*pi, r"45"), (.5*pi, r"90"),(.75*pi, r"135")] <NEW_LINE> grid_locator1 = FixedLocator([v for v, s in angle_ticks]) <NEW_LINE> tick_formatter1 = DictFormatter(dict(angle_ticks)) ... | With custom locator and formatter.
Note that the extreme values are swapped. | 625941ed45492302aab5e7fa |
def __init__(self, iterator): <NEW_LINE> <INDENT> self.iterator = iterator <NEW_LINE> self.peak = self.iterator.next() if self.iterator.hasNext() else None | Initialize your data structure here.
:type iterator: Iterator | 625941ed0c0af96317bb8718 |
def _make_dict_from_args(func, args): <NEW_LINE> <INDENT> args_keys = {} <NEW_LINE> for i, arg in enumerate(inspect.getargspec(func)[0]): <NEW_LINE> <INDENT> if arg not in ("self", "request"): <NEW_LINE> <INDENT> args_keys[arg] = args[i] <NEW_LINE> <DEDENT> <DEDENT> return args_keys | Inspects function for name of args | 625941eda4f1c619b28b055d |
def time_weighted_sound_level(pressure, sample_frequency, integration_time, reference_pressure=REFERENCE_PRESSURE): <NEW_LINE> <INDENT> levels = 10.0 * np.log10( integrate(pressure**2.0, sample_frequency, integration_time) / reference_pressure**2.0) <NEW_LINE> times = np.arange(levels.shape[-1]) * integration_time <NEW... | Time-weighted sound pressure level.
:param pressure: Dynamic pressure.
:param sample_frequency: Sample frequency.
:param integration_time: Integration time.
:param reference_pressure: Reference pressure. | 625941ed4e4d5625662d4901 |
def logAges(ages_common, round_f=5): <NEW_LINE> <INDENT> age_vals_all = np.round(np.log10(list(map(float, ages_common))), round_f) <NEW_LINE> sort_i = np.argsort(age_vals_all) <NEW_LINE> age_vals_all = age_vals_all[sort_i] <NEW_LINE> ages_strs = np.array(ages_common)[sort_i].astype(str) <NEW_LINE> return age_vals_all, ... | Convert ages to log10() and sort from min to max. | 625941edbe383301e01b59ac |
def del_node(self, node): <NEW_LINE> <INDENT> for edge in self.node_store[node].copy(): <NEW_LINE> <INDENT> self.del_edge(edge) <NEW_LINE> <DEDENT> del self.node_store[node] <NEW_LINE> del self.attribute_store[node] <NEW_LINE> self.commit() | delete node
Args:
node: node object that is a member of the graph, to be deleted | 625941eda05bb46b383ecd4d |
def verify_input(user): <NEW_LINE> <INDENT> if user == 'r': <NEW_LINE> <INDENT> print("Your Choice: %s "%CHOISE[0]) <NEW_LINE> <DEDENT> elif user == 'p': <NEW_LINE> <INDENT> print("Your Choice: %s "%CHOISE[1]) <NEW_LINE> <DEDENT> elif user == 's': <NEW_LINE> <INDENT> print("Your Choice: %s "%CHOISE[2]) | Check USER input | 625941ed8a349b6b435e86a3 |
def albus_method(tx, version = '1.0'): <NEW_LINE> <INDENT> def deco(fun): <NEW_LINE> <INDENT> def real_fun(self, *args, **kwargs): <NEW_LINE> <INDENT> uri = self.locator.locate(tx) <NEW_LINE> service = HessianProxy(uri, timeout=self.timeout) <NEW_LINE> res = service.invoke(Object('net.butfly.bus.Request', tx=tx, versio... | This decorator indicates that an instance-method
of a class is an Albus method.
`tx` : name of the remote method. may be different to local name.
`version` : desired protocol version of remote interface. | 625941edd6c5a10208144580 |
def _apply_event(self, event: rfxtrxmod.RFXtrxEvent): <NEW_LINE> <INDENT> assert isinstance(event, rfxtrxmod.ControlEvent) <NEW_LINE> super()._apply_event(event) <NEW_LINE> if event.values["Command"] in COMMAND_ON_LIST: <NEW_LINE> <INDENT> self._state = True <NEW_LINE> <DEDENT> elif event.values["Command"] in COMMAND_O... | Apply command from rfxtrx. | 625941ed656771135c3ebda6 |
def __init__(self, step_index=None, node_step_hash=None, interaction_description=None, damage_type_hash=None, can_activate_next_step=None, next_step_index=None, is_next_step_random=None, perk_hashes=None, start_progression_bar_at_progress=None, stat_hashes=None, affects_quality=None, affects_level=None, socket_replacem... | DestinyDefinitionsDestinyNodeStepDefinition - a model defined in Swagger | 625941ed099cdd3c635f1189 |
def test_viewlets(self): <NEW_LINE> <INDENT> expected = {'title_description_with_link': ['Title with description', 'title_description_with_link'], 'link_viewlet': ['Link Only', 'link_viewlet'], 'title_viewlet': ['Title', 'title_viewlet'], 'fragment_viewlet': ['HTML Fragment', 'fragment_viewlet'], 'title_date_viewlet': ... | This tests the viewlets registered in this tool. Normally 9
viewlets are created and we know what to expect as id, title and
skin_method for each one of them, so let's be thorough in testing. | 625941edc432627299f0517b |
def remaining_time_multiprocessing(self): <NEW_LINE> <INDENT> if (self.end_times is None) or (self.num_received == 0): <NEW_LINE> <INDENT> return 2 * self.elapsed_time() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> expected_per_job = self.end_times[self.num_received] / self.num_received <NEW_LINE> return expected_per_... | Return our best estimate of the remaining duration, or None
if we have no bases for guessing. | 625941edab23a570cc2506b8 |
def testLoggerLevels(self): <NEW_LINE> <INDENT> logging = Logger() <NEW_LINE> for level in range(len(logging.LEVELS)): <NEW_LINE> <INDENT> testString = "Test logging level" <NEW_LINE> logging.setLogLevel(level) <NEW_LINE> logging.log(level, testString) | _testLoggerLevels_
Just test logger levels and if correct message is printed | 625941eda8ecb033257d35fc |
def update_vertex(self, vertex_id, attributes): <NEW_LINE> <INDENT> url = "{0}/graph/vertex/{1}".format(self.rest_url, vertex_id) <NEW_LINE> payload = {} <NEW_LINE> for key in attributes: <NEW_LINE> <INDENT> payload[key] = [attributes[key]] <NEW_LINE> <DEDENT> update_payload = {'attributes': payload} <NEW_LINE> logging... | Update vertex_id object with specified attributes | 625941edcad5886f8bd27509 |
def get_status(self): <NEW_LINE> <INDENT> percentage = (self.content['current'] + 1) * 100.0 / self.content['no_chunks'] <NEW_LINE> return {'current': self.content['current'], 'total': self.content['no_chunks'], 'percentage': percentage, 'comments': self.__count_comments()} | Get the status, consisting of the current, total, percentage and
number of comments. NOTE current is reported zero based and it is up
to the GUI to change it for representation purposes | 625941ed187af65679ca5651 |
def compared_to(self,other,regex=False,ignore_defaults=False,attnames=None): <NEW_LINE> <INDENT> logging.info("Called compared_to") <NEW_LINE> logging.info("other.__class__ %s " % other.__class__) <NEW_LINE> logging.info("regex %s" % regex) <NEW_LINE> logging.info("ignore_defaults %s" % ignore_defaults) <NEW_LINE> logg... | @brief Compares only attributes of self by default
@param other The other object to compare to this object
@param regex A regex to use in the comparison
@param ignore_defaults
@param attnames | 625941ed0a50d4780f6673c8 |
def add_vm_ethernet_ports(self): <NEW_LINE> <INDENT> for i in range(self.node['properties']['adapters']): <NEW_LINE> <INDENT> port = {'id': self.port_id, 'name': 'Ethernet%s' % i, 'port_number': i} <NEW_LINE> self.node['ports'].append(port) <NEW_LINE> self.port_id += 1 | Add ethernet ports to Virtualbox and Qemu nodes | 625941ed29b78933be1e5bd7 |
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app(configure="testing") <NEW_LINE> self.client = self.app.test_client() <NEW_LINE> self.app_context = self.app.app_context() <NEW_LINE> self.app_context.push() <NEW_LINE> self.data = { "location" : "fhkdhf", "description" :"hdshgh" } <NEW_LINE> self.data2 = { "loc... | Set up test application. | 625941eda17c0f6771cbe580 |
@click.command() <NEW_LINE> @click.argument('full_name') <NEW_LINE> def repository(full_name): <NEW_LINE> <INDENT> session = db.get_session() <NEW_LINE> try: <NEW_LINE> <INDENT> repository = session.query(Repository) .filter(Repository.full_name == full_name) .one() <NEW_LINE> commit_shas = sessio... | Delete a specific repository. | 625941ed97e22403b379d4cd |
def add_dirichlet_noise(self, action_indices: List[Column], children_priorities: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> valid_children_priorities = children_priorities[action_indices] <NEW_LINE> dchl = np.random.dirichlet(np.zeros([len(valid_children_priorities)], dtype=np.float32) + 192) <NEW_LINE> valid_child... | Adds dirchlet noise for more exploration -> Research ws suggesting this is necessary
@param action_indices:
@param children_priorities:
@return: | 625941ed5510c4643540f908 |
@error_context.context_aware <NEW_LINE> def run(test, params, env): <NEW_LINE> <INDENT> def create_cdroms(cdrom_test): <NEW_LINE> <INDENT> test.log.info("creating test cdrom") <NEW_LINE> process.run("dd if=/dev/urandom of=test bs=10M count=1") <NEW_LINE> process.run("mkisofs -o %s test" % cdrom_test) <NEW_LINE> process... | QEMU boot from device:
1) Start guest from device
ide-hd/virtio-blk/scsi-hd/usb-storage
ide-cd/scsi-cd
2) Check the boot result
:param test: QEMU test object
:param params: Dictionary with the test parameters
:param env: Dictionary with test environment. | 625941eddc8b845886cb5a68 |
def __endog__(self, endog, p): <NEW_LINE> <INDENT> if self.is_spark_df == True: <NEW_LINE> <INDENT> Y = self.data[endog].astype('float64', errors = 'ignore') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Y = self.data[endog] <NEW_LINE> <DEDENT> for i in endog: <NEW_LINE> <INDENT> for j in range(p): <NEW_LINE> <INDENT> ... | Internal function trying to convert endog matrix into modeling form
Parameters:
-----------
endog : list
All endog variable names
k is the number of parameters
p : int,
Number of lags need to be included in VAR estimation
p is the number of lags
Returns
-------
Y : ndarray T * (kp)
A d... | 625941edf9cc0f698b140b28 |
def dmfilled(shape, fillval=0, dtype=None, order='C', attrs=None): <NEW_LINE> <INDENT> a = dmarray(numpy.empty(shape, dtype, order), attrs=attrs) <NEW_LINE> a.fill(fillval) <NEW_LINE> return a | Return a new dmarray of given shape and type, filled with a specified value (default=0).
See Also
--------
numpy.ones
Examples
--------
>>> import spacepy.datamodel as dm
>>> dm.dmfilled(5, attrs={'units': 'nT'})
dmarray([ 0., 0., 0., 0., 0.])
>>> dm.dmfilled((5,), fillval=1, dtype=np.int)
dmarray([1, 1, 1, 1, 1... | 625941edbe7bc26dc91cdb27 |
def test_404_custom_message(self): <NEW_LINE> <INDENT> @nice_json <NEW_LINE> def error_function(): <NEW_LINE> <INDENT> raise NotFound("Could not find the Grail!") <NEW_LINE> <DEDENT> response = error_function() <NEW_LINE> self.assertEqual( {'data': None, 'status': 404, 'error': "Could not find the Grail!"}, response.js... | Test that if the decorated function throws a NotFound error with a
specified message, a JSON response of status 404 is returned with
'error' set to the custom message. | 625941ed85dfad0860c3b38e |
def testStrangleCalcProfitLossWithDataUpdateBuyingStrangle(self): <NEW_LINE> <INDENT> putOpt = put.Put(underlyingTicker='SPX', underlyingPrice=decimal.Decimal(2786.24), strikePrice=decimal.Decimal(2690), dateTime=datetime.datetime.strptime('01/01/2021', "%m/%d/%Y"), expirationDateTime=datetime.datetime.strptime('01/20/... | Tests that the profit / loss is calculated correctly when buying a strangle. | 625941edcad5886f8bd2750a |
def status(self, ignored=False, clean=False): <NEW_LINE> <INDENT> stat = self._parsestatus(self._repo.status(change=strtobytes(self), ignored=ignored, clean=clean)) <NEW_LINE> self._unknown = self._ignored = self._clean = None <NEW_LINE> if ignored: <NEW_LINE> <INDENT> self._ignored = stat[5] <NEW_LINE> <DEDENT> if cle... | Explicit status query
Unless this method is used to query the working copy status, the
_status property will implicitly read the status using its default
arguments. | 625941edac7a0e7691ed45f3 |
@pytest.mark.parametrize("backward", ["sample", "precondition"]) <NEW_LINE> def test_ffb_4(backward): <NEW_LINE> <INDENT> num_samples = int(1e5) <NEW_LINE> factors = { "a": random_gaussian(OrderedDict({"a": Real})), "b": random_gaussian(OrderedDict({"b": Real})), "c": random_gaussian(OrderedDict({"i": Bint[2], "a": Rea... | def model(data):
a = pyro.sample("a", dist.Normal(0, 1))
b = pyro.sample("b", dist.Normal(0, 1))
with pyro.plate("i", 2):
c = pyro.sample("c", dist.Normal(a, 1))
d = pyro.sample("d", dist.Normal(b, 1))
with pyro.plate("j", 3):
pyro.sample("e", dist.Normal(c, d.exp()), obs... | 625941ed23849d37ff7b35bc |
def add_artist(self, a): <NEW_LINE> <INDENT> a.axes = self <NEW_LINE> self.artists.append(a) <NEW_LINE> self._set_artist_props(a) <NEW_LINE> a.set_clip_path(self.patch) <NEW_LINE> a._remove_method = lambda h: self.artists.remove(h) <NEW_LINE> self.stale = True <NEW_LINE> return a | Add any :class:`~matplotlib.artist.Artist` to the axes.
Use `add_artist` only for artists for which there is no dedicated
"add" method; and if necessary, use a method such as
`update_datalim` or `update_datalim_numerix` to manually update the
dataLim if the artist is to be included in autoscaling.
Returns the artist. | 625941ed3d592f4c4ed1d590 |
def RegisterCallback(self, callback_func): <NEW_LINE> <INDENT> if self.GetCallbackId(callback_func): <NEW_LINE> <INDENT> raise CallbackServerError("Function is already registered") <NEW_LINE> <DEDENT> id = 0 <NEW_LINE> if _functions: <NEW_LINE> <INDENT> id = int(max(_functions, key=int)) + 1 <NEW_LINE> <DEDENT> _functi... | Registers a callback function.
Args:
callback_func: The function to register.
Returns:
string, Id of the registered callback function.
Raises:
CallbackServerError is raised if the func_id is already registered. | 625941ed30bbd722463cc2fb |
@lru_cache(maxsize=128) <NEW_LINE> def naive_primality_test(n): <NEW_LINE> <INDENT> return (n > 2) and (n % 2 != 0) and all(n % i for i in range(3, int(sqrt(n))+1, 2)) | Returns true iff n is a prime number | 625941edd18da76e23532a0e |
def test_profiles_table_populated(self): <NEW_LINE> <INDENT> print('(' + self.test_profiles_table_populated.__name__ + ')', self.test_profiles_table_populated.__doc__) <NEW_LINE> test_table_populated(self, USERS_PROFILE_TABLE, INITIAL_USERS_PROFILE_COUNT) | Check that the users_profile table has been populated with default data successfully.
| 625941ed627d3e7fe0d69383 |
def _collect_slots(self): <NEW_LINE> <INDENT> self.__slots = deepcopy(self._slots_) <NEW_LINE> parents = self.__class__.__mro__ <NEW_LINE> for parent in reversed(parents): <NEW_LINE> <INDENT> if parent not in (self.__class__, object, type): <NEW_LINE> <INDENT> self.__slots.update(parent._slots_) <NEW_LINE> for slot_att... | Агрегация слотов от своих предков | 625941edd7e4931a7ee9e451 |
def convert2csv(self, save_path, category_list=[]): <NEW_LINE> <INDENT> header = [ 'file_name', 'width', 'height', 'category', 'xmin', 'ymin', 'xmax', 'ymax' ] <NEW_LINE> xmls_list = sorted(glob.glob(os.path.join(self.dir, '*.xml'))) <NEW_LINE> logger.info(f"Find {len(xmls_list)} xmls") <NEW_LINE> assert '.csv' == save... | find all bndbox info and save to csv file. If category_list exist, only save
the categories in list.
Arguments:
save_path: a csv file path.
category_list: a list for keep category to save.
Raises:
AssertionError: the save path not a csv file path. | 625941ed7d847024c06be7f2 |
def test_update_attempt_without_credit_state(self): <NEW_LINE> <INDENT> exam_attempt = self._create_started_exam_attempt() <NEW_LINE> set_runtime_service('credit', MockCreditServiceNone()) <NEW_LINE> new_attempt = update_attempt_status( exam_attempt.proctored_exam_id, self.user.id, ProctoredExamStudentAttemptStatus.ver... | Test updating an attempt that does not have a corresponding credit state. | 625941edb5575c28eb68e537 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.