content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def tokenize(chars: str) -> ListType[str]:
"""Returns the program as a list of tokens (including parenthesis)."""
return chars.replace("(", " ( ").replace(")", " ) ").split() | 61,400 |
def _make_coords(src_data_array, dst_affine, dst_width, dst_height):
"""Generate the coordinates of the new projected `xarray.DataArray`"""
coords = _get_nonspatial_coords(src_data_array)
new_coords = _warp_spatial_coords(src_data_array, dst_affine, dst_width, dst_height)
new_coords.update(coords)
r... | 61,401 |
def remove_ambiguous_solutions(fn_in, db_lines, strict=True, verbose=True):
""" Removes features with identical solutions.
During solving, some tags may be tightly coupled and solve to the same
solution. In these cases, those solutions must be dropped until
disambiguating information can be found.
... | 61,402 |
def fill_missing_values(df: pd.DataFrame):
"""Fill missing values with mean
Args:
df (pd.DataFrame): [Pandas DataFrame]
Returns:
[pd.DataFrame]: [Returns processed dataframe]
"""
filled_df = df.fillna(df.mean())
return filled_df | 61,403 |
def generate_cube(name, r, g, b, a=None):
"""
Takes input: alphabet, red, green, blue channels
"""
if a:
cube_name = '{}_{}'.format(name, a)
else:
cube_name = name
font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 200, encoding="unic")
# text_w... | 61,404 |
async def infer_env_add(self, engine, env1, env2):
"""Infer the return type of primitive `env_add`."""
return AbstractScalar({VALUE: ANYTHING, TYPE: xtype.EnvType}) | 61,405 |
def residuals(fit, obs):
"""Calculate residuals for fit compared to observed data
:fit: list of discrete fit data points
:obs: list of observed data points
:returns: fit minus observed data points
"""
return fit-obs | 61,406 |
def go_to_frame(vid, frame_pos, video_source, return_frame = False):
"""Jump to frame poisition in video
Parameters
----------
vid : cv2.VideoCapture object
Already opened video object. If empty, video from video_source is read.
video_source : str
path to video file
frame_p... | 61,407 |
def expected_traces(P, Γ, Λ, X):
"""The trace matrix for accumulating eligibility traces.
That is, a matrix with the same shape as `X`, but where the i-th row
corresponds to the expected value of the eligibility trace in the
steady-state given that the current state is `i`.
Parameters
---------... | 61,408 |
def test_nationality(root, printerror=False):
"""Verifies if there are problems with the nationalities in the
Lattes CV parsed in the argument root.
Args:
root: the Lattes CV that has been parsed with the ElementTree
language.
flag: if 0, there are languages defined in the Lattes CV.... | 61,409 |
def publish_uploaded_video(resp):
"""Publish a uploaded video.
Vid is pointted to the uploaded vidoe.
<meta>
args:
query:
- access_token
- openid
- title
- tags
- cat
- desc
... | 61,410 |
def _hashable2val(val):
"""Undo _val2hashable()
"""
if isinstance(val, ReadOnlyDict):
return dict(val)
elif isinstance(val, tuple):
return list(map(_hashable2val, val))
else:
return val | 61,411 |
def check_config(config):
""" Checking config """
if not os.path.exists(config['LOG_DIR']):
logging.error('No such directory {}'.format(config['LOG_DIR']))
raise FileExistsError
if not os.path.exists(config['REPORT_DIR']):
logging.info('Report dir doesn\'t exist. Creating new.')
... | 61,412 |
def get_method_url_protocol(text):
"""Method to extract the Request Method, URL, and Protocol in a string surrounded by quotes"""
match = re.search(r"\".+?\"", text)
if match:
match_string = match.group()
# Note: match should now be a combination of the Request Method, URL, and Protocol...
#... | 61,413 |
async def attended(ctx, player_name: str, date: str):
"""
Registers attendance at an event.
Usage:
!track attended "<player_name>" <date>
"""
ctx.trigger_typing()
player = Player.find(player_name)
player.events_attended += 1
player.total_points += points_per_attended
playe... | 61,414 |
def main():
"""Run the tests defined by the command line args.
Run the tests defined by the command line args or if none were provided
read the tests from the charms tests.yaml config file
"""
args = parse_args(sys.argv[1:])
level = getattr(logging, args.loglevel.upper(), None)
if not isins... | 61,415 |
def test_add_sync_with_no_details() -> None:
"""Test adding a sync with no details."""
timestamp = isoparse("2021-10-23T20:42:06.112Z")
error, sync = Sync.add_new_sync(timestamp)
assert not error
assert sync
assert sync.title == ""
assert sync.details == "" | 61,416 |
def Make_Full_Trial_Index(Features, Offset: int, Tr_Length: int, Epoch_Len: int):
"""
Parameters:
-----------
Features: list
Features: list
[Ch]->[Freq]->(Time Samples x Trials)
Offset: int
How much prior or after onset
Tr_Length: int
How many samples to use for ... | 61,417 |
def create_graphics(Eb_N0_dB, alg, simBer, color):
"""
Данная функция предназначена
для создания графика из двух
полученных аргументов
"""
fig, ax = plt.subplots()
ax.set(xlabel='ОСШ', ylabel='Битовый коэффициент ошибок', title='BER системы MIMO 2х2 в канале с МСИ, L=3')
ax.... | 61,418 |
def cj_curve_fit(x, y):
"""
Determines least squares fit of parabolic data. This is a vectorized
version of ``sdtoolbox.PostShock.LSQ_CJspeed`` using ``np.linalg.lstsq``.
Parameters
----------
x : np.array
Independent data points for curve fitting
y : np.array
Dependent data... | 61,419 |
def re_def_supper_class(obj, supper_class):
"""
重新定义父类
@param obj: 类 如 class A: 则obj为A 或者 A的实例 a.__class__
@param supper_class: 父类
@return:
"""
obj.__bases__ = (supper_class,) | 61,420 |
def raise_error(condition: bool, msg: str):
""" function to raise ValueError error
Parameter
-------------
condition: bool
if condition is True, raise ValueError
msg: str
manual error message
"""
if condition:
raise ValueError(msg) | 61,421 |
def feature2embedding(model, feature, edge_index, edge_attr, args):
"""
Convert further learned features to node embeddings with pre-trained GCN model.
:param model: an instance of GCN model. Remember to load the trained weights.
:param feature: further learned features.
:param edge_index: adja... | 61,422 |
def batch_get_projects(names=None):
"""
Gets information about build projects.
See also: AWS API Documentation
:example: response = client.batch_get_projects(
names=[
'string',
]
)
:type names: list
:param names: [REQUIRED]
The name... | 61,423 |
def do_addexpression(**kwargs):
"""
Worker to add expression to profile
profobj: Profile object
expname: list of expression names to add
return 0 if sucessful
"""
profobj = kwargs.get('profobj')
expname = kwargs.get('expname')
logger = logging.getLogger()
existing = profobj.profi... | 61,424 |
def visualize_variance(strain, stress_true, stress_calc, alpha=0.05):
"""
Visualize variance for batched examples
Args:
strain (torch.tensor): input strain
stress_true (torch.tensor): actual stress values
stress_calc (torch.tensor): simulated stress values
Keyword Args:
... | 61,425 |
def read_outputs():
"""Reads all outputs and returns them as a list"""
out_vals = []
for i in range(len(dfs)):
userid_element = driver.find_element_by_xpath(dfs.iloc[i, 2])
out_vals.append(float(userid_element.text.rstrip("%")))
return out_vals | 61,426 |
def _get_current_assets():
"""Returns the current set of assets in the request stack.
"""
return getattr(_request_ctx_stack.top, 'current_assets', None) | 61,427 |
def send_action(action):
"""Sends `action` while processing func command."""
def decorator(func):
@wraps(func)
def command_func(*args, **kwargs):
bot, update = args
bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)
return func(bot, ... | 61,428 |
def ipaddr_to_bin(num: str, t: int) -> list:
"""
Receives an IP address as a character string,
converts it to a decimal number received as
an argument for each octet, and returns it as a list.
"""
if num.count(".") != 3:
usage("invalid arguments")
ctype = "b" if t == 2 else "x"
... | 61,429 |
def train_model(depth,
width,
prior_prec_init,
prior_structure,
hessian_structure,
n_epoch=250,
batchsize=128,
seed=10,
optimizehypers=False,
hypers_lr = 0.01,
... | 61,430 |
def make_hash(o):
"""
Makes a hash from a dictionary, list, tuple or set to any level, that
contains only other hashable types (including any lists, tuples, sets, and
dictionaries). In the case where other kinds of objects (like classes) need
to be hashed, pass in a collection of object attributes t... | 61,431 |
def make_reflection_patches(instr_cfg,
tth_eta, ang_pixel_size, omega=None,
tth_tol=0.2, eta_tol=1.0,
rmat_c=np.eye(3), tvec_c=np.zeros((3, 1)),
npdiv=1, quiet=False,
compute_areas... | 61,432 |
def parse_comment(comment: Tag):
"""Extract a movie url and all video ids from an ICM comment."""
movie = comment.select_one('.link a')
if movie:
movie = movie['href']
text = comment.select_one('.span-18 > span')
text = text.get_text() if text else ''
# TODO: fix the line above for comme... | 61,433 |
def list_ids(group_id: str) -> List[str]:
"""List all person ids in a specified `group_id`.
:param group_id:
ID of the group to be listed. `group_id` is created in `group.create`.
:return:
An array of person ids.
"""
if group_id is None:
raise ValueError("Group ID must be sp... | 61,434 |
def deEmojify(inputString):
"""
Drop emojis
:param inputString:
:return:
"""
return inputString.encode('ascii', 'ignore').decode('ascii') | 61,435 |
def _validate_email(
value: Text,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> Dict[Text, Any]:
"""Validate email is in ticket system."""
if not value:
return {"1_email": None, "previous_email": None}
elif isinstance(value, bool):
value = ... | 61,436 |
def download(link, newdevice, video, delete,send):
"""Download a youtube video or playlist
in best audio and video quality
by providing a link, and then send to the
preferred device, or override it with `--newdevice`
option.
Provide the device name for `--newdevice` in quotes for e.g. "OnePlus ... | 61,437 |
def build_buy_limit_option_order(symbol, quantity, price):
"""Build Buy Limit: Single Option
Buy to open {quanity} contracts of the {symbol with date and option info}
at a Limit of {price} good for the Day.
Args:
symbol: symbol you want to trade. Includes date e.g., XYZ_032015C49
quan... | 61,438 |
def test_clip_points(point_gdf, single_rectangle_gdf):
"""Test clipping a points GDF with a generic polygon geometry."""
clip_pts = clip(point_gdf, single_rectangle_gdf)
pts = np.array([[2, 2], [3, 4], [9, 8]])
exp = GeoDataFrame([Point(xy) for xy in pts], columns=["geometry"], crs="EPSG:4326")
asse... | 61,439 |
def gettime():
"""return timestamp"""
import time
return time.time() | 61,440 |
def parse_speech_in_segment(nlp, segment: Segment) -> list:
"""
Parses all speeches in a segment.
:param segment: segment
:param nlp: spacy nlp object
:return: list of found speeches and its speakers
"""
speeches = []
for i, line in enumerate(segment.lines):
spoken_line, speaker... | 61,441 |
def parser_of_trace(data):
""" Given a dict of traceroute measurement, extract timestamps, valide hops and rtts to each hop
Args : data (dict)
{u'af': 4,
u'dst_addr': u'192.228.79.201', u'dst_name': u'192.228.79.201', u'endtime': 1483230652,
u'from': u'103.7.251.180', u'fw': 4740, u'lts': 551, u'... | 61,442 |
def perceptron(X, y, max_iter=10):
"""
感知机 算法
"""
X = np.mat(X)
y = np.mat(y).T
n, m = X.shape
w = np.zeros((1, m))
b = 0
h = 0.0001
for k in range(max_iter):
for i in range(n):
xi = X[i]
yi = y[i]
if (-1) * yi * (w ... | 61,443 |
def set_entitlement_policy(entitlement, site):
"""
Assign the appropriate CourseEntitlementPolicy to the given CourseEntitlement based on its mode and site.
Arguments:
entitlement: Course Entitlement object
site: string representation of a Site object
Notes:
Site-specific, mode... | 61,444 |
def is_s3_bucket_global(session, bucket):
""" Return bool for S3 bucket global accessibility
:param session: AWS session
:param bucket: S3 bucket
"""
s3_client = session.client('s3')
try:
s3_acls = s3_client.get_bucket_acl(Bucket=bucket).get('Grants')
if s3_acls:
for ... | 61,445 |
def test_bool(signal_listener: SignalListener, signals: List[Signal],
expected_truthiness: bool) -> None:
"""Test illud.inputs.signal_listener.SignalListener.__bool__."""
signal_queue: Queue = Queue()
for signal in signals:
signal_queue.put_nowait(signal)
signal_listener._signals ... | 61,446 |
def cumulative_integral(
control_points: ArrayLike, t: ArrayLike, *, axis: int = 0
) -> np.ndarray:
"""Estimate the cumulative integral along a curve.
Estimates the cumulative integral of a time-parameterized curve along the
chosen axis. The curve is given by a sequence of control points and their
... | 61,447 |
def _sqrt(x):
"""
Return square root of an ndarray.
This sqrt function for ndarrays tries to use the exponentiation operator
if the objects stored do not supply a sqrt method.
"""
x = np.clip(x, a_min=0, a_max=None)
try:
return np.sqrt(x)
except (AttributeError, TypeError):
... | 61,448 |
def get_keyboard_session():
"""Create a new GET_KEYBOARD_SESSION_MESSAGE."""
return create(protobuf.ProtocolMessage.GET_KEYBOARD_SESSION_MESSAGE) | 61,449 |
def EnsureSuperUser():
"""Ensures that current user has super user privileges."""
if os.getuid() != 0:
logging.warning('Tool must be run as root.')
exit(-1) | 61,450 |
def equilibrate(a: np.ndarray, b: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
""" Expand the shorter of two array by zero padding
"""
le = max(len(a), len(b))
tempa, tempb = np.zeros((le,)), np.zeros((le,))
tempa[:len(a)] = a
tempb[:len(b)] = b
return tempa, tempb | 61,451 |
def countObjects(meshes, skel):
"""
Count the total number of vertex groups and shapes combined, as required
for all specified meshes. If no skeleton rig is attached to the mesh, no
vertex groups for bone weights are required.
"""
nVertexGroups, nShapes = getObjectCounts(meshes)
if skel:
... | 61,452 |
async def test_arm_away_failure(hass: HomeAssistant) -> None:
"""Test arm away method failure."""
responses = [RESPONSE_DISARMED, RESPONSE_ARM_FAILURE, RESPONSE_USER_CODE_INVALID]
with patch(TOTALCONNECT_REQUEST, side_effect=responses) as mock_request:
await setup_platform(hass, ALARM_DOMAIN)
... | 61,453 |
def create_container(block_blob_service, account_name, container_name):
"""
This function creates the container if it does not exist
:param block_blob_service: The storage blob service instance
:param account_name: The storage account name
:param container_name: The storage container
:return: Th... | 61,454 |
def aoc_2019_4_1(data, **kwargs):
"""Password crackin' part 1"""
lower, upper = data.strip().split('-')
lower = int(lower)
upper = int(upper)
match_criteria = []
PATTERN = r'(\d)\1+'
for x in range(lower, upper+1):
matches = re.search(PATTERN, str(x))
if matches:
... | 61,455 |
def compute_groups(sequence):
"""
compute group index and flags
"""
# assume increasing group indexes along the program sequence
assert len(sequence) > 0, "empty stencil sequence"
print(r"\ constrain the group indexes")
print("g%0 = 0")
for index in range(1, len(sequence)):
print... | 61,456 |
def Evapotranspiration(Dir, latlim, lonlim, Startdate, Enddate, Product = 'MOD16'):
"""
This functions check the evapotranspiration files that needs to be downloaded, and send the request to the collect functions.
Parameters
----------
Dir : str
Path to all the output data of the Basin
... | 61,457 |
def abs_of_difference(num1: int, num2: int) -> int:
"""
precondition: parameters must be numbers
calculate difference between num1 and num2 and compute absolute value of the result
>>> abs_of_difference(-4,5)
9
>>> abs_of_difference(1,-3)
4
>>> abs_of_difference(2,2)
0
"""
r... | 61,458 |
def get_gpus():
"""
Get the number of gpus per node.
Args:
None
Returns:
num_gpus (int): number of gpus per node
"""
gpu_var = os.environ["SLURM_GPUS_PER_NODE"]
num_gpus = int(gpu_var)
return num_gpus | 61,459 |
def test_dynamic_numpy_field_with_type() -> None:
"""
Tests that we can define and construct a message type with a dynamic numpy field
with a dtype.
"""
assert isinstance(
MyDynamicNumpyIntMessage.__message_fields__["field2"].data_type,
NumpyDynamicType,
)
array = np.random.... | 61,460 |
def snapshot_container(
container_ref: "str", repository: "str", tag: "str" = "latest"
) -> "str":
"""Create a snapshot of a running container.
This will store the container's file system in Glance as a new Image.
You can then specify the Image ID in container create requests.
Args:
contai... | 61,461 |
def copy_node_info(src, dest):
"""Copy information from src to dest
Every node in the AST has to have line number information. Get
the information from the old stmt."""
for attr in ['lineno', 'fromlineno', 'tolineno',
'col_offset', 'parent']:
if hasattr(src, attr):
... | 61,462 |
def lambda_handler(event, context):
"""
Parse the incoming SNS notification for a Deep Security event
"""
timestamp_format = "%Y-%m-%dT%H:%M:%S.%fZ"
if type(event) == type({}):
if 'Records' in event:
print("Processing {} records".format(len(event['Records'])))
fo... | 61,463 |
def eval_marker(value):
"""
Evaluate an distutils2 environment marker.
This code is unsafe when used with hostile setup.cfg files,
but that's not a problem for our own files.
"""
value = value.strip()
class M:
def __init__(self, **kwds):
for k, v in kwds.items():
... | 61,464 |
def get_random_training_set(nenv):
"""Create a random training_set array with parameters
And generate four different kinds of hyperparameter sets:
* multi hypper parameters with two bond type and two triplet type
* constrained optimization, with noise parameter optimized
* constrained optimization, ... | 61,465 |
def test_section_update(api):
""" Verify the ``section_update`` method call """
SECTION_ID = 1234
PARAMS = {'param_key': 'param_value'}
api._session.request.return_value = SECT1
section = api.section_update(SECTION_ID, PARAMS)
exp_call = mock.call(method=POST,
path=AP['... | 61,466 |
def basic_ro(centers):
"""
sort the elements in the left-rigth-top-dowm order given its center
"""
return np.lexsort((centers[:,0],centers[:,1])) | 61,467 |
def synchronize_generator(
async_gen: AsyncGenerator[T, None],
loop: Optional[asyncio.BaseEventLoop] = None) -> Generator[T, None, None]:
"""
Maps ``__anext__`` to ``__next__`` to synchronously interact with async generators.
If you would write the following async code:
.. code-block: ... | 61,468 |
def get_constraints(
m,
foot_angles,
which_current_support,
next_foot_angles,
support_foot_pos,
swing_foot_pos,
stateX,
stateY,
N=16,
dt=0.1,
h=1.0,
g=9.81,
tPf=8,
):
"""
INPUTS
m (int): remaining time steps in current foot step;
foot_angles ([N, 1] ve... | 61,469 |
def compileHTMLTemplate (template, minimizeBooleanAtts = 0):
""" Reads the templateFile and produces a compiled template.
To use the resulting template object call:
template.expand (context, outputFile)
"""
if (isinstance (template, str)):
# It's a string!
templateFile = io.StringIO (template)
else:
temp... | 61,470 |
def singleton(cls):
"""Singleton pattern to avoid loading class multiple times
"""
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance | 61,471 |
def lookup_tables(request):
"""A view to render tables with all of the lookup values."""
# NOTE - defer spatial fields!
# Management Units
# Strains and Raw Strains
agencies = Agency.objects.all()
lakes = Lake.objects.all()
jurisdictions = Jurisdiction.objects.all()
species = Species.... | 61,472 |
def send_template_mail(recipient, template, variables, sender=None, html=True, subject=None):
"""
Send an e-mail using a template.
Arguments:
recipient -- the address(es) of the recipient(s)
template -- the template name to use. See below for details.
variables -- a dictionary of variables to ... | 61,473 |
def quit():
"""
Exit the program
"""
# Exit program
sys.exit() | 61,474 |
def combine_sample_data(gr):
"""Combine data from multiple sequencing runs for the same sample.
Take a pandas groupby object representing multiple data points
corresponding the same sequence and sample, from multiple sequence runs.
Sum the barcode and read counts for the combined result. Use the sequen... | 61,475 |
def copy_coco_data(force=False):
"""Copy the coco data to local machine for speed of reading.
Args:
force (bool, optional): Force copying coco data even if tmp folder exists.
"""
if not os.path.exists("/tmp/aa"):
os.system("mkdir /tmp/aa")
if not os.path.exists("/tmp/aa/... | 61,476 |
def compute_loss(
nn: NNApproximator, x: torch.Tensor = None, verbose: bool = False
) -> torch.float:
"""Compute the full loss function as interior loss + boundary loss
This custom loss function is fully defined with differentiable tensors therefore
the .backward() method can be applied to it
"""
... | 61,477 |
def wikifier_for_ethiopia_dataset(input_dataset: d3m_Dataset) -> typing.Tuple[bool, d3m_Dataset]:
"""
wrapped version for d3m dataset
"""
res_id, input_dataframe = d3m_utils.get_tabular_resource(dataset=input_dataset, resource_id=None)
wikifiered_dataframe = wikifier_for_ethiopia(input_dataframe... | 61,478 |
def get_serial_num_from_filepath(filepath):
"""
Parse the serial number from the file path
:param filepath: The full path of the file to extract the serial number from the name
:return: serial number
"""
# get just the filename from the full path
filename = os.path.basename(filepath)
#... | 61,479 |
def configure_callback(conf):
"""called by collectd to configure the plugin. This is called only once"""
global ES_HOST, ES_PORT, ES_NODE_URL, ES_HTTP_TLS_ENABLED, ES_TLS_CERT_PATH, \
ES_TLS_KEY_PATH, ES_VERSION, VERBOSE_LOGGING, ES_CLUSTER, \
ES_INDEX, ENABLE_INDEX_STATS, ENABLE_CLUSTER_STATS, ... | 61,480 |
def load_unknown(filepath):
"""Load any TSPLIB file.
This is particularly useful when you do not know in advance
whether the file contains a problem or a solution.
:param str filepath: path to a TSPLIB problem file
:return: either a problem or solution instance
"""
return load(filepath) | 61,481 |
def simulatie(n=20, m=10):
"""
Deze functie doet een simulatie van een gegeven hoeveelheid conformaties van het gegeven aantal atomen. Dit is ook de eerste versie die parallel kan lopen over meerdere cores.
:param int n: Het aantal atomen dat gebruikt wordt.
:param int m: Het aantal conformaties dat gesimuleerd m... | 61,482 |
def admin_field_generator(verbose_name, function_changer=None, path_to_field=None, html=False,
boolean=False, limit=-1, wrap_white_space=True):
"""
This function generates admin_get decorators for being used in admin.py field methods.
:param function_changer: this function holds th... | 61,483 |
def generate(parent_yaml, parent_name):
"""Generate child YAML configs as a dict {name: yaml_object}"""
# TODO documentation
hpsearch_config = parent_yaml['hpsearch']
if hpsearch_config.get('is_child', False):
raise RuntimeError('This YAML is itself a child config generated for an hyperpar... | 61,484 |
def getOptions():
""" Function to pull in arguments """
description = """"""
parser = argparse.ArgumentParser(
description=description, formatter_class=argparse.RawDescriptionHelpFormatter
)
# Standard Input
standard = parser.add_argument_group(description="Required Input")
standard... | 61,485 |
def get_mbc_objectives(doc):
"""Return dict of MBC results."""
objectives = collections.defaultdict(set)
for rule in rutils.capability_rules(doc):
if not rule["meta"].get("mbc"):
continue
mbcs = rule["meta"]["mbc"]
if not isinstance(mbcs, list):
raise ValueEr... | 61,486 |
def test_annotations_crop():
"""Test basic functionality of annotation crop."""
onset = np.arange(1, 10)
duration = np.full_like(onset, 10)
description = ["yy"] * onset.shape[0]
a = Annotations(onset=onset,
duration=duration,
description=description,
... | 61,487 |
def clustering_sax(locator, data, word_size, alphabet_size, gv):
"""
Function to cluster different days of the year following the SAX method (see class for more info)
:param locator: locator class
:param gv: global variables class
:param word_size: estimated word size, after optimization
:param ... | 61,488 |
def combine_histograms(histograms):
"""Takes a list of histograms and returns a new Histogram object that sums
the values in each bin.
All histograms in the list must be identical except for the count.
Parameters
----------
histograms: sequence
A lst of Histogram objects to co... | 61,489 |
def parse_all():
"""Parse all subjects and all sessions"""
for subject_id in ['kre', 'sah', 'tki']:
for session_id in ['cafe', 'inside', 'nearwork', 'outside1', 'outside2']:
cmd = "boris parse {subject_id} {session_id}".format(subject_id=subject_id,
... | 61,490 |
def save_to_file(config):
"""Finds current directory, creates file, saves file"""
global class_file
dir_path = os.path.dirname(os.path.realpath(__file__))
class_file = dir_path + '\\ClassMaps.xml'
try:
config.write(file_or_filename=class_file)
except OSError:
raise OS... | 61,491 |
def stick_module():
"""
@api {post} /v1/interfacemodule/stick InterfaceModule_置顶模块
@apiName interfaceModuleStick
@apiGroup Interface
@apiDescription 置顶模块
@apiParam {int} id 模块id
@apiParam {string} projectName 项目名称
@apiParamExample {json} Request-Example:
{
"id": 27,
"... | 61,492 |
def int_to_float(value: int) -> float:
"""Converts a uniformly random [[64-bit computing|64-bit]]
integer to uniformly random floating point number on interval <math>[0, 1)</math>.
"""
fifty_three_ones = 0xFFFFFFFFFFFFFFFF >> (64 - 53)
fifty_three_zeros = float(1 << 53)
return (value & fifty_thr... | 61,493 |
def load_attributes_from_hdf5_group(group, name):
"""Loads attributes of the specified name from the HDF5 group.
This method deals with an inherent problem
of HDF5 file which is not able to store
data larger than HDF5_OBJECT_HEADER_LIMIT bytes.
Args:
group: A pointer to a HDF5 group.
name: A nam... | 61,494 |
def login():
""" Login to user's account """
# Get login and password
login = request.authorization["username"]
password = request.authorization["password"]
# Do some check in the database
if True:
# Set username/password in the response
session["username"] = login
sess... | 61,495 |
def rank_mols(data, feature):
"""Ranks (or clusters) the molecules according to specified feature which must a column name of data
is pIC50
:param data: dataframe with processed data. Outputted by read_mols
:type data: :class:`pandas.DataFrame` with columns (minimally) ['mol','atag','btag',feature]
... | 61,496 |
def linux_ipv4_addr_get_from_console(target, ifname):
"""
Get the IPv4 address of a Linux Interface from the Linux shell
using the *ip addr show* command.
:param tcfl.tc.target_c target: target on which to find the IPv4
address.
:param str ifname: name of the interface for which we want to fi... | 61,497 |
def parse_args():
"""
usage: collect_ad_boilerplate.py [-h] [-t TARGET] [-d]
Utility for creating boilerplate areaDetector ophyd classes
optional arguments:
-h, --help show this help message and exit
-t TARGET, --target TARGET
Location of locally inst... | 61,498 |
def quit_session():
"""This function will close the session.
"""
s.close() | 61,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.