content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def nn_overlap(X1, X2, k=100):
"""
Compute the overlap between the k-nearest neighbor graph of X1 and X2 using Spearman correlation of the
adjacency matrices.
"""
assert len(X1) == len(X2)
n_samples = len(X1)
k = min(k, n_samples - 1)
nne = NearestNeighbors(n_neighbors=k + 1) # "n_jobs=... | 55,000 |
def login_registry():
"""
Login to a remote registry.
"""
if docker.login_registry():
return "success"
else:
return "fail" | 55,001 |
def get_owner_mention(line):
"""
起案者 <@123> は🗑と🆗リアクションで削除出来ます。
の<@123>の部分を抽出する
"""
return line[len(BODY_TEXT_2) + 1:-(len(BODY_TEXT_3) + 1)] | 55,002 |
def service_array_to_list(array_pointer, length):
"""Convert ble_gattc_service_array to python list."""
data_array = driver.ble_gattc_service_array.frompointer(array_pointer)
data_list = _populate_list(data_array, length)
return data_list | 55,003 |
def lfsr_next_one_seed(seed_iter, min_value_shift):
"""High-quality seeding for LFSR generators.
The LFSR generator components discard a certain number of their lower bits
when generating each output. The significant bits of their state must not
all be zero. We must ensure that when seeding the gen... | 55,004 |
def digits(n, reverse=False):
"""
Generates the sequence of digits of a given integer ``n``, starting from
the most significant digit, by default. If reverse is True then the
sequence is generated from the least significant digit, e.g.
::
123, False -> 1, 2, 3
123, True -> 3, 2, 1
... | 55,005 |
def matrix_to_pairwise_csv(matrix, document_ids, output_file):
"""
Arguments:
- `matrix`:
"""
batchsize = 100
headers = [["index1","index2","similarity"]]
if os.path.isfile(output_file):
os.remove(output_file)
with open(output_file, "w") as sim_pair_file:
writer = cs... | 55,006 |
def test_xnor_basic_block_forward():
"""Test forward pass of xnor basic block."""
torch.manual_seed(1234)
x = torch.randn(4, 3, 32, 32)
resnet = QResNet(loss_fn=F.cross_entropy, **XNOR_BASIC_CONFIG)
y = resnet(x)
assert y.shape == (4, 1000) | 55,007 |
def mle_prob_many_coal_counts(As, Bs, t, n0):
"""
Find the maximum likelihood estimate of going from 'As' lineages
to 'Bs' lineages over generations 't'.
"""
# count unique (a,b) pairs
counts = defaultdict(lambda: 0)
for a, b in zip(As, Bs):
counts[(a, b)] += 1
As = []
Bs = ... | 55,008 |
def _startlanerec(lane, starttime, duration, band, bf_data_dir, port0, stnid,
compress=True, threadqueue=None):
"""Start recording a lane using an external dumper process.
"""
if compress:
# Compress stored data using zstd.
compress_flag = ' --compress'
else:
co... | 55,009 |
def import_data(csvfile):
"""
Iterates through each row of the provided csv, creating the a SiteSummarySnapshot object and saving to the DB
:param csvfile:
:return:
"""
total_count_stats = {"snapshots": 0}
reader = csv.reader(csvfile)
iter_reader = iter(reader)
try:
header_ro... | 55,010 |
def get_cmap_labels(im_label, cmap_name='cool', alpha=1):
"""Create list of L colors where L is the number of labels in the image"""
#cmap_original = plt.get_cmap(cmap_name)
cmap_original = colorify.cmaps_def(cmap_name=cmap_name)
colors = cmap_original(np.linspace(0,1,im_label.max()+1))
# backgroun... | 55,011 |
def test_elementwise_max():
"""Test of the PyTorch max Node on Glow."""
def test_f(a, b):
c = torch.max(a, b)
return torch.max(c, c)
x = torch.randn(4)
y = torch.randn(4)
jitVsGlow(test_f, x, y, expected_fused_ops={"aten::max"}) | 55,012 |
def LASCA_processing(raw_mtx,mtx,chr_name,output_bedpe_name,resolution,start_bin,end_bin,distance_bins,FDR=0.1,q=0.90, adjust_by_scale=False,scaling_q_value_trhd=0.05,min_cluster=3, filter_bins=2,q_value_trhd=0.1,Intensity=True,as_intervals=True,bin_coverage=0.25, ... | 55,013 |
def getVerticalIntervalsFromPitches(pitches):
"""Cached method. Returns 6 vertical intervals: BT, BA, BS, TA, TS, AS."""
cachedGetVerticalIntervalsFromPitches.append(pitches)
return [
getInterval(pitches[i], pitches[j])
for i in range(3)
for j in range(i + 1, 4)
] | 55,014 |
def boom(message: str) -> None:
"""
This task raises an Exception.
"""
raise ValueError(message) | 55,015 |
def fits_ccddata_writer(ccd_data, filename, **kwd):
"""
Write CCDData object to FITS file
Parameters
----------
filename : str
Name of file
kwd :
All additional keywords are passed to :py:mod:`astropy.io.fits`
"""
hdu = fits.PrimaryHDU(data=ccd_data.data, header=ccd_da... | 55,016 |
def select_lines_by_tile(tile_xyz=(0, 0, 0), target_epsg_code='4326',
lines=None, include_intersections=False):
"""
Select lines by a tile
:param tile_xyz: tuple with tile x,y,z
:param target_epsg_code: the epsg_code to reproject the bbox to
before selecting.
:p... | 55,017 |
def query_passwd(md5sum: bytes) -> List[str]:
"""查询数据库中可能存在的密码,如果没有,则返回空列表
"""
query = CertainPassword.select(
CertainPassword.passwd).where(CertainPassword.md5sum == md5sum)
passwords = [it.passwd for it in query]
if passwords:
now = date.today()
with DB.atomic():
... | 55,018 |
def create_relative_bias(config: Union[BaseBenchmarkerConfig, T5Config]) -> Sequence[RelativePositionBiasBase]:
"""
Creates empty list or one/multiple relative biases.
:param config: Model's configuration
:return: Sequence with created bias modules.
"""
bias_list = []
if hasattr(config, "re... | 55,019 |
def get_dois_for_review(review: Review):
"""Gets a list of dois (primary key) that are associated to a given review.
Args:
review: review-object
Returns:
list of dois as str: ["doi1", "doi2"]
"""
result_ids = []
for query in review.queries:
result_ids += query.results
... | 55,020 |
async def load_text_async(
path: Path,
options: Dict[str, Any] = {},
) -> str:
"""Load a text file asynchronously."""
loop = asyncio.get_running_loop()
data = await loop.run_in_executor(None, load_text, path, options)
return data | 55,021 |
def find_as_products() -> Iterator:
"""
Returns a tuple with the following:
- full path to file
- ActiveState product the file is associated with
- product version
"""
files_to_check: Iterator[str] = dirwalker()
interesting_files_to_scan = filter(_accept_path_for_activestate,... | 55,022 |
def write_results(args, results):
"""Write results to pickle file"""
results_filename = "%s/%s" % (args.output_dir, constants.SIMULATION_RESULTS_FILENAME)
with open(results_filename, "wb") as results_file:
pickle.dump(results._asdict(), results_file) | 55,023 |
def function_to_dump(hallo,welt,with_default=1):
"""
non class function to be dumped and restored through
create_pickled_dataset and load_pickled_data
"""
return hallo,welt,with_default | 55,024 |
def is_valid_batch_event_settings(val, file):
""" Validates if the value passed batch_event_settings has correct data type and values or not.
Args:
val (dict): value to be tested
Returns:
bool: True if all conditions are passed else False
"""
logger = VWOLogger.getInstance()
i... | 55,025 |
def patch_django_nose():
"""Run 2to3 on django-nose and remove ``import new`` from its runner."""
# FIXME: delete once django-nose supports Python 3 (bug #16).
python = 'python' + '.'.join(map(str, sys.version_info[:2]))
django_nose = os.path.join(
VENV, 'lib', python, 'site-packages', 'django_n... | 55,026 |
def resources():
"""
:return: Renders Resource Page
"""
return render_template("resources.html") | 55,027 |
def objective(logits, labels, n_classes):
"""Defines classification loss and useful metrics"""
# defining the loss
cross_entr = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_mean(cross_entr)
inferred_class = tf.cast(tf.argmax(logits, 1), tf.i... | 55,028 |
def resolve_compression_type(compression_type):
"""Turn a compression type string into a valid one.
:raises: ``ValueError`` if the compression type is invalid.
"""
if compression_type in COMPRESSION_TYPE_ALIASES:
return COMPRESSION_TYPE_ALIASES[compression_type]
elif compression_type in COM... | 55,029 |
def validate_long_url(value):
"""
Append schema if needed and validate.
"""
long_url = check_and_update_url_schema(value)
if len(long_url) >= 500:
raise ValidationError("Length of URL should be below 500 chars")
URLValidator()(long_url)
return long_url | 55,030 |
def get_hashtag_spans(tokens):
"""
Finds the spans (start, end) of subtokes in a list of tokens
Args:
tokens: list[str]
Returns:
spans: list[tuple[int]]
"""
is_part = ["##" in t for t in tokens]
spans = []
pos_end = -1
for pos_start, t in enumerate(is_part):
if pos_start <= pos_end:
continue
if ... | 55,031 |
def _load_and_apply_indexer(
args: Tuple[Tuple[Tuple[str, int], ...], List[slice]],
delayed: bool,
fs: fsspec.AbstractFileSystem,
partition_handler: partitioning.Partitioning,
partition_properties: PartitioningProperties,
selected_variables: Optional[Iterable[str]],
) -> List[dataset.Dataset]:
... | 55,032 |
def _snap_mask_to_type(
float_mask: xr.DataArray,
enumeration: Mapping[float, str] = SURFACE_TYPE_ENUMERATION,
atol: float = 1e-7,
) -> xr.DataArray:
"""Convert float surface type array to categorical surface type array
Args:
float_mask: xr dataarray of float cell types
enumerat... | 55,033 |
def matrix_initialization(variable):
"""
Initialize the value of a variable inside a
force constant matrix, assuming the variable name
has the form 'Cnab' where n is an integer identifying
a set of independent variables and a and b identify
the directions (1,2 or 3).
Return a random numbe... | 55,034 |
def svn_io_remove_file2(*args):
"""svn_io_remove_file2(char const * path, svn_boolean_t ignore_enoent, apr_pool_t scratch_pool) -> svn_error_t"""
return _core.svn_io_remove_file2(*args) | 55,035 |
def test_update_company_from_dnb_data_partial_fields(dnb_response_uk):
"""
Test the update_company_from_dnb_data command when a subset of DNB fields are updated.
"""
company = CompanyFactory(duns_number='123456789')
original_company = Company.objects.get(id=company.id)
task_result = update_compa... | 55,036 |
def admin_kill(dbname, username):
""" Stop and remove container without using authtication.
Called from the admin command console Only. Clean up
admin_db. Implemented becuase I forget passwords.
"""
if stop_remove(dbname):
result = "Container %s successfully deleted " % dbname
resul... | 55,037 |
def create_fingers_dict_id():
"""
Create dictionary by ID of TCP group
usage: dict[id] return array with OS and theirs %
:return: dictionary from file with TCP params
"""
config = ConfigParser()
config.read('config.ini')
finger_path = config.get("TCP", "tcp_path")
with open(finger_pa... | 55,038 |
def clients():
""" Clients """ | 55,039 |
def cutout_sdss(ra, dec, bands=['u','g','r','i','z'], dr=12, objid=None, psfmags=None,\
imDir="/data/sdss/", input_filename=[], saveFITS=False,\
width_as=20., smooth=False, cmap="binary", minmax="MAD", origin="lower", figTitle=True, \
return_val=False, saveDir=None):
... | 55,040 |
def write_image(img_array: np.ndarray, parameters: dict, output_path: Path):
"""
Write a 3d US image with output spacing in mm
:param img_array: Numpy array corresponding to the image
:param parameters: Dictionary of parameters containing resolution keys
:param output_path: ... | 55,041 |
def problem():
"""
List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes
at each depth (e.g., if you have a tree with depth D, you'll have D linked lists).
"""
pass | 55,042 |
def convert_type_annotation(annot: object) -> Type:
""" Converts a type annotation to a cowait type """
if annot == inspect._empty:
# an empty type signature defaults to the Any type.
return Any()
return convert_type(annot) | 55,043 |
def body_cubic_5(size):
"""Generates symmetry preserving HNF's of a given size
for a base centered monoclinic basis
Args:
size (int): The determinate of the HNF matricies
Returns:
list (int): The generated HNF matricies
"""
symHNF = []
diags = find_HNF_dia... | 55,044 |
def roundToNearest(number, nearest):
""" Rounds a decimal number to the closest value, nearest, given
Arguments:
number: [float] the number to be rounded
nearest: [float] the number to be rouned to
Returns:
rounded: [float] the rounded number
"""
A = 1/nearest
rounde... | 55,045 |
def _parse_schema_location(root):
"""Get all schema locations from xml."""
try:
namespace = root.nsmap["xsi"]
except Exception as e:
raise SchemaError("Can't get schema location namespace", e)
try:
schema_location = root.attrib["{%s}schemaLocation" % namespace]
except Excepti... | 55,046 |
def search_async():
"""New endpoint supporting async search."""
encoded_domain_parameter = flask.request.args.get('ed')
domain_parameter = tools.parse_domain(encoded_domain_parameter)
if domain_parameter is None:
return handle_invalid_domain(encoded_domain_parameter)
return flask.render_te... | 55,047 |
def digraph_from_multi_graph_json(file_name):
"""
file_name should hold a JSON which represents a MultiDigraph where there is a maximum of two edges each in opposing
directions between each node
:param file_name:
"""
with open(file_name) as f:
data = json.load(f)
G = nx.DiGraph()
... | 55,048 |
def load_pretrained_model(root_dir, device=device):
"""load pretrained model for interpretation
"""
results = pkl.load(open(opj(root_dir, 'dnn_full_long_normalized_across_track_1_feat.pkl'), 'rb'))
dnn = neural_net_sklearn(D_in=40, H=20, p=0, arch='lstm')
dnn.model.load_state_dict(results['model_sta... | 55,049 |
def is_directory(filename):
"""Tells if the file is a directory"""
return os.path.isdir(filename) | 55,050 |
def compare_dict_keys(d1, d2):
"""
Returns [things in d1 not in d2, things in d2 not in d1]
"""
return [k for k in d1 if not k in d2], [k for k in d2 if not k in d1] | 55,051 |
def fontawesome_link_button_html(
url: str,
fa_code: str,
button_type: str,
tooltip: str = None,
disabled: bool = False,
) -> str:
"""create fontawesome button and return HTML"""
return format_html(
'<a href="{}" class="btn btn-{}"{}>{}{}</a>',
url,
button_type,
... | 55,052 |
def CompareVideos(options, cropped_ref_file, cropped_test_file):
"""Runs the compare_video.py script from src/webrtc/tools using the file path.
Uses the path from recording_result and writes the output to a file named
<options.app_name + '_' + CURRENT_TIME + '_result.txt> in the reference video
recording folde... | 55,053 |
def factor_cumulative_returns(factor_data,
period,
long_short=True,
group_neutral=False,
equal_weight=False,
quantiles=None,
groups=None):
... | 55,054 |
def rotate(X, angle):
"""
This function rotates an aribitrary set of point coordinates by a given angle (in degrees)
around the mean centre of the given points.
X, the point coordinates rotated, is an array of form (n_instances * 2)
If applied to a distribution of points, has the effect of changing ... | 55,055 |
def make_path(segments, close=1):
"""
This function prepares a path given by a list of lists of
coordinates for the use with app.
"""
first_point = segments[0][0]
last_point = first_point
new_path = [[] + first_point, [], sk2const.CURVE_OPENED]
points = new_path[1]
for seg in segments:
if seg[0] ... | 55,056 |
def make_stoppable(function_to_decorate):
"""Decorator allowing to stop or pause at the beginning of a task.
This is applied the perform method of every task marked as stoppable. This
check is performed before dealing with parallelism or waiting.
"""
def decorator(*args, **kwargs):
"""Wrap... | 55,057 |
def parse_search_results(data: dict) -> list[OmdbMovie]:
"""
Parse search results into a list of Movie objects.
"""
movies = []
for movie in data["Search"]:
movies.append(_parse_movie(movie))
return sorted(movies, key=lambda m: m.year, reverse=True) | 55,058 |
def cmd_args_parser():
"""Parsing command-line arguments"""
parser = argparse.ArgumentParser(
prog="DatasetUpdater", description="Updates datasets-properties",
)
parser.add_argument(
"--project_id",
type=str,
action="store",
dest="project_id",
help="Provid... | 55,059 |
def test_set_client_certificate(default_repo):
"""Set client certificate for session."""
assert default_repo.session.cert is None
default_repo.set_client_certificate(("/path/to/cert", "/path/to/key"))
assert default_repo.session.cert == ("/path/to/cert", "/path/to/key") | 55,060 |
def _parse_res(expr: Expression) -> ResDescription:
"""
Parses the res operand of the instruction and returns the corresponding ResDescription.
"""
if isinstance(expr, ExprDeref):
return _parse_res_deref(expr.addr)
elif isinstance(expr, ExprConst):
# In this case op0 is not involved.... | 55,061 |
def connect_to_uri(uri: str, loop=None) -> (Reader, Writer):
"""
Selecting connection type based on uri
"""
parsed = urlparse(uri)
if parsed.scheme not in AVAILABLE_SCHEMES:
raise UnavailableUriScheme(uri)
if parsed.scheme == 'tcp':
port = parsed.port
if parsed.host is No... | 55,062 |
def assert_badges(soup: BeautifulSoup, badge_class_name: str, expected_values: List[bool]) -> None:
"""Assert that the badge with the given class name is either present or not for all properties"""
property_cards = soup.find_all(class_="property-name-button")
assert len(property_cards) == len(expected_value... | 55,063 |
def command_talk(current_buffer, args):
"""
Open a chat with the specified user
/slack talk [user]
"""
server = servers.find(current_domain_name())
if server:
channel = server.channels.find(args)
if not channel:
channel.open()
else:
user = server.... | 55,064 |
def icon_path(name):
""" Load an icon from the res/icons folder using the name
without the .png
"""
path = os.path.dirname(os.path.dirname(__file__))
return os.path.join(path, 'res', 'icons', '%s.png' % name) | 55,065 |
def project_name(settings_dict):
"""Transform the base module name into a nicer project name
>>> project_name({'DF_MODULE_NAME': 'my_project'})
'My Project'
:param settings_dict:
:return:
"""
return " ".join(
[
x.capitalize()
for x in settings_dict["DF_MODU... | 55,066 |
def is_acceptable_smiles(smile: str, allowed_chars=smiles_encoding['indices_token'].values(),
min_len=smiles_encoding['min_smiles_len'], max_len=smiles_encoding['max_smiles_len']):
""" Checks which smiles
Args:
smile: (str) smiles string
allowed_chars: (lst) list of all... | 55,067 |
def parse_config_vars(config_vars):
"""Convert string descriptions of config variable assignment into
something that CrossEnvBuilder understands.
:param config_vars: An iterable of strings in the form 'FOO=BAR'
:returns: A dictionary of name:value pairs.
"""
result = {}
for val... | 55,068 |
def create_detections(detection_mat, frame_idx):
"""Create detections for given frame index from the raw detection matrix.
Parameters
----------
detection_mat : ndarray
Matrix of detections. The first 10 columns of the detection matrix are
in the standard MOTChallenge detection format. ... | 55,069 |
def GetFileSystemDebug(path: str, run_ps: bool = True) -> FileSystemDebugInfo:
"""Collect filesystem debugging information.
Dump some information to help find processes that may still be sing
files. Running ps auxf can also be done to see what processes are
still running.
Args:
path: Full path for direc... | 55,070 |
def q_values(state, actions, weights, xf_vec):
"""
Calculate q values for current state and actions
Parameters
----------
state : tuple
current state-
actions : ndarray
possible actions-
weights : ndarray
weights of linear function approximation-
xf_vec : list
... | 55,071 |
def _get_parsed_args():
"""Parses command line arguments and the config file.
Order of precedence for config values is: command line > config file values > defaults
Returns:
A "Namespace" object. See argparse.ArgumentParser.parse_args() for more details.
"""
parser = configargparse.Argume... | 55,072 |
def do_disk_delete(client, args):
""" Delete a virtual disk """
disk = client.disks.delete(args.id)
utils.print_dict(disk) | 55,073 |
def test_service_plan_put_not_supported(api_request):
"""Test to put ServicePlan endpoint"""
service_plan = InventoryServicePlanFactory()
response = api_request(
"put",
"inventory:inventoryserviceplan-detail",
service_plan.id,
{"name": "update"},
)
assert response.s... | 55,074 |
def sniff(start, data):
"""
Given the first byte (start) and an unspecified (maybe not all) amount of
a FASTA or FASTQ, return summary statistics.
"""
# scan through the file and get ids/seq_counts (and quality info)
if start == '>':
seq_count, ids, status = read_fasta(data)
elif sta... | 55,075 |
def is_power_of_two(x):
# type: (int) -> bool
"""Check if `x` is a power of two:
>>> is_power_of_two(0)
False
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(3)
False
"""
return x > 0 and x & (x-1) == 0 | 55,076 |
def link_account(external_id, community, platform_type, platform_identifier, community_platform_id=None,
custom_data=None, link_type=None, link_quality=None):
"""Links a new platform account to an existing user, as specified by their external metagov id."""
metagovID = MetagovID.objects.get(external_id=ext... | 55,077 |
def create_client(connectionSocket, id_num, clients, available_clients, blocklist):
"""Manage client's behavior"""
while 1:
msg = connectionSocket.recv(1024).decode()
if msg[:8] == '/unblock' and msg[9:] in clients and msg[9:] != id_num and msg[9:] in blocklist[id_num]:
blocklist[id_... | 55,078 |
def validate_jwt(scope, request, on_error=None):
"""
Validate the incoming JWT token, don't allow access to the endpoint unless we pass this test
:param scope: A list of scope identifiers used to protect the endpoint
:param request: The incoming request object
:param on_error: The error structure
... | 55,079 |
def cartesian(tensor1, tensor2):
"""
Computes the pair-wise combinations of first dimensions of
tensor1 and tensor2, leaving the last dimension.
"""
# exclude last dimension
*shape1, last1 = shape(tensor1)
*shape2, last2 = shape(tensor2)
if last1 != last2:
raise ShapeError(
... | 55,080 |
def add_malicious_key(entity, verdict):
"""Return the entity with the additional 'Malicious' key if determined as such by ANYRUN
Parameters
----------
entity : dict
File or URL object.
verdict : dict
Task analysis verdict for a detonated file or url.
Returns
-------
dic... | 55,081 |
def run (args, out=None) :
"""
Calculates number of non-bonded atoms overlaps in a model
prints to log:
When verbose=True the function print detailed results to log
When verbose=False it will print:
nb_overlaps_macro_molecule,
nb_overlaps_due_to_sym_op,
nb_overlaps_all
Args:
... | 55,082 |
def lock_dir(folder: PathLike = '.', lock: str = '.lock'):
"""
Lock the given ``folder`` by generating a special lock file - ``lock``.
Raises
------
FileExistsError: if ``lock`` already exists, i.e. the folder is already locked.
"""
lock = Path(folder) / lock
if lock.exists():
r... | 55,083 |
def _decrypt(cipher, key, data, iv, padding):
"""
Decrypts AES/RC4/RC2/3DES/DES ciphertext
:param cipher:
A kSecAttrKeyType* value that specifies the cipher to use
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The ciphertext - a byte string
... | 55,084 |
def pieColor(renderer, x, y, rad, start, end, color):
"""Draws an unfilled pie slice (i.e. circle segment) to the renderer.
The start and end of the pie are defined in units of degrees, with 0 being
the bottom of the circle and increasing counter-clockwise (e.g. 90 being
the rightmost point of the circ... | 55,085 |
def assimilate(left: pd.DataFrame, right: pd.DataFrame):
"""Assimilate ``right`` to look like ``left`` by casting column data types in ``right``
to the data types in ``left`` where the column name is the same.
:param left: left DataFrame
:param right: right DataFrame
"""
# give me all the eleme... | 55,086 |
def fix_armature_scale(armature_object, scale_factor, context, properties):
"""
This function scales the provided armature object and it's animations.
:param object armature_object: A object of type armature.
:param float scale_factor: The amount to scale the control rig by.
:param dict context: A ... | 55,087 |
def remove(property_name):
"""
Removes the given property.
:param property: The property (or property identifier) to remove
:type property: Host Specific
:return: True if the property was removed
"""
return None | 55,088 |
def get_locality(row_dict):
"""
Fetch the corresponding locality object for an occurrence and create a new one if necessary.
:param row:
:return locality_object:
"""
# Validate and build locality text
basis_of_record = row_dict['basis_of_record']
collection_code = row_dict['collection_c... | 55,089 |
def should_generate_badge(output, color, result):
"""Detect if existing badge needs updating.
This is to help avoid unnecessary newline updates. See
https://github.com/econchick/interrogate/issues/40
.. caution::
A badge will always be generated for PNG format.
.. versionadded:: 1.3.1 Fu... | 55,090 |
def set_normal_state(display, window):
"""
:type display: Display
:type window: Window
"""
change_state(display, window, Xutil.NormalState) | 55,091 |
def process_sentence(sentence) :
"""
Parameters
----------
sentence : a string of words
Returns
-------
clean_sentence : a string of words without having the unessasry words
"""
stemmer = PorterStemmer()
stopwords_english = stopwords.words('english')
# ... | 55,092 |
def scheduler_init_data(tangerine_state=None, scratch=False):
""" Creates a testmodule in the building state with all the components in the same batch
"""
clean_database()
mmd = load_mmd(read_staged_data("formatted_testmodule"))
mmd.get_rpm_component("tangerine").set_buildorder(0)
module_build... | 55,093 |
def make_js_get_color(color, use_time=False):
"""Converts color field or value to JS string for processing in browser
Arguments: color (`str`, `list` of `float`, or `slayer.ColorScale`): If string,
a hex value for the color all visualized items in the layer should have.
If a... | 55,094 |
def count_terms(terms: list) -> dict:
"""
Count the number of terms
:param terms: term list
:return dict_term: The dictionary containing terms and their numbers
"""
entity_dict = dict(Counter(terms))
print('There are %s entities in total.\n' % entity_dict.__len__())
# print({key: value f... | 55,095 |
def augmented_system_projections(A, m, n, orth_tol, max_refin, tol):
"""Return linear operators for matrix A - ``AugmentedSystem``."""
# Form augmented system
if A.size != 0:
K = np.block([[np.eye(n), A.T], [A, np.zeros((m,m))]])
else:
K = np.eye(n)
# LU factorization
# z = x - ... | 55,096 |
async def export_from_json_file(framework: Frameworks,
architecture_file: bytes = File(..., alias='architecture-file'),
line_break: LineBreaks = LineBreaks.lf,
indent: Indents = Indents.spaces_4,
... | 55,097 |
def display(s):
"""display(s)
Display a spectrum in the spectrum plot window. This method takes care of converting internal spectra into ScriptableSpectra as necessary."""
if isinstance(s, list) or isinstance(s, tuple):
for ss in s:
display(ss)
else:
DataManager.addSpectrum((s.getWra... | 55,098 |
def test_linked_identities(run_line, load_api_fixtures):
"""
Confirms --linked-identities sees foo2
"""
data = load_api_fixtures("foo_user_info.yaml")
username = data["metadata"]["username"]
linked_usernames = [x["username"] for x in data["metadata"]["linked_ids"]]
result = run_line("globus... | 55,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.