content
stringlengths
22
815k
id
int64
0
4.91M
def _lcmv_source_power(info, forward, noise_cov, data_cov, reg=0.01, label=None, picks=None, pick_ori=None, rank=None, verbose=None): """Linearly Constrained Minimum Variance (LCMV) beamformer. Calculate source power in a time window based on the provided data ...
78,000
def summary(d): """ Generate a summary message of the dictionary. :param d: A dictionary to summary. :return: A string as summary message. """ msg_list = [] for key, value in d.items(): msg = '- {}: '.format(key) if isinstance(value, np.ndarray): msg += 'shape {...
78,001
def connect_translate_into_pivots(source_transform, target_transform): """ Connect translate pivots from source to target :param source_transform: str, name of a transform :param target_transform: str, name of a transform """ maya.cmds.connectAttr('{}.translateX'.format(source_transform), '{}.r...
78,002
def get_folding_command(cand, obs): """ get_folding_command(cand, obs): Return a command for prepfold for folding the subbands using an obs_info instance, and a candidate instance that describes the observations and searches. """ # Folding rules are based on the facts th...
78,003
def valid_labels_regex(arg_value, pat=re.compile(r"^all|random|([a-z|0-9|,|\.]+)|([a-z|0-9|\.]+-[a-z]+-[1-9]-[0-9]-[1-9]-[c|h],?)+$")): """Get the params regex.""" if not pat.match(arg_value): raise argparse.ArgumentTypeError return arg_value
78,004
def execute(context: cli.CommandContext) -> Response: """ """ response = context.response project = cauldron.project.internal_project if not project: return response.fail( code='NO_OPEN_PROJECT', message='No project is open. Unable to refresh' ).console( ...
78,005
def test_construct(clear_db): """Test the construction of `UpfFamily` works.""" family = UpfFamily(label='family').store() assert isinstance(family, UpfFamily) description = 'SSSP description' family = UpfFamily(label='SSSP/v1.1', description=description).store() assert isinstance(family, UpfFa...
78,006
def get_username(strategy, user=None, *args, **kwargs): """Sets the `username` argument. If the user exists already, use the existing username. Otherwise generate username from the `new_uuid` using the `helusers.utils.uuid_to_username` function. """ storage = strategy.storage if not user: ...
78,007
def format_time(s): """Function that gets a time in seconds and returns it in format MM:SS""" minutes = int(s / 60) seconds = s % 60 if minutes < 10 and seconds < 10: print("0"+ str(minutes) + ":" + "0" + str(seconds), end="\r") else: if minutes >= 10 and seconds < 10: pr...
78,008
def buffer_create(config, name, size=None): """Create buffer reservation. :param config: configuration DB handle :param name: name :param size: size, uses default in chart if None """ deploy_id = name values = {} if size is not None: values["size"] = size deploy = ska_sdp_c...
78,009
def uptest_latest(request): """ Look up most recent test run and redirect to its record in the API. """ runs = models.TestRun.objects.filter(end__isnull=False).order_by('-start') if not runs: return http.HttpResponseNotFound() url = reverse('api_dispatch_detail', kwargs...
78,010
def one_to_three(one_letter): """ Convert a one letter code amino acid to a three letter code. """ assert one_letter.upper() in "FLSYCWPHERIMTNKVADQG*U", "Error, %s is not a valid amino acid" % one_letter AA = { "I": "Ile", "V": "Val", "L": "Leu", "F": "Phe", ...
78,011
def get_video_frame(video_path, frame_number): """ Obtain numpy array corresponding to a particular video frame in video_path :param video_path: local path to mp4 file :param frame_number: video frame to be returned :return: numpy array corresponding to frame of interest. Dimensions are (1024, 1280...
78,012
def float_product(size=DEF_MATRIX, rep=DEF_REP): """ Returns the execution time of performing a product of random real matrices. Parameters ---------- size : int The dimension of the square matrices that will be used in the operation. rep : in...
78,013
def _empty_frozen_http_headers() -> HttpHeaders: """Used for the 'default_factory' of the 'NodeConfig.headers'""" return HttpHeaders().freeze()
78,014
def reorder_evals(ev,times): """ Parameters ---------- evals : 2D numpy array containing a series of eigenvalues. times : 1D numpy array containing the corresponding times Returns ------- newev : 2D numpy array with continuous (along dim=0) eigenvalues """ evals = ev....
78,015
def get_public_members(): """Get public members in :mod:`bezier` package. Also validates the contents of ``bezier.__all__``. Returns: list: List of all public members **defined** in the main package (i.e. in ``__init__.py``). Raises: ValueError: If ``__all__`` has repeated ele...
78,016
def sha256_hash(stream, block_size=65536): """ Calculates a sha256 hash for the contents of the provided stream. :param stream: The stream of the content where to calculate the hash for. :type stream: IOStream :param block_size: The amount of bytes that are read each time. :type block_size: int...
78,017
def generate_map(output, lats=[], lons=[], wesn=None): """ Using Basemap and the matplotlib toolkit, this function generates a map and puts a red dot at the location of every IP addresses found in the list. The map is then saved in the file specified in `output`. """ print("Generating map and sa...
78,018
def central_time(sqrIR: np.ndarray, tstamp: np.ndarray) -> np.ndarray: """ Room parameter. Parameters ---------- sqrIR : np.ndarray Squared room impulsive response. tstamp : np.ndarray Time stamps of each IR sample. Returns ------- central_time : np.ndarray ...
78,019
def get_html_fields(fields): """ Converts a fields table with mandatory keywords type, text, id and partially optional keywords value, allowed_values, checked and help into html input lines. The tal in the templates has become too complicated therefore the python code handles most of the condition...
78,020
def GetAccessTokenIfEnabled(account=None, scopes=None, allow_account_impersonation=True): """Returns the access token of the given account or the active account. If credentials have been disabled via properties, this will return None. Otherwise it return th...
78,021
def plot_drifters(ax, DATA, DRIFT_OBJS=None, color='red', cutoff=24, zorder=15): """Plot a drifter track from ODL Drifter observations. :arg time_ind: Time index (current drifter position, track will be visible up until this point, ex. 'YYYY-mmm-dd HH:MM:SS', format is flexible) :type time_ind: str...
78,022
def quaternion_from_angle_axis( angle: float, axis: np.ndarray, axis_normalized: bool = False ) -> List[float]: """Gets a quaternion from an angle and an axis. For more information, check `this Wikipedia page <https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles>`_. Paramet...
78,023
def _overlaps(existing, new): """Check whether existing diff op shares a key with the new diffop, and if they also have the same op type. """ if not existing: return False existing = existing[-1] # Only need to check last op! if existing.op == new.op: if existing.key == new.key:...
78,024
def A000121(n: int) -> int: """Give Number of representations of n as a sum of Fibonacci numbers. (1 is allowed twice as a part). a(0) = 1; for n >= 1, a(n) = A000119(n) + A000119(n-1). - Peter Munn, Jan 19 2018 """ if n == 0: return 1 return A000119[n] + A000119[n - 1]
78,025
def fetch_cordis_organisations(): """Fetch cordis organisations""" logging.info("Fetching cordis organisations") orgs = pd.read_csv( "https://cordis.europa.eu/data/cordis-h2020organizations.csv", delimiter=";" ) orgs.columns = [camel_to_snake(c) for c in orgs.columns] orgs = orgs.rename...
78,026
def set_proxy_facts(facts): """ Set global proxy facts Args: facts(dict): existing facts Returns: facts(dict): Updated facts with missing values """ if 'common' in facts: common = facts['common'] if 'http_proxy' in common or 'https_proxy' in common or...
78,027
def run_program(memory, inputs): """Execute the successive instructions of the program""" instr_ptr = 0 output = [] while True: (opcode, modes) = parse_opcode(memory[instr_ptr]) if opcode == 99: # Program end break elif opcode in [1, 2]: # 1 = Addition, 2 = Multi...
78,028
def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Ret...
78,029
def choose_file(): """Opens a file chooser and returns selected filepath""" root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() logger.debug("Choosen filepath: %s", file_path) return(file_path)
78,030
def main(): """ Test the run of MEMM and HMM :return: nothing """ full_flow_start = time.time() train_sents, dev_sents, _, _, _, _ = preprocess(['rinap/rinap1', 'rinap/rinap3', 'rinap/rinap4', 'rinap/rinap5']) print(len(train_sents)) print(len(dev_sents)) vocab = compute_vocab_coun...
78,031
def build_pixel_sample_scale_display(node: hou.RopNode) -> str: """Build a label to display the adjusted pixel samples. :param node: The node to build the display for. :return: The display scale. """ samples = node.evalParmTuple("vm_samples") sample_scale = node.evalParm("ip_sample_scale") ...
78,032
def websocket_trace_get(hass, connection, msg): """Get an script or automation trace.""" key = (msg["domain"], msg["item_id"]) run_id = msg["run_id"] trace = hass.data[DATA_TRACE][key][run_id] message = websocket_api.messages.result_message(msg["id"], trace) connection.send_message(json.dumps(...
78,033
def _parse_args() -> Dict[str, Any]: """ Parse the command line parameters into a Config object. Aborts on error. :return: the parsed arguments """ args = docopt.docopt(USAGE, version=VERSION, options_first=True) source_dir = args["SRCDIR"] if not os.path.exists(source_dir): error(...
78,034
def test_oauth_logout(app, mockservice_url): """Verify that logout via the Hub triggers logout for oauth services 1. clears session id cookie 2. revokes oauth tokens 3. cleared session id ensures cached auth miss 4. cache hit """ service = mockservice_url service_cookie_name = 'service-...
78,035
def get_metadata_from_attributes(Object, skip_attributes = None, custom_classes = None): """ Get metadata dict from attributes of an object. Parameters ---------- Object : object from which the attributes are. skip_attributes : list, optional If given, these attributes are...
78,036
def sync_source(source): """ This celery task will sync the specified source. :param source: :return: """ function = f"{__name__}.{sys._getframe().f_code.co_name}" task_id = None if celery.current_task: task_id = celery.current_task.request.id log_data = { "functio...
78,037
def parse_config(configfile): """Parse the given config file and return configuration settings as a dictionary for further use. :param str configfile: the path to the configuration file. :returns: parsed configuration values. :rtype: dict """ parser = configparser.ConfigParser() pa...
78,038
def add_list(): """ Add new list """ # User reached route via PODT (as by submitting a form via POST) if request.method == "POST": # Ensure title was submitted if not request.form.get("title"): return apology("must provide title", 400) # Add new list into the database ...
78,039
def add_publications(generator): """ Populates context with a list of BibTeX publications. Configuration ------------- generator.settings['MY_PUBLICATIONS_SRC']: local path to the BibTeX file to read. Output ------ generator.context['publications']: List of tuples (key,...
78,040
def test_scene_parameter_clone(): """Tests the cloning of SceneParameters.""" param = two4two.SceneParameters() param_clone = param.clone() assert param_clone != param assert param.id != param_clone.id assert param_clone.original_id == param.id with pytest.raises(ValueError): param_c...
78,041
def tensorise_token_sequence( vocab: Vocabulary, length: int, token_seq: Iterable[str], ) -> List[int]: """ Tensorise a single example. Args: vocab: Vocabulary to use for mapping tokens to integer IDs length: Length to truncate/pad sequences to. token_seq: Sequence of tokens to ...
78,042
def config_changed(): """ Handle configuration changes """ cfg = config() if cfg.changed('iperf3'): if cfg['iperf3']: # start iperf in server + daemon mode cmd = "iperf3 -s -D" else: cmd = "killall iperf3" try: charms.sshproxy._run(cmd)...
78,043
def test_channel_abandon(): """Test channel abandonment function.""" ch_abandon = mob.calculate_channel_abandonment(chmap, basevalue, time_window) assert np.all(ch_abandon == np.array([[0., 0.25, 0.5, 0.75, 1.]]))
78,044
def test_types(horse): """The get_horse_by_runner method should return a Horse object""" assert isinstance(horse, racing_data.Horse)
78,045
def power_flow_2_bus(v1, theta1, v2, theta2, g, b): """ Calculate the power flow from bus 1 to bus 2 across the line with admittance g+jb from the given voltages and angles. """ p = 0 q = 0 # Build admittance matrix values g12, b12 = -g, -b g11, b11 = g, b p += v1 * v2 * (g12 *...
78,046
def main(): """Process results """ data_path, calc_path, output_path = load_config()['paths']['data'], load_config()[ 'paths']['calc'], load_config()['paths']['output'] modes = ['road', 'rail'] types = ['min', 'max'] percentage = [10,90,100] single_edge = True multi_modal = [Fal...
78,047
def _GetExtensionInfoFromCRX(crx_path): """Parse an extension archive and return information. Note: The extension name returned by this function may not be valid (e.g. in the case of a localized extension name). It's use is just meant to be informational. Args: crx_path: path to crx archive to look...
78,048
def update_state(td_state, job_results): """ Updates the torsiondrive state with the compute jobs. The state is updated inplace Parameters ---------- td_state : dict The current torsiondrive state job_results : dict A dictionary of completed jobs and job ID's Returns --...
78,049
def extract_script_classes(module, target_kls): """ Returns list of classes (`Script`) detected from the module. """ return iter(kls for name, kls in inspect.getmembers(module) if is_class_and_subclass(kls, target_kls))
78,050
def to_obj(cls, obj_data=None, *fields, **field_map): """ prioritize obj_dict when there are conficts """ obj_dict = obj_data.__dict__ if hasattr(obj_data, '__dict__') else obj_data if not fields: fields = obj_dict.keys() obj = cls() update_obj(obj_dict, obj, *fields, **field_map) return...
78,051
def get_airports(path='airports.dat'): """Return a generator that yields Airport objects.""" with open(path, 'rt') as fd: reader = csv.reader(fd) for row in reader: name = row[1] country = row[3] code = row[4] # IATA code (eg, 'BCN' for Bar...
78,052
def test_helmholtz_far_field_segments( default_parameters, helpers, device_interface, precision ): """Test Helmholtz far field on segments.""" import bempp.api from bempp.api import function_space from bempp.api.operators.far_field.helmholtz import single_layer from bempp.api.operators.far_field...
78,053
def V_NN(mol): """ Compute Nuclear-Nuclear repulsion energy """ nn = 0 for i in range(mol.num_atoms): for j in range(i+1, mol.num_atoms): # Select atoms from molecule Ri = mol.coordinates[i] Rj = mol.coordinates[j] Zi = mol.charges[i] ...
78,054
def report(request): """ 通过csrf_exempt装饰器,跳过Django的csrf安全机制,让post的数据能被接收,但这又会带来新的安全问题。 可以在客户端,使用自定义的认证token,进行身份验证。这部分工作,请根据实际情况,自己进行。 :param request: :return: """ if request.method == "POST": asset_data = request.POST.get('asset_data') data = json.loads(asset_data) #...
78,055
def find_adjacent(kmeans_img, start_row, start_col, width, height): """Start start_row, start_col, search LR then up for matching values, repeat. Return end col, return list of matching row,col ie x,y. Simple version of the "fill" command in Photoshop. These matching row,col will be used later to curv...
78,056
def parse_profile(obj: Element, profile: Element) -> Dict[str,str]: """Parses model profile and related object element. Function is called once per object element and profile information is repeated per object. Arguments: obj {Element} -- Profile object profile {Element} -- Profile Re...
78,057
def _format_rangeyaxis( axis: plt.axis, pdata: dict, rg_converter: bool = False, **kwargs ) -> plt.axis: """Zoom to a specific range interval and format yaxis. Args: axis: plot axis pdata: plot structure data rg_converter: if True convert range from meter...
78,058
def now_str(pattern=TIME_FMT): """Return a formatted timestring for the current time.""" # return time.strftime(pattern, time.gmtime()) return datetime.utcnow().strftime(pattern)
78,059
def categorical_crossentropy(Y, Yhat, eps=1e-8): """ Computes the categorical cross-entropy for one hot encoded labels Y - (m,dim_y) array of labels m=examples Yhat - (m,dim_y) array of logits """ m = np.shape(Y)[0] Yhat = np.clip(Yhat, eps, 1 - eps) # for numerical stability if th...
78,060
def yaml_remove_split(docstr: str) -> Tuple[str, str]: """Extract parameter summary within :yaml: tags in docstring, and clean up the :yaml: tag for the full docstring. Return cleaned up docstring, and summary version.""" key = ":yaml:" summary = "" i_start = docstr.find(key) while i_start >...
78,061
def test_list_unsigned_int_length_4_nistxml_sv_iv_list_unsigned_int_length_5_4(mode, save_output, output_format): """ Type list/unsignedInt is restricted by facet length with value 10. """ assert_bindings( schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsignedInt-length...
78,062
def isdictreversediterator(object: Iterator[Any]) -> bool: """Returns True or False based on whether the given object is a reversed dict iterator. Parameters ---------- object: Any The object to see if it's a reversed dict iterator. Returns ------- bool Whether the given ob...
78,063
def create_regex(s: str, initials: bool = True) -> str: """ Given a string representation of either a channel or marker, generate a standard regex string to be used in a panel template Parameters ---------- s: str String value of channel or marker to generate regex term for initials...
78,064
def verify_password(email_or_token, password): """ verifies the credentials provided by HTTP Auth, is invoked before endpoint is accessed Args: email_or_token: email address of user or authentication token password: user password (only required in case of login via email) Returns: ...
78,065
def main(): """ PARSE AND VALIDATE INTEGRATION PARAMS """ token = demisto.params().get('token') authtoken = '&auth=' + str(token) # get the service API url base_url = urljoin(demisto.params()['url'], '/admin/api.php') verify_certificate = not demisto.params().get('insecure', False)...
78,066
def dataverse_config_get(node_addon, auth, **kwargs): """API that returns the serialized node settings.""" return { 'result': serialize_settings(node_addon, auth.user), }, http.OK
78,067
def vgg_19(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19'): """Oxford Net VGG 19-Layers version E Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in c...
78,068
def get_metadata_param(param_name): """Fetch value of metadata parameter. Args: param_name: str. Name of the parameter to be fetched. """ # Send a request to get param details. resp = requests.get( '%s/%s' % (METADATA_ATTRIBUTES_URL, param_name), headers=METADATA_HEADERS) ...
78,069
def trace_size_converter(value, params, key): """ Converts trace size from seconds to samples """ params = params[key] if value is None: return None if not value: return value if not params['frequency']: raise AttributeError('No frequency specified for trace-size argu...
78,070
def get_instances_for_module(app, module, additional_xpaths=None): """ This method is used by CloudCare when filtering cases. """ modules = list(app.get_modules()) helper = DetailsHelper(app, modules) details = DetailContributor(None, app, modules).get_section_elements() detail_mapping = {de...
78,071
def cmd_get_files(document_title, document_uuid, print_format): """List files""" session = get_session() run_get_files(document_title, document_uuid, print_format, session)
78,072
def test_sdeint_dependencies(sde_cls, method, adaptive, device): """This test uses diagonal noise. This checks if the solvers still work when some of the functions don't depend on the states/params and when some states/params don't require gradients. """ if method == 'milstein_grad_free': metho...
78,073
def base_10_to_alphabet(number): """Convert a decimal number to its base alphabet representation""" return "".join(chr(A_UPPERCASE + part) for part in _decompose(number))[::-1]
78,074
def LINE(back=0): """ Prints the line number where this method is called from. :param back: the context of the call, typically you can omit """ return sys._getframe(back + 1).f_lineno
78,075
def plausibly_scopes(m: mrs.MRS) -> bool: """ Quickly test if MRS *m* can plausibly resolve a scopal reading. This tests a number of things: - Is the MRS's top qeq to a label - Do any EPs scope over themselves - Do multiple EPs use the handle constraint - Is the lo handle o...
78,076
def test_process_environment(monkeypatch, valid_settings, invalid_settings): """Test whether environment variables are set in settings.*.""" from tokendito import helpers, settings import os # ENV standard is uppercase valid_keys = {key.upper(): val for (key, val) in valid_settings.items()} inv...
78,077
def BuildAndRepack(context, signer=None, timestamp=None): """Run build and repack to create installers.""" # ISO 8601 date timestamp = timestamp or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) # Output directory like: 2015-02-13T21:48:47-0800/linux_amd64_deb/ spec = "_".join((args.platform, args.arch, ...
78,078
def decode_chrome_leveldb_bytes(value): """ decode the encoded localstorage values from the leveldb file """ if value[0] == 0: return value[1:].decode('utf-16le') elif value[0] == 1: return value[1:].decode('utf-8') else: msg = "Unable to process Chrome LevelDB bytes in u...
78,079
def generate_password() : """ Generate random characters to form the password. """ charSets = [ 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789', '^!\$%&/()=?{[]}+~#-_.:,;<>|\\', ] length = user_input() pwd = [] charset = cho...
78,080
def generate_output_paths( output_dir: str, file_name: str, subset_name: str, extension: str ) -> list: """ Generate output paths for results files based on the given output directory, file name, subset name, and extension. :param output_dir: Output directory to which results should be output :para...
78,081
def attack(attack_rsa_obj, publickey, cipher=[]): """use elliptic curve method, may return a prime or may never return only works if the sageworks() function returned True """ logger.warning( "[*] ECM Method can run forever and may never succeed, timeout set to %ssec. Hit Ctrl-C to bail out."...
78,082
def tau_screened_coulomb(energy: np.ndarray, mass_c: np.ndarray, screen_len: np.ndarray, n_imp: np.ndarray, dielectric: float) -> np.ndarray: """ Electron-ion scattering rate — Brook-Herring model Note that for highly doped semiconductors, screen length plays a significant role, ...
78,083
def test_multiple_optimizers_manual_return_and_log(tmpdir): """ Tests that only training_step can be used """ class TestModel(BoringModel): def __init__(self): super().__init__() self.automatic_optimization = False def training_step(self, batch, batch_idx): ...
78,084
def primary_fuel_ferc1(fuel_df, fuel_thresh=0.5): """ Determine the primary fuel for plants listed in the PUDL fuel_ferc1 table. Given a selection of records from the PUDL fuel_ferc1 table, determine the primary fuel type for each plant (as identified by a unique combination of report_year, respond...
78,085
def simulate_SPRT_fixedtime(sigma, stop_time, true_dist=1): """ Simulate a Sequential Probability Ratio Test with fixed time stopping rule. Two observation models are 1D Gaussian distributions N(1,sigma^2) and N(-1,sigma^2). Args: sigma (float): standard deviation stop_time (int): numb...
78,086
def get_url_descriptor(url): """ Returns an url descriptor or None on failure """ try: resp = requests.get(url) except requests.exceptions.ConnectionError: logging.error("Error connecting to {}".format(url)) return None if resp.ok: return resp return None
78,087
def butter_lowpass(cutoff, freq, order=5): """Butterworth lowpass filter""" nyq = 0.5 * freq normal_cutoff = cutoff / nyq numerator, denominator = scipy.signal.butter(order, normal_cutoff, btype='low', analog=False) return numerator, denominator
78,088
def test_matcher_should_raise_error_when_no_step_impl_found(mocker): """The matcher should raise an error when no Step Implementation is found""" # given registry_mock = mocker.MagicMock() registry_mock.step_implementations.return_value = [] step = Step(1, "Given", "Given", "pattern", None, None, No...
78,089
def year_isnt_int(YEARS): """A funciton to test if years are integers""" return any(type(x) != int for x in YEARS)
78,090
def similarity_matrix(DAG, similarity="intersection", neighbours="successors"): """ Function to produce a similarity matrix based on neighbourhoods of nodes in DAG. Input ----- DAG - networkx directed acyclic graph similarity - type of similarity of sets. Currently only implemented for the size...
78,091
def A12_2_Classification(CompType, Build, D, b, tw, Fy, E, sigma1 = 0.5, sigma2 = 0.5, alpha = 1.0): """ A.12.2 Classification definitions """ # print("") print ("A.12.2.3 Classification definitions") # # A.12.2.3.1 Tubular member classification if CompType =...
78,092
def open_mail(email: str): """Open up draft email tab in your default browser Args: email (str): email of the person Returns: bool, str: method status, empty string """ url_mail_people = f"mailto:{email}" command_success = True try: open_browser(url_mail_people) ...
78,093
def offset_to_timedelta(offset): """ Convert a pandas-compatible offset (e.g. '3H') to a Timedelta object. """ return pd.to_timedelta(pandas.tseries.frequencies.to_offset(offset))
78,094
def get_pictures(pictures_dir): """Return a list of picture files found in pictures_dir""" pictures = [] for directory, subdirs, files in os.walk(pictures_dir): for fname in files: if fname.lower().endswith(('.jpg', '.png')): pictures.append(os.path.join(directory, fname...
78,095
def fetch_process_warc_records(rows): """Retrieves document from S3 Data Lake. The argument is a row of warc_filename, warc_record_offset, warc_record_length. The html to be retrieved are pulled from the file using the offset and length. Args: rows: list[string, int, int] Returns: ...
78,096
def isJsonDict(s): """ Take a string and determine if valid JSON. """ try: data = json.loads(s) return type(data) == dict except ValueError: return False
78,097
def solve_safer_qp(P, q, G, h, sw, reg=1e-8, solver='mosek', initvals=None, sym_proj=False): """ Solve the Quadratic Program defined as: .. math:: \\begin{split}\\begin{array}{ll} \\mbox{minimize} & \\frac{1}{2} x^T P x + q^T x + \\fra...
78,098
def get_config_constant_file(): """Contiene la obtencion del objeto config para setear datos de constantes en archivo configurador :rtype: object """ # TEST _constants_file = "constants/constants.yml" # PROD # _constants_file = "constants/constants.yml" cfg = Const...
78,099