code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def fitness_function(items, m): <NEW_LINE> <INDENT> cost = 0 <NEW_LINE> weight = 0 <NEW_LINE> for key, is_selected in items.items(): <NEW_LINE> <INDENT> if is_selected: <NEW_LINE> <INDENT> weight += key[1] <NEW_LINE> cost += key[0] <NEW_LINE> <DEDENT> <DEDENT> res = cost if weight <= m else 0 <NEW_LINE> return res
Return sum of cost for child if weight < m otherwise return 0.
625941dc3539df3088e2e63c
def evaluate(self, rule, functor=None, arguments=None, ground_program=None): <NEW_LINE> <INDENT> if ground_program is None: <NEW_LINE> <INDENT> ground_program = self.ground(rule, functor, arguments) <NEW_LINE> <DEDENT> knowledge = get_evaluatable().create_from(ground_program) <NEW_LINE> return knowledge.evaluate()
Evaluate the given rule. :param rule: rule to evaluate :type rule: Rule :param functor: override rule functor :type functor: str :param arguments: query arguments (None if non-ground) :type arguments: list[tuple[Term]] | None :param ground_program: use pre-existing ground program (perform ground if None) :type ground_...
625941dc1b99ca400220ada4
def get_lookup_weighting(self, keys, strengths): <NEW_LINE> <INDENT> normalized_memory = tf.nn.l2_normalize(self.memory_matrix, 2) <NEW_LINE> normalized_keys = tf.nn.l2_normalize(keys, 1) <NEW_LINE> similiarity = tf.batch_matmul(normalized_memory, normalized_keys) <NEW_LINE> strengths = tf.expand_dims(strengths, 1) <NE...
retrives a content-based adderssing weighting given the keys Parameters: ---------- keys: Tensor (batch_size, word_size, number_of_keys) the keys to query the memory with strengths: Tensor (batch_size, number_of_keys, ) the list of strengths for each lookup key Returns: Tensor (batch_size, words_num, number_o...
625941dc851cf427c661a7fe
def post_config_override(self): <NEW_LINE> <INDENT> name = self.request.get('name') <NEW_LINE> item = None <NEW_LINE> if name and name in config.Registry.registered.keys(): <NEW_LINE> <INDENT> item = config.Registry.registered[name] <NEW_LINE> <DEDENT> if not item: <NEW_LINE> <INDENT> self.redirect('/admin?action=setti...
Handles 'override' property action.
625941dc38b623060ff0b0df
def _put(self,*args,**kwargs): <NEW_LINE> <INDENT> data = args[0] <NEW_LINE> if data.get('filename') is None: <NEW_LINE> <INDENT> self.send_response(255) <NEW_LINE> return <NEW_LINE> <DEDENT> file_size = data["file_size"] <NEW_LINE> dir_size = self.get_dir_size() <NEW_LINE> if file_size + dir_size +100 > self.quotation...
client send file to server
625941dc283ffb24f3c55bf0
def test_nonexistent_token(self): <NEW_LINE> <INDENT> self.datautils.create_session() <NEW_LINE> result = get_user_from_token(self.session, 'invalid_token') <NEW_LINE> self.assertEqual(result, None)
If the token doesn't exist, we should get None
625941dc3617ad0b5ed681e8
def __init__(self, dovarline=True, doexpr=True, expressionDelimiter="$", assignmentLineStart="$$", allowExec=False, assignmentDebug=None, specials=[]): <NEW_LINE> <INDENT> self.clip=len(expressionDelimiter) <NEW_LINE> self.specials=specials <NEW_LINE> tmp=list(expressionDelimiter) <NEW_LINE> tmp.reverse() <NEW_LINE> se...
Create the regexp once for performance reasons @param dovarline: look for variable lines that start with $$ @param doexpr: substitute expressions that are between $ @param expressionDelimiter: character/string that is used before and after an expression. After the expression the reverse of the string is used @param ass...
625941dcfbf16365ca6f64ba
def insert(self, val): <NEW_LINE> <INDENT> bool_ret = val not in self.l <NEW_LINE> self.d[val].add(len(self.l)) <NEW_LINE> self.l.append(val) <NEW_LINE> return bool_ret
Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool
625941dcb7558d58953c5201
def _elements(array): <NEW_LINE> <INDENT> return array.ndim and array.size
check if array has elements. https://stackoverflow.com/questions/11295609/how-can-i-check-whether-the-numpy-array-is-empty-or-not :param array: array to check if it has any elements :type array: np.ndarray
625941dcd164cc6175783040
def register_generator(self, generator): <NEW_LINE> <INDENT> self.url_generators.append(generator) <NEW_LINE> return generator
Register an URL generator. The function should return an iterable of URL paths or ``(endpoint, values)`` tuples to be used as ``url_for(endpoint, **values)``. :return: the original generator function
625941dc8a43f66fc4b54354
def send(sender_name, sender_email, subject, text): <NEW_LINE> <INDENT> sender = sender_name + " <" + sender_email + ">" <NEW_LINE> server = "<your_smtp_server>" <NEW_LINE> user_name = "<your_mail_login>" <NEW_LINE> user_password = "<your_mail_password>" <NEW_LINE> message = MIMEText(text, 'plain', 'utf-8') <NEW_LINE> ...
Отправляем заявку пользователя на почту администратора
625941dcd4950a0f3b08c63d
def file_parse(file_name): <NEW_LINE> <INDENT> open_file = open(file_name, 'r') <NEW_LINE> indi = indis_list() <NEW_LINE> fam = fams_list() <NEW_LINE> indi_list = [] <NEW_LINE> fam_list = [] <NEW_LINE> fams = 0 <NEW_LINE> indis = 0 <NEW_LINE> for line in open_file: <NEW_LINE> <INDENT> str = line.split() <NEW_LINE> if s...
Parsing the file
625941dce8904600ed9f2222
def p_declaration_statement(self, t): <NEW_LINE> <INDENT> if len(t.slice) == 6: <NEW_LINE> <INDENT> t[0] = ast.Declaration( name=t[2], type=t[3], value=t[5], type_scope=self.type_scope_stack.get_current_scope() ) <NEW_LINE> <DEDENT> elif len(t.slice) == 4 and t.slice[1].type == common_grammar.KEYWORDS.VAR.value: <NEW_L...
declaration_statement : VAR NAME type_declaration EQUALS expression | VAR NAME type_declaration | NAME WALRUS expression
625941dc627d3e7fe0d69143
def input_check(self, msg, data_type='str', scope=0, li=[]): <NEW_LINE> <INDENT> def entry(msg): <NEW_LINE> <INDENT> ret = input('请输入%s,或输入q退出: ' % msg).strip() <NEW_LINE> return ret <NEW_LINE> <DEDENT> s1 = entry(msg) <NEW_LINE> li.append(s1) <NEW_LINE> if not s1: <NEW_LINE> <INDENT> print('%s不能为空!' % msg) <NEW_LINE> ...
:param func: 返回主菜单方法,比如年龄 :param msg: 提示信息,比如年龄 :param data_type: 数据类型,模式是str :param scope: 如果为数字类型,不能超过这个数字,比如256 :return: True 检测成功 False 检测失败
625941dc8a349b6b435e8465
def could_be_end_of_sentence( next_token: Tok, test_set: FrozenSet[int] = TOK.TEXT, multiplier: bool = False ) -> bool: <NEW_LINE> <INDENT> return next_token.kind in TOK.END or ( next_token.kind in test_set and next_token.txt[0].isupper() and next_token.txt.lower() not in MONTHS and not RE_ROMAN_NUMERAL.match(next_toke...
Return True if next_token could be ending the current sentence or starting the next one
625941dc63d6d428bbe447e1
def import_graph(graph_file_or_filepath, rdf_format: str=None) -> 'PP(A x A)': <NEW_LINE> <INDENT> if rdf_format is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rdf_format = _rdflib.util.guess_format(graph_file_or_filepath) or 'turtle' <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> rdf_format = 't...
Return an absolute clan that represents the RDF graph ``graph_file_or_filepath``. - The :term:`graph` is represented by a :term:`regular`, :term:`absolute clan`. - The :term:`left component`\s are 's' (subject), 'p' (predicate) and 'o' (object) (see :term:`triple`). - Blank nodes are converted to IRIs (skole...
625941dce5267d203edcdf8b
def within(sdf, other, relation="CLEMENTINI"): <NEW_LINE> <INDENT> global _HASARCPY, _HASSHAPELY <NEW_LINE> if _HASARCPY == False and _HASSHAPELY == False: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ud = pd.Series([False] * len(sdf)) <NEW_LINE> if isinstance(other, (Point, Polygon, Polyline, MultiPoint)): <NEW...
Indicates if the base geometry is within the comparison geometry. `within` is the opposite operator of `contains`. ========================= ========================================================= **Argument** **Description** ------------------------- ------------------------------------------...
625941dc7b180e01f3dc4aea
def setup_logging_default(app): <NEW_LINE> <INDENT> log_level_str = app.config['MYDOJO_LOG_DEFAULT_LEVEL'].upper() <NEW_LINE> log_level = getattr( logging, log_level_str, None ) <NEW_LINE> if not isinstance(log_level, int): <NEW_LINE> <INDENT> raise ValueError( 'Invalid default log level: %s' % log_level_str ) <NEW_LIN...
Setup default application logging features.
625941dc507cdc57c6306fd3
def runDataRef(self, dataRef, coordList, makeDataRefList=True, selectDataList=[]): <NEW_LINE> <INDENT> result = super(PsfWcsSelectImagesTask, self).runDataRef(dataRef, coordList, makeDataRefList, selectDataList) <NEW_LINE> dataRefList = [] <NEW_LINE> exposureInfoList = [] <NEW_LINE> for dataRef, exposureInfo in zip(res...
Select images in the selectDataList that overlap the patch and satisfy PSF quality critera. This method is the old entry point for the Gen2 commandline tasks and drivers Will be deprecated in v22. @param dataRef: Data reference for coadd/tempExp (with tract, patch) @param coordList: List of ICRS coordinates (lsst.geo...
625941dc15fb5d323cde0e05
def shotResult(self, shot, hit, sunk): <NEW_LINE> <INDENT> ShotSelector.shotResult(self, shot, hit, sunk) <NEW_LINE> coordinates = self.mapToCoordinates(shot) <NEW_LINE> if sunk: <NEW_LINE> <INDENT> self.shipsToSink.append(SinkingShip(coordinates, sunk)) <NEW_LINE> self.sinkShips() <NEW_LINE> <DEDENT> self.printShipsAf...
Attempts to sink as many sinking ships as possible given the shot result. Arguments shot - Shot of the form LetterNumber. hit - True, if the shot was a hit. sunk - Size of the sunk ship, if the shot sunk it.
625941dca934411ee3751986
def dalignbed2annotationsbed(cfg): <NEW_LINE> <INDENT> datatmpd=cfg['datatmpd'] <NEW_LINE> alignmentbedp=cfg['alignmentbedp'] <NEW_LINE> alignmentbedsortedp=alignmentbedp+'.sorted.bed' <NEW_LINE> logging.info(basename(alignmentbedsortedp)) <NEW_LINE> if not exists(alignmentbedsortedp) or cfg['force']: <NEW_LINE> <INDEN...
Get annotations from the aligned BED file step#3 :param cfg: configuration dict
625941dc4e4d5625662d46c6
def uniform_mutation(solution): <NEW_LINE> <INDENT> res = "" <NEW_LINE> for bit in solution: <NEW_LINE> <INDENT> if random.random() < 1/len(solution): <NEW_LINE> <INDENT> if bit == "0": <NEW_LINE> <INDENT> res += "1" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res += "0" <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> ...
Generate a solution mutated from a given solution; that is for each vertex, the corresponding bit in the solution may be flipped. Default mutation probability is 1/len(solution). Args: solution (string): starting solution Returns: (string) Mutated solution.
625941dcd8ef3951e324382f
def Blead(x, y, x0, y0, z0, w, I, direction, infinity): <NEW_LINE> <INDENT> assert direction in ('x', 'y') <NEW_LINE> assert infinity in ('+', '-') <NEW_LINE> if direction == 'x': <NEW_LINE> <INDENT> x, y, x0, y0 = y, x, y0, x0 <NEW_LINE> I *= -1 <NEW_LINE> <DEDENT> if infinity == '+': <NEW_LINE> <INDENT> alpha = -1 <N...
x/y (array-like): 1D or 2D array of x/y values x0/y0: termination point on device (m) z0: height above device (m) w: width of wire (m) I: bias current (A). Positive current flows in +`direction` direction ('x' or 'y'): direction of wire infinity ('+' or '-'): which infinity the wire extends to
625941dc379a373c97cfae38
def new_request( uri, method="GET", body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None, ): <NEW_LINE> <INDENT> if headers is None: <NEW_LINE> <INDENT> headers = {} <NEW_LINE> <DEDENT> if "user-agent" in headers: <NEW_LINE> <INDENT> headers["user-agent"] = user_agent + " " + heade...
Modify the request headers to add the user-agent.
625941dc2eb69b55b151cba4
def __init__(self, n_layers, in_channels, out_channels_init, out_channels_final, channel_growth, coord_conv, transfer_layer=False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.layer_size_init = np.asarray((32, 256, 256)) <NEW_LINE> self.transfer_layer = transfer_layer <NEW_LINE> if self.transfer_layer: <NEW_...
Generalized UNet class, meant to be highly modular. Allows for variable number of layers and other features, but is less human-readable as a result. Args: n_layers (int): Number of down (up) layers to generate. Must be >=0 (input and output layers count as zeroth layer) in_channels (int): Number of i...
625941dc462c4b4f79d1d9c2
def task_report_deps(): <NEW_LINE> <INDENT> return { 'file_dep': ['req.in', 'req-dev.in'], 'actions': [ 'echo D: {dependencies}, CH: {changed} > {targets}', 'cat %(targets)s', ], 'targets': ['report.txt'], }
Report dependencies and changed dependencies to a file.
625941dc4d74a7450ccd44b6
def get_logger(name=None, level=logbook.NOTSET): <NEW_LINE> <INDENT> base_name = 'threema.gateway' <NEW_LINE> name = base_name if name is None else '.'.join((base_name, name)) <NEW_LINE> logger = logbook.Logger(name=name, level=level) <NEW_LINE> _logger_group.add_logger(logger) <NEW_LINE> return logger
Return a :class:`logbook.Logger`. Arguments: - `name`: The name of a specific sub-logger.
625941dc55399d3f055889a7
def pdip(self, fig=None, colorbar=True): <NEW_LINE> <INDENT> if fig is None: <NEW_LINE> <INDENT> fig = plt.figure() <NEW_LINE> <DEDENT> for j, cl in self.clust.sample_clusts: <NEW_LINE> <INDENT> pdip = cl.get_pdip() <NEW_LINE> ax = fig.add_subplot(1, len(self.clust.sample_clusts), j+1) <NEW_LINE> p = ax.pcolormesh(pdip...
Plot p-value of Hartigan's dip test for each cluster. Results are plotted order by cluster size, with largest cluster in top.
625941dcbe7bc26dc91cd8ed
def take_turn(self, entities, fov_map, game_map): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if entities[0].x == self.x and entities[0].y == self.y: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i < entities[0].inventory_size and entities[0].inventory[i] is not None: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> if i >= ...
Checks if the player is on top of it and, if so, performs the code to obtain the item.
625941dcd99f1b3c44c6787c
def _measureComplexity(self, footlist, boundstest): <NEW_LINE> <INDENT> if len(footlist) != self.LD.data['lfeet']: return 100 <NEW_LINE> feet = footlist[:] <NEW_LINE> points = 0 <NEW_LINE> prevIsTrochee = False <NEW_LINE> for inx, f in enumerate(feet): <NEW_LINE> <INDENT> if f[0] == '(': f = f[1:-1] <NEW_LINE> if f in ...
Add up weighted points for each foot substituted for the iamb. The point system is highly arbitrary. It is not used to determine the basic foot of the line, but only to rank possibilities proposed by the caller, which is always DoAlgorithm. Somewhat streamlined during design of corresponding anapestic method.
625941dc07d97122c4178b83
def _GetTotalApis(self, package_name, version, interface_name): <NEW_LINE> <INDENT> total_apis = set() <NEW_LINE> spec_proto = CompSpecMsg.ComponentSpecificationMessage() <NEW_LINE> if not package_name.startswith(DEFAULT_HAL_ROOT): <NEW_LINE> <INDENT> logging.warning("Unsupported hal package: %s", package_name) <NEW_LI...
Parse the specified vts spec and get all APIs defined in the spec. Args: package_name: string, HAL package name. version: string, HAL version. interface_name: string, HAL interface name. Returns: A set of strings, each string represents an API defined in the spec.
625941dc3317a56b86939f44
def target(num1, num2): <NEW_LINE> <INDENT> for i in range(4): <NEW_LINE> <INDENT> print("Executing target: " + str(num1) + " with process: " + str(os.getpid()) + "\nWhose parent process is: " + str(os.getppid())) <NEW_LINE> time.sleep(num2) <NEW_LINE> <DEDENT> os.abort()
:param num1: :param num2: :return: none
625941dc15baa723493c4269
def fit(self, X, y): <NEW_LINE> <INDENT> if self.metric == 'precomputed': <NEW_LINE> <INDENT> raise ValueError("Precomputed is not supported.") <NEW_LINE> <DEDENT> if self.metric == 'manhattan': <NEW_LINE> <INDENT> X, y = check_X_y(X, y, ['csc']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> X, y = check_X_y(X, y, ['cs...
Fit the NearestCentroid model according to the given training data. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. Note that centroid shrinking cannot be used with spa...
625941dc5f7d997b87174d8c
def bfs(self, s, e): <NEW_LINE> <INDENT> if s == e: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> visited = []
广度优先搜索,找到一条从s到e的路径,也就是最短路径 :param s: 起始顶点 :param e: 终止顶点 :return:
625941dc10dbd63aa1bd2e94
@Float.register(["floor"]) <NEW_LINE> def floor(s: "Stream[float]") -> "Stream[float]": <NEW_LINE> <INDENT> return s.apply(np.floor).astype("float")
Computes the floor of a float stream. Parameters ---------- s : `Stream[float]` A float stream. Returns ------- `Stream[float]` The floor stream of `s`.
625941dcf9cc0f698b1408eb
def set_Longitude(self, value): <NEW_LINE> <INDENT> super(WeatherForSinglePointSummarizedInputSet, self)._set_input('Longitude', value)
Set the value of the Longitude input for this Choreo. ((required, decimal) Enter the longitude coordinate of the point for which weather data is requested. West longitude is negative.)
625941dcaad79263cf390d37
def compare_models(X, y): <NEW_LINE> <INDENT> n = 100 <NEW_LINE> res = {'logistic':[], 'knn':[], 'tree': []} <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=12) <NEW_LINE> clf = LogisticRegression() <NEW_LINE> clf.fit(X_train, y_tra...
比较模型 使用相同的数据集进行模型训练和预测,比较测试精度
625941dc3eb6a72ae02ec7d6
def write_gridspec_xy(pism, spec_fname): <NEW_LINE> <INDENT> with netCDF4.Dataset(spec_fname, 'w') as nc: <NEW_LINE> <INDENT> xc = pism['x_centers'] <NEW_LINE> xb = center_to_boundaries(xc) <NEW_LINE> nc.createDimension('grid.x_boundaries.length', len(xb)) <NEW_LINE> nc_xb = nc.createVariable('grid.x_boundaries', 'd', ...
Given info gleaned from PISM, writes it out as a GridSpec_XY that can be read by the grid generator.
625941dc15fb5d323cde0e06
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument("--host", default="127.0.0.1", help="listen host") <NEW_LINE> parser.add_argument("--port", type=int, default=5010, help="listen port") <NEW_LINE> args = parser.parse_args() <NEW_LINE> run_simple(args.host, args.port, app,...
Run the web application from the console.
625941dc7d847024c06be5b1
def all_gather_list(data, max_size=4096): <NEW_LINE> <INDENT> world_size = torch.distributed.get_world_size() <NEW_LINE> if not hasattr(all_gather_list, '_in_buffer') or max_size != all_gather_list._in_buffer.size(): <NEW_LINE> <INDENT> all_gather_list._in_buffer = torch.cuda.ByteTensor(max_size) <NEW_LINE> all_gather_...
Gathers arbitrary data from all nodes into a list.
625941dc0a50d4780f667187
def plot_sc( sc ): <NEW_LINE> <INDENT> plt.plot(range(2, len(sc) + 2), sc, 'o-.') <NEW_LINE> plt.xlabel('value of k') <NEW_LINE> plt.ylabel('Silhouette-Coefficient score') <NEW_LINE> plt.grid(False) <NEW_LINE> plt.savefig('/home/renqiang/Desktop/2018MCMICM/TheThirdPractice/goodgrant/picture/Silhouette-Coefficient.png')...
画 Silhouette-Coefficient score :param ss: 要画的Silhouette-Coefficient score :return: None
625941dc7cff6e4e81117c78
def find_controllers(bus): <NEW_LINE> <INDENT> remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, "/"), DBUS_OM_IFACE) <NEW_LINE> objects = remote_om.GetManagedObjects() <NEW_LINE> controllers = [] <NEW_LINE> for o, props in objects.items(): <NEW_LINE> <INDENT> if GATT_MANAGER_IFACE in props.keys(): <NEW_LIN...
Returns objects that have the bluez service and a GattManager1 interface
625941dc07f4c71912b11776
def _find_unreferenced(self, local_vars="", indent=" "): <NEW_LINE> <INDENT> unreferenced = [] <NEW_LINE> for p in self.plist: <NEW_LINE> <INDENT> if not re.search( r'\b%s\b' % p.name, self.code + local_vars, re.IGNORECASE): <NEW_LINE> <INDENT> unreferenced.append(p.name) <NEW_LINE> <DEDENT> <DEDENT> if unreferenced:...
List the pragma Unreferenced statements that are needed for this subprogram.
625941dc31939e2706e4d158
def move_car(self, road): <NEW_LINE> <INDENT> self.position += self.speed <NEW_LINE> if self.position > road.length: <NEW_LINE> <INDENT> self.position = self.position % road.length
Change position of car on road based on speed
625941dc07f4c71912b11777
def load_split(data_dir=DEFAULT_DATA_DIR, val=True, permute=False, normalize=True, num_val=2000, seed=None): <NEW_LINE> <INDENT> train_images, train_labels, test_images, test_labels = load(data_dir) <NEW_LINE> H, W, C = HEIGHT, WIDTH, NUM_CHANNELS <NEW_LINE> if val: <NEW_LINE> <INDENT> num_train = train_images.shape[0]...
Load an MNIST train, test split. Args: data_dir: A string. The data directory. val: A boolean. If True, do not return any real test data. Instead, return a test set that is actually a validation set, formed by splitting the train set into two parts. permute: A boolean. If True, permute pixels in a random...
625941dcbe383301e01b5773
def inherit_group_privileges(stem, subject, privileges=[], stem_scope="SUB", filter_string=""): <NEW_LINE> <INDENT> valid_privileges = set(["read", "admin", "update", "view", "optin", "optout"]) <NEW_LINE> privileges = set(privileges) & valid_privileges <NEW_LINE> rule_config = { RULES_ATTRIBUTE_CHECK_OWNER_NAME: stem,...
inherit_group_privileges(stem, subject, privileges=[], stem_scope="SUB", filter_string="") Groups created within the specified stem have the specified privileges automatically assigned to the specified subject.
625941dc01c39578d7e7512e
def __init__(self, data: pd.DataFrame): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.data.loc[self.data.infection_momentum.isna(), "infection_momentum"] = 1 <NEW_LINE> self.zmat = torch.sqrt( torch.tensor(self.data["acs_pop_total"].values, dtype=torch.float32) ) / torch.sqrt( torch.sum(torch.tensor(self.data["a...
Initialize the internal rep of the dataset. Args: data (DataFrame): data from upstream, to be split into (X, y, weight) triples
625941dc9f2886367277ab7e
def test_bhl_contributor_to_collection2(): <NEW_LINE> <INDENT> INPUT = { "key1": "value1", "sourceResource": { "key1" : "value1", "contributor": "Missouri Botanical Garden, Peter H. Raven Library", "collection": { "@id": "http://dp.la/api/collections/bhl--item", "name": "Item Collection" } } } <NEW_LINE> EXPECTED = { "...
Should copy contributor to collection name and contributor acronym to collection @id
625941dc851cf427c661a7ff
def GPI_usage_percent(self, task_index): <NEW_LINE> <INDENT> counts = self.gpi_counters[task_index] <NEW_LINE> return 1. - (float(counts[task_index]) / np.sum(counts))
Counts the number of times that actions were transferred from other tasks. Parameters ---------- task_index : integer the index of the task Returns ------- float : the (normalized) number of actions that were transferred from other tasks in GPi.
625941dc63f4b57ef0001404
def topKFrequent(self, nums, k): <NEW_LINE> <INDENT> frequency={} <NEW_LINE> for i in nums: <NEW_LINE> <INDENT> if i not in frequency: <NEW_LINE> <INDENT> frequency[i]=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> frequency[i]+=1 <NEW_LINE> <DEDENT> <DEDENT> result=sorted(frequency,key=lambda w:(-frequency[w],w))[:k]...
:type nums: List[int] :type k: int :rtype: List[int]
625941dcb5575c28eb68e2f5
def generic_error_handler(error_object, status_code): <NEW_LINE> <INDENT> resp_dict = { "success": False, "message": error_object.__class__.__name__ + ": " + str(error_object), "status_code": status_code } <NEW_LINE> response = jsonify(resp_dict) <NEW_LINE> response.status_code = status_code <NEW_LINE> return response
:param error_object: Exception object :type error_object: Exception :param status_code: HTTP error code :type status_code: int :rtype: object
625941dce64d504609d74b32
def GetPointer(self): <NEW_LINE> <INDENT> return _itkMinMaxCurvatureFlowImageFilterPython.itkMinMaxCurvatureFlowImageFilterIF3IF3_GetPointer(self)
GetPointer(self) -> itkMinMaxCurvatureFlowImageFilterIF3IF3
625941dc460517430c394471
def test_init(self): <NEW_LINE> <INDENT> b1 = Base() <NEW_LINE> self.assertEqual(b1.id, 1) <NEW_LINE> b2 = Base() <NEW_LINE> self.assertEqual(b2.id, 2) <NEW_LINE> b2 = Base() <NEW_LINE> self.assertEqual(b2.id, 3)
Initialize with no arguments
625941dcfb3f5b602dac3989
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941dc4527f215b584c747
def inbreeding_co(plink_file_stage): <NEW_LINE> <INDENT> print ("Stage Four --- Removing individual with inbreeding coefficient > 0.2") <NEW_LINE> plink_cmd = ("plink --bfile "+ plink_file_stage +" --het --out inbreeding") <NEW_LINE> p = execute(plink_cmd) <NEW_LINE> Popen(""" awk ' $6 > 0.2 ' inbreeding.het | awk ' { ...
Inbreeding Coefficient
625941dc4a966d76dd551304
def add_cog(self, cog): <NEW_LINE> <INDENT> self.cogs[type(cog).__name__] = cog <NEW_LINE> try: <NEW_LINE> <INDENT> check = getattr(cog, '_{.__class__.__name__}__check'.format(cog)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add_check(check) <N...
Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. They are meant as a way to organize multiple relevant commands into a singular class that shares some state or no state at all. The cog can also have a ``__check`` member function that allows you to define a global check. See :m...
625941dc99cbb53fe6792ed9
def __add_clicked(self, obj): <NEW_LINE> <INDENT> skip_list = set() <NEW_LINE> iii = self.__model.get_iter_first() <NEW_LINE> while iii: <NEW_LINE> <INDENT> surname = self.__model.get_value(iii, 0) <NEW_LINE> skip_list.add(surname.encode('iso-8859-1', 'xmlcharrefreplace')) <NEW_LINE> iii = self.__model.iter_next(iii) <...
Handle the add surname button.
625941dc4e696a04525c973f
def setGain(self, x): <NEW_LINE> <INDENT> self._gain = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setGain(wrap(x,i)) for i, obj in enumerate(self._base_objs)]
Set the gain of the anaysis data. For drawing purpose. :Args: x : float new `gain` attribute, as linear values.
625941dcc4546d3d9de72d29
def __eq__(self, other): <NEW_LINE> <INDENT> if other == None: return False <NEW_LINE> if id(self) == id(other): return True <NEW_LINE> return self.terms == other.terms
Tests whether a Dimension is equivalent to this Dimension.
625941dc91af0d3eaac9bd0e
def set_user_hidden(user_id: int, hidden: bool) -> None: <NEW_LINE> <INDENT> user = get_user(user_id) <NEW_LINE> user.is_hidden = hidden <NEW_LINE> db.session.add(user) <NEW_LINE> db.session.commit()
Set whether a user should be hidden from user lists. :param user_id: the user ID of an existing user :param hidden: True, if the user should be hidden, False otherwise :raise errors.UserDoesNotExistError: when no user with the given user ID exists
625941dc24f1403a92600e57
def exit_example(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> print('Type exit to exit') <NEW_LINE> response = input() <NEW_LINE> if response == 'exit': <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> print('You typed ' + response + '.')
This is a test of the sys.exit() function imported from 'sys' module
625941dc23e79379d52ee853
def charter(self): <NEW_LINE> <INDENT> return Charter.objects.filter(member=self.user)
List of active charters to the player
625941dc2ae34c7f2600d424
@pytest.mark.parametrize("compressor_type", [ pytest.param(("XZ", LZMACompressor), id="XZ"), pytest.param(("BZ2", BZ2Compressor), id="BZ2"), pytest.param(("GZ", GzipCompressor), id="GZ"), pytest.param(("", NoneCompressor), id="Normal") ]) <NEW_LINE> def test_register_compressor_again(compressor_type): <NEW_LINE> <INDEN...
Test adding a compressor again.
625941dcd58c6744b4257f51
def test_0020_import_sale_order_with_exception(self): <NEW_LINE> <INDENT> Sale = POOL.get('sale.sale') <NEW_LINE> Party = POOL.get('party.party') <NEW_LINE> Product = POOL.get('product.product') <NEW_LINE> ChannelException = POOL.get('channel.exception') <NEW_LINE> with Transaction().start(DB_NAME, USER, CONTEXT): <NEW...
Tests if exception is created for sale order when order total mismatch
625941dccad5886f8bd272cc
def drawIndexEntryEnd(canvas, kind, label): <NEW_LINE> <INDENT> style = self.getLevelStyle(leveloffset) <NEW_LINE> pages = loads(decodestring(label)) <NEW_LINE> drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot)
Callback to draw dots and page numbers after each entry.
625941dcf548e778e58cd872
def test_max_at_middle(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([3, 4, 3]), 4)
Test max at the middle.
625941dc8e71fb1e9831da9b
def build_label(prob_yes, prob_no, label_yes): <NEW_LINE> <INDENT> label = "Not {}".format(label_yes) if prob_no > prob_yes else label_yes <NEW_LINE> proba = prob_no if prob_no > prob_yes else prob_yes <NEW_LINE> label = "{}: {:.2f}%".format(label, proba * 100) <NEW_LINE> return label
show the result
625941dcfff4ab517eb2f730
def get_test_func(test_func=None): <NEW_LINE> <INDENT> if getattr(settings, 'SHOP_FORCE_LOGIN', False): <NEW_LINE> <INDENT> if test_func: <NEW_LINE> <INDENT> return test_func <NEW_LINE> <DEDENT> return lambda u: u.is_authenticated() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return lambda u: True
Returns the test function to be used for authentication and takes the setting `SHOP_FORCE_LOGIN` into consideration. :param test_func: Optional. You can provide your own test function for authentication. This should be a lambda expression.
625941dc4428ac0f6e5baae7
def search(self, nums, target): <NEW_LINE> <INDENT> if len(nums) == 0 or nums is None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> left = 0 <NEW_LINE> right = len(nums)-1 <NEW_LINE> while left <= right: <NEW_LINE> <INDENT> mid = (left + right)/2 <NEW_LINE> mid = int(float(mid)) <NEW_LINE> if target < nums[mid]: <...
:type nums: List[int] :type target: int :rtype: int
625941dc7b25080760e3974b
def makeAllVariantsReplacements(streamWithVariants, variantNames=None, inPlace=False, recurse=False): <NEW_LINE> <INDENT> if inPlace is True: <NEW_LINE> <INDENT> returnStream = streamWithVariants <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> returnStream = copy.deepcopy(streamWithVariants) <NEW_LINE> <DEDENT> if recurs...
This function takes a stream and a list of variantNames (default works on all variants), and changes all insertion (elongations with replacementDuration 0) and deletion variants (with containedHighestTime 0) into variants with non-zero replacementDuration and non-null elements by adding measures on the front of inserti...
625941dc66656f66f7cbc4a0
def _parse_feature(self, feature_location, input_file_handle): <NEW_LINE> <INDENT> input_file_handle.seek(feature_location) <NEW_LINE> line = input_file_handle.readline() <NEW_LINE> line = re.split(',|\r|\n', line) <NEW_LINE> feature_id = line[deepnovo_config.col_feature_id] <NEW_LINE> feature_area = 0 <NEW_LINE> precu...
TODO(nh2tran): docstring.
625941dc796e427e537b08bb
def load_settings(self, path): <NEW_LINE> <INDENT> raise NotImplementedError("Doesn't work yet.")
Load camera settings from path. DOESNT WORK YET
625941dc7d847024c06be5b2
def pop(self) : <NEW_LINE> <INDENT> if len(self.myQueue) != 0 : <NEW_LINE> <INDENT> del self.myQueue[0]
queue에서 가장 앞에 있는 값을 제거하고, 그 수를 return 합니다. 만약 queue에 들어있는 값이 없을 경우에는 -1을 return 합니다.
625941dca05bb46b383ecb13
def most_specific_common_supertype(self, others: Sequence[trace.TraceType]): <NEW_LINE> <INDENT> if not all(self._has_same_structure(other) for other in others): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> new_components = [] <NEW_LINE> for i, component in enumerate(self.components): <NEW_LINE> <INDENT> common ...
See base class.
625941dc1b99ca400220ada6
def __call__(self, loss_type, assets, gmfs, _epsilons=None, _tags=None): <NEW_LINE> <INDENT> ffs = self.risk_functions['damage'] <NEW_LINE> damages = numpy.array( [[scientific.scenario_damage(ffs, gmv) for gmv in gmvs] for gmvs in gmfs]) <NEW_LINE> return scientific.Output(assets, 'damage', damages=damages)
:param loss_type: the string 'damage' :param assets: a list of N assets of the same taxonomy :param gmfs: an array of N x R elements :returns: an array of N assets and an array of N x R x D elements where N is the number of points, R the number of realizations and D the number of damage states.
625941dccc0a2c11143dd184
def plot(self, ax=None, show=True, plot_kwargs={'color':'b', 'marker':'o', 'lw':0}): <NEW_LINE> <INDENT> if ax is None: <NEW_LINE> <INDENT> ax = plt.gca() <NEW_LINE> <DEDENT> ax.plot(self.times.jd, self.fluxes, **plot_kwargs) <NEW_LINE> ax.set(xlabel='Time', ylabel='Flux', title=self.name) <NEW_LINE> def format_coord(x...
Plot light curve
625941dcadb09d7d5db6ca81
def read_from_json_file(filename: str) -> dict: <NEW_LINE> <INDENT> file = open(filename, 'r') <NEW_LINE> data = json.loads(file.read()) <NEW_LINE> file.close() <NEW_LINE> return data
Read the data from a json file. Parameters ---------- filename : str name of the file Returns ------- data : dict all data of the file
625941dc4f6381625f114d2f
def __sub__(self, other): <NEW_LINE> <INDENT> if isinstance(other, numbers.Number): <NEW_LINE> <INDENT> return self.value - other <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> total_bytes = self._byte_value - other.bytes <NEW_LINE> return (type(self))(bytes=total_bytes)
Supported operations with result types: - bm - bm = bm - bm - num = num - num - bm = num (see rsub)
625941dc66673b3332b92385
def s_matrix(sys, energies): <NEW_LINE> <INDENT> s = [] <NEW_LINE> for energy in energies: <NEW_LINE> <INDENT> s.append(kwant.smatrix(sys, energy)) <NEW_LINE> <DEDENT> return s
Compute the S-Matrix as a function of energy. Return a list of s of type <class 'kwant.solvers.common.SMatrix'>.
625941dc8a43f66fc4b54356
def mpf_zeta_int(s, prec, rnd=round_fast): <NEW_LINE> <INDENT> wp = prec + 20 <NEW_LINE> s = int(s) <NEW_LINE> if s < 2: <NEW_LINE> <INDENT> if s == 1: <NEW_LINE> <INDENT> raise ValueError("zeta(1) pole") <NEW_LINE> <DEDENT> if not s: <NEW_LINE> <INDENT> return mpf_neg(fhalf) <NEW_LINE> <DEDENT> return mpf_div(mpf_bern...
Optimized computation of zeta(s) for an integer s.
625941dc377c676e9127249b
def __setitem__(self, key, val): <NEW_LINE> <INDENT> super().__setitem__(key, val) <NEW_LINE> self._dumps()
Write data to the database.
625941dc96565a6dacc8f9be
def isCompatible(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.derivation == other.derivation <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return self.derivation == self.zero
Predicate that checks whether {other} has the same derivation as I do
625941dcbaa26c4b54cb1410
def maxSlidingWindow(self, nums, k): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if k == 0: <NEW_LINE> <INDENT> return nums <NEW_LINE> <DEDENT> indices = deque() <NEW_LINE> ans = [0] * (len(nums)-k+1) <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> while len(indices) != ...
:type nums: List[int] :type k: int :rtype: List[int]
625941dc8a349b6b435e8467
def to_json(self, simple=False): <NEW_LINE> <INDENT> return json.dumps(self.dict(simple=simple))
Returns a json string
625941dc596a897236089db1
def next(self): <NEW_LINE> <INDENT> pass
Returns a tuple whose first element is a command, and second element is an output.
625941dc44b2445a33932388
@pytest.fixture <NEW_LINE> def parameters_config(magic_dir): <NEW_LINE> <INDENT> filename = 'parameters.yaml' <NEW_LINE> config = magic_dir / filename <NEW_LINE> content = Path(__file__).parent.joinpath('files').joinpath(filename).read_text() <NEW_LINE> config.write_text(content) <NEW_LINE> yield config <NEW_LINE> os.r...
Provides a config file with parameters in the temp directory.
625941dce5267d203edcdf8d
def get_deposit_address(self, **params): <NEW_LINE> <INDENT> return self._request_withdraw_api('get', 'depositAddress.html', True, data=params)
Fetch a deposit address for a symbol
625941dc8e05c05ec3eea66a
def __repr__(self): <NEW_LINE> <INDENT> if self._have_basic: <NEW_LINE> <INDENT> info = [("Title", self.title), ("Author", self.author), ("ID", self.videoid), ("Duration", self.duration), ("Rating", self.rating), ("Views", self.viewcount), ("Thumbnail", self.thumb)] <NEW_LINE> nfo = "\n".join(["%s: %s" % i for i in inf...
Print video metadata. Return utf8 string.
625941dc7b180e01f3dc4aec
def lr_schedule(epoch): <NEW_LINE> <INDENT> lr = 0.001 <NEW_LINE> if epoch % 30 == 0 and epoch > 0: <NEW_LINE> <INDENT> lr *= 0.1 ** (epoch / 30) <NEW_LINE> <DEDENT> print('Learning rate: ', lr) <NEW_LINE> return lr
Learning rate is set to reduce by a factor of 10 after every 30 epochs
625941dc566aa707497f4859
def _action(self, action, volume, info=None, **kwargs): <NEW_LINE> <INDENT> body = {action: info} <NEW_LINE> self.run_hooks('modify_body_for_action', body, **kwargs) <NEW_LINE> url = '/volumes/%s/action' % base.getid(volume) <NEW_LINE> resp, body = self.api.client.post(url, body=body) <NEW_LINE> return common_base.Tupl...
Perform a volume "action."
625941dc0c0af96317bb84dc
def deactivate(self): <NEW_LINE> <INDENT> pass
Called at plugin deactivation, after bootloader has been installed.
625941dc4e4d5625662d46c8
def finditer(string): <NEW_LINE> <INDENT> p = re.compile(r'\d+') <NEW_LINE> ret1 = p.finditer('hello 123456 789') <NEW_LINE> ret2 = p.finditer(string, 0, 10) <NEW_LINE> print(type(ret1), type(ret2)) <NEW_LINE> for m1 in ret1: <NEW_LINE> <INDENT> print('matching string: {}, position: {}'.format(m1.group(), m1.span())) <...
[finditer] [finditer 方法的行为跟 findall 的行为类似,也是搜索整个字符串, 获得所有匹配的结果。但它返回一个顺序访问每一个匹配结果(Match 对象)的迭代器。] Arguments: string {[type]} -- [description]
625941dcd8ef3951e3243831
def c_let(self, syms, *code): <NEW_LINE> <INDENT> if type(syms) != list: <NEW_LINE> <INDENT> raise PolicyError('Expecting list as arg 1 in let') <NEW_LINE> <DEDENT> self.stack.enter_scope() <NEW_LINE> for sym in syms: <NEW_LINE> <INDENT> if type(sym) != list or len(sym) != 2: <NEW_LINE> <INDENT> raise PolicyError('Expe...
code code ...
625941dcb830903b967e9bfc
def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance.district_state = validated_data.get('district_state', instance.district_state) <NEW_LINE> instance.district_city = validated_data.get('district_city', instance.district_city) <NEW_LINE> instance.district_code = validated_data.get('district_code', ...
Update and return an existing `District` instance, given the validated data.
625941dc2eb69b55b151cba6
def flush(*args): <NEW_LINE> <INDENT> pass
fake flush
625941dc8e05c05ec3eea66b
@uber_vcr.use_cassette() <NEW_LINE> def test_cancel_current_ride(authorized_rider_sandbox_client): <NEW_LINE> <INDENT> response = authorized_rider_sandbox_client.cancel_current_ride() <NEW_LINE> assert response.status_code == codes.no_content
Test to cancel the current ride with access token.
625941dc4d74a7450ccd44b7
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941dc6fb2d068a760f395
def draw_lines_heatmap_array(self, image_shape, alpha=1.0, size=1, antialiased=True, raise_if_out_of_image=False): <NEW_LINE> <INDENT> assert len(image_shape) == 2 or ( len(image_shape) == 3 and image_shape[-1] == 1), ( "Expected (H,W) or (H,W,1) as image_shape, got %s." % ( image_shape,)) <NEW_LINE> arr = self.draw_li...
Draw the line segments of this line string as a heatmap array. Parameters ---------- image_shape : tuple of int The shape of the image onto which to draw the line mask. alpha : float, optional Opacity of the line string. Higher values denote a more visible line string. size : int, optional Thickness ...
625941dc4d74a7450ccd44b8
def default_facets_view ( self ): <NEW_LINE> <INDENT> return View( HGroup( VGroup( Item( 'content', style = 'custom' ), group_theme = margin_theme, label = 'Content', show_labels = False ), VGroup( Item( 'label', style = 'custom' ), group_theme = margin_theme, label = 'Label', show_labels = False ), VGroup(...
Returns the default facets view for the object's class.
625941dcd99f1b3c44c6787e
def __setSubscriptionEnabled(self, subscription, enable): <NEW_LINE> <INDENT> if enable: <NEW_LINE> <INDENT> sub = self.__manager.subscription(subscription.requiresLocation()) <NEW_LINE> requiresSubscriptions = [] if sub is None else [sub] <NEW_LINE> icon = UI.PixmapCache.getIcon("adBlockPlus.png") <NEW_LINE> <DEDENT> ...
Private slot to set the enabled state of a subscription. @param subscription subscription to set the state for (AdBlockSubscription) @param enable state to set to (boolean)
625941dc656771135c3ebb66