content
stringlengths
22
815k
id
int64
0
4.91M
def display(): """ duisplay the banner """ print(color(" β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”", fg="#b61042")) print( color(" β”‚ ", fg="#b61042") + color(f"Ο€-hole 5 list tool v{__version__}", "#FFF") + color(" β”‚", fg="#b61042") ) print(color(" β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜", fg="#b61042")) utils.info(" https://github.com/jessedp/pihole5-list-tool\n")
5,345,600
def calculate_class_probabilities(summaries, row) -> dict(): """ Calculate the probability of a value using the Gaussian Probability Density Function from inputs: summaries: prepared summaries of dataset row: a row in the dataset for predicting its label (a row of X_test) This function uses the statistics calculated from training data to calculate probabilities for the testing dataset (new data). Probabilities are calculated separately for each class. First, we calculate the probability that a new X vector from the testing dataset belongs to the first class. Then, we calculate the probabilities that it belongs to the second class, and so on for all the classes identified in the training dataset. The probability that a new X vector from the testing dataset belongs to a class is calculated as follows: P(class|data) = P(X|class) * P(class) Note we have simplified the Bayes theorem by removing the division as we do not strictly need a number between 0 and 1 to predict the class the new data belongs to as we will be simply taking the maximum result from the above equation for each class. It returns a dictionary where each key is the class label and the values are the probabibilities of that row belonging to each class on the dataset. """ # total number of training records calculated from the counts stored in the summary statistics # note that the count column has the same value for all rows, and hence picking up item [0] will suffice total_rows = sum([summaries[label]['count'][0] for label in summaries]) probabilities = dict() for class_value, class_summaries in summaries.items(): probabilities[class_value] = summaries[class_value]['count'][0]/float(total_rows) for i in range(len(class_summaries)-1): mean, stdev, _ = class_summaries.iloc[i] # probabilities are multiplied together as they accumulate. probabilities[class_value] *= calculate_probability(row[i], mean, stdev) # normalize probabilities so that they sum 1 max_prob = probabilities[max(probabilities, key=probabilities.get)] min_prob = probabilities[min(probabilities, key=probabilities.get)] for class_value, probability in probabilities.items(): if (max_val - min_val) > 0: probabilities[class_value] = (probability - min_val) / (max_val - min_val) else: probabilities[class_value] = float(0.0) sum_prob = sum(probabilities.values()) for class_value, probability in probabilities.items(): if sum_prob > 0: probabilities[class_value] = probability / sum_prob return probabilities
5,345,601
def discard_missing_files(df: pd.DataFrame, path_colname: str) -> pd.DataFrame: """Discard rows where the indicated file does not exist or has filesize 0. Log a warning with the number of rows discarded, if not zero. Args: df path_colname: Name of `df` column that specifies paths to check """ logging.info('Discarding missing files') nrows_before = len(df) file_exists = df.loc[:, path_colname].progress_apply( lambda x: os.path.isfile(x) and os.path.getsize(x) > 0 ) nrows_after = file_exists.sum() if nrows_after < nrows_before: logging.warning(f'{nrows_before - nrows_after} records discarded ' f'because file does not exist or is empty.' ) return df.loc[file_exists, :]
5,345,602
def find(sequence: Sequence, target_element: Any) -> int: """Find the index of the first occurrence of target_element in sequence. Args: sequence: A sequence which to search through target_element: An element to search in the sequence Returns: The index of target_element's first occurrence, -1 if it was not found or the sequence is empty """ if not sequence: return -1 try: return sequence.index(target_element) except ValueError: return -1
5,345,603
def read_time_data(fname, unit): """ Read time data (csv) from file and load into Numpy array """ data = np.loadtxt(fname, delimiter=',') t = data[:,0] x = data[:,1]*unit f = interp1d(t, x, kind='linear', bounds_error=False, fill_value=x[0]) return f
5,345,604
def configure_concepts(cursor,load_concepts,author): """This method configures concepts when a NEW CONFIGURATION is performed""" if author == 'admin': to_add = 'Manual and Automatic' elif author == 'robot': to_add = 'Automatic' for usecase in load_concepts: disease = '' if usecase.lower() == 'colon': disease = 'colon carcinoma' elif usecase.lower() == 'uterine cervix': disease = 'cervical cancer' elif usecase.lower() == 'lung': disease = 'lung cancer' if disease != '': workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in r = process_ontology(workpath,disease) # convert query output to DataFrame belong_to = [] concept_has_uc = [] conc = [] with transaction.atomic(): cursor.execute("SELECT c.concept_url FROM concept AS c inner join concept_has_uc as ch on ch.concept_url = c.concept_url where annotation_mode in %s and ch.name = %s",[tuple(['Manual','Manual and Automatic']),usecase]) ans = cursor.fetchall() if len(ans) > 0: concepts = [] for el in ans: concepts.append(el[0]) if author == 'admin': cursor.execute("DELETE FROM ground_truth_log_file WHERE gt_type = %s and (id_report,language) in (SELECT id_report, language FROM contains WHERE concept_url in %s AND ns_id = %s)", ['concepts',tuple(concepts),'Human']) cursor.execute("DELETE FROM ground_truth_log_file WHERE gt_type = %s and (id_report,language) in (SELECT id_report, language FROM linked WHERE concept_url in %s AND ns_id = %s)", ['concept-mention',tuple(concepts),'Human']) cursor.execute("DELETE FROM contains WHERE concept_url in %s AND ns_id = %s",[tuple(concepts),'Human']) cursor.execute("DELETE FROM linked WHERE concept_url in %s AND ns_id = %s", [tuple(concepts),'Human']) cursor.execute("DELETE FROM belong_to WHERE concept_url in %s ", [tuple(concepts)]) cursor.execute("DELETE FROM concept_has_uc WHERE concept_url in %s", [tuple(concepts)]) cursor.execute("DELETE FROM concept WHERE concept_url in %s", [tuple(concepts)]) cursor.execute( "SELECT c.concept_url FROM concept AS c inner join concept_has_uc as ch on ch.concept_url = c.concept_url where annotation_mode = %s and ch.name = %s", ['Automatic', usecase]) ans_auto = cursor.fetchall() if len(ans_auto) > 0: concepts = [] for el in ans_auto: concepts.append(el[0]) if author == 'admin': cursor.execute("UPDATE concept SET annotation_mode = %s WHERE annotation_mode = %s", ['Manual and Automatic', 'Automatic']) for e in r: if (e[0] is not None and e[1] is not None and e[2] is not None): concept = e[0].toPython() # print(e[2].toPython()) if concept == 'SevereColonDysplasia': concept = 'https://w3id.org/examode/ontology/SevereColonDysplasia' elif concept == 'uterusNOS': concept = 'https://w3id.org/examode/ontology/UterusNOS' cursor.execute("SELECT * FROM semantic_area WHERE name = %s",[e[2].toPython()]) ans = cursor.fetchall() if len(ans) == 0: cursor.execute("INSERT INTO semantic_area VALUES(%s)",[e[2].toPython()]) belong_to.append((concept, e[2].toPython())) concept_has_uc.append((concept, usecase)) conc.append((concept, e[1].toPython(), None)) cursor.execute('SELECT * FROM concept WHERE concept_url = %s',(concept,)) ans = cursor.fetchall() if len(ans) == 0: query = ("INSERT INTO concept (concept_url,name,annotation_mode) VALUES(%s,%s,%s);") values = (concept, e[1].toPython(),to_add) cursor.execute(query, values) # elif author == 'admin': else: cursor.execute("UPDATE concept SET annotation_mode = %s WHERE concept_url = %s", ['Manual and Automatic', e[0].toPython()]) cursor.execute('SELECT * FROM belong_to WHERE concept_url = %s AND name=%s',[concept,e[2].toPython()]) if len(cursor.fetchall()) == 0: query1 = ("INSERT INTO belong_to (name, concept_url) VALUES(%s,%s);") values1 = (e[2].toPython(), concept) cursor.execute(query1, values1) cursor.execute('SELECT * FROM concept_has_uc WHERE concept_url = %s AND name=%s',[concept,usecase.lower()]) if len(cursor.fetchall()) == 0: query2 = ("INSERT INTO concept_has_uc (concept_url,name) VALUES(%s,%s);") values2 = (concept, usecase.lower()) cursor.execute(query2, values2)
5,345,605
def main(): """run the test suite""" usage = "usage: %prog [options] file" nose.run()
5,345,606
def get_compliance_detail(PolicyId=None, MemberAccount=None): """ Returns detailed compliance information about the specified member account. Details include resources that are in and out of compliance with the specified policy. Resources are considered noncompliant for AWS WAF and Shield Advanced policies if the specified policy has not been applied to them. Resources are considered noncompliant for security group policies if they are in scope of the policy, they violate one or more of the policy rules, and remediation is disabled or not possible. See also: AWS API Documentation Exceptions :example: response = client.get_compliance_detail( PolicyId='string', MemberAccount='string' ) :type PolicyId: string :param PolicyId: [REQUIRED]\nThe ID of the policy that you want to get the details for. PolicyId is returned by PutPolicy and by ListPolicies .\n :type MemberAccount: string :param MemberAccount: [REQUIRED]\nThe AWS account that owns the resources that you want to get the details for.\n :rtype: dict ReturnsResponse Syntax { 'PolicyComplianceDetail': { 'PolicyOwner': 'string', 'PolicyId': 'string', 'MemberAccount': 'string', 'Violators': [ { 'ResourceId': 'string', 'ViolationReason': 'WEB_ACL_MISSING_RULE_GROUP'|'RESOURCE_MISSING_WEB_ACL'|'RESOURCE_INCORRECT_WEB_ACL'|'RESOURCE_MISSING_SHIELD_PROTECTION'|'RESOURCE_MISSING_WEB_ACL_OR_SHIELD_PROTECTION'|'RESOURCE_MISSING_SECURITY_GROUP'|'RESOURCE_VIOLATES_AUDIT_SECURITY_GROUP'|'SECURITY_GROUP_UNUSED'|'SECURITY_GROUP_REDUNDANT', 'ResourceType': 'string' }, ], 'EvaluationLimitExceeded': True|False, 'ExpiredAt': datetime(2015, 1, 1), 'IssueInfoMap': { 'string': 'string' } } } Response Structure (dict) -- PolicyComplianceDetail (dict) -- Information about the resources and the policy that you specified in the GetComplianceDetail request. PolicyOwner (string) -- The AWS account that created the AWS Firewall Manager policy. PolicyId (string) -- The ID of the AWS Firewall Manager policy. MemberAccount (string) -- The AWS account ID. Violators (list) -- An array of resources that aren\'t protected by the AWS WAF or Shield Advanced policy or that aren\'t in compliance with the security group policy. (dict) -- Details of the resource that is not protected by the policy. ResourceId (string) -- The resource ID. ViolationReason (string) -- The reason that the resource is not protected by the policy. ResourceType (string) -- The resource type. This is in the format shown in the AWS Resource Types Reference . For example: AWS::ElasticLoadBalancingV2::LoadBalancer or AWS::CloudFront::Distribution . EvaluationLimitExceeded (boolean) -- Indicates if over 100 resources are noncompliant with the AWS Firewall Manager policy. ExpiredAt (datetime) -- A timestamp that indicates when the returned information should be considered out of date. IssueInfoMap (dict) -- Details about problems with dependent services, such as AWS WAF or AWS Config, that are causing a resource to be noncompliant. The details include the name of the dependent service and the error message received that indicates the problem with the service. (string) -- (string) -- Exceptions FMS.Client.exceptions.ResourceNotFoundException FMS.Client.exceptions.InternalErrorException :return: { 'PolicyComplianceDetail': { 'PolicyOwner': 'string', 'PolicyId': 'string', 'MemberAccount': 'string', 'Violators': [ { 'ResourceId': 'string', 'ViolationReason': 'WEB_ACL_MISSING_RULE_GROUP'|'RESOURCE_MISSING_WEB_ACL'|'RESOURCE_INCORRECT_WEB_ACL'|'RESOURCE_MISSING_SHIELD_PROTECTION'|'RESOURCE_MISSING_WEB_ACL_OR_SHIELD_PROTECTION'|'RESOURCE_MISSING_SECURITY_GROUP'|'RESOURCE_VIOLATES_AUDIT_SECURITY_GROUP'|'SECURITY_GROUP_UNUSED'|'SECURITY_GROUP_REDUNDANT', 'ResourceType': 'string' }, ], 'EvaluationLimitExceeded': True|False, 'ExpiredAt': datetime(2015, 1, 1), 'IssueInfoMap': { 'string': 'string' } } } :returns: (string) -- (string) -- """ pass
5,345,607
async def feature(message: discord.Message, plugin: plugin_in_req, req_id: get_req_id=None): """ Handle plugin feature requests where plugin is a plugin name. See `{pre}plugin` for a list of plugins. """ if req_id is not None: assert feature_exists(plugin, req_id), "There is no such feature." # The feature request the specified id exists, and we format and send the feature request await client.say(message, "```diff\n" + format_req(plugin, req_id) + "```") else: format_list = "\n".join(format_req(plugin, req_id) for req_id in range(len(feature_reqs.data[plugin]))) assert format_list, "This plugin has no feature requests!" # Format a list of all requests for the specified plugin when there are any await client.say(message, "```diff\n{list}```".format(list=format_list))
5,345,608
def for_I(): """ Upper case Alphabet letter 'I' pattern using Python for loop""" for row in range(6): for col in range(5): if row in (0,5) or col==2: print('*', end = ' ') else: print(' ', end = ' ') print()
5,345,609
def run(connection, args): """Prints it out based on command line configuration. Exceptions: - SAPCliError: - when the given type does not belong to the type white list """ types = {'program': sap.adt.Program, 'class': sap.adt.Class, 'package': sap.adt.Package} try: typ = types[args.type] except KeyError: raise SAPCliError(f'Unknown type: {args.type}') aunit = sap.adt.AUnit(connection) obj = typ(connection, args.name) response = aunit.execute(obj) run_results = sap.adt.aunit.parse_run_results(response.text) if args.output == 'human': return print_results_to_stream(run_results, sys.stdout) if args.output == 'raw': return print_raw(response.text, run_results) if args.output == 'junit4': return print_junit4(run_results, args, sys.stdout) raise SAPCliError(f'Unsupported output type: {args.output}')
5,345,610
def read_nli_data(p: Path) -> List[Dict]: """Read dataset which has been converted to nli form""" with open(p) as f: data = json.load(f) return data
5,345,611
def stanley_control(state, cx, cy, cyaw, last_target_idx): """ Stanley steering control. :param state: (State object) :param cx: ([float]) :param cy: ([float]) :param cyaw: ([float]) :param last_target_idx: (int) :return: (float, int) """ current_target_idx, error_front_axle = calc_target_index(state, cx, cy) if last_target_idx >= current_target_idx: current_target_idx = last_target_idx # theta_e corrects the heading error theta_e = normalize_angle(cyaw[current_target_idx] - state.yaw) # theta_d corrects the cross track error theta_d = np.arctan2(k * error_front_axle, state.v) # Steering control delta = theta_e + theta_d return delta, current_target_idx
5,345,612
def get_predictions(my_map, reviews, restaurants): """ Get the topic predictions for all restaurants. Parameters: my_map - the Map object representation of the current city reviews - a dictionary of reviews with restaurant ids for keys restaurants - a list of restaurants of the current city Returns: A tuple of a dictionary of restaurant ids to topic distributions and the lda model """ predictor = LDAPredictor() lda = predictor.lda restaurant_ids_to_topics = {} for restaurant in restaurants: business_id = restaurant["business_id"] review = reviews[business_id] prediction = predictor.predict_topics(review) restaurant_ids_to_topics[business_id] = make_topic_array_from_tuple_list(prediction, NUM_TOPICS) #topic array of weights for each topic index normalized_restaurant_ids_to_topics = normalize_predictions(restaurant_ids_to_topics, restaurants) return normalized_restaurant_ids_to_topics, lda
5,345,613
def pin_memory_inplace(tensor): """Register the tensor into pinned memory in-place (i.e. without copying).""" if F.backend_name in ['mxnet', 'tensorflow']: raise DGLError("The {} backend does not support pinning " \ "tensors in-place.".format(F.backend_name)) # needs to be writable to allow in-place modification try: F.zerocopy_to_dgl_ndarray_for_write(tensor).pin_memory_() except Exception as e: raise DGLError("Failed to pin memory in-place due to: {}".format(e))
5,345,614
def decode_token(token, secret_key): """ θ§£ε―†websocket token :param token: :param secret_key: :return: """ info = jwt.decode(token, secret_key, algorithms=['HS256']) return info
5,345,615
def assertUrisEqual(testcase, expected, actual): """Test that URIs are the same, up to reordering of query parameters.""" expected = urllib.parse.urlparse(expected) actual = urllib.parse.urlparse(actual) testcase.assertEqual(expected.scheme, actual.scheme) testcase.assertEqual(expected.netloc, actual.netloc) testcase.assertEqual(expected.path, actual.path) testcase.assertEqual(expected.params, actual.params) testcase.assertEqual(expected.fragment, actual.fragment) expected_query = urllib.parse.parse_qs(expected.query) actual_query = urllib.parse.parse_qs(actual.query) for name in expected_query.keys(): testcase.assertEqual(expected_query[name], actual_query[name]) for name in actual_query.keys(): testcase.assertEqual(expected_query[name], actual_query[name])
5,345,616
def manning_friction_explicit(domain): """Apply (Manning) friction to water momentum Wrapper for c version """ from .shallow_water_ext import manning_friction_flat from .shallow_water_ext import manning_friction_sloped xmom = domain.quantities['xmomentum'] ymom = domain.quantities['ymomentum'] x = domain.get_vertex_coordinates() w = domain.quantities['stage'].centroid_values z = domain.quantities['elevation'].vertex_values uh = xmom.centroid_values vh = ymom.centroid_values eta = domain.quantities['friction'].centroid_values xmom_update = xmom.explicit_update ymom_update = ymom.explicit_update eps = domain.minimum_allowed_height if domain.use_sloped_mannings: manning_friction_sloped(domain.g, eps, x, w, uh, vh, z, eta, xmom_update, \ ymom_update) else: manning_friction_flat(domain.g, eps, w, uh, vh, z, eta, xmom_update, \ ymom_update)
5,345,617
def getPatternID(pattern_url): """asssumes pattern_url is a string, representing the URL of a ravelry pattern e.g.https://www.ravelry.com/patterns/library/velvet-cache-cou returns an int, the pattern ID """ permalink = pattern_url[41:] with requests.Session() as a_session: auth_name = "read-046277a3027f680ebe3fa030e755eb34" auth_pass = "O+mL0KzfjgQ1eLA7K8FO9s28QPvr6QuiL+pOvFHZ" a_session.auth = (auth_name, auth_pass) ravelry_adapter = HTTPAdapter(max_retries=3) a_session.mount('https://ravelry.com', ravelry_adapter) base_request = "https://api.ravelry.com/patterns/search.json?query=" pattern = a_session.get(base_request+permalink) if pattern.status_code != 200: raise RuntimeError("Ravelry not responding as expected.\ Please check your internet connection or try again later") pattern_id = pattern.json()['patterns'][0]['id'] return pattern_id
5,345,618
def make_multibonacci_modulo(history_length, limit): """Creates a function that generates the Multibonacci sequence modulo n.""" def sequence_fn(seq): return np.sum(seq[-history_length:]) % limit return sequence_fn
5,345,619
def checkpoint_nets(config, shared, task_id, mnet, hnet, hhnet=None, dis=None): """Checkpoint the main and (if existing) the current hypernet. Args: config (argparse.Namespace): Command-line arguments. shared (argparse.Namespace): Miscellaneous data shared among training functions (contains filenames). task_id (int): On which task have the networks been trained last. mnet: The main network. hnet: The hypernetwork. May be ``None``. hhnet (optional): The hyper-hypernetwork. dis (optional): The discriminator network. """ assert hasattr(shared, 'summary') if 'regression' in shared.experiment_type: perf_key = 'during_mse_task_%d' % task_id perf_val = shared.summary['aa_mse_during'][task_id] perf_score = -perf_val else: # Note, we use the "task-given" during accuracy on purpose, independent # of the CL scenario, since the during accuracies for "task-inferred" # scenarios don't make a lot of sense (they depend on the number of # tasks observed so far). perf_key = 'during_acc_task_%d' % task_id perf_val = shared.summary['acc_task_given_during'][task_id] perf_score = perf_val ts = time() tckpt.save_checkpoint({'state_dict': mnet.state_dict(), perf_key: perf_val}, shared.ckpt_mnet_fn % task_id, perf_score, train_iter=None, timestamp=ts) if hnet is not None: tckpt.save_checkpoint({'state_dict': hnet.state_dict(), perf_key: perf_val}, shared.ckpt_hnet_fn % task_id, perf_score, train_iter=None, timestamp=ts) if hhnet is not None: tckpt.save_checkpoint({'state_dict': hhnet.state_dict(), perf_key: perf_val}, shared.ckpt_hhnet_fn % task_id, perf_score, train_iter=None, timestamp=ts) if dis is not None: tckpt.save_checkpoint({'state_dict': dis.state_dict(), perf_key: perf_val}, shared.ckpt_dis_fn % task_id, perf_score, train_iter=None, timestamp=ts)
5,345,620
def _get_key(arguments): """ Determine the config key based on the arguments. :param arguments: A dictionary of arguments already processed through this file's docstring with docopt :return: The datastore path for the config key. """ # Get the base path. if arguments.get("felix"): base = CONFIG_PATH elif arguments.get("node"): base = BGP_HOST_PATH % {"hostname": hostname} else: base = BGP_GLOBAL_PATH # Determine the actual name of the field. Look this up from the config # data, otherwise just use the name. config_data = _get_config_data(arguments) name = arguments["<NAME>"] if name in config_data: name, _ = config_data[name] return base + name
5,345,621
def prepare_data_from_stooq(df, to_prediction = False, return_days = 5): """ Prepares data for X, y format from pandas dataframe downloaded from stooq. Y is created as closing price in return_days - opening price Keyword arguments: df -- data frame contaning data from stooq return_days -- number of day frame in which to calculate y. """ if 'Wolumen' in df.columns: df = df.drop(['Data', 'Wolumen', 'LOP'], axis=1) else: df = df.drop('Data', axis = 1) y = df['Zamkniecie'].shift(-return_days) - df['Otwarcie'] if not to_prediction: df = df.iloc[:-return_days,:] y = y[:-return_days]/df['Otwarcie'] return df.values, y
5,345,622
def represents_int_above_0(s: str) -> bool: """Returns value evaluating if a string is an integer > 0. Args: s: A string to check if it wil be a float. Returns: True if it converts to float, False otherwise. """ try: val = int(s) if val > 0: return True else: return False except ValueError: return False
5,345,623
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url('https://download.pytorch.org/models/resnet18-5c106cde.pth')) return model
5,345,624
def sydney(): """Import most recent Sydney dataset""" d = { 'zip':'Sydney_geol_100k_shape', 'snap':-1, } return(d)
5,345,625
def test_vm_entrypoint_stdin(mock_vm_from_stdin, mock_vm_parser): """ Test the vm entrypoint with stdin input. """ test_program = StringIO(""" A DATA 0 HLT A """) with patch("sys.stdin", test_program): with patch("sys.stdout", new_callable=StringIO): vm() assert mock_vm_from_stdin.called
5,345,626
async def apiAdminRoleNotExists(cls:"PhaazebotWeb", WebRequest:ExtendedRequest, **kwargs) -> Response: """ Optional keywords: ------------------ * msg `str` : (Default: None) * [Overwrites default] * name `str` * * role_id `str` * Default message (*gets altered by optional keywords): ---------------------------------------------------- No role has been found """ res:dict = dict(status=400, error="admin_role_not_exists") name:str = kwargs.get("name", "") if name: res["name"] = name role_id:str = kwargs.get("role_id", "") if role_id: res["role_id"] = role_id # build message default_msg:str = "No command has been found" if name: default_msg += f" with name '{name}'" if role_id: default_msg += f" (Role ID: {role_id})" msg:str = kwargs.get("msg", default_msg) res["msg"] = msg cls.BASE.Logger.debug(f"(API/Admin) 400 Role not found: {WebRequest.path}", require="api:400") return cls.response( text=json.dumps(res), content_type="application/json", status=400 )
5,345,627
def format_non_date(value): """Return non-date value as string.""" return_value = None if value: return_value = value return return_value
5,345,628
def get_loss(loss_str): """Get loss type from config""" def _get_one_loss(cur_loss_str): if hasattr(keras_losses, cur_loss_str): loss_cls = getattr(keras_losses, cur_loss_str) elif hasattr(custom_losses, cur_loss_str): loss_cls = getattr(custom_losses, cur_loss_str) else: raise ValueError('%s is not a valid loss' % cur_loss_str) return loss_cls if not isinstance(loss_str, list): loss_cls = _get_one_loss(loss_str) return loss_cls else: loss_cls_list = [] for cur_loss in loss_str: loss_cls = _get_one_loss(cur_loss) loss_cls_list.append(loss_cls) return loss_cls_list
5,345,629
def read(filename, columns, row_num): """test file reade""" if not pd: raise Exception("Module pandas is not found, please use pip install it.") df = pd.read_csv(CSV_FILE) count = 0 reader = FileReader(filename) for _, x in enumerate(reader.get_next()): for col in columns: assert x[col] == df[col].iloc[count] assert len(x) == len(columns) count = count + 1 if count == 1: logger.info("data: {}".format(x)) assert count == row_num reader.close()
5,345,630
def _hashable_policy(policy, policy_list): """ Takes a policy and returns a list, the contents of which are all hashable and sorted. Example input policy: {'Version': '2012-10-17', 'Statement': [{'Action': 's3:PutObjectAcl', 'Sid': 'AddCannedAcl2', 'Resource': 'arn:aws:s3:::test_policy/*', 'Effect': 'Allow', 'Principal': {'AWS': ['arn:aws:iam::XXXXXXXXXXXX:user/username1', 'arn:aws:iam::XXXXXXXXXXXX:user/username2']} }]} Returned value: [('Statement', ((('Action', (u's3:PutObjectAcl',)), ('Effect', (u'Allow',)), ('Principal', ('AWS', ((u'arn:aws:iam::XXXXXXXXXXXX:user/username1',), (u'arn:aws:iam::XXXXXXXXXXXX:user/username2',)))), ('Resource', (u'arn:aws:s3:::test_policy/*',)), ('Sid', (u'AddCannedAcl2',)))), ('Version', (u'2012-10-17',)))] """ # Amazon will automatically convert bool and int to strings for us if isinstance(policy, bool): return tuple([str(policy).lower()]) elif isinstance(policy, int): return tuple([str(policy)]) if isinstance(policy, list): for each in policy: tupleified = _hashable_policy(each, []) if isinstance(tupleified, list): tupleified = tuple(tupleified) policy_list.append(tupleified) elif isinstance(policy, string_types) or isinstance(policy, binary_type): policy = to_text(policy) # convert root account ARNs to just account IDs if policy.startswith('arn:aws:iam::') and policy.endswith(':root'): policy = policy.split(':')[4] return [policy] elif isinstance(policy, dict): sorted_keys = list(policy.keys()) sorted_keys.sort() for key in sorted_keys: element = policy[key] # Special case defined in # https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html if key in ["NotPrincipal", "Principal"] and policy[key] == "*": element = {"AWS": "*"} tupleified = _hashable_policy(element, []) if isinstance(tupleified, list): tupleified = tuple(tupleified) policy_list.append((key, tupleified)) # ensure we aren't returning deeply nested structures of length 1 if len(policy_list) == 1 and isinstance(policy_list[0], tuple): policy_list = policy_list[0] if isinstance(policy_list, list): policy_list.sort(key=cmp_to_key(_py3cmp)) return policy_list
5,345,631
def test_database(test_session): """Tests that the mock database was set up correctly""" # execute surveys = test_session.query(Survey).all() # validation assert len(surveys) == 2 for survey in surveys: assert survey.name in ["survey1", "survey2"] assert len(survey.responses) == 2 assert survey.questions.count() == 3 # needs count() b/c dynamic load assert survey.created_date is not None
5,345,632
def LF_CD_NO_VERB(c): """ This label function is designed to fire if a given sentence doesn't contain a verb. Helps cut out some of the titles hidden in Pubtator abstracts """ if len([x for x in nltk.pos_tag(word_tokenize(c.get_parent().text)) if "VB" in x[1]]) == 0: if "correlates with" in c.get_parent().text: return 0 return -1 return 0
5,345,633
def has_file_allowed_extension(filename: PATH_TYPE, extensions: Tuple[str, ...]) -> bool: """Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (tuple of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions """ return str(filename).lower().endswith(extensions)
5,345,634
def get_account_html(netid, timestamp=None): """ The Libraries object has a method for getting information about a user's library account """ return _get_resource(netid, timestamp=timestamp, style='html')
5,345,635
def AddBookkeepingOperators(model): """This adds a few bookkeeping operators that we can inspect later. These operators do not affect the training procedure: they only collect statistics and prints them to file or to logs. """ # Print basically prints out the content of the blob. to_file=1 routes the # printed output to a file. The file is going to be stored under # root_folder/[blob name] model.Print('accuracy', [], to_file=1) model.Print('loss', [], to_file=1) # Summarizes the parameters. Different from Print, Summarize gives some # statistics of the parameter, such as mean, std, min and max. for param in model.params: model.Summarize(param, [], to_file=1) model.Summarize(model.param_to_grad[param], [], to_file=1) # Now, if we really want to be verbose, we can summarize EVERY blob # that the model produces; it is probably not a good idea, because that # is going to take time - summarization do not come for free. For this # demo, we will only show how to summarize the parameters and their # gradients.
5,345,636
def gcd_multiple(*args) -> int: """Return greatest common divisor of integers in args""" return functools.reduce(math.gcd, args)
5,345,637
def sleep_countdown(duration, steps=1): """Sleep that prints a countdown in specified steps Input duration: int for seconds of sleep duration steps: in which steps the countdown is printed Return None: sys.stdout output in console """ sys.stdout.write("\r Seconds remaining:") for remaining in range(duration, 0, -1): # display only steps if remaining % steps == 0: sys.stdout.write("\r") sys.stdout.write("{:2d}".format(remaining)) sys.stdout.flush() time.sleep(1) sys.stdout.write("\r Complete!\n")
5,345,638
def chars_to_family(chars): """Takes a list of characters and constructs a family from them. So, A1B2 would be created from ['B', 'A', 'B'] for example.""" counter = Counter(chars) return "".join(sorted([char + str(n) for char, n in counter.items()]))
5,345,639
def get_config_properties(config_file="config.properties", sections_to_fetch = None): """ Returns the list of properties as a dict of key/value pairs in the file config.properties. :param config_file: filename (string). :param section: name of section to fetch properties from (if specified); all sections are returned by default (iterable). :return: A flat (no sections) Python dictionary of properties. """ cf = configparser.ConfigParser() try: cf.read(config_file) except Exception as e: print("[ERROR] exception {} reading configurations from file {}".format(e, config_file)) properties = {} for section in cf.sections(): # only include args section if requested if (not sections_to_fetch or (section in sections_to_fetch)): for item in cf.items(section): properties[item[0]] = item[1] return properties
5,345,640
def process_speke(): """Processes an incoming request from MediaLive, which is using SPEKE A key is created and stored in DynamoDB.""" input_request = request.get_data() # Parse request tree = ET.fromstring(input_request) content_id = tree.get("id") kid = tree[0][0].get("kid") iv = tree[0][0].get("explicitIV") or "" keyPeriod = tree[2][0].get("id") index = tree[2][0].get("index") # Create key key = base64.b64encode(secrets.token_bytes(16)).decode("ascii") # Expire key tomorrow expiry = round(time.time()) + 24 * 60 * 60 # Create the pssh systems = [] for drmsystem in tree[1]: if drmsystem.get("systemId") == CLEARKEY_SYSTEM_ID: pssh = psshgen.genClearkeyPssh([kid]) systems.append( f"""<!-- ClearKey --> <cpix:DRMSystem kid="{kid}" systemId="{CLEARKEY_SYSTEM_ID}"> <cpix:PSSH>{pssh}</cpix:PSSH> </cpix:DRMSystem>""" ) # Save key info in dynamo dynamo.put_item( TableName=TABLE, Item={ "content_id": {"S": content_id}, "kid": {"S": kid}, "iv": {"S": iv}, "keyPeriod": {"S": keyPeriod}, "index": {"S": index}, "key": {"S": key}, "expiry": {"N": str(expiry)}, }, ) if iv: iv = f'explicitIV="{iv}"' # Craft response response = f"""<cpix:CPIX xmlns:cpix="urn:dashif:org:cpix" xmlns:pskc="urn:ietf:params:xml:ns:keyprov:pskc" xmlns:speke="urn:aws:amazon:com:speke" id="{content_id}"> <cpix:ContentKeyList> <cpix:ContentKey {iv} kid="{kid}"> <cpix:Data> <pskc:Secret> <pskc:PlainValue>{key}</pskc:PlainValue> </pskc:Secret> </cpix:Data> </cpix:ContentKey> </cpix:ContentKeyList> <cpix:DRMSystemList> {''.join(systems)} </cpix:DRMSystemList> <cpix:ContentKeyPeriodList> <cpix:ContentKeyPeriod id="{keyPeriod}" index="{index}" /> </cpix:ContentKeyPeriodList> <cpix:ContentKeyUsageRuleList> <cpix:ContentKeyUsageRule kid="{kid}"> <cpix:KeyPeriodFilter periodId="{keyPeriod}" /> </cpix:ContentKeyUsageRule> </cpix:ContentKeyUsageRuleList> </cpix:CPIX>""" return response
5,345,641
def yaml_save(filename, data): """ Save contents of an OrderedDict structure to a yaml file :param filename: name of the yaml file to save to :type filename: str :param data: configuration data to to save :type filename: str :type data: OrderedDict :returns: Nothing """ ordered = type(data).__name__ == "OrderedDict" dict_type = "dict" if ordered: dict_type = "OrderedDict" LOGGER.info("Saving '{}' to '{}'".format(dict_type, filename)) if ordered: sdata = _ordered_dump( data, Dumper=yaml.SafeDumper, indent=4, width=768, allow_unicode=True, default_flow_style=False, ) else: sdata = yaml.dump( data, Dumper=yaml.SafeDumper, indent=4, width=768, allow_unicode=True, default_flow_style=False, ) sdata = _format_yaml_dump(sdata) with open(filename, "w") as outfile: outfile.write(sdata)
5,345,642
def start_model_server(handler_service=DEFAULT_HANDLER_SERVICE): """Configure and start the model server. Args: handler_service (str): python path pointing to a module that defines a class with the following: - A ``handle`` method, which is invoked for all incoming inference requests to the model server. - A ``initialize`` method, which is invoked at model server start up for loading the model. Defaults to ``sagemaker_inference.default_handler_service``. """ _adapt_to_mms_format(handler_service) _create_model_server_config_file() mxnet_model_server_cmd = ['mxnet-model-server', '--start', '--model-store', DEFAULT_MMS_MODEL_DIRECTORY, '--mms-config', MMS_CONFIG_FILE, '--log-config', DEFAULT_MMS_LOG_FILE, ] logger.info(mxnet_model_server_cmd) mms_process = subprocess.Popen(mxnet_model_server_cmd) _add_sigterm_handler(mms_process) subprocess.call(['tail', '-f', '/dev/null'])
5,345,643
def merge(source: Dict, destination: Dict) -> Dict: """ Deep merge two dictionaries Parameters ---------- source: Dict[Any, Any] Dictionary to merge from destination: Dict[Any, Any] Dictionary to merge to Returns ------- Dict[Any, Any] New dictionary with fields in destination overwritten with values from source """ new_dict = {**destination} for key, value in source.items(): if isinstance(value, dict): # get node or create one node = new_dict.get(key, {}) new_dict[key] = merge(value, node) else: new_dict[key] = value return new_dict
5,345,644
async def async_api_adjust_volume_step(hass, config, directive, context): """Process an adjust volume step request.""" # media_player volume up/down service does not support specifying steps # each component handles it differently e.g. via config. # For now we use the volumeSteps returned to figure out if we # should step up/down volume_step = directive.payload['volumeSteps'] entity = directive.entity data = { ATTR_ENTITY_ID: entity.entity_id, } if volume_step > 0: await hass.services.async_call( entity.domain, SERVICE_VOLUME_UP, data, blocking=False, context=context) elif volume_step < 0: await hass.services.async_call( entity.domain, SERVICE_VOLUME_DOWN, data, blocking=False, context=context) return directive.response()
5,345,645
def CreateHead(turtle): """ Creates the head for the puppy we're making! :return: none """ turtle.penup() turtle.speed(0) turtle.setpos(100,-50) turtle.pendown() turtle.color("#bd9f60") turtle.shape('arrow') turtle.begin_fill() for head in range(4): turtle.left(90) turtle.forward(200) turtle.end_fill()
5,345,646
def load_recordings(path: str, activityLabelToIndexMap: dict, limit: int = None) -> 'list[Recording]': """ Load the recordings from a folder containing csv files. """ recordings = [] recording_files = os.listdir(path) recording_files = list(filter(lambda file: file.endswith('.csv'), recording_files)) if limit is not None: recording_files = recording_files[:limit] recording_files = sorted(recording_files, key=lambda file: int(file.split('_')[0])) for (index, file) in enumerate(recording_files): print(f'Loading recording {file}, {index+1} / {len(recording_files)}') recording_dataframe = pd.read_csv(os.path.join(path, file)) time_frame = recording_dataframe.loc[:, 'SampleTimeFine'] activities = recording_dataframe.loc[:, 'activity'].map(lambda label: activityLabelToIndexMap[label]) sensor_frame = recording_dataframe.loc[:, recording_dataframe.columns.difference(['SampleTimeFine', 'activity'])] subject = file.split('_')[1] recordings.append(Recording(sensor_frame, time_frame, activities, subject, index)) print(f'Loaded {len(recordings)} recordings from {path}') return recordings
5,345,647
def minio_prometheus(storage_share): """Contact Minio's Prometheus URL to obtain storage information. Obtains storage stats from Minio's Prometheus URL by extracting these metrics: minio_disk_storage_available_bytes minio_disk_storage_total_bytes minio_disk_storage_used_bytes or for newer version >= RELEASE.2019-12-17T23-26-28Z disk_storage_available disk_storage_total disk_storage_used Attributes: storage_share -- dynafed_storagestats StorageShare object. """ # Generate the URL to contact _api_url = '{scheme}://{netloc}/minio/prometheus/metrics'.format( scheme=storage_share.uri['scheme'], netloc=storage_share.uri['netloc'] ) # We need to initialize "response" to check if it was successful in the # finally statement. _response = False try: _response = requests.request( method="GET", url=_api_url, verify=storage_share.plugin_settings['ssl_check'], timeout=int(storage_share.plugin_settings['conn_timeout']) ) # Save time when data was obtained. storage_share.stats['endtime'] = int(datetime.datetime.now().timestamp()) # Log contents of response _logger.debug( "[%s]Endpoint reply: %s", storage_share.id, _response.text ) except requests.exceptions.InvalidSchema as ERR: raise dynafed_storagestats.exceptions.ConnectionErrorInvalidSchema( error='InvalidSchema', schema=storage_share.uri['scheme'], debug=str(ERR), ) except requests.exceptions.SSLError as ERR: # If ca_path is custom, try the default in case # a global setting is incorrectly giving the wrong # ca's to check against. try: _response = requests.request( method="GET", url=_api_url, verify=storage_share.plugin_settings['ssl_check'], timeout=int(storage_share.plugin_settings['conn_timeout']) ) # Save time when data was obtained. storage_share.stats['endtime'] = int(datetime.datetime.now().timestamp()) # Log contents of response _logger.debug( "[%s]Endpoint reply: %s", storage_share.id, _response.text ) except requests.exceptions.SSLError as ERR: raise dynafed_storagestats.exceptions.ConnectionError( error=ERR.__class__.__name__, status_code="092", debug=str(ERR), ) except requests.ConnectionError as ERR: raise dynafed_storagestats.exceptions.ConnectionError( error=ERR.__class__.__name__, debug=str(ERR), ) finally: if _response: try: _metrics = _response.text except ValueError: raise dynafed_storagestats.exceptions.ConnectionErrorS3API( error="NoContent", status_code=_response.status_code, api=storage_share.plugin_settings['storagestats.api'], debug=_response.text, ) else: # Extract the metrics. for family in text_string_to_metric_families(_metrics): for sample in family.samples: if sample.name == 'minio_disk_storage_available_bytes' or \ sample.name == 'disk_storage_available': storage_share.stats['bytesfree'] = int(sample.value) elif sample.name == 'minio_disk_storage_used_bytes' or \ sample.name =='disk_storage_used': storage_share.stats['bytesused'] = int(sample.value) elif sample.name == 'minio_disk_storage_total_bytes' or \ sample.name == 'disk_storage_total': storage_share.stats['quota'] = int(sample.value) # If the quota is overridden in the settings: if storage_share.plugin_settings['storagestats.quota'] != 'api': storage_share.stats['quota'] = int(storage_share.plugin_settings['storagestats.quota']) storage_share.stats['bytesfree'] = storage_share.stats['quota'] - storage_share.stats['bytesused']
5,345,648
def add_storage_capacity(obj, info): """Sets storage parameters in change table. :param powersimdata.input.change_table.ChangeTable obj: change table :param list info: each entry is a dictionary. The dictionary gathers the information needed to create a new storage device. Required keys: "bus_id", "capacity". "capacity" denotes the symmetric input and output power limits (MW). Optional keys: "duration", "min_stor", "max_stor", "energy_value", "InEff", "OutEff", "LossFactor", "terminal_min", "terminal_max". "duration" denotes the energy to power ratio (hours). "min_stor" denotes the minimum energy limit (unitless), e.g. 0.05 = 5%. "max_stor" denotes the maximum energy limit (unitless), e.g. 0.95 = 95%. "energy_value" denotes the value of stored energy at interval end ($/MWh). "InEff" denotes the input efficiency (unitless), e.g. 0.95 = 95%. "OutEff" denotes the output efficiency (unitless), e.g. 0.95 = 95%. "LossFactor" denotes the per-hour relative losses, e.g. 0.01 means that 1% of the current state of charge is lost per hour). "terminal_min" denotes the minimum state of charge at interval end, e.g. 0.5 means that the storage must end the interval with at least 50%. "terminal_max" denotes the maximum state of charge at interval end, e.g. 0.9 means that the storage must end the interval with no more than 90%. :raises TypeError: if ``info`` is not a list. :raises ValueError: if any of the new storages to be added have bad values. """ if not isinstance(info, list): raise TypeError("Argument enclosing new storage(s) must be a list") info = copy.deepcopy(info) new_storages = [] required = {"bus_id", "capacity"} optional = { "duration", "min_stor", "max_stor", "energy_value", "InEff", "OutEff", "LossFactor", "terminal_min", "terminal_max", } anticipated_bus = obj._get_transformed_df("bus") for i, storage in enumerate(info): obj._check_entry_keys(storage, i, "storage", required, None, optional) if storage["bus_id"] not in anticipated_bus.index: raise ValueError( f"No bus id {storage['bus_id']} available for {ordinal(i)} storage" ) for o in optional: if o not in storage: storage[o] = obj.grid.storage[o] for k, v in storage.items(): if not isinstance(v, (int, float)): err_msg = f"values must be numeric, bad type for {ordinal(i)} {k}" raise ValueError(err_msg) if v < 0: raise ValueError( f"values must be non-negative, bad value for {ordinal(i)} {k}" ) for k in {"min_stor", "max_stor", "InEff", "OutEff", "LossFactor"}: if storage[k] > 1: raise ValueError( f"value for {k} must be <=1, bad value for {ordinal(i)} storage" ) new_storages.append(storage) if "storage" not in obj.ct: obj.ct["storage"] = [] obj.ct["storage"] += new_storages
5,345,649
def load_img(path, grayscale=False, color_mode='rgb', target_size=None, interpolation='nearest'): """Loads an image into PIL format. # Arguments path: Path to image file. grayscale: DEPRECATED use `color_mode="grayscale"`. color_mode: The desired image format. One of "grayscale", "rgb", "rgba". "grayscale" supports 8-bit images and 32-bit signed integer images. Default: "rgb". target_size: Either `None` (default to original size) or tuple of ints `(img_height, img_width)`. interpolation: Interpolation method used to resample the image if the target size is different from that of the loaded image. Supported methods are "nearest", "bilinear", and "bicubic". If PIL version 1.1.3 or newer is installed, "lanczos" is also supported. If PIL version 3.4.0 or newer is installed, "box" and "hamming" are also supported. Default: "nearest". # Returns A PIL Image instance. # Raises ImportError: if PIL is not available. ValueError: if interpolation method is not supported. """ if grayscale is True: warnings.warn('grayscale is deprecated. Please use ' 'color_mode = "grayscale"') color_mode = 'grayscale' if pil_image is None: raise ImportError('Could not import PIL.Image. ' 'The use of `load_img` requires PIL.') with open(path, 'rb') as f: img = pil_image.open(io.BytesIO(f.read())) if color_mode == 'grayscale': # if image is not already an 8-bit, 16-bit or 32-bit grayscale image # convert it to an 8-bit grayscale image. if img.mode not in ('L', 'I;16', 'I'): img = img.convert('L') elif color_mode == 'rgba': if img.mode != 'RGBA': img = img.convert('RGBA') elif color_mode == 'rgb': if img.mode != 'RGB': img = img.convert('RGB') else: raise ValueError('color_mode must be "grayscale", "rgb", or "rgba"') if target_size is not None: width_height_tuple = (target_size[1], target_size[0]) if img.size != width_height_tuple: if interpolation not in _PIL_INTERPOLATION_METHODS: raise ValueError( 'Invalid interpolation method {} specified. Supported ' 'methods are {}'.format( interpolation, ", ".join(_PIL_INTERPOLATION_METHODS.keys()))) resample = _PIL_INTERPOLATION_METHODS[interpolation] img = img.resize(width_height_tuple, resample) return img
5,345,650
def check_compatible_system_and_kernel_and_prepare_profile(args): """ Checks if we can do local profiling, that for now is only available via Linux based platforms and kernel versions >=4.9 Args: args: """ res = True logging.info("Enabled profilers: {}".format(args.profilers)) logging.info("Checking if system is capable of running those profilers") if "Linux" not in platform.system(): logging.error( "Platform needs to be Linux based. Current platform: {}".format( platform.system() ) ) res = False # check for release >= 4.9 release = platform.release() logging.info("Detected platform release: {}".format(release)) major_minor = release.split(".")[:2] system_kernel_major_v = major_minor[0] system_kernel_minor_v = major_minor[1] if float(system_kernel_major_v) < 4: logging.error( "kernel version needs to be >= 4.9. Detected version: {}".format(release) ) res = False if float(system_kernel_major_v) == 4 and float(system_kernel_minor_v) < 9: logging.error( "kernel version needs to be >= 4.9. Detected version: {}".format(release) ) res = False # a map between profiler name and profiler object wrapper res, profilers_map = get_profilers_map(args.profilers.split(",")) return res, profilers_map
5,345,651
def crop_file(in_file, out_file, ext): """Crop a NetCDF file to give rectangle using NCO. The file is automatically converted to [0,360] Β°E longitude format. Args: in_file: Input file path. out_file: Output file path. It will not be overwritten. ext: The rectangular region (extent) to crop to, given as a list of [lon1, lon2, lat1, lat2]. Longitude in [0,360) Β°E and latitude in [-90,+90] Β°N. Returns: Name of output file (same as `out_file`). Raises: FileNotFoundError: `in_file` doesn’t exist. RuntimeError: Executable `ncks` is not in the PATH. RuntimeError: NCKS failed or no output file was created. """ if not os.path.isfile(in_file): raise FileNotFoundError("Input file doesn’t exist: '%s'" % in_file) if skip(in_file, out_file): return out_file out_dir = os.path.dirname(out_file) if not os.path.isdir(out_dir): cprint(f"Directory '{out_dir}' does not exist yet. I will create it.", 'yellow') os.makedirs(out_dir) cprint("Cropping file '%s'..." % in_file, 'yellow') if shutil.which("ncks") is None: raise RuntimeError("Executable `ncks` not found.") try: # ADJUST LONGITUDE ext_adj = list() ext_adj[:] = ext ext_adj[0] = adjust_longitude(in_file, ext[0]) ext_adj[1] = adjust_longitude(in_file, ext[1]) # CROP subprocess.run(["ncks", "--overwrite", "--dimension", "lon,%.2f,%.2f" % (ext_adj[0], ext_adj[1]), "--dimension", "lat,%.2f,%.2f" % (ext_adj[2], ext_adj[3]), in_file, out_file], check=True) # ROTATE LONGITUDE # See here for the documentation about rotating longitude: # http://nco.sourceforge.net/nco.html#msa_usr_rdr # Unlike in the instructions in the documentation, we don’t need to # re-order the longitude dimension with --msa_usr_rdr because through # the `ncks` cropping/hyperslabbing command the longitude is already # ordered correctly from East to West. # Note that we rotate after cropping for performance reasons. This way # only the cropped grid cells need to be rotated. subprocess.run(['ncap2', '--overwrite', '--script', 'where(lon < 0) lon=lon+360', out_file, out_file], check=True) except Exception: print(f'DEBUG: ext = {ext}') print(f'DEBUG: ext_adj = {ext_adj}') if os.path.isfile(out_file): cprint(f"Removing file '{out_file}'.", 'red') os.remove(out_file) # Remove temporary file created by ncks. for g in glob(f'{out_file}.pid*.ncks.tmp'): cprint(f"Removing file '{g}'.", 'red') os.remove(g) raise if not os.path.isfile(out_file): raise RuntimeError("Cropping with `ncks` failed: No output file " "created.") cprint(f"Successfully created '{out_file}'.", 'green') return out_file
5,345,652
def get_instance_string(params): """ combine the parameters to a string mostly used for debug output use of OrderedDict is advised """ return "_".join([str(i) for i in params.values()])
5,345,653
def recv_bgpmon_updates(host, port, queue): """ Receive and parse the BGP update XML stream of bgpmon """ logging.info ("CALL recv_bgpmon_updates (%s:%d)", host, port) # open connection sock = _init_bgpmon_sock(host,port) data = "" stream = "" # receive data logging.info(" + receiving XML update stream ...") while(True): data = sock.recv(1024) if not data: sock.close() time.sleep(60) sock = _init_bgpmon_sock(host,port) continue stream += data stream = str.replace(stream, "<xml>", "") while (re.search('</BGP_MONITOR_MESSAGE>', stream)): messages = stream.split('</BGP_MONITOR_MESSAGE>') msg = messages[0] + '</BGP_MONITOR_MESSAGE>' stream = '</BGP_MONITOR_MESSAGE>'.join(messages[1:]) result = parse_bgp_message(msg) if result: queue.put(result) return True
5,345,654
def is_string_expr(expr: ast.AST) -> bool: """Check that the expression is a string literal.""" return ( isinstance(expr, ast.Expr) and isinstance(expr.value, ast.Constant) and isinstance(expr.value.value, str) )
5,345,655
def events_to_img( xs: np.ndarray, ys: np.ndarray, tots: np.ndarray, cluster_ids: np.ndarray, x_img: np.ndarray, y_img: np.ndarray, minimum_event_num: int = 30, extinguish_dist: float = 1.41422, # sqrt(2) = 1.41421356237 ) -> np.ndarray: """ Converting given events into a flatten image array defined by given image pixel positions @param xs: event x position, must be float @param ys: event y position, must be float @param tots: event time of threshold (as intensity), must be float @param cluster_ids: ID labels @param x_img: pixel position of the target image (see np.meshgrid) @param y_img: pixel position of the target image (see np.meshgrid) @param minimum_event_num: minimum number of events needed to be included @param extinguish_dist: signal impact ends outside this range @returns: the image converted from given events using weighted centroid method """ # preparation unique_cids = np.unique(cluster_ids) img_shape = x_img.shape x_img = x_img.flatten() y_img = y_img.flatten() img = x_img * 0.0 for i in numba.prange(unique_cids.shape[0]): cid = unique_cids[i] idx = np.where(cluster_ids == cid)[0] # skip cluster with too few events if idx.shape[0] < minimum_event_num: continue # compute the centroid position and weighted equivalent intensity wgts = tots[idx] / np.sum(tots[idx]) xc = np.dot(wgts, xs[idx]) yc = np.dot(wgts, ys[idx]) # ic = np.dot(wgts, tots[idx]) # propogate the signal to the image idx = np.where( np.logical_and( np.logical_and( x_img >= xc - extinguish_dist, x_img < xc + extinguish_dist, ), np.logical_and( y_img >= yc - extinguish_dist, y_img < yc + extinguish_dist, ), ))[0] wgts = (x_img[idx] - xc)**2 + (y_img[idx] - yc)**2 wgts = 1.0 / wgts wgts = wgts / np.sum(wgts) img[idx] += wgts # return the results return img.reshape(img_shape)
5,345,656
def plot_average_spatial_concs4lon(ds, year=2018, vars2use=None, use_local_CVAO_area=False, show_plot=False, dpi=320, verbose=False,): """ Make a PDF of average spatial concentrations by level """ # Setup PDF to save plots to. savetitle = 'ARNA_avg_spatial_concs_{}'.format(year) pdff = AC.plot2pdfmulti(title=savetitle, open=True, dpi=dpi) # Which variables to plot if not isinstance(vars2use, list): vars2use = [i for i in ds.data_vars] vars2use = ['NOy', 'PM2.5(dust)', ] # Now loop and plot for var in vars2use: # for var in vars2use[:2]: # For testing # Plot up by level # for lev2use in ds.lev.values: for lon2use in list(ds.lon.values): if verbose: print(var, lev2use) # Get units for species units = ds[var].units # Select for level and variable, and average over time ds_tmp = ds.sel(lon=lon2use).mean(dim='time') # Get the LateX for of the species name try: LaTeX_spec = AC.latex_spec_name(var) except KeyError: print('WARNING: not converted {} to LaTeX form'.format(var)) LaTeX_spec = var # Set title title = 'Average [{}] @ {:.0f}hPa in Feb {}'.format( LaTeX_spec, lev2use, year) # Plot up and add title # quick_map_plt_CV_1layer(ds_tmp, var2plot=var, title=title, # use_local_CVAO_area=use_local_CVAO_area, # save_plot=False, units=units) # vertical plot del ds_tmp # Save to PDF AC.plot2pdfmulti(pdff, savetitle, dpi=dpi, tight=True) if show_plot: plt.show() plt.close() # Save entire pdf AC.plot2pdfmulti(pdff, savetitle, close=True, dpi=dpi) plt.close('all')
5,345,657
def test_sleep_physionet_age_missing_recordings(physionet_tmpdir, subject, recording, download_is_error): """Test handling of missing recordings in Sleep Physionet age fetcher.""" with pytest.raises( ValueError, match=f'Requested recording {recording} for subject'): age.fetch_data(subjects=[subject], recording=[recording], on_missing='raise', path=physionet_tmpdir) with pytest.warns(RuntimeWarning, match=f'Requested recording {recording} for subject'): age.fetch_data(subjects=[subject], recording=[recording], on_missing='warn', path=physionet_tmpdir) paths = age.fetch_data(subjects=[subject], recording=[recording], on_missing='ignore', path=physionet_tmpdir) assert paths == []
5,345,658
def _chromosome_collections(df, y_positions, height, **kwargs): """ Yields BrokenBarHCollection of features that can be added to an Axes object. Parameters ---------- df : pandas.DataFrame Must at least have columns ['chrom', 'start', 'end', 'color']. If no column 'width', it will be calculated from start/end. y_positions : dict Keys are chromosomes, values are y-value at which to anchor the BrokenBarHCollection height : float Height of each BrokenBarHCollection Additional kwargs are passed to BrokenBarHCollection """ del_width = False if "width" not in df.columns: del_width = True df["width"] = df["end"] - df["start"] for chrom, group in df.groupby("chrom"): yrange = (y_positions["chr" + chrom], height) xranges = group[["start", "width"]].values yield BrokenBarHCollection( xranges, yrange, facecolors=group["colors"], **kwargs ) if del_width: del df["width"]
5,345,659
def connect_colour(scene, attributes, ui_name, ui_mix_with, ui_mix_spin, ui_mix_slider, ui_strength_spin, ui_strength_slider): """Connect colour.""" ui_name.currentIndexChanged.connect( lambda x: connect_combobox_abstract(x, scene, attributes, 'name', c.attribute_values(c.Colour), True)) ui_mix_with.currentIndexChanged.connect( lambda x: connect_combobox_abstract(x, scene, attributes, 'mix_with', c.attribute_values(c.Colour), True)) ui_mix_slider.sliderMoved.connect( lambda x: connect_slider_moved_abstract(x, scene, attributes, 'mix_percent', lambda x: x, ui_mix_spin)) ui_mix_slider.sliderReleased.connect( lambda : connect_slider_released_abstract(scene)) ui_strength_slider.sliderMoved.connect( lambda x: connect_slider_moved_abstract(x, scene, attributes, 'strength', lambda x: x, ui_strength_spin)) ui_strength_slider.sliderReleased.connect( lambda : connect_slider_released_abstract(scene))
5,345,660
def worker(job): """Run a single download job.""" logger = logging.getLogger("ncbi-genome-download") ret = False try: if job.full_url is not None: req = requests.get(job.full_url, stream=True) ret = save_and_check(req, job.local_file, job.expected_checksum) if not ret: return ret ret = create_symlink(job.local_file, job.symlink_path) except KeyboardInterrupt: # pragma: no cover # TODO: Actually test this once I figure out how to do this in py.test logger.debug("Ignoring keyboard interrupt.") return ret
5,345,661
def test_upload_findings(): """Tests uploading of findings""" responses.add(responses.PUT, get_project_service_mock('add-external-findings'), body=SUCCESS, status=200) resp = get_client().upload_findings(_get_test_findings(), datetime.datetime.now(), "Test message", "partition-name") assert "content" in responses.calls[1].request.body assert "test-id" in responses.calls[1].request.body assert resp.text == SUCCESS
5,345,662
def generate_ar(n_series, n_samples, random_state=0): """Generate a linear auto-regressive series. This simple model is defined as:: X(t) = 0.4 * X(t - 1) - 0.6 * X(t - 4) + 0.5 * N(0, 1) The task is to predict the current value using all the previous values. Parameters ---------- n_series : int Number of time series to generate. n_samples : int Number of samples in each time series. random_state : int, default 0 Seed to use in the random generator. Returns ------- X, Y : ndarray, shape (n_series, 1, n_stamps, 1) Input and output sequences, `Y` is just delayed by 1 sample version of `X`. """ n_init = 4 n_discard = 20 X = np.zeros((n_series, n_init + n_discard + n_samples + 1)) rng = np.random.RandomState(random_state) X[:, n_init] = rng.randn(n_series) for i in range(n_init + 1, X.shape[1]): X[:, i] = (0.4 * X[:, i - 1] - 0.6 * X[:, i - 4] + 0.1 * rng.randn(n_series)) Y = X[:, n_init + n_discard + 1:, None] X = X[:, n_init + n_discard: -1, None] return X, Y
5,345,663
def get_current_commit_id() -> str: """Get current commit id. Returns: str: current commit id. """ command = "git rev-parse HEAD" commit_id = ( subprocess.check_output(command.split()).strip().decode("utf-8") # noqa: S603 ) return commit_id
5,345,664
def get_raw_code(file_path): """ Removes empty lines, leading and trailing whitespaces, single and multi line comments :param file_path: path to .java file :return: list with raw code """ raw_code = [] multi_line_comment = False with open(file_path, "r") as f: for row in f: # remove leading and trailing whitespaces line = row.strip() # remove '/* comments */' line = re.sub(r''' ^ # start of string /\* # "/*" string .* # any character (except line break) zero or more times \*/ # "*/" string \s* # zero or many whitespaces ''', '', line, 0, re.VERBOSE) # remove '//comments' line = re.sub(r''' ^ # start of string // # "//" string .* # any character (except line break) zero or more times $ # end of string ''', '', line, 0, re.VERBOSE) # ignore empty lines if line != '': # skip multi-line comments (/*) if re.search(r''' ^ # start of string /\* # "/*" string .* # any character (except line break) zero or more times ''', line, re.VERBOSE): multi_line_comment = True continue # check if multi-line comment was closed (*/) elif re.search(r''' .* # any character (except line break) zero or more times \*/ # "*/" string $ # end of string ''', line, re.VERBOSE): multi_line_comment = False line = re.sub(r''' .* # any character (except line break) zero or more times \*/ # "*/" string \s* # zero or many whitespaces ''', '', line, 0, re.VERBOSE) if line == '': continue # add line if it's not multi-line comment if not multi_line_comment: raw_code.append(line) return raw_code
5,345,665
def test_is_component_dockerised(): """Tests for is_component_dockerised().""" from reana.cli import is_component_dockerised assert is_component_dockerised( 'reana') is False
5,345,666
def load_content(file_path): """ Loads content from file_path if file_path's extension is one of allowed ones (See ALLOWED_EXTS). Throws UnsupportedMetaException on disallowed filetypes. :param file_path: Absolute path to the file to load content from. :type file_path: ``str`` :rtype: ``dict`` """ file_name, file_ext = os.path.splitext(file_path) if file_ext not in ALLOWED_EXTS: raise Exception('Unsupported meta type %s, file %s. Allowed: %s' % (file_ext, file_path, ALLOWED_EXTS)) parser_func = PARSER_FUNCS.get(file_ext, None) with open(file_path, 'r') as fd: return parser_func(fd) if parser_func else fd.read()
5,345,667
def _yaml_comment_regex() -> Pattern: """ From https://yaml-multiline.info/, it states that `#` cannot appear *after* a space or a newline, otherwise it will be a syntax error (for multiline strings that don't use a block scalar). This applies to single lines as well: for example, `a#b` will be treated as a single value, but `a #b` will only capture `a`, leaving `#b` as a comment. For lines that *do* use a block scalar, the YAML parser will throw a syntax error if there is additional text on the same line as the block scalar. Comments however, are fine. e.g. key: | # this is ok blah key: | but this is not blah Given that we've made it to this stage, we can assume the YAML file is syntactically correct. Therefore, if we add whitespace before the comment character, we can know that everything else *after* the comment character is a comment for a given line. """ return re.compile(r'(\s+#[\S ]*)')
5,345,668
def to_list(name: str) -> "Expr": """ Aggregate to list """ return col(name).list()
5,345,669
def format_ipc_dimension(number: float, decimal_places: int = 2) -> str: """ Format a dimension (e.g. lead span or height) according to IPC rules. """ formatted = '{:.2f}'.format(number) stripped = re.sub(r'^0\.', '', formatted) return stripped.replace('.', '')
5,345,670
def mean_test(data, muy0, alternative = 'equal', alpha = 0.95): """ This function is used to create a confidence interval of two.sided hypothesis Input: data (1D array): the sample of the whole column that you want to evaluate confidence (float) : confidence_level, must be in (0, 1) Output: the dictionary that contains the info of - Confidence_Interval (tupple) - T_statistics (float) - Two-sided p-value. """ # convert datapoint to float a = 1.0 * np.array(data) confidence = np.round(1 - alpha, 3) # Number of observations n = len(a) # Compute mean and standard_errors m, se = np.mean(a), stats.sem(a) # result of testing T_stat = ((m - muy0) / se)*np.sqrt(n) # compute the interval_radius if alternative in ['equal', "two.side"]: h = se * stats.t.ppf((1 + confidence) / 2., n-1) conf_itv = (float(m - h), float(m + h)) alt = "true mean (muy) is not equal to muy0 = {}".format(muy0) cnls = "true mean (muy) = muy0 = {}".format(muy0) p_val = 2*min(stats.t.cdf(T_stat, n-1), 1 - stats.t.cdf(T_stat, n-1)) elif alternative == 'greater': h = se * stats.t.ppf(1 - confidence, n-1) conf_itv = (float(m - h), '+inf') alt = "true mean (muy) > muy0 = {}".format(muy0) cnls = "true mean (muy) <= muy0 = {}".format(muy0) p_val = 1 - stats.t.cdf(T_stat, n-1) elif alternative == 'less': h = se * stats.t.ppf(1 - confidence, n-1) conf_itv = ('-inf', float(m + h)) alt = "true mean (muy) < muy0 = {}".format(muy0) cnls = "true mean (muy) >= muy0 = {}".format(muy0) p_val = stats.t.cdf(T_stat, n-1) # conclusion if p_val < alpha: kl = 'reject the hypothesis, {}'.format(alt) else: kl = 'can not reject the null hypothesis, so the {}'.format(cnls) # save all the output-results dic_data = pd.DataFrame( { 'alpha / confidence_level': [{'significance level':alpha, 'confidence_level': 1- alpha}], 'Confidence_Interval': [conf_itv], 'T_statistic': T_stat, 'sample_mean': m, 'alternative_hypothesis': alt, 'p_value': p_val, 'conclusion': "For confidence_level = {}%, we {}".format(100*confidence, kl) } ) return dic_data
5,345,671
def __build_command(command, name, background=None, enable=None): """ Constuct args for systemctl command. Args: command: The systemctl command name: The unit name or name pattern background: True to have systemctl perform the command in the background enable: True to enable/disable, False to start/stop only, None for default. Returns: The name with type suffix """ args = ['--quiet'] if background: args.append('--no-block') if ((enable or name.startswith('appscale-')) and not enable==False and command in ('start', 'stop')): args.append('--now') args.append('--runtime') if command == 'start': args.append('enable') else: args.append('disable') else: args.append(command) args.append(__expand_name(name)) return args
5,345,672
def dockerFetchLatestVersion(image_name: str) -> list[str]: """ Fetches the latest version of a docker image from hub.docker.com :param image_name: image to search for :return: list of version suggestions for the image or 'not found' if error was returned """ base_url = "https://hub.docker.com/v2/repositories/library" request = f"{base_url}/{image_name}/tags" params = { "ordering": "last_updated", "name": "." } version_list = [] response = requests.get(request, params=params) if response.status_code == requests.codes.ok: json = response.json() version_list = list( map(lambda i: i["name"], json["results"]) )[:5] if len(version_list) == 0: version_list = [NOT_FOUND] else: del params["name"] response = requests.get(request, params=params) if response.status_code == requests.codes.ok: json = response.json() version_list += list( map(lambda i: i["name"], json["results"]) )[:5] return sorted(sorted(list(set(version_list)), reverse=True), key=lambda it: _isfloat(it), reverse=True)
5,345,673
def _dataset( dataset_type: str, transform: str, train: bool = True ) -> torch.utils.data.Dataset: """ Dataset: mnist: MNIST cifar10: CIFAR-10 cifar100: CIFAR-100 Transform: default: the default transform for each data set simclr: the transform introduced in SimCLR """ try: transform = _get_transform(dataset_type, transform, train) except KeyError: raise DatasetNotIncludeError(f"Dataset {dataset_type} or transform {transform} is not included.\n" \ f"Refer to the following: {_dataset.__doc__}") if dataset_type == "mnist": dataset = torchvision.datasets.MNIST( root=ROOT, train=train, download=False, transform=transform ) elif dataset_type == "fashionmnist": dataset = torchvision.datasets.FashionMNIST( root=ROOT, train=train, download=False, transform=transform ) elif dataset_type == "cifar10": dataset = torchvision.datasets.CIFAR10( root=ROOT, train=train, download=False, transform=transform ) elif dataset_type == "cifar100": dataset = torchvision.datasets.CIFAR100( root=ROOT, train=train, download=False, transform=transform ) return dataset
5,345,674
def inferCustomerClasses(param_file, evidence_dir, year): """ This function uses the variable elimination algorithm from libpgm to infer the customer class of each AnswerID, given the evidence presented in the socio-demographic survey responses. It returns a tuple of the dataframe with the probability distribution over all classes for each AnswerID and the BN object. """ bn = loadbn(param_file) evidence, a_id = readEvidence(year, evidence_dir) query = {"customer_class":''} cols = bn.Vdata.get('customer_class')['vals'] result = pd.DataFrame(columns=cols) #create empty dataframe in which to store inferred probabilities count = 0 #set counter for e in evidence: bn = loadbn(param_file) fn = TableCPDFactorization(bn) try: inf = fn.condprobve(query, e) classprobs = list(inf.vals) result.loc[count] = classprobs count += 1 except: result.loc[count] = [None] * len(cols) count += 1 result['AnswerID'] = a_id result.set_index(keys='AnswerID',inplace=True) return result
5,345,675
def MidiSegInfo(segment): """ Midi file info saved in config file for speed """ class segInfo: iMsPerTick = 0 bpm = 4 ppqn = 480 total_ticks = 0 iLengthInMs = 0 iTracks = 0 trackList = [] ver = "1.5" ret = segInfo() savedVer = IniGetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "Ver") savedDateTime = IniGetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "DateTime") dateTime = FileDateTime(segment.filename) if ver != savedVer or dateTime != savedDateTime: mi = GetMidiInfo(segment.filename) if mi.err == 0: IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "Ver", ver) IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "DateTime", str(dateTime)) IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "PPQN", str(mi.ppqn)) IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "BPM", str(mi.beats_per_measure)) IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "totalTicks", str(mi.totalTicks)) IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "maxTracks", str(mi.maxTracks)) iLengthInMs = GetMidiFileLength(segment.filename) * 1000 IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "LengthInMs", str(iLengthInMs)) if iLengthInMs > 0: IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "MsPerTick", str(iLengthInMs / mi.totalTicks)) #have to write out the tracklist in format that can be saved in INI file tl = [] for track in mi.trackList: tl.append((track.track, track.channel, track.name)) IniSetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "Tracks", tl) trackList = [] tl = IniGetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "Tracks", 'list', []) for t in tl: trackList.append(trackGrid(t[0], t[1], t[2],False)) iTracks = IniGetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "maxTracks", 'int', 0) iMsPerTick = IniGetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "MsPerTick", 'float', 0) bpm = IniGetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "BPM", 'int', 0) ppqn = IniGetValue(JetDefs.JETMIDIFILES_INI, segment.filename, "PPQN", 'int', 480) if iMsPerTick == 0 or bpm == 0 or ppqn == 0: return ret tb = TimeBase(ppqn, bpm) total_ticks = tb.ConvertStrTimeToTicks(segment.length) if total_ticks == 0: total_ticks = tb.MbtDifference(tb.ConvertStrTimeToTuple(segment.start), tb.ConvertStrTimeToTuple(segment.end)) if total_ticks == 0: return ret ret.iTracks = iTracks ret.iMsPerTick = iMsPerTick ret.bpm = bpm ret.ppqn = ppqn ret.total_ticks = total_ticks ret.iLengthInMs = total_ticks * iMsPerTick ret.trackList = trackList return ret
5,345,676
def num_in_row(board, row, num): """True if num is already in the row, False otherwise""" return num in board[row]
5,345,677
def load_mnist(dataset="mnist.pkl.gz"): """ dataset: string, the path to dataset (MNIST) """ data_dir, data_file = os.path.split(dataset) # download MNIST if not found if not os.path.isfile(dataset): import urllib origin = ( 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz' ) print 'Downloading MNIST from %s' % origin assert urllib.urlretrieve(origin, dataset) print "Loading Data ..." with gzip.open(dataset, 'rb') as handle: train_set, valid_set, test_set = cPickle.load(handle) rval = [(train_set[0],to_categorical(train_set[1])), (valid_set[0],to_categorical(valid_set[1])), (test_set[0], to_categorical(test_set[1]))] #train_X, train_y = shared_data(train_set[0]),shared_data_int32(to_categorical(train_set[1])) #valid_X, valid_y = shared_data(valid_set[0]),shared_data_int32(to_categorical(valid_set[1])) #test_X, test_y = shared_data(test_set[0]),shared_data_int32(to_categorical(test_set[1])) # #rval = [(train_X, train_y), (valid_X, valid_y), (test_X, test_y)] return rval
5,345,678
def select_sklearn_training_regiment(model: base.ModelType, cross_validate: int = None, grid_search: dict = None, **kwargs): """ Select the type of sklearn training regime. :model (base.ModelType): The model to be trained. :cross_validate (int, default = None): The number of folds to use for cross validation. :grid_search (dict, default = None): The parameters to search over. """ if grid_search is not None: train_sklearn_gridsearch_model(model, cross_validate = cross_validate, grid_search = grid_search, **kwargs) elif cross_validate is not None: train_sklearn_cv_model(model, cross_validate = cross_validate, **kwargs) else: train_sklearn_model(**kwargs)
5,345,679
def test_row_units() -> None: """First row unit is as expected""" first_row = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9'] # pylint: disable=protected-access assert SB._row_units()[0] == first_row
5,345,680
def _patch_streams(out: TextIO) -> Iterator[None]: """Patch and subsequently reset a text stream.""" sys.stderr = sys.stdout = out try: yield finally: sys.stderr = sys.__stderr__ sys.stdout = sys.__stdout__
5,345,681
def colmap_localize(kapture_path: str, colmap_path: str, input_database_path: str, input_reconstruction_path: str, colmap_binary: str, pairs_file_path: Optional[str], keypoints_type: Optional[str], use_colmap_matches_importer: bool, image_registrator_options: List[str], skip_list: List[str], force: bool) -> None: """ Localize images on a colmap model using default SIFT features with the kapture data. :param kapture_path: path to the kapture to use :param colmap_path: path to the colmap build :param input_database_path: path to the map colmap.db :param input_database_path: path to the map colmap.db :param input_reconstruction_path: path to the map reconstruction folder :param colmap_binary: path to the colmap binary executable :param pairs_file_path: Optional[str], :param keypoints_type: type of keypoints, name of the keypoints subfolder :param use_colmap_matches_importer: bool, :param image_registrator_options: options for the image registrator :param skip_list: list of steps to skip :param force: Silently overwrite kapture files if already exists. """ # Load input files first to make sure it is OK logger.info('loading kapture files...') with kapture.io.csv.get_all_tar_handlers(kapture_path) as tar_handlers: kapture_data = kapture.io.csv.kapture_from_dir(kapture_path, pairs_file_path, tar_handlers=tar_handlers) colmap_localize_from_loaded_data(kapture_data, kapture_path, tar_handlers, colmap_path, input_database_path, input_reconstruction_path, colmap_binary, keypoints_type, use_colmap_matches_importer, image_registrator_options, skip_list, force)
5,345,682
def load_hs13_ZSBB_params(): """Load the standard parameters to generate SocioPatterns HS13 surrogate networks using the ZSBB model. Returns ------- :obj:`dict` The `kwargs` to pass to :func:`tacoma.ZSBB_model`. """ fn = os.path.join(path,'ht09_zsbb_params.json') return tc.load_json_dict(fn)
5,345,683
def factorial_3(n, acc=1): """ Replace all recursive tail calls f(x=x1, y=y1, ...) with (x, y, ...) = (x1, y1, ...); continue """ while True: if n < 2: return 1 * acc (n, acc) = (n - 1, acc * n) continue break
5,345,684
def load(filename='haas.cfg'): """Load the configuration from the file 'haas.cfg' in the current directory. This must be called once at program startup; no configuration options will be available until then. If the configuration file is not available, this function will simply load an empty configuration (i.e. one with no options). """ cfg.read(filename)
5,345,685
async def app(scope, receive, send): """Example application which servers a simple HTML page""" html = b""" <!doctype html> <html> <head> <title>Hello ASGI!</title> </head> <body> <main> <h1>Hello ASGI!</h1> </main> </body> </html> """ await send( { "type": "http.response.start", "status": 200, "headers": [[b"content-type", b"text/html"], [b"content-length", b"269"],], } ) await send( {"type": "http.response.body", "body": html, "more_body": False,} )
5,345,686
def test_upload_file(mocker): """Sanity check upload function.""" runner = CliRunner() with runner.isolated_filesystem(): with open("foo.txt", "w") as fastq_file: fastq_file.write("AAABBB") mocked_s3_client = mocker.Mock() assert upload_file( mocked_s3_client, "foo.txt", "foo-bucket", object_name="foo-object.txt", ) mocked_s3_client.upload_file.assert_called_once()
5,345,687
def get_all_functions(module: types.ModuleType) -> Iterator[Callable]: """ Retrieve all functions defined inside a module, including all it submodules Args: module: Module inside which functions are to be searched Returns: Iterator over all functions inside the module, and all its submodules """ LOGGER.debug("Trying to get all functions inside module %s and it submodules", module.__name__) all_members: Iterator[List[Tuple[str, Callable]]] = map( lambda mod: inspect.getmembers(mod, inspect.isfunction), get_submodules(module)) all_functions: Iterator[List[Tuple[str, Callable]]] = filter(lambda x: len(x) > 1, all_members) yield from map(lambda func_info: func_info[1], itertools.chain(*all_functions))
5,345,688
def main(criteria1, criteria2, criteria3, ad_steps, path=DIR, out_freq=FREQ, output=OUTPUT_FOLDER, numfolders=False, topology=None, skip_first=False, resname="LIG", percentage=30, threshold=None, cpus=1): """ Description: Rank the traj found in the report files under path by the chosen criteria. Finally, output the best n_structs. Input: Path: Path to look for *report* files in all its subfolders. Criteria: Criteria to sort the structures. Needs to be the name of one of the Pele's report file column. (Default= "Binding Energy") n_structs: Numbers of structures to create. sort_order: "min" if sorting from lower to higher "max" from high to low. out_freq: "Output frequency of our Pele control file" Output: f_out: Name of the n outpu """ # Check whether is adaptive simulation or not adaptive = is_adaptive() # Find reports reports = find_reports(path, numfolders) # Retrieve Column Names from report steps, crit1_name, crit2_name, crit3_name = get_column_names(reports, STEPS, criteria1, criteria2, criteria3) # Retrieve Data from reports data = parse_values(reports, criteria1, criteria2, steps, crit1_name, crit2_name, skip_first) # Filter values if threshold: filter_data = Filter(data, percentage, crit1_name, thresh=threshold) else: filter_data = Filter(data, percentage, crit1_name) # cluster cluster(filter_data, resname, out_freq, cpus)
5,345,689
def autocorr(x, axis=0, fast=False): """ Estimate the autocorrelation function of a time series using the FFT. :param x: The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. :param axis: (optional) The time axis of ``x``. Assumed to be the first axis if not specified. :param fast: (optional) If ``True``, only use the largest ``2^n`` entries for efficiency. (default: False) """ x = np.atleast_1d(x) m = [slice(None), ] * len(x.shape) # For computational efficiency, crop the chain to the largest power of # two if requested. if fast: n = int(2**np.floor(np.log2(x.shape[axis]))) m[axis] = slice(0, n) x = x else: n = x.shape[axis] # Compute the FFT and then (from that) the auto-correlation function. f = np.fft.fft(x-np.mean(x, axis=axis), n=2*n, axis=axis) m[axis] = slice(0, n) acf = np.fft.ifft(f * np.conjugate(f), axis=axis)[m].real m[axis] = 0 return acf / acf[m]
5,345,690
def decode_element( elem: "DataElement", dicom_character_set: Optional[Union[str, List[str]]] ) -> None: """Apply the DICOM character encoding to a data element Parameters ---------- elem : dataelem.DataElement The :class:`DataElement<pydicom.dataelem.DataElement>` instance containing an encoded byte string value to decode. dicom_character_set : str or list of str or None The value of (0008,0005) *Specific Character Set*, which may be a single value, a multiple value (code extension), or may also be ``''`` or ``None``, in which case ``'ISO_IR 6'`` will be used. """ if elem.is_empty: return if not dicom_character_set: dicom_character_set = ['ISO_IR 6'] encodings = convert_encodings(dicom_character_set) # decode the string value to unicode # PN is special case as may have 3 components with different chr sets if elem.VR == "PN": if elem.VM == 1: # elem.value: Union[PersonName, bytes] elem.value = cast(PersonName, elem.value).decode(encodings) else: # elem.value: Iterable[Union[PersonName, bytes]] elem.value = [ cast(PersonName, vv).decode(encodings) for vv in elem.value ] elif elem.VR in text_VRs: # You can't re-decode unicode (string literals in py3) if elem.VM == 1: if isinstance(elem.value, str): return elem.value = decode_bytes(elem.value, encodings, TEXT_VR_DELIMS) else: output = list() for value in elem.value: if isinstance(value, str): output.append(value) else: output.append( decode_bytes(value, encodings, TEXT_VR_DELIMS) ) elem.value = output
5,345,691
def parse_date(filename_html): """Parse a file, and return the date associated with it. filename_html -- Name of file to parse. """ match = re.search(r"\d{4}-\d{2}-\d{2}", filename_html) if not match: return None match_date = match.group() file_date = dateutil.parser.parse(match_date).date() return file_date
5,345,692
def build_static_runtime( workspace, compiler, module, compiler_options, executor=None, extra_libs=None, ): """Build the on-device runtime, statically linking the given modules. Parameters ---------- compiler : tvm.micro.Compiler Compiler instance used to build the runtime. module : IRModule Module to statically link. compiler_options : dict The return value of tvm.micro.default_options(), with any keys overridden to inject compiler options specific to this build. If not given, tvm.micro.default_options() is used. This dict contains the `options` parameter passed to Compiler.library() and Compiler.binary() at various stages in the compilation process. executor : Optional[str] Executor used for runtime. Based on this we determine the libraries that need to be linked with runtime. extra_libs : Optional[List[MicroLibrary|str]] If specified, extra libraries to be compiled into the binary. If a MicroLibrary, it is included into the binary directly. If a string, the path to a directory; all direct children of this directory matching RUNTIME_SRC_REGEX are built into a library. These libraries are placed before any common CRT libraries in the link order. Returns ------- MicroBinary : The compiled runtime. """ mod_build_dir = workspace.relpath(os.path.join("build", "module")) os.makedirs(mod_build_dir) mod_src_dir = workspace.relpath(os.path.join("src", "module")) if not executor: executor = "host-driven" libs = [] for mod_or_src_dir in (extra_libs or []) + get_runtime_libs(executor): if isinstance(mod_or_src_dir, MicroLibrary): libs.append(mod_or_src_dir) continue lib_src_dir = mod_or_src_dir lib_name = os.path.basename(lib_src_dir) lib_build_dir = workspace.relpath(f"build/{lib_name}") os.makedirs(lib_build_dir) lib_srcs = [] for p in os.listdir(lib_src_dir): if RUNTIME_SRC_REGEX.match(p): lib_srcs.append(os.path.join(lib_src_dir, p)) libs.append(compiler.library(lib_build_dir, lib_srcs, compiler_options["lib_opts"])) mod_src_dir = workspace.relpath(os.path.join("src", "module")) os.makedirs(mod_src_dir) libs.append( module.export_library( mod_build_dir, workspace_dir=mod_src_dir, fcompile=lambda bdir, srcs, **kwargs: compiler.library( bdir, srcs, compiler_options["generated_lib_opts"] ), ) ) runtime_build_dir = workspace.relpath(f"build/runtime") os.makedirs(runtime_build_dir) return compiler.binary(runtime_build_dir, libs, compiler_options["bin_opts"])
5,345,693
def mod(a1, a2): """ Function to give the remainder """ return a1 % a2
5,345,694
async def autopaginate( text: str, limit: int, ctx: Union[commands.Context, KurisuContext], codeblock: bool = False, ): """Automatic Paginator""" wrapped_text: list[str] = wrap(text, limit) embeds: list[discord.Embed] = [] for t in wrapped_text: embeds.append( discord.Embed( description=box(t, "py") if codeblock else t, color=get_color("ok_color"), ).set_footer( text=f"Page {wrapped_text.index(t) + 1} out of {len(wrapped_text)}" ) ) await vbu.Paginator(embeds, per_page=1).start(ctx)
5,345,695
def _unfreeze_and_add_param_group(module: torch.nn.Module, optimizer: Optimizer, lr: Optional[float] = None, train_bn: bool = True): """Unfreezes a module and adds its parameters to an optimizer.""" _make_trainable(module) params_lr = optimizer.param_groups[0]['lr'] if lr is None else float(lr) optimizer.add_param_group( {'params': filter_params(module=module, train_bn=train_bn), 'lr': params_lr / 10., })
5,345,696
def select_theme_dirs(): """ Load theme templates, if applicable """ if settings.THEME_DIR: return ["themes/" + settings.THEME_DIR + "/templates", "templates"] else: return ["templates"]
5,345,697
def encode_string(s): """ Simple utility function to make sure a string is proper to be used in a SQL query EXAMPLE: That's my boy! -> N'That''s my boy!' """ res = "N'"+s.replace("'","''")+"'" res = res.replace("\\''","''") res = res.replace("\''","''") return res
5,345,698
def monitor_submissions(syn, api): """Monitoring evaluating submissions""" evaluation_queue_id = 9614883 sub_bundles = syn.getSubmissionBundles(evaluation_queue_id, status='EVALUATION_IN_PROGRESS') for _, sub_status in sub_bundles: task_id = sub_status.submissionAnnotations['task_id'][0] synapse_task_folder = sub_status.submissionAnnotations['task_output'][0] task = api.tasks.get(task_id) # Update final submission status if task.status == "INVALID": sub_status.status = "INVALID" elif task.status == "QUEUED": print("Task is queued") continue elif task.status == "RUNNING": execution_details = task.get_execution_details() jobs_completed = [ job.status == "COMPLETED" for job in execution_details.jobs ] print( "Task is running. " f"{sum(jobs_completed)}/{len(jobs_completed)} jobs completed." ) continue elif task.status == "COMPLETED": sub_status.status = "ACCEPTED" # Store task outputs if the task is complete task_outputs = task.outputs # Download outputs except for bam files (large) temp_dir = tempfile.TemporaryDirectory() output_files = [] for _, output_value in task_outputs.items(): if output_value is not None: if not output_value.name.endswith(".bam"): output_file = api.files.get(output_value.id) output_path = os.path.join(temp_dir.name, output_value.name) output_file.download(output_path) output_files.append(output_path) # Unfortunately no recursive store function currently... for output_file in output_files: syn.store( synapseclient.File(path=output_file, parent=synapse_task_folder) ) temp_dir.cleanup() else: raise ValueError(f"status {task.status} not supported:") sub_status = syn.store(sub_status)
5,345,699