content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def demean_dataframe_two_cat(df_copy, consist_var, category_col, is_unbalance):
"""
reference: Baltagi http://library.wbi.ac.id/repository/27.pdf page 176, equation (9.30)
:param df_copy: Dataframe
:param consist_var: List of columns need centering on fixed effects
:param category_col: List of fixed... | a6a3f0bd56be214660eca857f0fb8630879bb2a8 | 22,731 |
from datetime import datetime
import time
def get_time_string(time_obj=None):
"""The canonical time string format (in UTC).
:param time_obj: an optional datetime.datetime or timestruct (defaults to
gm_time)
Note: Changing this function will change all times that this project uses
... | 73a623474e70850dc4194e2657b7e15aaa53996f | 22,732 |
def apply_activation_checkpointing_wrapper(
model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=lambda _: True
):
"""
Applies :func:`checkpoint_wrapper` to modules within `model` based on a user-defined
configuration. For each module within `model`, the `check_fn` is used to decide
whether `mo... | ea4f7efef1f1c1c49a7cd078cae95be754f68c93 | 22,733 |
def train_validation_split(x, y):
"""
Prepare validation data with proper size
Args:
x: (pandas.DataFrame) Feature set / Affecting features
y: (pandas.Dataframe) Target set / dependent feature
Returns:
x_train: (pandas.DataFrame) Feature set / Affecting features for training
... | eac70c13b2ebd592681dfdc5cc181b558a93b233 | 22,734 |
from typing import Union
from typing import Tuple
from typing import List
def topk_accuracy(
rankings: np.ndarray, labels: np.ndarray, ks: Union[Tuple[int, ...], int] = (1, 5)
) -> List[float]:
"""Computes Top-K accuracies for different values of k
Args:
rankings: 2D rankings array: shape = (inst... | 36d3ac84b69b7d0f8764ad1213f56f82da717482 | 22,735 |
def has_substr(line, chars):
""" checks to see if the line has one of the substrings given """
for char in chars:
if char in line:
return True
return False | cf438600894ca43c177af1661a95447daa8b6b0d | 22,736 |
def multifiltertestmethod(testmethod, strfilters):
"""returns a version of the testmethod that operates on filtered strings using strfilter"""
def filteredmethod(str1, str2):
return testmethod(multifilter(str1, strfilters), multifilter(str2, strfilters))
filteredmethod.__doc__ = testmethod.__doc__
... | eec5e580bcc2987f8abfc23dd118897ed5d2b4c4 | 22,737 |
def getbasins(basin,Nx,Ny,Nz,S1,S2,S3):
"""
Args:
basin (numpy array): including the
Returns:
N/A
Only Extend CHGCAR while mode is 'all'
"""
temp = np.zeros(Nx*Ny*Nz*S1*S2*S3)
basins = np.resize(temp,(Nz*S3,Ny*S2,Nx*S1))
block = np.resize(temp,(Nz*S3,Ny*S2,Nx*S1))
flag = 0
b = 1
teemp = []
for kss in... | 97c489a7453aced3624f6898896924647f387d55 | 22,738 |
def makeframefromhumanstring(s):
"""Create a frame from a human readable string
Strings have the form:
<request-id> <stream-id> <stream-flags> <type> <flags> <payload>
This can be used by user-facing applications and tests for creating
frames easily without having to type out a bunch of const... | b588e61fb8b67b4160ac673eb3e70f373c7027b4 | 22,739 |
def display_full_name_with_correct_capitalization(full_name):
"""
See documentation here: https://github.com/derek73/python-nameparser
:param full_name:
:return:
"""
full_name.strip()
full_name_parsed = HumanName(full_name)
full_name_parsed.capitalize()
full_name_capitalized = str(fu... | 05133fc04631a39a19f2e27355456418ab7c78a7 | 22,740 |
from typing import Optional
from typing import Iterable
from typing import Dict
from typing import Any
import collections
def load_experiment_artifacts(
src_dir: str, file_name: str, selected_idxs: Optional[Iterable[int]] = None
) -> Dict[int, Any]:
"""
Load all the files in dirs under `src_dir` that matc... | 67d8b9aba64f79b0361e7ed175ae597b22367f8a | 22,741 |
from datetime import datetime
from typing import Tuple
def get_market_metrics(market_portfolio: pd.DataFrame, t_costs: float, index_id: str, index_name: str,
test_data_start_date: datetime.date, test_data_end_date: datetime.date, market_logs=False) -> \
Tuple[pd.Series, pd.Series, pd.Se... | f5c77114c79ef901683ffdd4495a8a1022e42dc9 | 22,742 |
def get_puf_columns(seed=True, categorical=True, calculated=True):
"""Get a list of columns.
Args:
seed: Whether to include standard seed columns: ['MARS', 'XTOT', 'S006']
categorical: Whether to include categorical columns: ['F6251', 'MIDR', 'FDED', 'DSI']
calculated: Whether to includ... | af7d6799b7f17b2b05b62a7ed88d0695784cde59 | 22,743 |
def list_all_vms(osvars):
"""Returns a listing of all VM objects as reported by Nova"""
novac = novaclient.Client('2',
osvars['OS_USERNAME'],
osvars['OS_PASSWORD'],
osvars['OS_TENANT_NAME'],
... | b03bc9c5e458d62403b86346bdb4f9a2c3081909 | 22,744 |
def exec_cmd(cmd, path):
""" Execute the specified command and return the result. """
out = ''
err = ''
sys.stdout.write("-------- Running \"%s\" in \"%s\"...\n" % (cmd, path))
parts = cmd.split()
try:
process = subprocess.Popen(parts, cwd=path,
stdout=subprocess.PIPE,
... | ea75de47eebe526188533539a4d33e07d5a5bed3 | 22,745 |
def contains_numbers(iterable):
""" Check if first iterable item is a number. """
return isinstance(iterable[0], Number) | 0c6dc3031087e14ea50cb7d228da50b19a55a013 | 22,746 |
import tempfile
from pathlib import Path
import requests
def get_image(img: PathStr) -> PILImage:
"""Get picture from either a path or URL"""
if str(img).startswith("http"):
with tempfile.TemporaryDirectory() as tmpdirname:
dest = Path(tmpdirname) / str(img).split("?")[0].rpartition("/")[-... | 374e2ff8f97c4d63ceb3d621ced25451d10b6793 | 22,747 |
def FAIMSNETNN_model(train_df, train_y, val_df, val_y, model_args, cv=3):
"""FIT neuralnetwork model."""
input_dim = train_df.shape[1]
if model_args["grid"] == "tiny":
param_grid = {"n1": [100], "d1": [0.3, 0.1], "lr": [0.001, 0.01], "epochs": [50],
"batch_size": [32, 128], "in... | 6f6520a3f9a746e6e1241f638358f00ce4f20ede | 22,748 |
def assign_exam_blocks(data, departments, splitted_departments, number_exam_days):
"""
Assign departments to exam blocks and optimize this schedule to reduce conflicts.
data (pandas.DataFrame): Course enrollments data
departments (dict): Departments (str key) and courses in departments (list value)
... | ae272ea00a277960497d96b2593371bc35a9c3cb | 22,749 |
def aq_name(path_to_shp_file):
"""
Computes the name of a given aquifer given it's shape file
:param path_to_shp_file: path to the .shp file for the given aquifer
:return: a string (name of the aquifer)
"""
str_ags = path_to_shp_file.split('/')
str_aq = ""
if len(str_ags) >= 2:
... | 1cb6f9881383b4627ea4f78bf2f6fd9cdf97dbc4 | 22,751 |
def gini(arr, mode='all'):
"""Calculate the Gini coefficient(s) of a matrix or vector.
Parameters
----------
arr : array-like
Array or matrix on which to compute the Gini coefficient(s).
mode : string, optional
One of ['row-wise', 'col-wise', 'all']. Default is 'all'.
Returns
... | 9fb3116506db949d273000510724bcce0ed165e2 | 22,752 |
import requests
def getIndex():
"""
Retrieves index value.
"""
headers = {
'accept': 'application/json',
}
indexData = requests.get(
APIUrls.lnapi+APIUrls.indexUrl,
headers=headers,
)
if indexData.status_code == 200:
return indexData.json()
else:
... | ba35e1573a62e76d1f413036761b8a9054a3a878 | 22,753 |
def input_as_string(filename:str) -> str:
"""returns the content of the input file as a string"""
with open(filename, encoding="utf-8") as file:
return file.read().rstrip("\n") | 0343de48580a71a62895aa093af1213c3f0c0b84 | 22,755 |
def channame_to_python_format_string(node, succgen=None):
"""See channame_str_to_python_format_string
@succgen is optional, if given will check that identifiers can be found.
"""
if not node: #empty AST
return (True, "")
if node.type == 'Identifier': # and len(node.children) >= 1:
... | f7e71bd49624657e98e6f2c172e6f02d8bfc7307 | 22,756 |
import numpy
import pandas
def is_bad(x):
""" for numeric vector x, return logical vector of positions that are null, NaN, infinite"""
if can_convert_v_to_numeric(x):
x = safe_to_numeric_array(x)
return numpy.logical_or(
pandas.isnull(x), numpy.logical_or(numpy.isnan(x), numpy.isin... | b4cf9de18cd8e52ff90a801f1eccf6a4ee2500db | 22,757 |
def T0_T0star(M, gamma):
"""Total temperature ratio for flow with heat addition (eq. 3.89)
:param <float> M: Initial Mach #
:param <float> gamma: Specific heat ratio
:return <float> Total temperature ratio T0/T0star
"""
t1 = (gamma + 1) * M ** 2
t2 = (1.0 + gamma * M ** 2) ** 2
t3 = 2... | 2e5c8ec2ab24dd0d4dfa2feddd0053f277665b33 | 22,760 |
from typing import Optional
def remount_as(
ip: Optional[str] = None, writeable: bool = False, folder: str = "/system"
) -> bool:
"""
Mount/Remount file-system. Requires root
:param folder: folder to mount
:param writeable: mount as writeable or readable-only
:param ip: ... | 8f343f96d066543359bdfcea3c42f41f40dcaf4d | 22,761 |
def flip_channels(img):
"""Flips the order of channels in an image; eg, BGR <-> RGB.
This function assumes the image is a numpy.array (what's returned by cv2
function calls) and uses the numpy re-ordering methods. The number of
channels does not matter.
If the image array is strictly 2D, no re-orde... | 7aab0222f6fd66c06f8464cd042f30c6eac01c72 | 22,762 |
def parse_main(index):
"""Parse a main function containing block items.
Ex: int main() { return 4; }
"""
err = "expected main function starting"
index = match_token(index, token_kinds.int_kw, ParserError.AT, err)
index = match_token(index, token_kinds.main, ParserError.AT, err)
index = mat... | ab932cf3d99340b97ec7d32fa668c4e00e16a3d1 | 22,764 |
def elist2tensor(elist, idtype):
"""Function to convert an edge list to edge tensors.
Parameters
----------
elist : iterable of int pairs
List of (src, dst) node ID pairs.
idtype : int32, int64, optional
Integer ID type. Must be int32 or int64.
Returns
-------
(Tensor, ... | a38c26a13b2fc7f111e3ec2c036e592b5b4c3c70 | 22,765 |
from datetime import datetime
def _term_to_xapian_value(term, field_type):
"""
Converts a term to a serialized
Xapian value based on the field_type.
"""
assert field_type in FIELD_TYPES
def strf(dt):
"""
Equivalent to datetime.datetime.strptime(dt, DATETIME_FORMAT)
but... | 8fe2926a7093ff9a7b22cc222c4a3c5c8f6bc155 | 22,766 |
def pop_stl1(osurls, radiourls, splitos):
"""
Replace STL100-1 links in 10.3.3+.
:param osurls: List of OS platforms.
:type osurls: list(str)
:param radiourls: List of radio platforms.
:type radiourls: list(str)
:param splitos: OS version, split and cast to int: [10, 3, 3, 2205]
:type... | d88576028bbfbf61ab6fec517e7a66d731b4ebf3 | 22,767 |
def empty_search():
"""
:return: json response of empty list, meaning empty search result
"""
return jsonify(results=[]) | 59ac0a6d3b9a3d17f7a80e633ea4bb5b2d07ca33 | 22,768 |
def clip_raster_mean(raster_path, feature, var_nam):
""" Opens a raster file from raster_path and applies a mask based on
a polygon (feature). It then extracts the percentage of every class
with respects to the total number of pixels contained in the mask.
:param raster_path: raster path (ras... | 82244272c2da713f679d0f56f5736810fcf8649c | 22,769 |
import json
def load_data(in_file):
"""load json file from seqcluster cluster"""
with open(in_file) as in_handle:
return json.load(in_handle) | 93c1766cb1e36410a8c67e2291b93aa7280abd63 | 22,770 |
import re
def expand_at_linestart(P, tablen):
"""只扩展行开头的制表符号"""
def exp(m):
return m.group().expandtabs(tablen)
return ''.join([ re.sub(r'^\s+', exp, s) for s in P.splitlines(True) ]) | 2b8310e89efdba54b121667e11454281e2c214e3 | 22,772 |
def configs():
"""Create a mock Configuration object with sentinel values
Eg.
Configuration(
base_jar=sentinel.base_jar,
config_file=sentinel.config_file,
...
)
"""
return Configuration(**dict(
(k, getattr(sentinel, k))
for k in DEFAU... | c8aa44e1c9695a8fe0188d739c87be07ab06bdb0 | 22,773 |
def svn_fs_revision_root_revision(root):
"""svn_fs_revision_root_revision(svn_fs_root_t * root) -> svn_revnum_t"""
return _fs.svn_fs_revision_root_revision(root) | ce153da9527fb8b1235f5591dbd68e2f1c1ecab2 | 22,774 |
from typing import Any
def is_floatscalar(x: Any) -> bool:
"""Check whether `x` is a float scalar.
Parameters:
----------
x: A python object to check.
Returns:
----------
`True` iff `x` is a float scalar (built-in or Numpy float).
"""
return isinstance(x, (
float,
n... | 2a93524290eaa4b4e1f0b0cc7a8a0dcb2a46f9d3 | 22,776 |
def http_header_control_cache(request):
""" Tipo de control de cache
url: direccion de la pagina web"""
print "--------------- Obteniendo cache control -------------------"
try:
cabecera = request.headers
cache_control = cabecera.get("cache-control")
except Exception:
cache_c... | 976adffa3c3601c6f0fd49617e15e25aa9cb2c9b | 22,777 |
def summation(limit):
"""
Returns the summation of all natural numbers from 0 to limit
Uses short form summation formula natural summation
:param limit: {int}
:return: {int}
"""
return (limit * (limit + 1)) // 2 if limit >= 0 else 0 | 1ff16c7c4131458e50c9c9bd5c0f20895d8ab121 | 22,778 |
def load_and_initialize_hub_module(module_path, signature='default'):
"""Loads graph of a TF-Hub module and initializes it into a session.
Args:
module_path: string Path to TF-Hub module.
signature: string Signature to use when creating the apply graph.
Return:
graph: tf.Graph Graph of the module.
... | b04b5f77c7e0207d314ebb5910ec1c5e61f4755c | 22,779 |
def j_index(true_labels, predicts):
""" j_index
Computes the Jaccard Index of the given set, which is also called the
'intersection over union' in multi-label settings. It's defined as the
intersection between the true label's set and the prediction's set,
divided by the sum, or union, of th... | 33bef64196acf441c299a4a90da64b2bb866e364 | 22,780 |
import torch
def odefun(x, t, net, alph=[1.0,1.0,1.0]):
"""
neural ODE combining the characteristics and log-determinant (see Eq. (2)), the transport costs (see Eq. (5)), and
the HJB regularizer (see Eq. (7)).
d_t [x ; l ; v ; r] = odefun( [x ; l ; v ; r] , t )
x - particle position
l - log... | 1523b28f1568bcd668a3f8cc8ce39dfb7d8096fe | 22,781 |
def create_transform(num_flow_steps,
param_dim,
context_dim,
base_transform_kwargs):
"""Build a sequence of NSF transforms, which maps parameters x into the
base distribution u (noise). Transforms are conditioned on strain data y.
Note that the... | d4d556163af777f50aed2f4d86b1ae9c1de81047 | 22,782 |
def for_in_pyiter(it):
"""
>>> for_in_pyiter(Iterable(5))
[0, 1, 2, 3, 4]
"""
l = []
for item in it:
l.append(item)
return l | 7d5c44ce771ea9847d57749235a31f200a01b67f | 22,784 |
def train_test_split_with_none(X, y=None, sample_weight=None, random_state=0):
"""
Splits into train and test data even if they are None.
@param X X
@param y y
@param sample_weight sample weight
@param random_state random state
@return ... | 8a789d6001a56096eba556301e130c57edd8cf87 | 22,785 |
def measure_time(func, repeat=1000):
"""
Repeatedly executes a function
and records lowest time.
"""
def wrapper(*args, **kwargs):
min_time = 1000
for _ in range(repeat):
start = timer()
result = func(*args, **kwargs)
curr_time = timer() - start
... | 0515eca9cfa96a7395b3461bd3302a9780d05366 | 22,786 |
def initialise_players(frame_data, params):
"""
initialise_players(team,teamname,params)
create a list of player objects that holds their positions and velocities from the tracking data dataframe
Parameters
-----------
team: row (i.e. instant) of either the home or away team tracking Datafram... | 4126ba5cf1cdcd61017692260026dbdd03523874 | 22,787 |
import gc
def read_edgelist(f, directed=True, sep=r"\s+", header=None, keep_default_na=False, **readcsvkwargs):
"""
Creates a csrgraph from an edgelist.
The edgelist should be in the form
[source destination]
or
[source destination edge_weight]
The first column needs to be... | dd4110700857c3deb86c53a176ab93b0366cd900 | 22,788 |
def is_comment(txt_row):
""" Tries to determine if the current line of text is a comment line.
Args:
txt_row (string): text line to check.
Returns:
True when the text line is considered a comment line, False if not.
"""
if (len(txt_row) < 1):
return True
if ((txt_row... | db54b90053244b17ec209ed1edb1905b62151165 | 22,789 |
import json
def updateBillingPlanPaymentDefinition(pk, paypal_payment_definition):
"""Update an existing payment definition of a billing plan
:param pk: the primary key of the payment definition (associated with a billing plan)
:type pk: integer
:param paypal_payment_definition: Paypal billing plan ... | b4bf58088c8e501ccf380dda98587467a8683ff9 | 22,790 |
from typing import List
def format_float_list(array: List[float], precision: int = 4) -> List[str]:
"""
Formats a list of float values to a specific precision.
:param array: A list of float values to format.
:param precision: The number of decimal places to use.
:return: A list of strings contain... | b790379327acc5ebdf54f99621a06edd6228941d | 22,791 |
import html
def counts_card() -> html.Div:
"""Return the div that contains the overall count of patients/studies/images."""
return html.Div(
className="row",
children=[
html.Div(
className="four columns",
children=[
html.Div(
... | f80ba28b7ef1b2407d6a8b3e8eaccf26c734566a | 22,792 |
import logging
def validate_est(est: EstData, include_elster_responses: bool = False):
"""
Data for a Est is validated using ERiC. If the validation is successful then this should return
a 200 HTTP response with {'success': bool, 'est': est}. Otherwise this should return a 400 response if the
validati... | 2565572efd9b1ee52fabb98473b7934e13b691ca | 22,793 |
from typing import Callable
from typing import List
async def list_solver_releases(
solver_key: SolverKeyId,
user_id: int = Depends(get_current_user_id),
catalog_client: CatalogApi = Depends(get_api_client(CatalogApi)),
url_for: Callable = Depends(get_reverse_url_mapper),
):
""" Lists all releases... | 0461e6ba72c01e789af8571d75b7da21d2f17801 | 22,794 |
import copy
def offset_perimeter(geometry, offset, side='left', plot_offset=False):
"""Offsets the perimeter of a geometry of a :class:`~sectionproperties.pre.sections.Geometry`
object by a certain distance. Note that the perimeter facet list must be entered in a
consecutive order.
:param geometry: C... | e8b2851ea5ffd17faeb62bd3ca094e4cb6dd162a | 22,796 |
def WalterComposition(F,P):
"""
Calculates the melt composition generated as a function of F and P, using the
parameterisation of Duncan et al. (2017).
Parameters
-----
F: float
Melt fraction
P: float
Pressure in GPa
Returns
-----
MeltComposition: series
... | 54b2b5d6e6f4500da1c17e54bcb9b8804a65e9b0 | 22,797 |
from pathlib import Path
def fetch_study_metadata(
data_dir: Path, version: int = 7, verbose: int = 1
) -> pd.DataFrame:
"""
Download if needed the `metadata.tsv.gz` file from Neurosynth and load
it into a pandas DataFrame.
The metadata table contains the metadata for each study. Each study (ID)
... | e04a0dd631f8b8a53708118134b8d5039e83bcdf | 22,798 |
from typing import Union
def proveFormula(formula: str) -> Union[int, str]:
"""
Implements proveFormula according to grader.py
>>> proveFormula('p')
1
>>> proveFormula('(NOT (NOT (NOT (NOT not)) )\t)')
1
>>> proveFormula('(NOT (NOT (NOT (NOT not)) )')
'E'
>>> proveFormula('(IF p ... | 4c078bdfa586b9807b6265db43ee7187e6aef349 | 22,799 |
def sendSingleCommand(server, user, password, command):
"""Wrapper function to open a connection and execute a single command.
Args:
server (str): The IP address of the server to connect to.
username (str): The username to be used in the connection.
password (str): The password asso... | 78a339b2bcb320ad81e79b8656867b894be22ecd | 22,801 |
def test_piecewise_fermidirac(precision):
"""Creates a Chebyshev approximation of the Fermi-Dirac distribution within
the interval (-3, 3), and tests its accuracy for scalars, matrices, and
distributed matrices.
"""
mu = 0.0
beta = 10.0
def f(x):
return 1 / (np.exp(beta * (x - mu)) + 1)
is_vectori... | 587b7acfc5a114677f1bf5ab5a72a9f2019c6063 | 22,802 |
def load_img(flist):
""" Loads images in a list of arrays
Args : list of files
Returns list of all the ndimage arrays """
rgb_imgs = []
for i in flist:
rgb_imgs.append(cv2.imread(i, -1)) # flag <0 to return img as is
print "\t> Batch import of N frames\t", len(rgb_imgs)
size_var = ... | 74d3c312e936f434b3738eae79b8f499755cdd0a | 22,803 |
import astropy.io.fits as pyfits
def makesimpleheader(headerin,naxis=2,radesys=None,equinox=None,pywcsdirect=False):
"""
Function to make a new 'simple header' from the WCS information in the input header.
Parameters
----------
headerin : astropy.io.fits.header
Header object
nax... | ffdc8f755227451e3df2329e8ec804b7444a553d | 22,804 |
def _callcatch(ui, func):
"""like scmutil.callcatch but handles more high-level exceptions about
config parsing and commands. besides, use handlecommandexception to handle
uncaught exceptions.
"""
detailed_exit_code = -1
try:
return scmutil.callcatch(ui, func)
except error.AmbiguousC... | 495531b930187f1d3aff329453235f9683bc25bc | 22,805 |
def _determ_estim_update(new_bit, counts):
"""Beliefs only a sequence of all ones or zeros.
"""
new_counts = counts[:]
new_counts[new_bit] += 1
if new_counts[0] > 0 and new_counts[1] > 0:
return LOG_ZERO
log_p_new = _determ_log_p(new_counts)
log_p_old = _determ_log_p(counts)
ret... | ea6f172161b215d5d474241da18fdd222692f245 | 22,806 |
def get_projects(config):
"""Find all XNAT projects and the list of scan sites uploaded to each one.
Args:
config (:obj:`datman.config.config`): The config for a study
Returns:
dict: A map of XNAT project names to the URL(s) of the server holding
that project.
"""
proje... | 09824b67e73f8190d777ec782454940f27b70e33 | 22,807 |
import json
def load_jsonrpc_method(name):
"""Load a method based on the file naming conventions for the JSON-RPC.
"""
base_path = (repo_root() / "doc" / "schemas").resolve()
req_file = base_path / f"{name.lower()}.request.json"
resp_file = base_path / f"{name.lower()}.schema.json"
request = C... | 173fdaad563989042f6ff3c5622c4b56be1a5fa5 | 22,808 |
def client_decrypt_hello_reply(ciphertext, iv1, key1):
"""
Decrypt the server's reply using the IV and key we sent to it.
Returns iv2, key2, salt2 (8 bytes), and the original salt1.
The pair iv2/key2 are to be used in future communications.
Salt1 is returned to help confirm the integrity of the oper... | 70f3361acbeaa26376d4a54605a526ecac5ea61e | 22,810 |
import pandas
def load_labeled_data(filename):
""" Loads data from a csv, where the last column is the label of the data in that row
:param filename: name of the file to load
:return: data frames and labels in separate arrays
"""
dataframe = pandas.read_csv(filename, header=None)
dataset = dat... | 727691d376b744ccfdffbd62dd9f386e7bd7c4dd | 22,811 |
def _get_data_tuple(sptoks, asp_termIn, label):
"""
Method obtained from Trusca et al. (2020), no original docstring provided.
:param sptoks:
:param asp_termIn:
:param label:
:return:
"""
# Find the ids of aspect term.
aspect_is = []
asp_term = ' '.join(sp for sp in asp_termIn).... | 2dae699ba4da27f6a36b7aac21cc8bc759a71d67 | 22,814 |
from pathlib import Path
def setup_environment(new_region: Path) -> bool:
"""Try to create new_region folder"""
if new_region.exists():
print(f"{new_region.resolve()} exists, this may cause problems")
proceed = input("Do you want to proceed regardless? [y/N] ")
sep()
return pro... | 175e21b10aca860d9886841be743d8f2a240dfc6 | 22,815 |
def headers():
"""Default headers for making requests."""
return {
'content-type': 'application/json',
'accept': 'application/json',
} | 53e42df6cae8ba9cbdc5f0e0a86a0154d3ba360e | 22,817 |
def merge_two_lists(l1: ListNode, l2: ListNode) -> ListNode:
"""Returns a single sorted, in-place merged linked list of two sorted input linked lists
The linked list is made by splicing together the nodes of l1 and l2
Args:
l1:
l2:
Examples:
>>> l1 = linked_list.convert_list_t... | 49033ef17e0940a201c70555cc0e49b8e745fb3b | 22,818 |
import csv
def map_SOPR_to_firm():
"""
Map SOPR identifiers to a lobbying CUID.
Return a dictionnary.
"""
firms = {}
with open(DATASET_PATH_TO['LOBBYING_FIRMS'], 'rb') as f:
reader = csv.reader(f, delimiter='%', quoting=csv.QUOTE_NONE)
for record in reader:
SOPR_reports =... | e0f00d7f720512eef3e32685bb8ba5ed4ed0203c | 22,819 |
from typing import Set
def specialbefores_given_external_square(
befores: Set[Before],
directly_playable_squares: Set[Square],
external_directly_playable_square: Square) -> Set[Specialbefore]:
"""
Args:
befores (Set[Before]): a set of Befores used to create Specialbefores.
... | bb0405cc783ee94130893d0dca0f0b06e43d71c5 | 22,820 |
import pytest
def check_if_all_tests_pass(option='-x'):
"""Runs all of the tests and only returns True if all tests pass.
The -x option is the default, and -x will tell pytest to exit on the first encountered failure.
The -s option prints out stdout from the tests (normally hidden.)"""
options =... | 81e41cb985bcf346d9351d327d0ca0941ed7320e | 22,822 |
import http
def init(api, _cors, impl):
"""Configures REST handlers for allocation resource."""
namespace = webutils.namespace(
api, __name__, 'Local nodeinfo redirect API.'
)
@namespace.route('/<hostname>/<path:path>')
class _NodeRedirect(restplus.Resource):
"""Redirects to loca... | 77430c891ceac87bec3d8b1cfa46557fbc1fd9f5 | 22,823 |
def split_matrix_2(input1):
"""
Split matrix.
Args:
inputs:tvm.Tensor of type float32.
Returns:
akg.tvm.Tensor of type float32 with 3d shape.
"""
dim = input1.shape[0]
split_num = dim // split_dim
result_3 = allocate((split_num, split_dim, split_dim), input1.dtype, 'loc... | 8ee5b4069c28166ef6181cb8c6ef1e21232239a4 | 22,824 |
import glob
def load_all(path, jobmanager=None):
"""Load all jobs from *path*.
This function works as a multiple execution of |load_job|. It searches for ``.dill`` files inside the directory given by *path*, yet not directly in it, but one level deeper. In other words, all files matching ``path/*/*.dill`` ar... | f76e2baeaa0b35283eed4748d68403827bdaff97 | 22,825 |
import numpy
def relative_error(estimate, exact):
"""
Compute the relative error of an estimate, in percent.
"""
tol = 1e-15
if numpy.abs(exact) < tol:
if numpy.abs(estimate - exact) < tol:
relative_error = 0.0
else:
relative_error = numpy.inf
else:
... | 4170fd4a7c448eb312ea9f42d436d12acd828695 | 22,826 |
def list_users(cursor):
"""
Returns the current roles
"""
cursor.execute(
"""
SELECT
r.rolname AS name,
r.rolcanlogin AS login,
ARRAY(
SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
W... | b51efbae5da08089987e3bc2753e1da3c13ee365 | 22,828 |
def get_job_exe_output_vol_name(job_exe):
"""Returns the container output volume name for the given job execution
:param job_exe: The job execution model (must not be queued) with related job and job_type fields
:type job_exe: :class:`job.models.JobExecution`
:returns: The container output volume name
... | c625b596f9ee819eb0c7afc9aed1328ecef0e206 | 22,830 |
def bytes2human(n, format='%(value).1f %(symbol)s', symbols='customary'):
"""
Convert n bytes into a human readable string based on format.
symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs
>>> bytes2human(0)
'0.0 B'
>>> bytes2human(0.9)
... | 21d3f52fe60a25a860c8350c20e0b43209802751 | 22,831 |
def check_if_free(driver, available, movie_hulu_url):
"""
Check if "Watch Movie" button is there
if not, it's likely available in a special package (Starz etc) or availabe for Rent on Hulu.
"""
is_free = False
if available:
driver.get(movie_hulu_url)
sleep(3)
watch_movie_button = driver.find_elements_... | e27d62538e5bf9c416bcaedb4b7c5c4706493ba0 | 22,832 |
def scatter_add(data, indices, updates, axis=0):
"""Update data by adding values in updates at positions defined by indices
Parameters
----------
data : relay.Expr
The input data to the operator.
indices : relay.Expr
The index locations to update.
updates : relay.Expr
... | 641d96562700553a2ed4a5c4df323d468bba1bd8 | 22,833 |
def generate_test_linked_list(size=5, singly=False):
"""
Generate node list for test case
:param size: size of linked list
:type size: int
:param singly: whether or not this linked list is singly
:type singly: bool
:return: value list and generated linked list
"""
assert size >= 1
... | 5d6d5fc3c6027cc18fd6da24a7cefc506e64eb2a | 22,834 |
def _bytes_to_long(bytestring, byteorder):
"""Convert a bytestring to a long
For use in python version prior to 3.2
"""
result = []
if byteorder == 'little':
result = (v << i * 8 for (i, v) in enumerate(bytestring))
else:
result = (v << i * 8 for (i, v) in enumerate(reversed(byt... | fcaa038b21aef2822ad7a513c28a7a2ed3c08cbc | 22,835 |
import contextlib
import ast
def SoS_exec(script: str, _dict: dict = None, return_result: bool = True) -> None:
"""Execute a statement."""
if _dict is None:
_dict = env.sos_dict.dict()
if not return_result:
if env.verbosity == 0:
with contextlib.redirect_stdout(None):
... | c524aa064dfc396d421cdef9962d81ca79c7010b | 22,837 |
def aten_dim(mapper, graph, node):
""" 构造获取维度的PaddleLayer。
TorchScript示例:
%106 : int = aten::dim(%101)
参数含义:
%106 (int): 输出,Tensor的维度。
%101 (Tensor): 输入的Tensor。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_outputs_name(node)[0]
lay... | 8037cc1943577aed2737aceee47b97b59c6a9244 | 22,838 |
def plot_LA(mobile, ref, GDT_TS, GDT_HA, GDT_ndx,
sel1="protein and name CA", sel2="protein and name CA",
cmap="GDT_HA", **kwargs):
"""
Create LocalAccuracy Plot (heatmap) with
- xdata = residue ID
- ydata = frame number
- color = color-coded pair distance
.. Note... | 8103dbeb9801b08125ebb5e26cb5f76c948262ec | 22,840 |
def simulateGVecs(pd, detector_params, grain_params,
ome_range=[(-np.pi, np.pi), ],
ome_period=(-np.pi, np.pi),
eta_range=[(-np.pi, np.pi), ],
panel_dims=[(-204.8, -204.8), (204.8, 204.8)],
pixel_pitch=(0.2, 0.2),
... | bdff9dc1b7fd15d7b3b1cf45a4364dc495790293 | 22,842 |
import logging
def get_logger(name: str):
"""Get logger call.
Args:
name (str): Module name
Returns:
Logger: Return Logger object
"""
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(get_file_handler())
logger.addHandler(get_stream_hand... | 6d661896d38e2227b6825e649bdbd719dd64670a | 22,843 |
def create_label_colormap(dataset=_PASCAL):
"""Creates a label colormap for the specified dataset.
Args:
dataset: The colormap used in the dataset.
Returns:
A numpy array of the dataset colormap.
Raises:
ValueError: If the dataset is not supported.
"""
if dataset == _PASCAL:
return create... | 683d52f3f2c476b0e39e41ae7f2a0f897fee60d3 | 22,844 |
def SDM_lune(params, dvals, title=None, label_prefix='ham='):
"""Exact calculation for SDM circle intersection. For some reason mine is a slight upper bound on the results found in the book. Uses a proof from Appendix B of the SDM book (Kanerva, 1988). Difference is neglible when norm=True."""
res = expected_i... | e1465e002632ceb1431fa1a668abfdaa7deb307b | 22,845 |
def font_match(obj):
"""
Matches the given input againts the available
font type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
"""
return match(obj, f... | 8cf99e626578d278b3ce9e598233cb6dfa407820 | 22,846 |
import six
def time_monotonically_increases(func_or_granularity):
"""
Decorate a unittest method with this function to cause the value
of :func:`time.time` and :func:`time.gmtime` to monotonically
increase by one each time it is called. This ensures things like
last modified dates always increase.... | f3f76502cf0cd5f402cb4f585d6cd06db8eb5851 | 22,848 |
def rotate_coordinates(coords: np.ndarray, axis_coords: np.ndarray) -> np.ndarray:
"""
Given a set of coordinates, `coords`, and the eigenvectors of the principal
moments of inertia tensor, use the scipy `Rotation` class to rotate the
coordinates into the principal axis frame.
Parameters
------... | 686657f464fdf846fa394128ad1f8be6d00adf06 | 22,849 |
from typing import Type
from typing import Any
def get_maggy_ddp_wrapper(module: Type[TorchModule]):
"""Factory function for MaggyDDPModuleWrapper.
:param module: PyTorch module passed by the user.
"""
class MaggyDDPModuleWrapper(TorchDistributedDataParallel):
"""Wrapper around PyTorch's DDP... | 53f7e5096c41221072d7584470dd8a1bcf32a04f | 22,850 |
def random_jitter(cv_img, saturation_range, brightness_range, contrast_range):
"""
图像亮度、饱和度、对比度调节,在调整范围内随机获得调节比例,并随机顺序叠加三种效果
Args:
cv_img(numpy.ndarray): 输入图像
saturation_range(float): 饱和对调节范围,0-1
brightness_range(float): 亮度调节范围,0-1
contrast_range(float): 对比度调节范围,0-1
Retur... | f7ff6d2e0bbe1656abe5ad1dca404e1903417166 | 22,851 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.