code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_double_spend(self): <NEW_LINE> <INDENT> self.sync_all() <NEW_LINE> self.split_network() <NEW_LINE> utxos = self.nodes[2].listunspent() <NEW_LINE> utxo = utxos[0] <NEW_LINE> privkey = self.nodes[2].dumpprivkey(utxo['address']) <NEW_LINE> self.nodes[1].importprivkey(privkey) <NEW_LINE> change = '%.8f' % (float(u... | This tests the case where the same UTXO is spent twice on two separate
blocks as part of a reorg.
ab0
/ aa1 [tx1] bb1 [tx2]
| |
aa2 bb2
| |
aa3 bb3
|
bb4
Problematic case:
1. User 1 receives IOP in tx1 from utxo1 in block aa1.
2. U... | 625941debaa26c4b54cb1457 |
def addImport(self, node): <NEW_LINE> <INDENT> self.imports.append(node) | Adds an import statement to this scope's import list.
This is called by DeclarationVisitor. Import statements can't be processed until the
declaration analysis has visited the entire AST. processImports should be called for
every scope after that. | 625941de099cdd3c635f0f94 |
def random_binary(size, prob): <NEW_LINE> <INDENT> binaries = [] <NEW_LINE> for _ in range(size): <NEW_LINE> <INDENT> binaries.append(fake.boolean(chance_of_getting_true=prob)) <NEW_LINE> <DEDENT> return binaries | Generate a set of random binary variables | 625941de796e427e537b0902 |
def save_samples(self): <NEW_LINE> <INDENT> self.straditizer().update_samples_sep(remove=False) | Save the samples to the :attr:`straditizer` without removing them | 625941deab23a570cc2504bf |
def test_help(): <NEW_LINE> <INDENT> assert run(["rm", "-h"]).stdout.split(" ")[0] == "Usage:" <NEW_LINE> assert run(["rm", "--help"]).stdout.split(" ")[0] == "Usage:" <NEW_LINE> assert run(["rm", "-h"]).returncode > 0 <NEW_LINE> assert run(["rm", "--help"]).returncode > 0 | Passing -h or --help => print help text. | 625941dedc8b845886cb5871 |
def save2db(temp, humid): <NEW_LINE> <INDENT> conn = sqlite3.connect("/home/abhpi/rht03/db.sqlite3") <NEW_LINE> c = conn.cursor() <NEW_LINE> now = time.time() <NEW_LINE> c.execute("INSERT INTO Measurements VALUES ({}, {}, {})".format(now, temp, humid)) <NEW_LINE> conn.commit() <NEW_LINE> conn.close() | takes 'temp' fleat and 'humid'float and saves to sqlite3 db | 625941decc40096d61595c8a |
def print_stats(self, num_dirs): <NEW_LINE> <INDENT> if self.stats.genres: <NEW_LINE> <INDENT> genres = self.stats.genres.most_common() <NEW_LINE> print("\n%d different genres used this often:" % len(genres)) <NEW_LINE> print(tag_display(genres)) <NEW_LINE> <DEDENT> if self.conf.args.release and self.stats.reltyps: <NE... | Print some statistics. | 625941def8510a7c17cf9a39 |
def valid(self, invalidation_time: Optional[timedelta]) -> bool: <NEW_LINE> <INDENT> age = datetime.utcnow() - self._authenticated <NEW_LINE> return age <= (invalidation_time or timedelta(0)) | Whether a user's authentication has been temporally invalidated
@param invalidation_time Cache invalidation duration (timedelta; None for no caching)
@return Validity status (boolean) | 625941de76e4537e8c3519af |
def mousePressEvent(self, e): <NEW_LINE> <INDENT> click_point = QtCore.QPoint(e.pos().x(), e.pos().y()) <NEW_LINE> pos = self.mapToScene(click_point) <NEW_LINE> self.start_x = pos.x() <NEW_LINE> self.start_y = pos.y() <NEW_LINE> if self.pov_mode == True and self.draw_type == 'PIX': <NEW_LINE> <INDENT> self.drawInPov(po... | mousePressEvent(self, e) -> None.
Handles a mousepressEvent - reimplemented from default.
Key parameters:
e -- the event which contains information as to the location
of the click.
Does not return. | 625941def7d966606f6aa343 |
def _find_huc(source, shply, crs, hint): <NEW_LINE> <INDENT> logging.debug('searching: %s'%hint) <NEW_LINE> hint_level = len(hint) <NEW_LINE> search_level = hint_level + 2 <NEW_LINE> if search_level > source.lowest_level: <NEW_LINE> <INDENT> return hint <NEW_LINE> <DEDENT> profile, subhus = source.get_hucs(hint, search... | Searches in hint to find shp. | 625941de7d847024c06be5fa |
def test_CategoriesDelete(self): <NEW_LINE> <INDENT> trans1 = DebitsCredits.objects.create(account=self.account, currency=self.euro, name="Shopping", amount=1, category=self.cat1) <NEW_LINE> self.cat1.delete() <NEW_LINE> self.assertEqual(self.cat1.active, False) <NEW_LINE> trans1.delete() <NEW_LINE> self.assertEqual(se... | Try to delete a Category. If it has transaction, is just disable to keep trace, and if not, is delete. | 625941de498bea3a759b9de9 |
def handle_operation(self, message, client=False): <NEW_LINE> <INDENT> self.active_peer = self.get_peer(message) <NEW_LINE> if client: <NEW_LINE> <INDENT> operation = TextOperation(message["operation"]) <NEW_LINE> self.apply_client(operation) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if message["src_id"] == self.ma... | Forwards the operation message to the correct handler based on whether it
was sent by the client or server | 625941de71ff763f4b5499cc |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'retail_billing.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 y... | Run administrative tasks. | 625941de956e5f7376d711a7 |
def get_by_custom_id(self, custom_id): <NEW_LINE> <INDENT> if not custom_id: <NEW_LINE> <INDENT> raise ValueError("Invalid custom_id parameter") <NEW_LINE> <DEDENT> collection = self.search(query="customId==" + custom_id) <NEW_LINE> collection.populate(offset=0, limit=1) <NEW_LINE> if not len(collection): <NEW_LINE> <I... | Gets an invoice using its custom_id
@param custom_id:str Custom ID of the invoice to retrieve | 625941de23e79379d52ee89b |
def _annotate(ax, annotate, height, left, width): <NEW_LINE> <INDENT> annotate_yrange_factor = 0.010 <NEW_LINE> xticks = np.array(left) + width / 2.0 <NEW_LINE> ymin, ymax = ax.get_ylim() <NEW_LINE> yrange = ymax - ymin <NEW_LINE> if ymax > 0: <NEW_LINE> <INDENT> ymax += yrange * 0.15 <NEW_LINE> <DEDENT> if ymin < 0: <... | Annotate axis with labels.
| 625941de30c21e258bdfa7da |
def _file_path(): <NEW_LINE> <INDENT> file_path = os.environ.get('PGPASSFILE', _default_path()) <NEW_LINE> if not path.exists(file_path): <NEW_LINE> <INDENT> raise FileNotFound(file_path) <NEW_LINE> <DEDENT> if platform.system() != 'Windows': <NEW_LINE> <INDENT> s = os.stat(file_path) <NEW_LINE> if ((s.st_mode & stat.S... | Return the path to the Password file, checking first for the value of
the PGPASSFILE environment variable, falling back to ``.pgpass`` in the
user's home directory.
On Microsoft Windows, it is assumed that the file is stored in a directory
that is secure, so no special permissions check is made.
:return: str
:raises:... | 625941debd1bec0571d90969 |
def backup_file(self, filename): <NEW_LINE> <INDENT> from shutil import copy2 <NEW_LINE> if not path.exists(filename): <NEW_LINE> <INDENT> msg = "File to be backed up was not found: {}".format(filename) <NEW_LINE> logging.error(msg) <NEW_LINE> raise Exception(msg) <NEW_LINE> return "" <NEW_LINE> <DEDENT> version_number... | Make a copy of the file and give it a suffix plus version number
:param filename: Full path to the file
:type filename: string
:return: New file name or '' if unsuccessful
:rtype: bool | 625941de16aa5153ce3627b3 |
def test_delete_account_authenticated(self): <NEW_LINE> <INDENT> self._require_login() <NEW_LINE> new_user = Account.objects.create_user(username="test2", email='test2@test.com', password='testing') <NEW_LINE> url = reverse('account-detail', args=[new_user.pk]) <NEW_LINE> response = self.client.delete(url) <NEW_LINE> s... | Trying to delete an account with an other account | 625941de4c3428357757c661 |
@profiler.benchmark(field='Computation') <NEW_LINE> def accumulate_data(dataset, size): <NEW_LINE> <INDENT> nmc = dataset.shape[0] <NEW_LINE> mat = np.zeros((nmc * (size + 1), nmc * (size + 1))) <NEW_LINE> for mc in range(nmc): <NEW_LINE> <INDENT> mat += np.outer(dataset[mc], dataset[mc]) <NEW_LINE> <DEDENT> return mat | Accumulate random vectors into a matrix.
Parameters
-----------
* dataset: 2D array, (nmc, nmc * (size + 1)) array
containing your measurements.
* size: int, boost factor to expand the size of our vector | 625941de6e29344779a6294b |
def add_tab(self, tab, title='', icon=None): <NEW_LINE> <INDENT> if icon: <NEW_LINE> <INDENT> tab._icon = icon <NEW_LINE> <DEDENT> if not hasattr(tab, 'clones'): <NEW_LINE> <INDENT> tab.clones = [] <NEW_LINE> <DEDENT> if not hasattr(tab, 'original'): <NEW_LINE> <INDENT> tab.original = None <NEW_LINE> <DEDENT> if icon: ... | Adds a tab to main tab widget.
:param tab: Widget to add as a new tab of the main tab widget.
:param title: Tab title
:param icon: Tab icon | 625941de2c8b7c6e89b35afa |
def get_hostname(): <NEW_LINE> <INDENT> host = uname()[1] <NEW_LINE> return "%s.%s" % (host[0], host) | Work out the current hostname | 625941dede87d2750b8600d0 |
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): <NEW_LINE> <INDENT> if system == "win32": <NEW_LINE> <INDENT> if appauthor is None: <NEW_LINE> <INDENT> appauthor = appname <NEW_LINE> <DEDENT> path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) <NEW_LINE> if appname: <NEW_LIN... | Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning ... | 625941de7b25080760e39793 |
def get_user_hostname(): <NEW_LINE> <INDENT> sys_info = dict() <NEW_LINE> sys_info['user'] = getuser() <NEW_LINE> sys_info['hostname'] = gethostname() <NEW_LINE> sys_info['ip'] = get('https://api.ipify.org').text <NEW_LINE> os_name = uname() <NEW_LINE> sys_info['os'] = f"{os_name[0]} {os_name[2]} {os_name[3]}" <NEW_LIN... | Retrieve user, hostname, IP, and OS configuration
:return sys_info: dictionary with 'user' 'hostname' and 'ip' dictionary | 625941de5fcc89381b1e19fc |
def CapsNet(input_shape, n_class, routings, primary_capsules=16, number_of_primary_channels=32, digit_capsules=16): <NEW_LINE> <INDENT> x = keras.layers.Input(shape=input_shape) <NEW_LINE> conv1 = keras.layers.Conv2D(filters=256, kernel_size=5, strides=2, padding='valid', name='conv1', kernel_regularizer=keras.regulari... | A Capsule Network on FER2013.
:param input_shape: data shape, 3d, [width, height, channels]
:param n_class: number of classes
:param routings: number of routing iterations
:return: Two Keras Models, the first one used for training, and the second one for evaluation.
`eval_model` can also be used for training. | 625941de046cf37aa974d080 |
def serve(host, port): <NEW_LINE> <INDENT> command_to_run_server = "gunicorn -b {host}:{port} py_google_auth.app:app".format( host=host, port=port) <NEW_LINE> subprocess.call(command_to_run_server, shell=True) | Function to run the server. | 625941de507cdc57c630701d |
def test_type_xhtml(self): <NEW_LINE> <INDENT> self.assert_selector( self.wrap_xhtml(self.MARKUP), "tag", ["2"], flags=util.XHTML ) <NEW_LINE> self.assert_selector( self.wrap_xhtml(self.MARKUP), "Tag", ["1"], flags=util.XHTML ) <NEW_LINE> self.assert_selector( self.wrap_xhtml(self.MARKUP), "TAG", ["3"], flags=util.XHTM... | Test type for XHTML. | 625941de21bff66bcd684c8a |
def changeAttribute(self, obj, attribute, new_value): <NEW_LINE> <INDENT> obj_before_modification = Snapshot(obj, providing=providedBy(obj)) <NEW_LINE> if attribute == 'duplicateof': <NEW_LINE> <INDENT> obj.markAsDuplicate(new_value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(obj, attribute, new_value) <NEW_... | Set the value of `attribute` on `obj` to `new_value`.
:return: The value of `attribute` before modification. | 625941deec188e330fd5aad4 |
def gen_match_set(Pop: list, perception: list): <NEW_LINE> <INDENT> m = [] <NEW_LINE> action = [False] * 4 <NEW_LINE> while True: <NEW_LINE> <INDENT> m = [] <NEW_LINE> for cl in Pop: <NEW_LINE> <INDENT> if does_match(cl, perception): <NEW_LINE> <INDENT> m.append(cl) <NEW_LINE> action[cl.action] = True <NEW_LINE> <DEDEN... | :param Pop:
:param perception:
:return: list | 625941de96565a6dacc8fa06 |
def __init__(self, module_filename, module_name, docindex=None, url_func=None, name_to_docs=None, tab_width=8): <NEW_LINE> <INDENT> try: module_filename = py_src_filename(module_filename) <NEW_LINE> except: pass <NEW_LINE> self.module_filename = module_filename <NEW_LINE> self.module_name = module_name <NEW_LINE> self.... | Create a new HTML colorizer for the specified module.
@param module_filename: The name of the file containing the
module; its text will be loaded from this file.
@param module_name: The dotted name of the module; this will
be used to create links back into the API source
documentation. | 625941de60cbc95b062c687e |
@document_it <NEW_LINE> @square_it <NEW_LINE> def add_ints1(add_a, add_b): <NEW_LINE> <INDENT> return add_a + add_b | add with decrator of @square_it @document_it in order. | 625941dee76e3b2f99f3ab42 |
def compare(self, f1_name, f2_name, bins1 = 5, bins2 = 5): <NEW_LINE> <INDENT> if isinstance(bins1, int): <NEW_LINE> <INDENT> f1_bins = qcut(self.trade_df[f1_name], bins1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f1_bins = cut(self.trade_df[f1_name], bins1) <NEW_LINE> <DEDENT> if isinstance(bins2, int): <NEW_LINE>... | Provides a matrix comparing mean, std dev, and count for each combination of filter
values. Note only the first type of each filter is considered. | 625941deb545ff76a8914151 |
def get_formats(data_class=None): <NEW_LINE> <INDENT> from ..table import Table <NEW_LINE> format_classes = sorted(set(_readers) | set(_writers), key=lambda tup: tup[0]) <NEW_LINE> rows = [] <NEW_LINE> for format_class in format_classes: <NEW_LINE> <INDENT> if (data_class is not None and not _is_best_match(data_class, ... | Get the list of registered I/O formats as a Table.
Parameters
----------
data_class : classobj
Filter readers/writer to match data class (default = all classes)
Returns
-------
format_table: Table
Table of available I/O formats | 625941de004d5f362079a66d |
def add_station(self, station, order=None): <NEW_LINE> <INDENT> if order is None: <NEW_LINE> <INDENT> agg = self.links.aggregate(max_order=models.Max('order')) <NEW_LINE> order = agg['max_order'] is not None and agg['max_order'] + 1 or 0 <NEW_LINE> <DEDENT> return RatpLink.objects.create(line=self, station=station, ord... | Add a station to this line
Append when no order given | 625941deeab8aa0e5d26de94 |
def _more_precision(self): <NEW_LINE> <INDENT> AlgebraicNumber_base._more_precision(self) <NEW_LINE> self._ensure_real() | Recompute the interval bounding this number with higher-precision
interval arithmetic.
EXAMPLES::
sage: a = QQbar(sqrt(2))
sage: a._more_precision()
TESTS:
We have to ensure after doing this that self._value is still
real which is not the case without calling _ensure_real (see
:trac:`11728`)::
sage: P ... | 625941de45492302aab5e602 |
def get_start_end_year(df, column='period'): <NEW_LINE> <INDENT> if not isinstance(df, pd.DataFrame): <NEW_LINE> <INDENT> raise TypeError('input should be DataFrame, got {} instead'.format(type(df))) <NEW_LINE> <DEDENT> if not isinstance(column, str): <NEW_LINE> <INDENT> raise TypeError('input should be string, got {} ... | Function to return start and end year to dataframe
Args:
df: A with tables from generate_gemeente_tables_info
column: A column within the dataframe that identifies the time active for each table
Returns:
df with two new columns, 'start_year' and 'end_year', in pd.datetime format | 625941dede87d2750b8600d1 |
def _get_tmat_from_euler_dt(abgxyz): <NEW_LINE> <INDENT> a = abgxyz[0] <NEW_LINE> b = abgxyz[1] <NEW_LINE> g = abgxyz[2] <NEW_LINE> dx = abgxyz[3] <NEW_LINE> dy = abgxyz[4] <NEW_LINE> dz = abgxyz[5] <NEW_LINE> tmat = np.array([ [np.cos(a)*np.cos(b), (np.cos(a)*np.sin(b)*np.sin(g))-(np.sin(a)*np.cos(g)), (np.cos(a)*np.s... | abgxyz is a 6 valued vector: Alpha_yaw, Beta_pitch, Gamma_roll, DeltaX, DeltaY, DeltaZ
Output is a 3x4 tmat
For rotation matrix:
http://planning.cs.uiuc.edu/node102.html
For Translation side:
dX, dY, dZ are last column | 625941de097d151d1a223193 |
def test_structure_json(self): <NEW_LINE> <INDENT> course_id = 'a/b/c' <NEW_LINE> structure = { 'root': course_id, 'blocks': { course_id: { 'id': course_id } } } <NEW_LINE> structure_json = json.dumps(structure) <NEW_LINE> structure = CourseStructure.objects.create(course_id=self.course.id, structure_json=structure_jso... | Although stored as compressed data, CourseStructure.structure_json should always return the uncompressed string. | 625941deaad79263cf390d81 |
def read(self): <NEW_LINE> <INDENT> pass | Reads value of configured GPIO pin.
:return: 1 or 0 | 625941debde94217f3683129 |
def get_stellar_part(self, sed_or_cube, fit_stellar=False, fit_dust=False, full=False): <NEW_LINE> <INDENT> import traceback <NEW_LINE> log.warning("The get_stellar_part function in its current form should NOT be used for science results and only for comparisons, as it is very inacurrate") <NEW_LINE> log.warning("This ... | This function ...
:param sed_or_cube:
:param fit_stellar: improve the accuracy by fitting a smooth function to the stellar part of the SED (or cube pixels)
:param fit_dust: improve the accuracy by fitting a smooth function (MBB) to the dust part of the SED (or cube pixels), and subtracting this from the total
:param fu... | 625941de4c3428357757c662 |
def testQuoteviewGetAuthenticated(self): <NEW_LINE> <INDENT> self.client.login(username='samuel', password='testing') <NEW_LINE> response = self.client.get(reverse('pub_quote', args=[1])) <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> self.assertEquals(type(response.context[-1]['quote_form']), type(... | Ensures the quote view works properly with a GET when authenticated | 625941ded8ef3951e3243879 |
@app.route("/api/posts/<int:id>", methods=["PUT"]) <NEW_LINE> @decorators.accept("application/json") <NEW_LINE> @decorators.require("application/json") <NEW_LINE> def post_put(id): <NEW_LINE> <INDENT> post = session.query(models.Post).get(id) <NEW_LINE> if not post: <NEW_LINE> <INDENT> message = "Could not find post wi... | Update an existing post | 625941de656771135c3ebbae |
def _handleMouseClick(self, modelIndex): <NEW_LINE> <INDENT> _logger.debug('self._handleMouseClick called') <NEW_LINE> if self.__lastButton not in [qt.Qt.LeftButton, qt.Qt.RightButton]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not modelIndex.isValid(): <NEW_LINE> <INDENT> _logger.debug('_handleMouseClick -- In... | Distinguish between mouse click on Legend
and mouse click on CheckBox by setting the
currentCheckState attribute in LegendListItem.
Emits signal sigLegendSignal(ddict)
:param QModelIndex modelIndex: index of the clicked item | 625941dea219f33f34628ca1 |
def zvalues( zs=4.0, z0=0.0, nz=100 ): <NEW_LINE> <INDENT> dz = (zs - z0)/nz <NEW_LINE> return np.arange( z0, zs+dz, dz ) | Creates an np.array of z values between z0 and zs [unitless]
zs=4.0, z0=0.0, nz=100 | 625941deb7558d58953c524a |
def test_177(self): <NEW_LINE> <INDENT> input = r"""__count in function""" <NEW_LINE> output = r"""Error Token _""" <NEW_LINE> self.assertTrue(TestLexer.checkLexeme(input,output,177)) | Created automatically | 625941de30bbd722463cc103 |
def IDFT(X): <NEW_LINE> <INDENT> x=np.array([]) <NEW_LINE> N=np.size(X) <NEW_LINE> for k in np.arange(N): <NEW_LINE> <INDENT> x=np.append(x, sum(X * genNCComplexSine(k, N))/(1.0 * N)) <NEW_LINE> <DEDENT> return (x) | Input:
X (numpy array) = frequency spectrum (length N)
Output:
The function should return a numpy array of length N
x (numpy array) = The N point IDFT of the frequency spectrum X | 625941de7d43ff24873a2fde |
def _get_lines_order(self): <NEW_LINE> <INDENT> return [ ('date', 'ASC') ] | Return the order on which the lines to reconcile will be returned | 625941de379a373c97cfae82 |
def trim_features(df, min_sample_frac, val=None): <NEW_LINE> <INDENT> print('eliminate features that appear in less than {0:.0f}% of ' 'samples'.format(min_sample_frac*100)) <NEW_LINE> counts = df.astype(bool).sum(axis=0) <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> counts_val = val.astype(bool).sum(axis=0) <NEW_... | trim features that appear less than n times.
If validation data is provided, include that data so there are more samples
that can count, but also a larger total expected number of samples. | 625941de50485f2cf553d0d7 |
def telnet_User(self, user): <NEW_LINE> <INDENT> self.username = user <NEW_LINE> self.write(IAC + WILL + ECHO + b"password: ") <NEW_LINE> return "Password" | I take a username, set it to the 'self.username' attribute,
print out a password prompt, and switch to 'Password' mode. If
you want to do something else when the username is received (ie,
create a new user if the user doesn't exist), override me. | 625941dea934411ee37519d0 |
def _test_args(): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> return { 'start': pd.Timestamp('2013-10-07', tz='utc'), 'end': pd.Timestamp('2013-11-30', tz='utc'), 'capital_base': 100000, } | Extra arguments to use when gateway's automated tests run this example.
Notes for testers:
Gross leverage should be roughly 2.0 on every day except the first.
Net leverage should be roughly 2.0 on every day except the first.
Longs Count should always be 3 after the first day.
Shorts Count should be 3 after the first... | 625941de8e7ae83300e4b309 |
@test_context <NEW_LINE> def test_check_pending_upload_not_expired(app): <NEW_LINE> <INDENT> with app.app_context(), set_time(): <NEW_LINE> <INDENT> expires = time.now() + timedelta(seconds=10) <NEW_LINE> pu_row, file_row = add_pending_upload_and_file_row( len(DATA), DATA_DIGEST, expires, 'us-west-2') <NEW_LINE> sessio... | check_pending_upload doesn't check anything if the URL isn't expired yet | 625941de7047854f462a1742 |
def display(self): <NEW_LINE> <INDENT> self.window.erase() <NEW_LINE> self.window.addstr(0, 0, "p = Edit commit, c = Checkout, R = Revert, h or ? for more options", curses.color_pair(3)) <NEW_LINE> for idx, item in enumerate(self.items[self.top:self.top + self.max_lines]): <NEW_LINE> <INDENT> if idx == self.current: <... | Display the items on window | 625941de30c21e258bdfa7db |
def test_create_category(self): <NEW_LINE> <INDENT> set_credentials(self.client) <NEW_LINE> response = create_category(self.client) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_201_CREATED) <NEW_LINE> self.assertEqual(Category.objects.count(), 1) <NEW_LINE> self.assertEqual(Category.objects.get(name='F... | Ensure we can create a new Category object. | 625941de32920d7e50b2850f |
def register_resource_links_extender(config: Configurator, adapter, resource_class): <NEW_LINE> <INDENT> config.registry.registerAdapter(adapter, required=resource_class, provided=IHalResourceLinks) | Add into the pyramid registry an adapter for extend resource links.
:param config: A pyramid configurator.
:param adapter: Some callable object (takes only resource instance) which implements IResourceLinks.
:param resource_class: Class or interface of resource which links will be extended by adapter. | 625941de97e22403b379d2d7 |
def update_accumulator(self, container): <NEW_LINE> <INDENT> new_quantity = container.state['quantity'] * self.factor <NEW_LINE> container.state['price'] = average_price( container.state['quantity'], container.state['price'], new_quantity, 0 ) <NEW_LINE> container.state['quantity'] += new_quantity | Add stocks received as bonus shares do the accumulator. | 625941deeab8aa0e5d26de95 |
def test_new_user_normalized(self): <NEW_LINE> <INDENT> email = 'test@GMAIL.COM' <NEW_LINE> user = get_user_model().objects.create_user(email,'test123') <NEW_LINE> self.assertEqual(user.email,email.lower()) | test the email for a new user is normalized | 625941de8a349b6b435e84af |
def make_absolute_paths(config): <NEW_LINE> <INDENT> if not 'streamcorpus_pipeline' in config: <NEW_LINE> <INDENT> logger.critical('bad config: %r', config) <NEW_LINE> raise ConfigurationError('missing "streamcorpus_pipeline" from config') <NEW_LINE> <DEDENT> root_path = config['streamcorpus_pipeline'].pop('root_path',... | given a config dict with streamcorpus_pipeline as a key, find all
keys under streamcorpus_pipeline that end with "_path" and if the
value of that key is a relative path, convert it to an absolute
path using the value provided by root_path | 625941dedc8b845886cb5872 |
def _parse_bulk_params(params): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for recording in params.split(";"): <NEW_LINE> <INDENT> parts = str(recording).split(":") <NEW_LINE> mbid = parts[0] <NEW_LINE> if not mbid: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if len(parts) == 1: <NEW_LINE> <INDENT> offset = None <NEW... | Validate and parse a bulk query parameter string.
A valid parameter string takes the form
mbid[:offset];mbid[:offset];...
Where offset is a number >=0. Offsets are optional.
mbid must be a UUID.
If an offset is not specified, is non-numeric, or negative it is replaced with 0.
If an mbid is not valid, an APIBadReque... | 625941dea05bb46b383ecb5b |
def run_length_encoder(msk): <NEW_LINE> <INDENT> y = msk.shape[0] <NEW_LINE> l = sorted([(y * i) + j + 1 for j, i in np.argwhere(msk)]) <NEW_LINE> if l == []: <NEW_LINE> <INDENT> raise ValueError("Something is wrong") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> encoded = [l[0], 1] <NEW_LINE> last = l[0] <NEW_LINE> <D... | Run length encoder function
Args:
msk: 2D mask of one object
Returns:
run length encoded string
Raises:
ValueError if the mask is empty | 625941de91af0d3eaac9bd57 |
def test_reference_2frame_1sample(self): <NEW_LINE> <INDENT> assert (2, 4, 5) == self.ref_2_1.shape <NEW_LINE> assert np.array_equal( self.ref_2_1[0, :, :], np.asarray( [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]] ) ) <NEW_LINE> assert np.array_equal( self.ref_2_1[1, :, :], np.asarray( [[25, 26,... | Test the 2 frame 1 sample/pixel reference array is as expected. | 625941de9f2886367277abc7 |
def __init__(self, pluginManager, parent = None): <NEW_LINE> <INDENT> QDialog.__init__(self, parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.pm = pluginManager <NEW_LINE> self.__autoActivateColumn = 3 <NEW_LINE> self.__activeColumn = 4 <NEW_LINE> self.pluginList.headerItem().setText(self.pluginList.columnCount(),... | Constructor
@param pluginManager reference to the plugin manager object
@param parent parent of this dialog (QWidget) | 625941dec4546d3d9de72d72 |
def semiptc2seret_productsShown(self): <NEW_LINE> <INDENT> if self._productsShown is not None: <NEW_LINE> <INDENT> if len(self._productsShown) > 0: <NEW_LINE> <INDENT> xmpproducts = [] <NEW_LINE> for product in self._productsShown: <NEW_LINE> <INDENT> xmpproduct = {} <NEW_LINE> if product.gtin is not None: <NEW_LINE> <... | Transforms the semantic IPTC property Products Shown in Image to metadata serialized as Exif/IIM/XMP
using ExifTool naming | 625941de85dfad0860c3b198 |
def get_deleted_placeholders_for_object(obj, revision): <NEW_LINE> <INDENT> if object_has_placeholders(obj): <NEW_LINE> <INDENT> placeholders_versions = get_deleted_placeholders(revision) <NEW_LINE> placeholders_pks = [getattr(obj, '{0}_id'.format(field_name)) for field_name in get_placeholder_fields_names(obj) if geta... | Return deleted placeholders for object given | 625941dedd821e528d63b4e3 |
def longestPalindromeSubseq(self, s): <NEW_LINE> <INDENT> if len(s) < 2: <NEW_LINE> <INDENT> return len(s) <NEW_LINE> <DEDENT> dp = [[0 for col in range(len(s))] for row in range(len(s))] <NEW_LINE> for i in range(len(dp)): <NEW_LINE> <INDENT> dp[i][i] = 1 <NEW_LINE> <DEDENT> for length in range(1,len(s)): <NEW_LINE> <... | :type s: str
:rtype: int | 625941de3317a56b86939f8d |
def __call__(self, trainer): <NEW_LINE> <INDENT> observation = trainer.observation <NEW_LINE> summary = self._summary <NEW_LINE> key = self._key <NEW_LINE> if key in observation: <NEW_LINE> <INDENT> summary.add({key: observation[key]}) <NEW_LINE> <DEDENT> if not self._interval_trigger(trainer): <NEW_LINE> <INDENT> retu... | Decides whether the extension should be called on this iteration.
Args:
trainer (~chainer.training.Trainer): Trainer object that this
trigger is associated with. The ``observation`` of this trainer
is used to determine if the trigger should fire.
Returns:
bool: ``True`` if the corresponding ex... | 625941dee1aae11d1e749ff6 |
def culaDeviceSgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt): <NEW_LINE> <INDENT> status = _libcula.culaDeviceSgesvd(jobu, jobvt, m, n, int(a), lda, int(s), int(u), ldu, int(vt), ldvt) <NEW_LINE> culaCheckStatus(status) | SVD decomposition. | 625941dee8904600ed9f226d |
def all_parse_comment_one_page(self, html, movieId): <NEW_LINE> <INDENT> doc = PyQuery(html) <NEW_LINE> title = doc.find('#content > h1:nth-child(1)').text() <NEW_LINE> items = list(doc('div.comment').items()) <NEW_LINE> print("items" , items) <NEW_LINE> length = len(items) <NEW_LINE> print(length) <NEW_LINE> comment_l... | 分析获得的短评页面
:param html:
:return: | 625941ded486a94d0b98e483 |
def rgb_combination(opts, pool, output_img, reference, inputs): <NEW_LINE> <INDENT> from cvastrophoto.util import demosaic <NEW_LINE> from cvastrophoto.image import rgb <NEW_LINE> image = output_img.postprocessed <NEW_LINE> for ch, img in enumerate(align_inputs(opts, pool, reference, inputs[:3])): <NEW_LINE> <INDENT> p... | Combine RGB input channels into a color image | 625941decad5886f8bd27315 |
def lock(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.rpc.lock_configuration() <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> if isinstance(err, RpcError): <NEW_LINE> <INDENT> raise LockError(rsp=err.rsp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise LockError(rsp=JXML.remove_namespa... | Attempts an exclusive lock on the candidate configuration. This
is a non-blocking call.
:returns:
``True`` always when successful
:raises LockError: When the lock cannot be obtained | 625941de956e5f7376d711a8 |
def find_expression(string_to_search, rgx_pattern): <NEW_LINE> <INDENT> if string_to_search: <NEW_LINE> <INDENT> pattern = re.compile(rgx_pattern) <NEW_LINE> match = pattern.search(string_to_search) <NEW_LINE> if match : <NEW_LINE> <INDENT> return match.group() | Returns the first group that matches the rgx_pattern in the string_to_search | 625941de8c3a8732951586fa |
def get_serialized_data(self, obj): <NEW_LINE> <INDENT> return serializers.serialize( self.get_serialization_format(), (obj,), fields = list(self.get_fields_to_serialize()), ) | Returns a string of serialized data for the given obj. | 625941deaad79263cf390d82 |
def generate_death_dict(self): <NEW_LINE> <INDENT> self.death_dict = defaultdict(list) <NEW_LINE> for i in range(self.num_people()): <NEW_LINE> <INDENT> self.death_dict[self.people[i].death_age].append(i) <NEW_LINE> <DEDENT> return True | Generates a new dictionary of death ages based on current
list of People in the Population.
Args:
None.
Returns:
<Boolean> True. | 625941dee64d504609d74b7c |
def np2vector(u=u_z,RF=N): <NEW_LINE> <INDENT> e1,e2,e3 = u[0],u[1],u[2] <NEW_LINE> vec = e1*RF.x + e2*RF.y + e3*RF.z <NEW_LINE> return vec | construct a sympy vector from a 1D numpy array ( len = 3 )
arguments
---------
u: default = array[ 0 , 0 , 0 ], numpy array to convert
RF: default = N, standard CC at origin
returns
-------
sympy.physics.vector.vector.Vector | 625941deab23a570cc2504c1 |
def decorator(model_cls, registration_name=None): <NEW_LINE> <INDENT> model_name = registration_name or default_model_name(model_cls) <NEW_LINE> if model_name in _MODELS: <NEW_LINE> <INDENT> raise LookupError("Model %s already registered." % model_name) <NEW_LINE> <DEDENT> model_cls.REGISTERED_NAME = model_name <NEW_LI... | Registers & returns model_cls or default name.
GANs have alot of caps so we don't use snake_case | 625941de9b70327d1c4e1112 |
def active_logger(): <NEW_LINE> <INDENT> LOGGER = logging.getLogger('pygpssurvey') <NEW_LINE> LOGGER.setLevel(logging.INFO) <NEW_LINE> logging.getLogger('pylink').setLevel(logging.INFO) <NEW_LINE> formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s ') <NEW_LINE> stream_handler = logging.StreamHandler(... | Initialize a speaking logger with stream handler (stderr). | 625941de7d847024c06be5fb |
def set_sections(self, sections): <NEW_LINE> <INDENT> if not isinstance(sections, list): <NEW_LINE> <INDENT> raise TypeError("The sections must be passed as a list.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for s in sections: <NEW_LINE> <INDENT> missing = [] <NEW_LINE> if "path" not in s: <NEW_LINE> <INDENT> miss... | Check if the sections were passed as a valid list.
:param list sections: The data structure that contains the sections info. | 625941de3cc13d1c6d3c76b5 |
def runRelax(simu, conf, dimers, conf_params, stop_params={'contact_ratio': 0.05, 'min_gap': -0.01}): <NEW_LINE> <INDENT> for i in range(2*conf_params['N']): <NEW_LINE> <INDENT> conf.radius[i] *= 1.02 <NEW_LINE> <DEDENT> setupSimu(simu, conf, dimers) <NEW_LINE> simusys = simu.getSys() <NEW_LINE> contact_nb = lfdem.coun... | Generate an initial set of positions/radii that is relaxed up
to small remaining overlaps.
conf_params in a dict of parameters that must contain:
'd', 'N', 'N1', 'rad1', 'rad2', 'lx', 'ly', 'lz'. | 625941de711fe17d825426a1 |
def ExpectedEnginesToBuild(self, run_params): <NEW_LINE> <INDENT> return ["TRTEngineOp_0", "TRTEngineOp_1", "TRTEngineOp_2"] | Return the expected engines to build. | 625941de4e4d5625662d4710 |
def draw_word(canvas, word, pos): <NEW_LINE> <INDENT> box = [pos, [pos[0], pos[1] - ROW_HEIGHT], [pos[0] + COLUMN_WIDTH, pos[1] - ROW_HEIGHT], [pos[0] + COLUMN_WIDTH, pos[1]], pos] <NEW_LINE> canvas.draw_text(word, [pos[0] + 2, pos[1] - 4], FONT_SIZE, "White") <NEW_LINE> canvas.draw_polyline(box, 1, "White") | Helper function to draw word on canvas at given position | 625941defbf16365ca6f6506 |
def set_reference_channel(self, chname): <NEW_LINE> <INDENT> idx = self.chnames.index(str(chname)) <NEW_LINE> self.w.ref_channel.set_index(idx) <NEW_LINE> return self._set_reference_channel(chname) | This is the API call to set the reference channel.
| 625941de287bf620b61d3d9e |
def interpret_2822_date(date_str): <NEW_LINE> <INDENT> components = rfc822.parsedate_tz(date_str) <NEW_LINE> return datetime.date(components[0], components[1], components[2]) | Interpret RFC 2822 date as a datetime.
Interpret a string like "Mon, 05 Jun 2015 19:12:08 -0500" which contains a
RFC 2822 date as a Python native datetime.date.
@param date_str: String to interpret as a date.
@type date_str: basestring
@return: Parsed date from the given string
@rtype: datetime.date | 625941de3cc13d1c6d3c76b6 |
def run_threads(self, simulate=False): <NEW_LINE> <INDENT> logging.debug('Start meta threads') <NEW_LINE> os.chdir(self.bank.config.get('process.dir')) <NEW_LINE> threads = [] <NEW_LINE> running_th = [] <NEW_LINE> for thread_tasks in self.threads_tasks: <NEW_LINE> <INDENT> meta_thread = MetaProcess(self.bank, thread_ta... | Start meta threads
:param simulate: do not execute processes
:type simulate: bool
:return: tuple global execution status and status per meta process | 625941de009cb60464c636ec |
def login(self,user='admin',psw='Li@12345'): <NEW_LINE> <INDENT> self.driver.get(locgin_url) <NEW_LINE> self.input_user(user) <NEW_LINE> self.input_psw(psw) <NEW_LINE> self.click_login_button() | 登陆方法 | 625941de5fc7496912cc3cbb |
def has_integration(self, path, method): <NEW_LINE> <INDENT> method = self._normalize_method_name(method) <NEW_LINE> return self.has_path(path, method) and isinstance(self.paths[path][method], dict) and bool(self.paths[path][method].get(self._X_APIGW_INTEGRATION)) | Checks if an API Gateway integration is already present at the given path/method
:param string path: Path name
:param string method: HTTP method
:return: True, if an API Gateway integration is already present | 625941de7d847024c06be5fc |
def pgrads(self, inputs, deltas, l1_weight=0, l2_weight=0): <NEW_LINE> <INDENT> if inputs.ndim == 4: <NEW_LINE> <INDENT> inputs = inputs.reshape(inputs.shape[0], -1) <NEW_LINE> <DEDENT> l2_W_penalty, l2_b_penalty = 0, 0 <NEW_LINE> if l2_weight > 0: <NEW_LINE> <INDENT> l2_W_penalty = l2_weight*self.W <NEW_LINE> l2_b_pen... | Return gradients w.r.t parameters
:param inputs, input to the i-th layer
:param deltas, deltas computed in bprop stage up to -ith layer
:param kwargs, key-value optional arguments
:return list of grads w.r.t parameters dE/dW and dE/db in *exactly*
the same order as the params are returned by get_params()
Note: ... | 625941de63b5f9789fde7423 |
def __init__(self,BV,nMB,c_a): <NEW_LINE> <INDENT> self.BV=BV <NEW_LINE> self.nMB=nMB <NEW_LINE> self.c_a=c_a | Initialize | 625941dea17c0f6771cbe38c |
def api_view(http_method_names=None, **kwargs): <NEW_LINE> <INDENT> http_method_names = ['GET'] if (http_method_names is None) else http_method_names <NEW_LINE> def decorator(func): <NEW_LINE> <INDENT> WrappedAPIView = type( six.PY3 and 'WrappedAPIView' or b'WrappedAPIView', (APIView,), {'__doc__': func.__doc__} ) <NEW... | Decorator that converts a function-based view into an APIView subclass.
Takes a list of allowed methods for the view as an argument. | 625941de15fb5d323cde0e51 |
def test_get_image_members(self): <NEW_LINE> <INDENT> memb_list = self.client.get_image_members(2) <NEW_LINE> num_members = len(memb_list) <NEW_LINE> self.assertEquals(num_members, 0) | Tests getting image members | 625941defb3f5b602dac39d4 |
def polyMapCut(*args, **kwargs): <NEW_LINE> <INDENT> pass | Cut along edges of the texture mapping. The cut edges become map borders.
Flags:
- caching : cch (bool) [create,edit]
Toggle caching for all attributes so that no recomputation is needed.
- constructionHistory : ch (bool) [create,query]
Turn the construction hi... | 625941de23849d37ff7b33ca |
def add(self, y): <NEW_LINE> <INDENT> if type(y) is not int: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> return self.x + y | Returns the addition result of x and y
:param y: number
:return: x + y | 625941de099cdd3c635f0f97 |
def test_from_proto_creates_rawpoint(self): <NEW_LINE> <INDENT> proto = StatPointProto(time=1,min=2,mean=3,max=4,count=5,stddev=6) <NEW_LINE> point = StatPoint.from_proto(proto) <NEW_LINE> assert isinstance(point, StatPoint) | Assert from_proto creates a new instance of StatPoint | 625941deb57a9660fec33bc5 |
def read(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data, header = fits.getdata(self.filename, header=True) <NEW_LINE> return data, header <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> dbclasses_logger.error('\nERROR: Problem reading image.') | Reads FITS image data and header. | 625941debe8e80087fb20f7b |
def design_members_id_put(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.design_members_id_put_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.design_members_id_put_with_http_... | Replace attributes for a model instance and persist it into the data source.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>... | 625941deb545ff76a8914152 |
def init_engine(self): <NEW_LINE> <INDENT> self._context_change_enabled = False | Called when engine is initialized. | 625941de2c8b7c6e89b35afc |
def _get_team_name(self, team_result): <NEW_LINE> <INDENT> return team_result.rsplit(" ", 1)[0].strip() | Remove the team name portion from the result string. Assumes the name is the section
before the last space.
:param team_result:
:return: | 625941de5fcc89381b1e19fe |
@pytest.fixture(scope='module') <NEW_LINE> def celery_config(): <NEW_LINE> <INDENT> return dict( CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', ) | Celery configuration (defaults to eager tasks).
Scope: module
This fixture provides the default Celery configuration (eager tasks,
in-memory result backend and exception propagation). It can easily be
overwritten in a specific test module:
.. code-block:: python
# test_something.py
import pytest
pytest... | 625941de56b00c62f0f14998 |
def __init__(self, *attributes): <NEW_LINE> <INDENT> self._attributes = tuple(attributes) if attributes else tuple(['url']) | Initialize comparison attributes | 625941ded4950a0f3b08c688 |
def compStats(self, start=None, end=None): <NEW_LINE> <INDENT> if start == None: <NEW_LINE> <INDENT> start = self.execrec <NEW_LINE> <DEDENT> if end == None: <NEW_LINE> <INDENT> rundata = self.data[start:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rundata = self.data[start:end] <NEW_LINE> <DEDENT> self.compZnosesai... | This routine will compute the max/min for each data channel
between start and end times. The values are stored in 4 seperate lists
that can be used by the analysis routines | 625941de2ae34c7f2600d46e |
def all_versions(self, stix_id, _composite_filters=None): <NEW_LINE> <INDENT> results = [] <NEW_LINE> stix_objs_to_filter = None <NEW_LINE> if is_marking(stix_id): <NEW_LINE> <INDENT> stix_obj = self._data.get(stix_id) <NEW_LINE> if stix_obj: <NEW_LINE> <INDENT> stix_objs_to_filter = [stix_obj] <NEW_LINE> <DEDENT> <DED... | Retrieve STIX objects from in-memory dict via STIX ID, all versions
of it.
Args:
stix_id (str): The STIX ID of the STIX 2 object to retrieve.
_composite_filters (FilterSet): collection of filters passed from
the parent CompositeDataSource, not user supplied
Returns:
(list): list of STIX objects th... | 625941de60cbc95b062c6880 |
def paginate(self, request, qs): <NEW_LINE> <INDENT> return Paginator(request, qs, self.limit_per_page) | Paginate queryset.
| 625941ded99f1b3c44c678c7 |
def flag_doublu_day(): <NEW_LINE> <INDENT> now = int(time.time()) <NEW_LINE> t = time.localtime(now) <NEW_LINE> time1 = time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00', t), '%Y-%m-%d %H:%M:%S')) <NEW_LINE> return int(time1/(24*60*60)) % 2 | return 0 or 1 | 625941deec188e330fd5aad6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.