anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Precautions You can call the [CreateDBInstance](~~61763~~) operation to restore a database for an ApsaraDB for MongoDB instance. For more information, see [Restore one or more databases of an ApsaraDB for MongoDB instance](~~112274~~).
def describe_backup_dbs( self, request: dds_20151201_models.DescribeBackupDBsRequest, ) -> dds_20151201_models.DescribeBackupDBsResponse: runtime = util_models.RuntimeOptions() return self.describe_backup_dbs_with_options(request, runtime)
Run a single epoch
def eval_model(device, model, sampler, loss_compute, logit_modifier_fxn, token_sampler, print_every, max_len, user_items_df, max_name_len=15, ingr_map=None, base_save_dir='', pad_ingr=None, ppx_only=False, **tensor_kwargs): start = datetime.now() results_dicts = [] # Extract ...
Optionally add the commitment commitment to the list of 'used', and optionally remove the available external commitment whose key value is the utxo in external_to_remove, persist updated entries to disk.
def update_commitments(commitment=None, external_to_remove=None, external_to_add=None): c = {} if os.path.isfile(PODLE_COMMIT_FILE): with open(PODLE_COMMIT_FILE, "rb") as f: try: c = json.loads(f.read()) except ValueError: pr...
Looks up rawdata id iraw and unpacks the job output tarballs from all jobs that completed successfully into a new directory named iraw under the pwd. If iraw is not known, alternatively one can supply the run number and sequence number of the raw data input file.
def unpack(run=0, seqno=0, iraw=0): if iraw == 0 and run == 0: print("Usage: osgprod_bind.unpack(iraw=<iraw>)") print(" or: osgprod_bind.unpack(run=<run>, seqno=<seqno>)") return 0 if iraw: with db_connection() as conn: with conn.cursor() as curs: curs.execute("""SEL...
player names and bid / trick / score headers
def init_column_headers(self): col_headers = {1: "bid", 2: "tricks", 3: "score"} for player in range(1, 5): ent_player_name = tk.Entry(self.master, font='courier 10 bold', fg='blue', borderwidth=2, relief="groove") ent_player_name.grid(...
Run the entire NBA_bet project.
def run_all(): db = DBInterface() year = Config.get_property("league_year") session = Session(bind=db.engine) scraper.scrape_all(db, session, year) session.commit() bets.predict_all(db, session) session.commit() session.close()
Finds the intersection of two lines given in Hesse normal form. Returns closest integer pixel locations.
def intersection(line1, line2): rho1, theta1 = line1 rho2, theta2 = line2 A = np.array([ [np.cos(theta1), np.sin(theta1)], [np.cos(theta2), np.sin(theta2)] ]) b = np.array([[rho1], [rho2]]) x0, y0 = np.linalg.solve(A, b) x0, y0 = int(np.round(x0)), int(np.round(y0)) retur...
(Personalization Only) The flag to enable statistics of Bing Search.
def event_hub_connection_string(self) -> Optional[str]: return pulumi.get(self, "event_hub_connection_string")
Ouput log of actions taken on method
def replay(method: Callable) -> None: counter_key = method.__qualname__ i_keys = method.__qualname__ + ':inputs' o_keys = method.__qualname__ + ':outputs' this = method.__self__ counter = this.get_str(counter_key) history = list(zip(this.get_list(i_keys), this.get_list(o_...
This funtion is to get the dataframe of yield to maturity and discount rate value.
def get_ytm_discount_data(self): ytm=Bootstrapping.get_ytm_dict(self) data = pd.DataFrame() for i in ytm.keys(): data.loc[i / 2, 'Yield to maturity'] = ytm[i] data.loc[i / 2, 'discount_rate'] = Bootstrapping.P_Tn(self,ytm[i], i) return data
Actually invoke the underlying function (but only if it hasn't been invoked already).
def start(self) -> None: cb = self._callback if cb is not None: self._callback = None propagate(from_=ensure_future(cb()), to=self._future)
Returns Json list of all Packages
def get_rest_list(request): if request.method == "GET": rest_list = Package.objects.order_by('-location') serializer = PackageSerializer(rest_list, many=True) return JsonResponse(serializer.data, safe=False)
Set the logger to log info in terminal and file `log_path`. In general, it is useful to have a logger so that every output to the terminal is saved in a permanent file. Here we save it to `model_dir/train.log`.
def set_logger(save=False, log_path=None): logger = logging.getLogger() logger.setLevel(logging.INFO) if not logger.handlers: if save: # Logging to a file file_handler = logging.FileHandler(log_path) file_handler.setFormatter(logging.Formatter('%(asctime)s:%(leve...
Method creates new population by choosing mi best individuals from children and current population
def choose_mi_best(self, R): population = np.empty([self.P.shape[0] + R.shape[0], 2*self.d + 1]) i = 0 for individual in np.vstack([self.P, R]): population[i, 0] = -self.J(individual[0:self.d], self.nCEC) population[i, 1:] = individual i = i+1 sorted_...
Calculate the inner product of the two patterns as a vecter.
def inner_product(pattern_one, pattern_two): return np.sum(np.multiply(pattern_one, pattern_two))
Return the list of full paths for pictures and movies in source directory
def list_of_medias(args, sourcedir, recursive): files = list_of_files(sourcedir, recursive) return [_ for _ in files if is_media_within_dates(_, args.dates)]
Conduct classification and calculate metrics
def classify(self, verbose=True, print_scores=False): if verbose: print("%s: Training model ..." % self.clf_name) self.clf.fit(self.X_train, self.y_train) if verbose: print("%s: Calculating probablities ... " % self.clf_name) y_proba = self.clf.predict_proba(self...
Identify distinct MPTCP Connections that reached Successful handshake Look for Ack packets with MPTCP option Header For each MPTCP connection report Receiver's token value which acts as the connectionID
def mptcp_connections(self, pkts): count = 0 #MPTCP_Capable = 0x0 #MPTCP_CapableACK ---> successful handshake print "======================================================================" print "Successful Handshake --- Look for Ack packets with MPTCP option Header" print """Token = connectionID = SHA1(key...
Returns a dict of predictions.
def _logits_to_predictions(self, logits): key = prediction_key.PredictionKey.SCORES with ops.name_scope(None, "predictions", (logits,)): if self.logits_dimension == 1: logits = array_ops.squeeze(logits, squeeze_dims=(1,), name=key) return {key: logits}
Creates a new subgroup of the outcome group with the same title and description as the source group, then creates links in that new subgroup to the same outcomes that are linked in the source group. Recurses on the subgroups of the source group, importing them each in turn into the new subgroup. Allows you to copy orga...
def import_outcome_group_global(request_ctx, id, source_outcome_group_id, **request_kwargs): path = '/v1/global/outcome_groups/{id}/import' payload = { 'source_outcome_group_id' : source_outcome_group_id, } url = request_ctx.base_api_url + path.format(id=id) response = client.post(request_c...
Getter method for weight, mapped from YANG variable /input/LocatorRecord/weight (uint8)
def _get_weight(self): return self.__weight
First Python implementation method of the Levenshtein distance between strings
def levenshtein(s1, s2): if len(s1) < len(s2): return levenshtein(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = pr...
Compute the gradient of the loglikelihood function for part f.
def find_mle_by_grad_descent(initial_sensor_loc, obj_loc, distance, lr=0.001, num_iters = 1000): sensor_loc = initial_sensor_loc # Your code: finish the gradient descent return sensor_loc
Saves the config file
def save_config_file(self): with open(self.config_file_name, 'w',encoding='utf-8') as outfile: json.dump(self._config, outfile,indent=2)
Delete a setting in the central setting file
def DeleteSetting(appname, section, key): settings = _OptionsDB(appname) settings.delete(section, key)
Read file returns read file as string
def rSeqFile(FilePath): f=open(FilePath, 'r') #check if file open if f.mode == 'r': return(f.read())
Method to remove the stop words used in get_left_right_lists() This method does not work for Catalan language.
def remove_stop_words(tokens, language): if not remove_stop_words_activated or language.__eq__("Catalan"): return tokens output = [] stop = stopwords.words(language.lower()) for token in tokens: if token not in stop: output.append(token) return output
Returns the number of sequences >= bound with len() <= max_len accepted by this NFA.
def num_accepts_ge(self, max_len: int, bound: Sequence[Text] = ()) -> int: _, num_accepted_eq, num_accepted_gt = self.num_accepts(max_len, bound) return num_accepted_eq + num_accepted_gt
Should return Python datetime object.
def test_06_dt_to_milliseconds_str(self): dt = datetime.datetime.utcnow() ts = utils.dt_to_milliseconds_str(dt) self.assertIsInstance(ts, str)
A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial.
def nullHeuristic(state, problem=None): return 0
Rearrange Array Elements so as to form two number such that their sum is maximum.
def rearrange_digits(input_list): ## Corner cases: if len(input_list) == 0: return [0, 0] elif len(input_list) == 1: return [input_list[0], 0] # Sort an array using merge-sort sorted_list = merge_sort(input_list) # Create two empty array and pop largest number from an sorted_li...
Supports an additional argument ``jsonp_callback``. If specified, the JSON serialized data string will be wrapped in parenthesis and prefixed by the value of ``jsonp_callback``.
def __init__(self, *args, **kwargs): self.jsonp_callback = kwargs.pop('jsonp_callback', None) super(JsonResponse, self).__init__(*args, **kwargs)
Plots an image and the projections (sums) of it on the x, y axes.
def plot_image_and_proj(image, title="", **kwargs): fig = plt.figure() gs = gridspec.GridSpec(3, 2, width_ratios=[3, 1], height_ratios=[0.2, 3, 1]) ax0 = plt.subplot(gs[1,0]) plt.title(title) ims = plt.imshow(image, aspect="auto", **kwargs) ax2 = plt.subplot(gs[2,0], sharex=ax0, ) plt....
Print a message to the standard output, in case show_info is enabled.
def info(self, message): if self.show_info: print(message)
Find coordinates of a single run time, output and space dimensions.
def _getCoordsFromRun(self, run_dict, bold=False): run_dict = copy.deepcopy(run_dict) run_dict = self._filterDictionaryBold(run_dict, bold=bold) timeDictKey = "" if "t" in run_dict: timeDictKey = "t" else: for k in run_dict: if k.startswith...
def readtask(self,filename_): if isinstance(filename_,unicode): filename_ = filename_.encode("utf-8",errors="replace") res = __library__.MSK_XX_readtask(self.__nativep,filename_) if res != 0: _,msg = self.__getlasterror(res) raise Error(rescode(res),msg)
Load task data from a file. readtask(self,filename_)
def insert(self, dataset: List[Read]) -> bool: node_to_insert = Node(self.k, self.num_buckets, self.fp_size, self.bucket_size, self.max_iter) node_to_insert.populate_dataset_info(dataset) self.aggregate_size += node_to_insert.get_size() if self.root is None: self.root = node...
Creates a new node from this read and adds it into the tree
def test_from_knx_wrong_parameter2(self): with self.assertRaises(ConversionError): DPTValue1Ucount().from_knx("0x23")
Test parsing of DPTValue1Ucount with wrong value (array containing string).
def _ready_to_decrypt(self, shares: Dict[GuardianId, DecryptionShare]) -> bool: # If all guardian shares are represented including if necessary # the missing guardians reconstructed shares, the decryption can be made return len(shares) == self._context.number_of_guardians
Shares are ready to decrypt.
def server_closed_connection(self): print("Game Over!") if self._winner: print("Player {} wins!".format(self._winner)) else: print("Draw!")
Print out the end status of the game when the server closes the connection.
def lights(id, all, connect, info, action, bri): try: bridge = phue.Bridge(BRIDGE_IP) except Exception: click.secho( "Press the bridge buttom and call the connect again", fg='red') if connect: # If the app is not registered and the button is not pressed, # press ...
Actions to control hue lights
def _BoolOp(self, t): self.write("(") s = " %s " % self.boolops[t.op.__class__] interleave(lambda: self.write(s), self.dispatch, t.values) self.write(")")
Translate to logical and/or operators in C
def delete_outcome_group_courses(request_ctx, course_id, id, **request_kwargs): path = '/v1/courses/{course_id}/outcome_groups/{id}' url = request_ctx.base_api_url + path.format(course_id=course_id, id=id) response = client.delete(request_ctx, url, **request_kwargs) return response
Deleting an outcome group deletes descendant outcome groups and outcome links. The linked outcomes themselves are only deleted if all links to the outcome were deleted. Aligned outcomes cannot be deleted; as such, if all remaining links to an aligned outcome are included in this group's descendants, the group deletion ...
def train(args): log_header('Training network') train_retriever(args)
Run the training procedure
def server_hostname(self): result = c_char_p(self.lib.iperf_get_test_server_hostname(self._test)).value if result: self._server_hostname = result.decode('utf-8') else: self._server_hostname = None return self._server_hostname
The server hostname to connect to. Accepts DNS entries or IP addresses
def put(self, key, value): hi = self.hash_index(key) if self.storage[hi]: current = self.storage[hi] while current.next and current.key != key: current = current.next if current.key == key: current.value = value else: ...
Store the value with the given key. Hash collisions should be handled with Linked List Chaining. Implement this.
def aslist(something): return something if isinstance(something, list) else [something]
If something is not a list already make it one, otherwise simply return something
def create_wall_shape(self): self.shape_walls = arcade.ShapeElementList() self.shape_walls.center_x = 0 self.shape_walls.center_y = 0 self.shape_walls.angle = 0 point_list = [] color_list = [] # create the walls into a single shape walls = self.g...
Instead of rendering each wall block, we create a single shape which can be drawn in a single call, rather than a call for each wall block
def handle_port_config_change(sel, asic_context, stop_event, port_mapping, logger, port_change_event_handler): if not stop_event.is_set(): (state, _) = sel.select(SELECT_TIMEOUT_MSECS) if state == swsscommon.Select.TIMEOUT: return if state != swsscommon.Select.OBJECT: ...
Select CONFIG_DB PORT table changes, once there is a port configuration add/remove, notify observers
def confusion_matrix(predicted, gt): tp = [k for k in predicted if predicted[k] and gt[k]] tn = [k for k in predicted if not predicted[k] and not gt[k]] fp = [k for k in predicted if predicted[k] and not gt[k]] fn = [k for k in predicted if not predicted [k] and gt[k]] return tp, tn, fp, fn
Takes dictionaries of predicted and ground truth and returns confusion matrix
def _get_btc_gbp_15min(self) -> None: self._get_eur_gbp_last_daily() self.btc_gbp_15min = self.btc_eur_15min * self.eur_gbp_last_day
Calculate the 15min delayed BTC market price in GBP.
def test_documentation_popxl_adv_get_write(self): filename = "tensor_get_write_adv.py" self.run_python(filename, file_dir=working_dir, working_dir=working_dir)
Test the popxl advanced getting / writing tensor data example that shows exactly when devicehost transfers occur
def str_to_unicode(text, encoding='utf-8'): if isinstance(text, str): return text.decode(encoding) elif isinstance(text, unicode): return text else: raise TypeError('str_to_unicode must receive a str or unicode object, got %s' % type(text).__name__)
convert string to unicode
def _fetch_current_remote_metadata(conn): content = _get(conn, REMOTE_METADATA_FILE) metadata = json.loads(content) if content else {} return metadata
Fetches the metadata remote file REMOTE_METADATA_FILE and returns the metadata dict equivalent.
def close_window(self, button_msgs): if self.messages_window is not None: self.messages_window.destroy() self.messages_window = None button_msgs.config(command=lambda: self.new_window_messages(button_msgs))
closing the second Tk object
def kludge_gvars(mangled): # Loop in reverse looking for '+-', but don't run off the end for idx in range(len(mangled) - 1)[::-1]: if mangled[idx + 1] == '+-': reunited = ' '.join(mangled[idx:idx + 3]) # Throw away the used elements... for _ in...
Occasionally, gvars get rendered to strings as, e.g., 4e06 + 1 instead of 0.000006(1.0). This makes a complete mess of trying to parse the a list of gvar which has been turned into a string, e.g., '[1(2) 1 + 2 0.003(2)]', since the usual str.split() separates '1 + 2' > ['1','+','2']. This function is a kludge which wor...
def txt_file_reader(path): return open(path, encoding=cfg.ENCODING)
Opens a text file
def get_board(self): return self._board
get_board returns copy of the game's _board object
def parse_command(self, command): split_list = command.split() command = local[split_list[0]] if 'python' in split_list[0]: self.logger.debug(self.venv_pip) command = self.venv_python if split_list[0] == 'pip' or split_list[0] == 'pip3': self.logger.d...
generate plumbum command given an incoming string
def selectfont(self, char): charcode = ord(char) for font in fontchecksequence: for fontrange in fontmapping[font]: if charcode in xrange(fontrange[0], fontrange[1]): return font return "Helvetica" # fallback, if no thirdparty font is installed
Select font according to the input character
def test_users_dictionary(self): new_user = self.app self.assertEqual(len(new_user.users), 0) new_user.create_user() self.assertIsInstance(new_user, User) self.assertEqual(len(new_user.users), 1)
Test user's dict is empty at first
def dtype(self): return self.config["dtype"]
The data type of the master array.
def pygame_to_cvimage( surface ): cv_image = cv.CreateImageHeader( surface.get_size(), cv.IPL_DEPTH_8U, 3 ) image_string = surface_to_string( surface ) cv.SetData( cv_image, image_string ) return cv_image
Convert a pygame surface into a cv image
def load_data(self, inroot=None): self.data = {} # Load for night in self.mexp_dict.keys(): qaNight = QA_Night(night, specprod_dir=self.specprod_dir, qaprod_dir=self.qaprod_dir) qaNight.load_data() # self.data[night] = qaNight.data[night]
Load QA data from night objects on disk
def saveClassroomData(): with open("ClassRoomData.txt","wb") as classroomData: pickle.dump(classroomEntities,classroomData)
saves classroomEntities in the ClassRoomData file
def _ref_pixel_calc(ifg_paths: List[str], params: dict) -> Tuple[int, int]: lon = params[cf.REFX] lat = params[cf.REFY] ifg = Ifg(ifg_paths[0]) ifg.open(readonly=True) # assume all interferograms have same projection and will share the same transform transform = ifg.dataset.GetGeoTransform() ...
Wrapper for reference pixel calculation
def offset_all(x, y, beck_bed, t): length = x.size xyz1 = np.zeros((length, 3)) xyz2 = np.zeros((length, 3)) xyz1[:, 0] = np.copy(x) xyz1[:, 1] = np.copy(y) xyz1[:, 2] = np.copy(beck_bed[:, NUM]) allxyz = np.copy(xyz1) offsetx = np.zeros((length, 2)) offsety = np.zeros((length, 2)) ...
Compute the offset polylines of centerline. Merge coordinates data (x & y information) with bed topography data (z information) to form a point cloud dataset in 3column xyz format.
def reset_obstacles(self): self.obstacles = np.array([])
Reset the obstacles' positions within the map (should be called when map is refreshed to clean the array)
def test_render_to_console(self, _step: PropertyMock): message = ' {{ a }} is not {{ b }}.' _step_mock = MagicMock() write_source = MagicMock() _step_mock.report.stdout_interceptor.write_source = write_source _step.return_value = _step_mock step = exposed.ExposedStep()...
Should render to the console using a write_source function call on the internal step report's stdout_interceptor.
def generate_graph(params): alignedreads = read_paf(params, should_filter_paf=True) aligned = [(t, h) for t, h, _ in alignedreads] graph = nx.Graph() graph.add_edges_from(aligned) return graph
generates and returns overlap graph from .paf files
def generate_totp_seed(self, user_id, mfa_totp_device_id, **kwargs): resource_path = "/users/{userId}/mfaTotpDevices/{mfaTotpDeviceId}/actions/generateSeed" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "if_match" ] ...
Generate seed for the MFA TOTP device.
def _addSessionToWishlist(self, request): # Preload necessary data items user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # Verify that the session actually exists session = _getEntityByWebsafeKey(request...
Add a session to the user's wishlist, returning a boolean.
def __hamming_distance(s1, s2): if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") return sum(el1 != el2 for el1, el2 in zip(s1, s2))
Return the Hamming distance between equallength sequences
def pre_installation(self): pass
Called before anything else, i.e. just after installer controller creation. Return value is ignored.
def get_center(self,lonlat=False): lon, lat = np.asarray(self.rotator.rots[0][0:2])*180/pi if lonlat: return lon,lat else: return pi/2.-lat*dtor, lon*dtor
Get the center of the projection.
def l2_reg_create_layer(prev, n, activation, lambtha): reg = tf.contrib.layers.l2_regularizer(lambtha) init = tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG") t = tf.layers.Dense(units=n, activation=activation, kernel_initializer=init, kernel_reg...
returns output of new layer
def _test_app_running(self, running_set, sysproid, cell, appname): full_app_name = '%s.%s.%s' % (sysproid, appname, cell) self.assertIn(full_app_name, running_set)
Check {sysproid}.{appname}.{cell} is running.
def test_for_template(self): self.assertTemplateUsed(self.response, 'my_info_template.html')
Test for template correctness
async def authorization(request): # Decode tokens, load/check users and etc # ... # in the example we just ensure that the authorization header exists return request.headers.get("authorization", "")
Setup authorization for whole API. Can be redefined for an endpoint. OpenAPI Authorization Specs
def RestoreDatabase(self, database, backupfile, arguments, result): self.RunProgram("\""+self.__context["gbak_path"]+"\"", [ self.__context["gbak_path"] ] + [ "-C ", backupfile ] + arguments + [ database ], "", self.__context, result)
Restore a database from a backup file. 'database' A database specification. 'backupfile' A backup file name. 'arguments' A list of the arguments to the GBAK without backup file name and database location. 'result' A 'Result' object. The outcome will be 'Result.PASS' when this method is called. The 'result' may be modif...
def get_epoch(timestamp): timestamp_dt = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ") epoch = calendar.timegm(timestamp_dt.timetuple()) return epoch
Converts Strava datetime to epoch timestamp
def roundUP(x): return int(ceil(x / 10.0)) * 10
Rounding up to next 10th
def BaseDataContext( # noqa: PLR0913 project_config: Union[DataContextConfig, Mapping], context_root_dir: Optional[PathStr] = None, runtime_environment: Optional[dict] = None, cloud_mode: bool = False, cloud_config: Optional[GXCloudConfig] = None, # Deprecated as of 0.15.37 ge_cloud_mode: b...
A lightweight wrapper around `get_context()`. While this used to be the canonical method of instantiating a DataContext before 0.15.40, it is now recommended to use `get_context()`.
def classify(dataset,classifier,feat_mask=None): train = dataset.get_data('train',True) X_train = train['x'] if feat_mask is not None: X_train = X_train[:,feat_mask] y_train = train['y'] classifier.fit(X_train,y_train) test = dataset.get_data('test',True) X_...
Performs a standard classification test with the given classifier.
def pingpong(n): # define two helper function, the recursion start from the bottom # from 1 to n "*** YOUR CODE HERE ***" def positive(n, k, turn): if turn == n: return k else: if (k % 7 == 0) or has_seven(k): return negative(n, k-1, turn + 1) else: return positive(n, k+1, turn + 1) def negat...
Return the nth element of the pingpong sequence. >>> pingpong(7) 7 >>> pingpong(8) 6 >>> pingpong(15) 1 >>> pingpong(21) 1 >>> pingpong(22) 0 >>> pingpong(30) 6 >>> pingpong(68) 2 >>> pingpong(69) 1 >>> pingpong(70) 0 >>> pingpong(71) 1 >>> pingpong(72) 0 >>> pingpong(100) 2 >>> from construct_check import check >>> ch...
def set_light(r, g, b): for x in range(4): set_pixel(x, r, g, b) """Output the buffer """ _sof() for pixel in pixels: r, g, b, brightness = pixel _write_byte(0b11100000 | brightness) _write_byte(b) _write_byte(g) _write_byte(r) _eof()
Set the RGB colour of an individual light in your Plasma chain. This will set all four LEDs on the Plasma light to the same colour.
def authorizes(self, user): return self.owner == user or self.workers.filter(pk=user.id).exists()
Return True if the campaign authorizes the user to provide data to the campaign. This is the case if the user owns or works for the campaign. Otherwise, return False.
def description(self) -> pulumi.Output[str]: return pulumi.get(self, "description")
A humanreadable description of the new Role.
def solar_elevation(self, dateandtime=None): if self.astral is None: self.astral = Astral() if dateandtime is None: dateandtime = datetime.datetime.now(tz=self.tz) return self.astral.solar_elevation(dateandtime, self.latitude, self.longitude)
Calculates the solar elevation angle for a specific time.
def test_stock_and_price_must_be_numbers(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock='stock', price='money' ) resp = s...
Tests that stock and price fields must be numbers
def test_tenant_setup_celery_reset(self): msg = mock.Mock() tenant = mock.Mock() tenant.client_name = 'mock-tenant' _send_celery_mail(msg, tenant, send=False) self.assertFalse(hasattr(properties, 'tenant')) self.assertEqual(properties.tenant_properties, {})
after _send_celery_mail finishes, the tenant should be cleared again
def args(self): return self._parse_args
The arguments into which the python args and kwargs are collected
def itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args): return _itkTernaryAddImageFilterPython.itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args)
itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(itkLightObject obj) > itkTernaryAddImageFilterIUL2IUL2IUL2IUL2
def poll_tests(self): for i, test in enumerate(self.tests): if test.process.poll() is not None: self.check_test(test) self.tests.pop(i) if self.test_numbers: self.start_next_test()
Poll tests for completion. When one finishes, start another one if there are more to run. Stop when all are finished.
def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs)
Wrapper for requests GET method
def is_active(self): return self.active
DEPERECIATED FUNCTION PLEASE USE active field of subscription
def edit_profile(request): user = request.user profile = Profile.objects.for_user(user) if request.method != 'POST': profile_form = ProfileForm(instance=profile) user_form = UserForm(instance=user) else: profile_form = ProfileForm(request.POST, instance=profile) ...
Used to allow a user to edit their own profile.
def putbarsj(self,whichsol_,j_,barsj_): _barsj_minlength = self.getlenbarvarj((j_)) if self.getlenbarvarj((j_)) > 0 and barsj_ is not None and len(barsj_) != self.getlenbarvarj((j_)): raise ValueError("Array argument barsj is not long enough: Is %d, expected %d" % (len(barsj_),self.getlenbarvarj((j_)))) ...
Sets the dual solution for a semidefinite variable. putbarsj(self,whichsol_,j_,barsj_)
def wass_distance(X, Y, order=2, type='exact'): if order == 2: M = ot.dist(X, Y) elif order == 1: M = ot.dist(X, Y, metric='euclidean') else: raise Exception("Order should be 1 or 2.") a = np.ones((X.shape[0],))/X.shape[0] b = np.ones((Y.shape[0],))/Y.shape[0] if type == ...
Computes the (exact or approximate) Wasserstein distance of order 1 or 2 between empirical distributions
def find_functions(code): regex = "^\s*" + re_func_decl + "\s*{" funcs = [] while True: m = re.search(regex, code, re.M) if m is None: return funcs rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] ...
Return a list of (name, arguments, return type) for all function definition2 found in code. Arguments are returned as [(type, name), ...].