code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def SetCreatedAt(self, date): <NEW_LINE> <INDENT> self._date = date
Set the time this direct message was posted. Args: date: The time this direct message was created
625941ec283ffb24f3c55dfb
@utils.exports <NEW_LINE> def padded_grid(positions, padding, npoints=25): <NEW_LINE> <INDENT> mins = positions.min(axis=0)-padding <NEW_LINE> maxes = positions.max(axis=0)+padding <NEW_LINE> xr = (mins[0], maxes[0]) <NEW_LINE> yr = (mins[1], maxes[1]) <NEW_LINE> zr = (mins[2], maxes[2]) <NEW_LINE> return VolumetricGri...
Creates a 3D, rectangular grid of points surrounding a set of positions The points in the grid are evenly spaced in each dimension, but spacing may differ between in different dimensions. Args: positions (Matrix[shape=(*,3)]): positions to create the grid around padding (Scalar): how far to extend the grid pas...
625941ecad47b63b2c50a47e
def get_identity_dict(): <NEW_LINE> <INDENT> proxy = _get_proxy() <NEW_LINE> addresses = json.loads(proxy.listAddresses2())['addresses'] <NEW_LINE> return _make_lookup(addresses)
Returns a lookup dictionary between BitMessage addresses and labels.
625941ec73bcbd0ca4b2c574
def get_lists(): <NEW_LINE> <INDENT> return INDEX_LIST
A list of the TLG's lists.
625941ec5166f23b2e1a5658
def read_raster_value(dem,band_1,easting,northing): <NEW_LINE> <INDENT> if (np.isnan(easting) or np.isnan(northing)): <NEW_LINE> <INDENT> raise Exception("Easting and northing must not be NaN") <NEW_LINE> <DEDENT> row, col = dem.index(easting,northing) <NEW_LINE> row = int(row) <NEW_LINE> col = int(col) <NEW_LINE> if (...
Read a value in a raster grid given easting/northing Args: dem (rasterio dataset): dem band_1 (numpy array): the band 1 from the DEM easting (float): easting value northing (float): northing value Returns: (float): the value of the band at the specified point
625941ecbe383301e01b597b
def test_create_group_snapshot(self, req): <NEW_LINE> <INDENT> req.side_effect = xms_request <NEW_LINE> d = self.data <NEW_LINE> snapshot_obj = fake_snapshot.fake_snapshot_obj(d.context) <NEW_LINE> snapshot_obj.consistencygroup_id = d.group['id'] <NEW_LINE> self.driver.create_group(d.context, d.group) <NEW_LINE> self.d...
Test create group snapshot.
625941ec7047854f462a1903
def attack(self, other): <NEW_LINE> <INDENT> pass
:param other: 被攻击对象
625941ec2eb69b55b151cdb6
def from_file(self): <NEW_LINE> <INDENT> dump = aapt_command("dump", "badging", self.host_path.__fspath__(), return_output=True, as_list=False) <NEW_LINE> if "error: dump failed" in dump.lower(): <NEW_LINE> <INDENT> unknown = f"Unknown! ({self.host_path.name})" <NEW_LINE> self.app_name = unknown <NEW_LINE> self.display...
Load app data from a local apk file.
625941ec8e05c05ec3eea878
def mark_sensitive(ds, path_glob=None): <NEW_LINE> <INDENT> sens_kwargs = dict( init=[('distribution-restrictions', 'sensitive')] ) <NEW_LINE> if path_glob: <NEW_LINE> <INDENT> paths = glob(op.join(ds.path, path_glob)) <NEW_LINE> if not paths: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> sens_kwargs['path'] = paths <...
Parameters ---------- ds : Dataset to operate on path_glob : str, optional glob of the paths within dataset to work on Returns ------- None
625941eca17c0f6771cbe54e
def gExcel2pdDict(gexcel,sheet_names): <NEW_LINE> <INDENT> all_dict={} <NEW_LINE> for st in sheet_names: <NEW_LINE> <INDENT> tmp_st=gexcel.worksheet(st) <NEW_LINE> tmp_df=gsheet2pandas(tmp_st) <NEW_LINE> all_dict[st]=tmp_df <NEW_LINE> print('Loaded '+str(st)+' successfully') <NEW_LINE> <DEDENT> return all_dict
from Gspread Google Sheet Object, load all the specified tabs as a Python dictionary, similar to Pandas from_excel Uses gsheet2pandas function
625941ecb5575c28eb68e504
def disapprovewitness(self, witnesses, account=None, **kwargs): <NEW_LINE> <INDENT> if not account: <NEW_LINE> <INDENT> if "default_account" in self.config: <NEW_LINE> <INDENT> account = self.config["default_account"] <NEW_LINE> <DEDENT> <DEDENT> if not account: <NEW_LINE> <INDENT> raise ValueError("You need to provide...
Disapprove a witness. :param list witnesses: list of Witness name or id :param str account: (optional) the account to allow access to (defaults to ``default_account``)
625941ec76e4537e8c351b76
def test_bed_code(self): <NEW_LINE> <INDENT> field = self.bed_record.find('field[@name=\'code\']') <NEW_LINE> self.assertEqual(field.text, 'A1', 'Code field incorrect')
Make sure that the code field is correct
625941ec30dc7b7665901e60
def _update_branch(self, git_repo, branch, conanfile, skip_push): <NEW_LINE> <INDENT> git_repo.git.checkout(branch) <NEW_LINE> self.output_remote_update("On branch {}".format(git_repo.active_branch)) <NEW_LINE> try: <NEW_LINE> <INDENT> conanfile = "conanfile.py" if conanfile is None else conanfile <NEW_LINE> result_con...
Update local branch and push to origin :param git_repo: Git repository :param branch: Branch name to be updated :param conanfile: Conan recipe path :param skip_push: Do not push
625941ec3317a56b8693a14b
def parse_www_authenticate_header( value: t.Optional[str], on_update: t.Optional[t.Callable[["ds.WWWAuthenticate"], None]] = None, ) -> "ds.WWWAuthenticate": <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return ds.WWWAuthenticate(on_update=on_update) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> auth_type, auth_...
Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` ...
625941ec090684286d50f1ed
def page_context(self, page_index): <NEW_LINE> <INDENT> return { 'items': self._items_for_page(page_index), 'next': self._get_filename(page_index + 1), 'prev': self._get_filename(page_index - 1), 'file_name': self._get_filename(page_index), }
Return a context dict for the given page index.
625941eca79ad161976cc645
def createPlayer(self): <NEW_LINE> <INDENT> self.players.append( Player(Vector(self.x, self.y, self.z), self.speed, lambda: 3)) <NEW_LINE> return self.players[-1]
Create a L{Player}, recording it in C{self.players}.
625941ec4f6381625f114f3a
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): <NEW_LINE> <INDENT> from torngas.settings_manager import settings <NEW_LINE> if settings.TORNADO_CONF.debug: <NEW_LINE> <INDENT> import inspect <NEW_LINE> assert callable(receiver), "Signal receivers must be callable." <NEW_LINE> try: <NEW_LINE> <I...
Connect receiver to sender for signal. Arguments: receiver A function or an instance method which is to receive signals. Receivers must be hashable objects. If weak is True, then receiver must be weak-referencable (more precisely saferef.safeRef() must be able to create a referenc...
625941ec23e79379d52eea5c
def test_train_split_group_label(df_y, list_train, list_test, list_groups, label_index): <NEW_LINE> <INDENT> num_of_samples = len(list_groups) <NEW_LINE> y_train = get_label_for_list(df_y, list_train, label_index) <NEW_LINE> y_test = get_label_for_list(df_y, list_test, label_index) <NEW_LINE> assert y_train.shape[0] + ...
Groupwise splitting of labels into train and test data. :param df_y: Dataframe of labels. :param list_train: List of case_names for training. :param list_test: List of case_names for testing. :param list_groups: List of case_names in sample order. :param label_index: Index for the label/marker/metric. :return: Arrays f...
625941ecaad79263cf390f48
def get_entity_by_regex(self, cls, regex): <NEW_LINE> <INDENT> return self._get_entity_by_name(cls, self.mor, regex, regex_match)
Recursively search entity by regular expression. :param cls: ManagedObject sub class. :param regex: regular expression to match entity name. :returns: first found entity. None if nothing found.
625941ecd8ef3951e3243a3d
def get_all_available_jobs(): <NEW_LINE> <INDENT> from . import job <NEW_LINE> results = [] <NEW_LINE> for job_class_package in settings.JOB_CLASS_PACKAGES: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> package = importlib.import_module(job_class_package) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> logge...
Returns a list of available jobs info. Looks like this: [ { 'job_class_string': 'myscheduler.jobs.myjob.MyJob', 'arguments': [ {'type': 'string', 'description': 'name of this channel'}, {'type': 'string', 'description': 'what this channel does'}, ...
625941ec596a897236089fb9
def model_random_data(data: Dict[str, Any], figure: Optional[Figure]=None, progress: Optional[Progressbar]=None) -> float: <NEW_LINE> <INDENT> n = int(data.get('time [days]', 1)) <NEW_LINE> ylo1, yhi1 = data.get('n3', -3), data.get('n4', 7) <NEW_LINE> ylo2, yhi2 = data.get('n5', -7), 7 <NEW_LINE> start = time.time() <N...
Implements user-defined model, plots otput on canvas, updates progress bar Args: data: parameter and results of model figure: figure on plotting canvas, contains: .axes and .canvas progress: progress bar, update with: progress['value'] = int/fl...
625941ec91af0d3eaac9bf1d
@simple_pass <NEW_LINE> def parse_args_str(line, strict_parsing=False, arg_extractors=ARG_EXTRACTORS_PRESET): <NEW_LINE> <INDENT> args_str = line.evt_args <NEW_LINE> args_dict = {} <NEW_LINE> while args_str: <NEW_LINE> <INDENT> next_arg_match = _ARG_NAME_REGEX.match(args_str) <NEW_LINE> if not next_arg_match: <NEW_LINE...
Parse log line arguments string in Sysdig log.
625941ec3d592f4c4ed1d55f
def is_ai_dead(self, index): <NEW_LINE> <INDENT> if self.aihealth[index] <= 0: <NEW_LINE> <INDENT> self.ai[index].delete() <NEW_LINE> self.aix[index] = -100 <NEW_LINE> self.aiy[index] = -100 <NEW_LINE> self.aihealth[index] = 0 <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Checks to see if the ai unit is dead or alive
625941ec97e22403b379d49b
def setUpEnv(self): <NEW_LINE> <INDENT> robot = ATRV() <NEW_LINE> motion = MotionVW() <NEW_LINE> robot.append(motion) <NEW_LINE> motion.add_stream('socket') <NEW_LINE> camera = DepthCamera() <NEW_LINE> camera.translate(z = 1) <NEW_LINE> camera.frequency(3) <NEW_LINE> robot.append(camera) <NEW_LINE> camera.add_stream('s...
Defines the test scenario
625941ec7b25080760e39955
def get_influence_history(uid, period=10, reftime=None): <NEW_LINE> <INDENT> today = today_datetime() <NEW_LINE> if reftime and reftime < today: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reftime = today <NEW_LINE> <DEDENT> from_date = reftime - timedelta(period) <NEW_LINE> result = MONGODB_...
获取一个influence历史记录的列表
625941ec6aa9bd52df0372a7
def deal(self, deck): <NEW_LINE> <INDENT> self.hand.append(deck.deal()) <NEW_LINE> self.totalvalue += self._value(self.hand[-1]) <NEW_LINE> if self.hand[-1].startswith('A'): <NEW_LINE> <INDENT> self.acecount +=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return
Appends a new card from deck to hand. This adds the value of new card to total value and adds 1 to acecount for every drawn Ace.
625941ec442bda511e8be910
def _is_paragraph_break(self, line_region, line, pure=False): <NEW_LINE> <INDENT> if self._is_blank_line(line): return True <NEW_LINE> scope_name = self.view.scope_name(line_region.begin()) <NEW_LINE> log(2, 'scope_name=%r %r line=%r', scope_name, line_region, line) <NEW_LINE> if 'heading' in scope_name: <NEW_LINE> <IN...
A paragraph "break" is something like a blank line, or a horizontal line, or anything that should not be wrapped and treated like a blank line (i.e. ignored).
625941ec711fe17d8254285f
def mylen(s1): <NEW_LINE> <INDENT> length = 0 <NEW_LINE> for i in s1: <NEW_LINE> <INDENT> length = length+1 <NEW_LINE> <DEDENT> return length
计算s1的长度
625941ec7b180e01f3dc4cf2
def test_blur(given_image): <NEW_LINE> <INDENT> average = cv2.blur(given_image, (5, 5)) <NEW_LINE> gaussian = cv2.GaussianBlur(given_image, (5, 5), 0) <NEW_LINE> median = cv2.medianBlur(given_image, 5) <NEW_LINE> bilateral = cv2.bilateralFilter(given_image, 9, 75, 75) <NEW_LINE> titles = ['original', 'averaging', 'gaus...
Show 4 types of blurring on given image. :param given_image: original image to be blurred :return: none
625941eccc40096d61595e4e
def weighted_impurity(classes, y_left, y_right): <NEW_LINE> <INDENT> left_impurity = impurity(classes, y_left) <NEW_LINE> right_impurity = impurity(classes, y_right) <NEW_LINE> total_count = len(y_left) + len(y_right) <NEW_LINE> left_count = len(y_left) <NEW_LINE> right_count = len(y_right) <NEW_LINE> return (left_coun...
Weighted entropy impurity for a possible split. :param classes: list of the classes y_left: class labels for the left node in the split y_right: class labels for the right node in the spit :return: A scalar with the weighted entropy
625941ec07d97122c4178d97
def __init__(self, expr, var): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._expr = possibly_parse_literal(expr) <NEW_LINE> self._var = possibly_parse_literal(var) <NEW_LINE> if isinstance(self._var, Value): <NEW_LINE> <INDENT> raise ValueError('Invalid respect to')
Args: expr: The expression to take the derivative of var: The variable (or expression) to take with respect to
625941ecd268445f265b536f
def search(self, queryList): <NEW_LINE> <INDENT> pass
void QHelpSearchEngine.search(list-of-QHelpSearchQuery queryList)
625941ece8904600ed9f2435
def mostrar_instalacao(self): <NEW_LINE> <INDENT> if self.checkBox_luzinclusa.checkState() == 2: <NEW_LINE> <INDENT> self.label_4.setEnabled(True) <NEW_LINE> self.campo_numero_instalacao.setEnabled(True) <NEW_LINE> self.label_3.setEnabled(True) <NEW_LINE> self.CPF_titular.setEnabled(True) <NEW_LINE> <DEDENT> else: <NEW...
VIEW - responsavel por mostrar os itens da parte instalação eletrica
625941ec4f88993c3716c562
def _get(self, metric, *arg): <NEW_LINE> <INDENT> if metric == 'ping': <NEW_LINE> <INDENT> url = arg[0] <NEW_LINE> return self.get_ping(url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise CheckFail("unknown metric: %s" % metric)
Return requested metric
625941ec379a373c97cfb047
def mean_average_precision(predictions_list): <NEW_LINE> <INDENT> return mean(map(average_precision, predictions_list))
Computes the mean average precision of a list of prediction lists. Parameters ---------- predictions_list : list of list of boolean The predictions to measure. Returns ------- out : float The MAP of the predictions.
625941ecbe8e80087fb2113a
def __init__(self): <NEW_LINE> <INDENT> self.nodes = {} <NEW_LINE> self.relations = {} <NEW_LINE> self.edges = []
self.nodes[symbol] = {"positions":[], "predicates":[(predsym, locations)]} self.relations[symbol] = {"positions":[], "predicates":""} self.edges = [(par, dep, lab)]
625941eccc0a2c11143dd391
def usable_rw_dir(directory): <NEW_LINE> <INDENT> if os.path.isdir(directory): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fd, path = tempfile.mkstemp(dir=directory) <NEW_LINE> os.close(fd) <NEW_LINE> os.unlink(path) <NEW_LINE> return True <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT...
Verify whether we can use this dir (read/write). Checks for appropriate permissions, and creates missing dirs as needed. :param directory: Directory
625941ec99fddb7c1c9de88e
def run_action(self, feature, action, run_if_error=False): <NEW_LINE> <INDENT> if len(self._error_dict[feature]) > 0 and not run_if_error: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> instance = self.features[feature] <NEW_LINE> try: <NEW_LINE> <INDENT> result = getattr(instance, action)() <NEW_LINE> if result: <NEW_...
Run an action, and log it's output in case of errors
625941ec656771135c3ebd75
def test_set_encoding(self): <NEW_LINE> <INDENT> self._set_encoding('admin', 'testcases', 'cp1252') <NEW_LINE> self.assertStatus(200) <NEW_LINE> self.assertInBody("Updated") <NEW_LINE> self.assertEqual('cp1252', self.app.store.get_user( self.USERNAME).get_repo(self.REPO).encoding) <NEW_LINE> self._settings('admin', 'te...
Check to update the encoding with cp1252.
625941ec7b25080760e39956
def configure_stac_io(filesystem=None): <NEW_LINE> <INDENT> return CustomIO(filesystem)
Configure PySTAC to read from/write to the provided file system. :param filesystem: `fsspec` compatible file system instance.
625941eca934411ee3751b95
def _build_json(self, row): <NEW_LINE> <INDENT> key, timestamp, exc_type, value, traceback, handlers = row <NEW_LINE> return { 'id': key, 'timestamp': timestamp.strftime('%Y-%m-%d %H:%M:%S'), 'type': exc_type, 'value': value, 'traceback': traceback, 'handlers': json.loads(handlers), }
return a json obj from a row result
625941ecd18da76e235329dc
def train_network(model, criterion, optimizer, loader, validationloader, epoch_number = 3, progress_update = 20, gpu_cpu = 'gpu'): <NEW_LINE> <INDENT> epoch_num = epoch_number <NEW_LINE> steps = 0 <NEW_LINE> check_progress_every = progress_update <NEW_LINE> for e in range(epoch_num): <NEW_LINE> <INDENT> train_loss = 0 ...
input: model, criterion, optimizer, epoch_number (int), progress_update (int), gpu_cpu ('gpu' or 'cpu') output: none
625941ec236d856c2ad44ce1
@app.route("/retrieve", methods=['GET', 'POST']) <NEW_LINE> def retrieve(): <NEW_LINE> <INDENT> platform = app.config['ACCESS_PLATFORM'] <NEW_LINE> ref_data = ReferenceData(platform) <NEW_LINE> channels = ref_data.get_data("channel") <NEW_LINE> return render_template( 'retrieve.html', channels=channels, ark_prefix=app....
Access to the retrieve form
625941ec7cff6e4e81117e85
def get_router_cidrs(self, device): <NEW_LINE> <INDENT> if not self.fip_ns: <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> fip_ns_name = self.fip_ns.get_name() <NEW_LINE> fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) <NEW_LINE> device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) <NE...
As no floatingip will be set on the rfp device. Get floatingip from the route of fip namespace.
625941ecbe8e80087fb2113b
def addBinary(self, a, b): <NEW_LINE> <INDENT> if not a: <NEW_LINE> <INDENT> return b <NEW_LINE> <DEDENT> if not b: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> carry, i, j = 0, len(a) - 1, len(b) - 1 <NEW_LINE> res = [] <NEW_LINE> while i >= 0 or j >= 0 or carry == 1: <NEW_LINE> <INDENT> if i >= 0: <NEW_LINE> <IND...
:type a: str :type b: str :rtype: str
625941ecfb3f5b602dac3b98
def test_cv_coverage_by_split(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> split_data = [] <NEW_LINE> split_data.extend(self.cv_splitter.request_data_for_training(False)) <NEW_LINE> split_data.extend(self.cv_splitter.request_data_for_testing()) <NEW_LINE> for orig_datapoint, orig_label in self.source.time...
Tests that each split during crossvalidation covers the whole data set
625941ecd53ae8145f87a766
def _cancel_email(self, user): <NEW_LINE> <INDENT> portal_title = self.context.title <NEW_LINE> envelope_from = self.context.email_from_address <NEW_LINE> subject = u"{0} Cancelation - [{1}]".format( portal_title, user.getUserName() ) <NEW_LINE> options = dict( fullname=user.getProperty('fullname'), username=user.getUs...
Send an notification message to site support email address when user cancels.
625941ec287bf620b61d3f60
@register_make_test_function() <NEW_LINE> def make_range_tests(options): <NEW_LINE> <INDENT> test_parameters = [{ "dtype": [tf.int32], "offset": [10, 100, 1000], "delta": [1, 2, 3, 4, -1, -2, -3, -4], }] <NEW_LINE> def build_graph(parameters): <NEW_LINE> <INDENT> input_tensor = tf.placeholder( dtype=parameters["dtype"]...
Make a set of tests to do range.
625941ec9c8ee82313fbbc77
def cast(*args): <NEW_LINE> <INDENT> return _itkMaskNegatedImageFilterPython.itkMaskNegatedImageFilterIRGBUS3IUL3IRGBUS3_cast(*args)
cast(itkLightObject obj) -> itkMaskNegatedImageFilterIRGBUS3IUL3IRGBUS3
625941ec3539df3088e2e84b
def lemmatize(words): <NEW_LINE> <INDENT> lem = WordNetLemmatizer() <NEW_LINE> return [lem.lemmatize(word) for word in words]
Lemma conversion
625941ece5267d203edce196
def uninit(self, ): <NEW_LINE> <INDENT> pass
Uninitialize the plugin. Do nothing This function gets called when the plugin is unloaded by the plugin manager. :returns: :rtype: :raises:
625941ec32920d7e50b286d5
def standRegres(xArr,yArr): <NEW_LINE> <INDENT> xMat = np.mat(xArr) <NEW_LINE> yMat = np.mat(yArr).T <NEW_LINE> xTx = xMat.T * xMat <NEW_LINE> if np.linalg.det(xTx) == 0.0: <NEW_LINE> <INDENT> print("矩阵为奇异矩阵,不能求逆") <NEW_LINE> return <NEW_LINE> <DEDENT> ws = xTx.I * (xMat.T*yMat) <NEW_LINE> return ws
Parameters: xArr - x数据集 yArr - y数据集 Returns: ws - 回归系数
625941ec3eb6a72ae02ec9eb
def change_description(self, id, description): <NEW_LINE> <INDENT> pass
Parameters: - id - description
625941ec0383005118ecfae1
def execute_command_line(cmd_list): <NEW_LINE> <INDENT> logger.debug('Executing: %s', ' '.join(cmd_list)) <NEW_LINE> try: <NEW_LINE> <INDENT> subprocess.check_output(cmd_list, stderr=subprocess.STDOUT) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as ex: <NEW_LINE> <INDENT> raise CommandError('Exit code %i: ...
Executes the given command list on the command line :param cmd_list: The list of commands :type cmd_list: list
625941eca8ecb033257d35cb
def test__return_list_brackets(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.obj._return_list_brackets(variant_brackets), list, "Must be list")
We verify the statement that: The _return_list_brackets() method returns of type list
625941ec1b99ca400220afb4
def _F4(self, z): <NEW_LINE> <INDENT> A = self._delta*self._beta1 + self._beta2*self._beta12/self._gamma <NEW_LINE> C = self._beta1*self._beta + A*self._gamma <NEW_LINE> S = - (self._beta1*self._gamma + self._beta*A) <NEW_LINE> denom = (self._beta**2 - self._gamma**2) <NEW_LINE> F4 = np.exp(self._beta*z) / denom ...
Calculate integral of function f4 from Hellstrom (1991) Parameters ---------- z : float Depth (in meters) to evaluate the fluid temperature coefficients.
625941ec566aa707497f4a62
def buy(self, stock, qty, bracket_order_info, order_class=TC.ORDER_CLASS_SIMPLE) -> tradeapi.entity.Order: <NEW_LINE> <INDENT> if order_class == TC.ORDER_CLASS_SIMPLE: <NEW_LINE> <INDENT> return self.api.submit_order( symbol=stock, side=TC.BUY_ORDER, qty=qty, type=TC.ORDER_MARKET, time_in_force=TC.TIME_IN_FORCE_DAY, or...
buy a given stock Parameters: stock (str): the symbol of the stock to buy qty (str): number of stocks to buy as a string bracket_order_info (dict): information needed to make a bracket order see "take_profit" and "stop_loss" here https://alpaca.markets/docs/trading-on-alpaca/orders/#bracket...
625941ec4c3428357757c825
@app.route('/posts/<postid>/edit', methods=['POST']) <NEW_LINE> def handle_edit_post(postid): <NEW_LINE> <INDENT> post = Post.query.get(postid) <NEW_LINE> post.title = request.form['post_title'] <NEW_LINE> post.content = request.form['post_content'] <NEW_LINE> db.session.add(post) <NEW_LINE> db.session.commit() <NEW_LI...
Handle editing of a post - redirect back to the post view
625941ec7cff6e4e81117e86
def getPaopaoContent(url): <NEW_LINE> <INDENT> contentHtml='' <NEW_LINE> content= HtmlGetUtils.getHtml(url) <NEW_LINE> soup = BeautifulSoup(content, 'html.parser') <NEW_LINE> head=soup.find('head').prettify() <NEW_LINE> print(url) <NEW_LINE> if soup.find('div', 'title3')!=None: <NEW_LINE> <INDENT> divTitle=soup.find('d...
访问目的网页然后去广告之后返回过来 :param url: :return: 处理之后的html文本
625941ecfbf16365ca6f66cf
def test_valid_collect_errors_and_warnings(): <NEW_LINE> <INDENT> message = validate.collect_errors_and_warnings('', '') <NEW_LINE> assert message == "YOUR FILE IS VALIDATED!\n"
Tests if no error and warning strings are passed that returned valid and message is correct
625941ec5f7d997b87174f9d
def get_array_value_lock_free(self, name, *, allow_cache=False): <NEW_LINE> <INDENT> if allow_cache and name in self._cache: <NEW_LINE> <INDENT> return self._cache[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = self.get_array_value_cache_free(name) <NEW_LINE> self._cache[name] = v <NEW_LINE> return v
Lock-free version of get_array_value. @see: get_array_value
625941eca219f33f34628e62
def create_products(self, parents, tags): <NEW_LINE> <INDENT> def create_images(page: Page): <NEW_LINE> <INDENT> def create_image(file_path, slug): <NEW_LINE> <INDENT> with open(file_path, mode='rb') as file_src: <NEW_LINE> <INDENT> Image.objects.create( model=page, slug=slug, image=ImageFile(file_src) ) <NEW_LINE> <DE...
Create products for every non-root category.
625941ec091ae35668667456
@register.filter <NEW_LINE> def verbose_name(model): <NEW_LINE> <INDENT> return model._meta.verbose_name
Returns the verbose name of a model. This filter is necessary as verbose names are defined in a model's meta class, which is accessible through model._meta. However, Django's default template system does not allow attribute or variable names to begin with an underscore. We get around this limitation by defining a filt...
625941ecf7d966606f6aa50b
def build_list_of_type_validator(item_validator, allow_empty=False): <NEW_LINE> <INDENT> def validator(value, config_context): <NEW_LINE> <INDENT> if allow_empty and not value: <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> seq = valid_list(value, config_context) <NEW_LINE> if not seq: <NEW_LINE> <INDENT> msg = "Req...
Build a validator which validates a list contains items which pass item_validator.
625941ecfff4ab517eb2f940
def test_having(self): <NEW_LINE> <INDENT> self.assertEquals( Select([self.schema.FOO.BAR], From=self.schema.FOO, Having=Max(self.schema.FOO.BAZ) < 7).toSQL(), SQLFragment("select BAR from FOO having max(BAZ) < ?", [7]) )
A L{Select} object with a 'Having' keyword parameter will generate a SQL statement with a 'having' expression.
625941ec63d6d428bbe449f1
def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev")
See base class.
625941ec4e4d5625662d48d1
def test_annotations(): <NEW_LINE> <INDENT> assert session6.poker_winner.__annotations__, "Annotations not used!"
Test case to check the function typing are implemented in the function definition.
625941ecd10714528d6001e9
def product(seq): <NEW_LINE> <INDENT> total_product = 1 <NEW_LINE> for item in seq: <NEW_LINE> <INDENT> total_product *= item <NEW_LINE> <DEDENT> return total_product
Multiply each item in the list and return the value
625941eccc0a2c11143dd392
def path(self) -> Path: <NEW_LINE> <INDENT> return self.hooks_dir / self.name
Return the path of the script.
625941ecb57a9660fec33d8c
def forward(self, x): <NEW_LINE> <INDENT> x = self.pool1(F.relu(self.conv1(x))) <NEW_LINE> x = self.pool2(F.relu(self.conv2(x))) <NEW_LINE> x = self.drop(x) <NEW_LINE> x = x.view(-1, self.num_flat_features(x)) <NEW_LINE> x = F.relu(self.fc1(x)) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> x = F.relu(self.fc3(x)) <NEW_...
:param x: 一个batch的数据,输入结构:[batch_size, image_channel, image_width, image_height] :return: 前向传播结果
625941ec92d797404e30468d
def get_danmu_per_user(self): <NEW_LINE> <INDENT> sql = 'select count(*) from danmu' <NEW_LINE> self.cursor.execute(sql) <NEW_LINE> danmu_all = self.cursor.fetchone()[0] <NEW_LINE> sql = 'select count(distinct(uid)) from danmu' <NEW_LINE> self.cursor.execute(sql) <NEW_LINE> user_all = self.cursor.fetchone()[0] <NEW_LIN...
得到平均每个用户发的弹幕数
625941ec21bff66bcd684e4e
def make_names_and_lengths(names, lengths=None): <NEW_LINE> <INDENT> lengths = lengths or range(3, 21) <NEW_LINE> return list(itertools.product(names, lengths))
Create a list pairing palette names with lengths. (Mostly used to define the set of palettes that are automatically built.) Parameters ---------- names : sequence of str lengths : sequence of int, optional Returns ------- list of tuple Pairs of names and lengths.
625941ec31939e2706e4d363
def getWaveGaugeLoc(self, gaugenumber): <NEW_LINE> <INDENT> self._waveGaugeURLlookup(gaugenumber) <NEW_LINE> try: <NEW_LINE> <INDENT> ncfile = nc.Dataset(self.FRFdataloc + self.dataloc) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> ncfile = nc.Dataset(self.chlDataLoc + self.dataloc) <NEW_LINE> <DEDENT> out = ...
This function gets gauge location data quickly, faster than getwavespec. Args: gaugenumber (str, int): wave gauge numbers pulled from self.waveGaugeURLlookup Returns: dictionary with keys lat: latitude lon: longitude Notes: see help on self.waveGaugeURLlookup for gauge keys
625941eccdde0d52a9e53538
def categorical_cmap(numUniqueSamples, uniqueSampleNames, numCatagories, reverseSampleOrder=False, flipColorOrder=False, cmap='seaborn_default', continuous=False): <NEW_LINE> <INDENT> if cmap == 'seaborn_default': <NEW_LINE> <INDENT> channel_color_list = sns.color_palette() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>...
Generate a categorical colormap of length numUniqueSamples. cmap = 'tab10', 'seaborn_default', etc.
625941ec4527f215b584c952
def count(node): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> while node: <NEW_LINE> <INDENT> node = node.next <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> return count
performance: cache the length in the node?
625941ecb830903b967e9e06
def test(self): <NEW_LINE> <INDENT> self.dynamicCall("SetInputValue(String, String)", "시작일자", "20200401") <NEW_LINE> self.dynamicCall("SetInputValue(String, String)", "종료일자", "20200404") <NEW_LINE> self.dynamicCall("SetInputValue(String, String)", "매매구분", "1") <NEW_LINE> self.dynamicCall("SetInputValue(String, String)"...
print("test 시작")
625941ecf548e778e58cda80
def fill_na(tX, method=np.mean): <NEW_LINE> <INDENT> columns_with_missing_values = [] <NEW_LINE> n_total_features=tX.shape[1] <NEW_LINE> for i in range(n_total_features): <NEW_LINE> <INDENT> if -999 in tX[:, i]: <NEW_LINE> <INDENT> columns_with_missing_values.append(i) <NEW_LINE> <DEDENT> <DEDENT> filled = tX.copy() <N...
fill NA term with method provided
625941ec6e29344779a62b11
def save_prediction(preds, step, ckpt_dir, max_pred_to_keep=20): <NEW_LINE> <INDENT> if max_pred_to_keep <= 0: return <NEW_LINE> pred_dir = os.path.join(ckpt_dir, 'prediction') <NEW_LINE> if not os.path.exists(pred_dir): <NEW_LINE> <INDENT> os.makedirs(pred_dir) <NEW_LINE> <DEDENT> to_save = os.path.join(pred_dir, 'dep...
Save predictions. Args: preds: NxHxWx1 depth prediction step: current interation number in training ckpt_dir: checkpoint directory to save the predcition max_pred_to_keep: maximum number o predictions to keep
625941ec507cdc57c63071e7
def enabled_for(self, inpt): <NEW_LINE> <INDENT> signals.switch_checked.call(self) <NEW_LINE> signal_decorated = partial(self.__signal_and_return, inpt) <NEW_LINE> if self.state is self.states.GLOBAL: <NEW_LINE> <INDENT> return signal_decorated(True) <NEW_LINE> <DEDENT> elif self.state is self.states.DISABLED: <NEW_LIN...
Checks to see if this switch is enabled for the provided input. If ``compounded``, all switch conditions must be ``True`` for the switch to be enabled. Otherwise, *any* condition needs to be ``True`` for the switch to be enabled. The switch state is then checked to see if it is ``GLOBAL`` or ``DISABLED``. If it is ...
625941ec236d856c2ad44ce2
def __init__(self, message: str): <NEW_LINE> <INDENT> self.message = message
Constructor for help.InviteText: Instance of InviteText.
625941ec293b9510aa2c3791
def _handleInvertAxesSelected(self, evt): <NEW_LINE> <INDENT> if len(self._axisId) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for ax_id in self._axisId: <NEW_LINE> <INDENT> if self._menu.IsChecked(ax_id): <NEW_LINE> <INDENT> self._menu.Check(ax_id, False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._me...
Called when the invert all menu item is selected
625941ecec188e330fd5ac95
def hasQueue(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(self.queue, name) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False
Returns <True> when queue with <name> exists.
625941ec4428ac0f6e5bacf8
def list_teachers(request): <NEW_LINE> <INDENT> if 'q' in request.GET: <NEW_LINE> <INDENT> query = request.GET['q'] <NEW_LINE> print("Attempting to query teachers by search string: %s" % query) <NEW_LINE> return json_response([teacher_dict(p) for p in Profile.objects.filter( profile_type=Profile.TEACHER).fil...
Provides a listing of all of the teachers.
625941ec099cdd3c635f1159
def create_summaries(self, df, myVar, aggVars): <NEW_LINE> <INDENT> g = df.groupby(aggVars) <NEW_LINE> rez = g.agg([np.sum, lambda x: np.shape(x)[0], np.mean]).rename(columns={ 'sum': self.summary_types[0], '<lambda>': self.summary_types[1], 'mean': self.summary_types[2], })[myVar] <NEW_LINE> return rez
Summarize data into multi-level pandas df.
625941ecad47b63b2c50a480
def schedule(self, action: typing.ScheduledAction, state: Optional[typing.TState] = None ) -> typing.Disposable: <NEW_LINE> <INDENT> return self._gtk_schedule(0.0, action, state)
Schedules an action to be executed. Args: action: Action to be executed. state: [Optional] state to be given to the action function. Returns: The disposable object used to cancel the scheduled action (best effort).
625941ec507cdc57c63071e8
def test_translation(self): <NEW_LINE> <INDENT> expected_result = numpy.identity(4) <NEW_LINE> offset = 0.0 <NEW_LINE> azimuthal = 0.0 <NEW_LINE> zenith = 0.0 <NEW_LINE> wrist_roll = 0.0 <NEW_LINE> radial = 0.0 <NEW_LINE> gripper_matrix = numpy.identity(4) <NEW_LINE> expected_result[2, 3] = offset <NEW_LINE> result = t...
Translation test.
625941ec460517430c394678
def _R2deriv(self,R,z,phi=0.,t=0.): <NEW_LINE> <INDENT> denom= 1./(R**2.+(z/self._q)**2.+self._core2) <NEW_LINE> return denom-2.*R**2.*denom**2.
NAME: _R2deriv PURPOSE: evaluate the second radial derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the second radial derivative HISTORY: 2011-10-09 - Written - Bovy (IAS)
625941ec2eb69b55b151cdb8
def test_externals_can_post(self): <NEW_LINE> <INDENT> event = self.new_object('events', additional_fields=None, allow_email_signup=True) <NEW_LINE> self.api.post('eventsignups', data={ 'event': str(event['_id']), 'email': 'test@bla.com', }, status_code=201)
Test that post is possible with email address without login
625941ec7047854f462a1905
def model_device(n_gpu, model): <NEW_LINE> <INDENT> device, device_ids = prepare_device(n_gpu) <NEW_LINE> if len(device_ids) > 1: <NEW_LINE> <INDENT> logger.info(f"current {len(device_ids)} GPUs") <NEW_LINE> model = torch.nn.DataParallel(model, device_ids=device_ids) <NEW_LINE> <DEDENT> if len(device_ids) == 1: <NEW_LI...
:param n_gpu: :param model: :return:
625941ec090684286d50f1ee
def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> best_move = (-1, -1) <NEW_LINE> try: <NEW_LINE> <INDENT> print('inside get_move, self.search_depth = {}'.format(self.search_depth)) <NEW_LINE> for d in range(self.search_depth): <NEW_LINE> <INDENT> print('\n\n') <NEW_LINE> pr...
Search for the best move from the available legal moves and return a result before the time limit expires. Modify the get_move() method from the MinimaxPlayer class to implement iterative deepening search instead of fixed-depth search. ********************************************************************** NOTE: If ti...
625941ec7c178a314d6ef969
def test_dll_constructs_empty_none_tail(empty_dll): <NEW_LINE> <INDENT> d = empty_dll <NEW_LINE> assert d.tail is None
Test that empty dll is created with tail of None.
625941eca17c0f6771cbe550
def smooth(array, smoothing_horizon=100., initial_value=0.): <NEW_LINE> <INDENT> smoothed_array = [] <NEW_LINE> value = initial_value <NEW_LINE> b = 1. / smoothing_horizon <NEW_LINE> m = 1. <NEW_LINE> for x in array: <NEW_LINE> <INDENT> m *= 1. - b <NEW_LINE> lr = b / (1 - m) <NEW_LINE> value += lr * (x - value) <NEW_L...
Smoothing function (moving average) for plotting
625941ec76e4537e8c351b78
def getCellXlsx( row , col , isDigit , sheet ): <NEW_LINE> <INDENT> ccc = sheet.cell(row=row, column=col) <NEW_LINE> cellType = ccc.data_type <NEW_LINE> cellValue = ccc.value <NEW_LINE> if (isDigit == 'Y') : <NEW_LINE> <INDENT> if (cellValue == None) : <NEW_LINE> <INDENT> ss = '0' <NEW_LINE> <DEDENT> elif (cellType i...
Функция возвращает значение xls-ячейки в виде строки. Для цифровых ячеек делается предварительное преобразование в число (пустые и нечисловые значения преобразуются в "0")
625941ec6aa9bd52df0372a8
def test_signal_proxy_no_slot_start(qapp): <NEW_LINE> <INDENT> sender = Sender(parent=qapp) <NEW_LINE> receiver = Receiver(parent=qapp) <NEW_LINE> proxy = SignalProxy(sender.signalSend, delay=0.0, rateLimit=0.6) <NEW_LINE> assert proxy.blockSignal is True <NEW_LINE> assert proxy is not None <NEW_LINE> assert sender is ...
Test the connect mode of SignalProxy without slot at start`
625941ecb5575c28eb68e506
def check_border(self, room): <NEW_LINE> <INDENT> if room in self.borders: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
returns True if the rooms border one another, False if otherwise
625941ec9f2886367277ad8a
def lineHeight(self, value): <NEW_LINE> <INDENT> self._dummyContext.lineHeight(value) <NEW_LINE> self._addInstruction("lineHeight", value)
Set the line height. .. downloadcode:: lineHeight.py # set line height lineHeight(150) # set font size fontSize(60) # draw text in a box textBox("Hello World " * 10, (100, 100, 800, 800))
625941ec15baa723493c447b
def create_neighbourhood(self): <NEW_LINE> <INDENT> self.save()
Saves NeighbourHood instance to db
625941ec30dc7b7665901e62
def fix_orientation(img): <NEW_LINE> <INDENT> h, w,c = img.shape <NEW_LINE> loc=match_loc(img) <NEW_LINE> print("loc is here",loc, "h, w:", h, w) <NEW_LINE> if loc[1]>160 and loc[1]<240: <NEW_LINE> <INDENT> return img <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rotated = imutils.rotate(img, 90) <NEW_LINE> return rota...
Based on the location of 'connect logo' it rotates the image or returns the image as it receives Parameters ---------- img: ndarray and opencv image array
625941ec3317a56b8693a14d
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = novatel_msgs.msg.CommonHeader() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 150 <NEW_LINE> (_x.header.id, _x.header.msg_type, _x.h...
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
625941ec4f6381625f114f3c
def delete_web_application(self, Name=None): <NEW_LINE> <INDENT> return self._connection.delete_web_application(WebService=self.Name, Site=self._Site, ServerGroup=self._ServerGroup, Name=Name)
See :py:meth:`imperva_sdk.MxConnection.delete_web_application`.
625941ec4f6381625f114f3d