content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _check_model_fields(
field_matrix, field_name, pressure_level_pascals, valid_times_unix_sec):
"""Checks model fields for errors.
M = number of rows (unique grid-point y-coordinates)
N = number of columns (unique grid-point x-coordinates)
T = number of time steps
:param field_matrix: T-... | 5,286,200 |
def _exception_to_dict(exception):
"""Convert exception to an error object to be sent as response to APIs."""
return {"error": {"type": type(exception).__name__,
"message": exception}} | 5,286,201 |
def get_depth_prediction(
depth_logits: torch.Tensor,
use_dgc_scaling: bool,
camera_matrix: torch.Tensor = None,
real_camera_height: torch.Tensor = None,
panoptic_seg: torch.Tensor = None,
road_class_id: int = -1,
depth_filter_class_ids: List[int] = None,
):
"""
Post-processing for d... | 5,286,202 |
def sync_wait_and_get_s3_object(
uri: Optional[str]=None,
bucket: Optional[str]=None,
key: Optional[str]=None,
sess: Optional[boto3.session.Session]=None,
region_name: Optional[str]=None,
max_wait_seconds: float=DEFAULT_S3_OBJECT_WAIT_TIMEOUT_SECONDS, # -1 for infinite wait
pol... | 5,286,203 |
def test_eviction_node_split():
"""
active nodes (replying in time) should not be evicted
"""
proto = get_wired_protocol()
proto.routing = routing_table(1000) # set lpw, so we'll split
wire = proto.wire
# get a full bucket
full_buckets = [b for b in proto.routing.buckets if b.is_full a... | 5,286,204 |
def tanks():
"""
The Tank List or Create API Endpoint
GET: List Dealer Tanks
POST: Create New Tank
:return: list or pk
"""
id = get_dealer(current_user.id)
if request.method == 'GET':
pass
elif request.method == 'PUT':
pass | 5,286,205 |
def load_temporal_data(resource_dir):
"""Load preprocessed temporal information about when an account has edited."""
app.logger.info("Loading temporal data")
expected_header = ["user_text", "day_of_week", "hour_of_day", "num_edits"]
with open(os.path.join(resource_dir, "temporal.tsv"), "r") as fin:
... | 5,286,206 |
def test_sineWave_disp_rotation_invariance(comm, pnp, nx, ny, basenpoints):
"""
for a sinusoidal displacement, test if the energy depends on if the wave is
oriented in x or y direction
Parameters
----------
comm
pnp
fftengine_class
nx
ny
basenpoints
Returns
-------
... | 5,286,207 |
def compute_validation_summary(ot_model, day_pairs_triplets=None, save_interpolated=False,
interp_size=10000, compute_full_distances=False):
"""
Compute the validation summary for the given OTModel
Parameters
----------
ot_model : wot.OTModel
The OTModel to va... | 5,286,208 |
def read_ceps_test(test_file):
"""
Reads the MFCC features from disk and
returns them in a numpy array.
"""
X = []
y = []
ceps = np.load(test_file)
num_ceps = len(ceps)
X.append(np.mean(ceps[int(num_ceps / 10):int(num_ceps * 9 / 10)], axis=0))
return np.array(X), np.array... | 5,286,209 |
def dict_to_object(dictionary):
"""
parse a dictionary and return a dynamic object
:param dictionary: dict
:return: dynamic_object
"""
obj = DynamicClass()
for key in dictionary:
setattr(obj, key, dictionary[key])
return obj | 5,286,210 |
def batchify(fn, chunk):
"""
Constructs a version of 'fn' that applies to smaller batches.
"""
if chunk is None:
return fn
def ret(inputs):
return torch.cat([fn(inputs[i:i + chunk]) for i in range(0, inputs.shape[0], chunk)], 0)
return ret | 5,286,211 |
def log_loss(y, p):
""" Compute the log loss by tensorflow from binary truth and predicted score
Parameters
----------
y:
The binary truth: 0 or 1
p:
The predicted score in [0, 1]
Returns
-------
the value of the log loss
"""
return -( y*log(p) + (1-y)*log(1-p) ... | 5,286,212 |
def cleanstrings(df, columns, stringmaps, unmapped=None, simplify=True):
"""Consolidate freeform strings in several dataframe columns.
This function will consolidate freeform strings found in `columns` into
simplified categories, as defined by `stringmaps`. This is useful when
a field contains many dif... | 5,286,213 |
def get_tst_loader(
data_dir: str,
batch_size: int,
shuffle: bool = True,
num_workers: int = 4,
pin_memory: bool = False,
):
"""
Utility function for loading and returning a multi-process
test iterator over the CIFAR-100 dataset.
If using CUDA, num_workers should be set to 1 and pin_... | 5,286,214 |
def _any_none(*args):
"""Returns a boolean indicating if any argument is None"""
for arg in args:
if arg is None:
return True
return False | 5,286,215 |
def precision(judged_data):
"""
Our relevance judgments are on a graded scale of 0-3, where scores of 1-3 are considered
relevant, and less than 1 is irrelevant. We compute precision of the result set based on
this quanitization.
Args:
judged_data (pandas.DataFrame): A DataFrame with at a m... | 5,286,216 |
def filter_cycles(cycle_list, **filters):
"""Puts cycles through filters to meet specific requirements.
cycle_list is a list of tuples where the first item is an intake and
the second action is a placement or drop.
filters are the specifications that certain data points inside the
cycles must fit t... | 5,286,217 |
def ansi_escape(text):
"""
Replace characters with a special meaning.
"""
return text.replace('\x1b', '?').replace('\b', '?') | 5,286,218 |
def ajax_get_commandes(request):
"""
This view comes before the feature of sending mass mails to customers. It goes up the number of customers selected by status.
"""
if request.method == 'POST':
try:
event = request.POST.get('event').split(',') if request.POST.get('event').split(',... | 5,286,219 |
def global_counter() -> int:
""" A really dumb global counter.
This is useful for giving output files a unique number, so if we run the
same command multiple times we can keep their output separate.
"""
global _global_counter
_global_counter += 1
return _global_counter | 5,286,220 |
def _GetAndroidVersionFromMetadata(metadata):
"""Return the Android version from metadata; None if is does not exist.
In Android PFQ, Android version is set to metadata in master
(MasterSlaveLKGMSyncStage).
"""
version_dict = metadata.GetDict().get('version', {})
return version_dict.get('android') | 5,286,221 |
def render(engine: str,
format: str,
filepath: typing.Union[os.PathLike, str],
renderer: typing.Optional[str] = ...,
formatter: typing.Optional[str] = ...,
quiet: bool = ..., *,
outfile: typing.Union[os.PathLike, str, None] = ...,
raise_if_res... | 5,286,222 |
def files(path=None):
"""
Function that prints list of files and their last modified date
:param path: path to the directory
:return: nothing to return
"""
files = get_files(path)
for file_ in files:
print(f"{file_['name']}\t Last Modified: {file_['date_str']}") | 5,286,223 |
def identify(disc, logfile):
"""Identify disc attributes"""
logging.info("Starting disc dentification: " + str(disc))
# If UDF CHeck is on
# if cfg['ARM_CHECK_UDF']:
logging.info("Mounting disc to: " + str(disc.mountpoint))
if not os.path.exists(str(disc.mountpoint)):
os.makedirs(str... | 5,286,224 |
def get_in(d, t, default=None):
"""
look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {}
"""
result = reduce(lambda d, t: d.get(t, {}), t, d)
if resul... | 5,286,225 |
def visualize_dumped_camera_parameter(dumped_dir: str,
interactive: bool = True,
show: bool = True):
"""Visualize all cameras dumped in a directory.
Args:
dumped_dir (str):
Path to the directory.
interactive... | 5,286,226 |
def test_capture_output_no_stderr():
"""test capture_output(stderr=False)"""
rich = capture.RichOutput(data=full_data)
# add nested capture_output so stderr doesn't make it to nose output
with capture.capture_output(), capture.capture_output(stderr=False) as cap:
print(hello_stdout, end="")... | 5,286,227 |
def prev(expr, **kwargs):
"""
sympy preview abbreviation
"""
KWargs = {'output':'pdf'}
KWargs.update(kwargs)
sp.preview(expr, **KWargs) | 5,286,228 |
def update_health_check(HealthCheckId=None, HealthCheckVersion=None, IPAddress=None, Port=None, ResourcePath=None, FullyQualifiedDomainName=None, SearchString=None, FailureThreshold=None, Inverted=None, Disabled=None, HealthThreshold=None, ChildHealthChecks=None, EnableSNI=None, Regions=None, AlarmIdentifier=None, Insu... | 5,286,229 |
def divisible_by_five(n: int) -> bool:
"""Return True if an integer is divisible by 5, and false otherwise."""
if n % 5 > 0:
return False
return True | 5,286,230 |
def saveJSON(g, data, backup=False):
"""
Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't prompt for filename
"""
... | 5,286,231 |
def get_imaging_root_data_dir() -> str:
"""
get_imaging_root_data_dir() -> str
Retrieve the root data directory - e.g. containing all subject/sessions data
:return: a string for full path to the root data directory
"""
return _linking_module.get_imaging_root_data_dir() | 5,286,232 |
def _input_is_valid(
dataset: np.ndarray, predictive_model: object, as_probabilistic: bool,
categorical_indices: Union[None, List[Index]],
class_names: Union[None, List[str]], classes_number: Union[None, int],
feature_names: Union[None, List[str]],
unique_predictions: Union[None,... | 5,286,233 |
def cvPtr1D(*args):
"""cvPtr1D(CvArr arr, int idx0, int type=None) -> uchar"""
return _cv.cvPtr1D(*args) | 5,286,234 |
def _should_package_clang_runtime(ctx):
"""Returns whether the Clang runtime should be bundled."""
# List of crosstool sanitizer features that require packaging some clang
# runtime libraries.
features_requiring_clang_runtime = {
"asan": True,
"tsan": True,
"ubsan": True,
}
... | 5,286,235 |
def round_nearest_towards_infinity(x, infinity=1e+20):
""" Rounds the argument to the nearest integer.
For ties like 1.5 the ceiling integer is returned.
This is called "round towards infinity"
Args:
x: the value to round
infinity: the model's infinity value. All values above i... | 5,286,236 |
def json_schema(request, ref: str):
"""Return a JSON Schema for a given reference."""
if ref not in SCHEMA_REFS:
return HttpResponseBadRequest("Unknown ref")
return SCHEMA_REFS[ref].schema_json(indent=2) | 5,286,237 |
def emprestimo(id):
"""
Deleta uma reserva e gera um empréstimo.
Certifica que a reserva existe.
Atualiza o status do livro para emprestado
"""
reserva = get_reserva(id)
try:
livro = db.query_one('select * from livro where tombo = %s' % reserva['tombo'])
print(livro)
... | 5,286,238 |
def saveImage(img_dirs, mid_name, image):
"""
保存图像
img_dirs:保存目录
mid_name:新保存图片后缀
image:图像
"""
basename = os.path.basename(img_dirs)
file = os.path.splitext(basename)
file_prefix = file[0]
suffix = file[-1]
image_file = os.path.join("\\".join(img_dirs.split("\\")[:-1]), file_... | 5,286,239 |
def main():
"""
main process
"""
q = Queue()
plist = []
for i in range(4):
proc = Process(target=process, args=(q,))
plist.append(proc)
for proc in plist:
proc.start()
for proc in plist:
proc.join()
while True:
if q.empty():
print "... | 5,286,240 |
def update_cache_needed(filenames, cachefile=None):
"""Returns True if the cache file needs to be updated.
:param filenames:
:param cachefile: (Default value = None)
"""
for filename in filenames:
if cachefile is None:
current_cachename = cache_file(filename)
else:
... | 5,286,241 |
def intersection(line1, line2):
"""Finds the intersection of two lines given in Hesse normal form.
Returns closest integer pixel locations.
See https://stackoverflow.com/a/383527/5087436
"""
rho1, theta1 = line1[0]
rho2, theta2 = line2[0]
A = np.array([
[np.cos(theta1), np.sin(theta... | 5,286,242 |
def make_kwargs(proxy_info: ProxyInfo, *, nosave: bool = False,
**kwargs: Any) -> Dict[str, Any]:
"""Form the proxy kwargs for requests or urllib
:param proxy_info: ProxyInfo
a namedtuple of the form
(server: str, port: int, domain: str, usr: str?)
:param nosave: bool
... | 5,286,243 |
def get_moonboard(year: int) -> MoonBoard:
"""
Factory function. Given a year, return a Moonboard object encapsulating the
Moonboard layout info of that year.
:param year: Year of the desired Moonboard layout
:type year: int
:return: Moonboard object encapsulating the Moonboard layout info
... | 5,286,244 |
def test_get_gradeable_submissions(mock_base_req, test_app):
""" Tests if gradable submissions filters the correct values """
mock_values = [
{'id': 1, 'assignment_id': 1, 'name': 'kmom01'},
{'id': 2, 'assignment_id': 2, 'name': 'kmom02'},
{'id': 3, 'assignment_id': 3, 'name': 'kmom03'}
... | 5,286,245 |
def model_to_estimator(model):
"""given a model , return a estimator"""
tf=model.copy()
tp=type(tf)
from1=re.search(r'(pyspark.*)\.',str(tp)).group(1)
from2=re.search(r'(pyspark.*)\.(\w+)',str(tp)).group(2)
from2=re.sub(pattern='DecisionTreeRegressionModel', repl='DecisionTreeRegressor', string=... | 5,286,246 |
def sdc_pandas_series_operator_mod(self, other):
"""
Pandas Series operator :attr:`pandas.Series.mod` implementation
Note: Currently implemented for numeric Series only.
Differs from Pandas in returning Series with fixed dtype :obj:`float64`
.. only:: developer
**Test**: python -m sdc.run... | 5,286,247 |
def regex_chomp(regex, state, tracker):
"""
:param regex: regex object to match with
:param state: ChompState
:param tracker: FroParseErrorTracker
:return: Match object of regex match, or throws ChompError
"""
line = state._curr # state.current()
index = state._column # state.column()
... | 5,286,248 |
def create_html_popup(friends: list) -> str:
"""creates html popup for markrer
Args:
friends (list): list of names
Returns:
str: html in string format
"""
html_template = "Friends:"
for friend in friends:
html_template += f"""<br>
<p>{friend}</p><br>
"""... | 5,286,249 |
def collect_radolan_data(
date_times: List[datetime],
time_resolution: TimeResolution,
prefer_local: bool = False,
write_file: bool = False,
folder: Union[str, Path] = DWD_FOLDER_MAIN,
) -> List[Tuple[datetime, BytesIO]]:
"""
Function used to collect RADOLAN data for given datetimes and a ti... | 5,286,250 |
def testSetUp(test):
"""
install test packages so that they can be imported
and their egg info examined in test runs
"""
testing.buildoutSetUp(test)
import tempfile
target_dir = tempfile.mkdtemp('.z3c.autoinclude.test-installs')
install_projects(test_packages, target_dir) | 5,286,251 |
def SetFlags(ea, flags):
"""
Set new value of flags
This function should not used be used directly if possible.
It changes properties of a program byte and if misused, may lead to
very-very strange results.
@param ea: adress
@param flags: new flags value
"""
return idaapi.... | 5,286,252 |
def evaluate(ts, not_found_list):
"""
The function evaluates the embeddings. It gets a folder name as input. If embeddings are generated by the triplet model,
the input folder name is a time stamp.
The function then reads all the image level embedding csv files within that folder. Normally, there shoul... | 5,286,253 |
def createMiddleWare(app, exporter):
"""
Configure a flask middleware that listens for each request and applies automatic tracing.
This needs to be set up before the application starts.
:param app: WSGI application
:param exporter: Exporter instance object (StackdriverExporter)
:return:
"""
... | 5,286,254 |
def other():
"""
Note to contributors:
Other signal-to-noise masks must be named with the author or method
name. If already published, the full citation must be provided. Please,
add "unpub." otherwise. E.g: Smith et al. (unpub.)
Please, check contribute.md to follow ... | 5,286,255 |
def period_range(start: Literal["2000"], periods: int, freq: Literal["W"]):
"""
usage.statsmodels: 1
"""
... | 5,286,256 |
def get_long_description() -> str:
"""Extract the content of the sdk/README.md and replace relative links when
running `python3 setup.py sdist`. Return the abbreviated LONG_DESCRIPTION when
running `pip install .`
:return: long_description, Github flavored Markdown from the sdk/README.md
"""
if... | 5,286,257 |
def euler_step(theta,dtheta,ddtheta,dt):
"""
Euler Step
Parameters
----------
theta (tf.Tensor):
Joint angles
(N,nq)
dtheta (tf.Tensor):
Joint velocities
(N,nq)
ddtheta (tf.Tensor):
Joint accelerations
(N,nq)
dt (float):
Delta t
... | 5,286,258 |
def get_cif(ams_id):
"""
get CIF Structure by AMS ID
"""
db = get_amscifdb()
return db.get_cif(ams_id) | 5,286,259 |
def generate_scheme_caps(metadata_define, metadata_request, arguments, pset_schemes, ccpp_field_maps, caps_dir):
"""Generate scheme caps for all schemes parsed."""
success = True
# Change to caps directory
os.chdir(caps_dir)
# List of filenames of scheme caps
scheme_caps = []
for module_name... | 5,286,260 |
def no_xray_disturbance(nodist,hole):
"""
takes an archive measurement DataFrame and removes disturbed intervals using XRAY disturbance files
Parameters
__________
nodist : Pandas DataFrame
data frame filtered by iodp_funcs.remove_disturbance
hole : str
IODP hole
Return... | 5,286,261 |
def git_diff_files(oldrev, newrev):
"""Get list of files in diff."""
files_modified = subprocess.check_output(["git",
"diff",
"--name-only",
oldrev + ".." + newrev])
retu... | 5,286,262 |
def beta1() -> float:
"""Mock beta1."""
return 0.9 | 5,286,263 |
def dhcp_relay_show(dut, family="ipv4", interface=None, cli_type=""):
"""
API to show the DHCP relay brief output
Author Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:return:
"""
cli_type = st.get_ui_type(dut, cli_type=cli_type)
if cli_type in ['click', 'klish']:
... | 5,286,264 |
def split_condition_code(tree, fields, field, depth,
pre_condition, term_analysis_fields,
item_analysis_fields, cmv):
"""Condition code for the split
"""
predicate = get_predicate(tree)
optype = fields[field]['optype']
operator = PYTHON_OPERATOR[pre... | 5,286,265 |
def get_cases_country(path: str) -> List[int]:
"""
Counts the number of cases based on the COUNTRIES for the parameter of interest.
Arguments:
path {str} -- path to the dataset csv file for the parameter of interest
Returns:
List[int] -- an ordered list of the number of cases for each country
"""
# load t... | 5,286,266 |
def tf_optimize(inputs, outputs, graph_def, fold_constant=None):
"""Optimize tensorflow graph for inference."""
transforms = []
if fold_constant:
transforms.extend([
"fold_constants(ignore_errors=true)",
"remove_attribute(attribute_name=_class)", # remove node colocation att... | 5,286,267 |
def list_bootstrap_actions(ClusterId=None, Marker=None):
"""
Provides information about the bootstrap actions associated with a cluster.
See also: AWS API Documentation
:example: response = client.list_bootstrap_actions(
ClusterId='string',
Marker='string'
)
:... | 5,286,268 |
def parse_mask(line):
""" parses the string formated as the PASCAL pixel mask annotation
e.g. Pixel mask for object 1 "PASpersonWalking" :
"PennFudanPed/PedMasks/FudanPed00001_mask.png"
line: string
line in the PASCAL annotation file with mask information
returns: ... | 5,286,269 |
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""Program description""")
parser.add_argument(
"input",
type=is_dir,
action=FullPaths,
help="""The path to a directory of PHYLIP-formatted alignments."""
... | 5,286,270 |
def parse_assignments(lines, lineNo=0, input_vars=None):
"""
Parse given `lines` as an assignment title and either single oder double lines of assignments.
A single line of assignment is "<var> = <value[;]".
A double line of assignment is "<var> =\n<value>[;]".
:param lines: array of strings to be ... | 5,286,271 |
def delete_node_layout(node_id):
"""
API entry point to delete the layout for a node.
"""
return node_layout.delete_node_layout(node_id) | 5,286,272 |
def _create_nodes_map(
graph_dict: Dict[str, Dict[str, PCollection]]
) -> PCollection[Tuple[NodeId, Node]]:
"""Create a map from Node ID to Node from the given `graph_dict`.
Args:
graph_dict: The map returned from a `unigraph` graph reading.
Returns:
A collection of all the nodes, keyed by their uni... | 5,286,273 |
def generatePosSeqList(length):
""" Generates HALF of the possible weaves of a given length or less """
posSeqList = [] # list that will contain the generated weaves
curSeq = [0]*int(length//2) # We devide by 2 as the sigmas have pair powers
endSeq = [4]*int(length//2)
while curSeq != end... | 5,286,274 |
def prepare_script_args(spec):
"""
Uses the default script args if those items are not specified for
the script.
Args:
spec (dict): Script args to modify with defaults as needed.
Returns:
dict: Modified dictionary with values as needed.
"""
spec['run_in'] = spec.pop... | 5,286,275 |
def period_range(start: Literal["1959Q1"], end: Literal["2009Q3"], freq: Literal["Q"]):
"""
usage.statsmodels: 1
"""
... | 5,286,276 |
def fetch_MEN(which="all", form="natural"):
"""
Fetch MEN dataset for testing similarity and relatedness
Parameters
----------
which : "all", "test" or "dev"
form : "lem" or "natural"
Returns
-------
data : sklearn.datasets.base.Bunch
dictionary-like object. Keys of interes... | 5,286,277 |
def plot_p4m(f, fignum=None, rlabels='cayley_mr', rcolor='red', mcolor='blue', rlinestyle='-', mlinestyle='-',
fontsize=20, labelpad_factor_1=1.5, labelpad_factor_2=1.5, labelpad_factor_3=2.5, labelpad_factor_4=2.5,
figsize=(3, 3)):
"""
Plot a function f : p4m -> R or f : p4m -> R^... | 5,286,278 |
def custom_payload(claims, expiration):
"""
Creates JWT payload.
Author:
Lucas Antognoni
Arguments:
claims (list): Token payload claims.
expiration (datetime.timedelta): Timedelta.
Response:
payload (dict): JWT payload.
... | 5,286,279 |
def save_checkpoint(
train_state: train_states.TrainState,
checkpoint_dir: str,
overwrite: bool = False,
unreplicate: bool = True,
checkpoint_type: CheckpointType = CheckpointType.CHECKPOINT_FLAX,
state_specs: Optional[train_states.TrainState] = None,
) -> None:
"""Saves a checkpoint into the ... | 5,286,280 |
def b64s_to_s(b64s: str) -> str:
"""convert base 64 strting to string
:param b64s: input base 64 string
:type b64s: str
:return: output string
:rtype: str
"""
s = base64.b64decode(b64s.encode('utf8')).decode('utf8')
return s | 5,286,281 |
def test_utilities(app, models_fixture):
"""Test utilities."""
datastore = app.extensions['invenio-accounts'].datastore
assert obj_or_import_string('invenio_oauthclient.errors')
# User
existing_email = 'existing@inveniosoftware.org'
user = datastore.find_user(email=existing_email)
# Authen... | 5,286,282 |
def solve_tsp_dynamic_programming(
distance_matrix: np.ndarray,
maxsize: Optional[int] = None,
) -> Tuple[List, float]:
"""
Solve TSP to optimality with dynamic programming.
Parameters
----------
distance_matrix
Distance matrix of shape (n x n) with the (i, j) entry indicating the
... | 5,286,283 |
def get_c_files(path):
# type: (str) -> List[str]
"""Get C/C++ files in the path"""
return [f for f in os.listdir(path)
if os.path.splitext(f)[1] in ['.c', '.cc', '.cpp']] | 5,286,284 |
def unify (a, b):
"""Unify the two types a and b"""
(a, b) = (a.prune (), b.prune ())
if isinstance (a, Var):
a.unify (b)
else:
b.unify (a) | 5,286,285 |
def rename_dict_keys(dic: Dict, changes: Dict[str, str]):
"""Rename dict keys. Inplace."""
for old, new in changes.items():
dic[new] = dic.pop(old) | 5,286,286 |
def counter(data, n=None):
"""counter方法用于统计元素数量
Parameters
----------
data : list
列表数据
n : int
前n个元素
Returns
----------
"""
ret = Counter(data)
if not n:
ret = ret.most_common(len(ret))
else:
ret = ret.most_common(n)
return ret | 5,286,287 |
def col255_from_RGB(red,green,blue):
""" returns a term256 colour index from RGB value
found at :
https://unix.stackexchange.com/questions/269077/
"""
if red > 255:
red = 255
if green > 255:
green = 255
if blue > 255:
blue = 255
if red < 75:
red = 0... | 5,286,288 |
def save_plot(pcds, dimension, save_path):
"""
Input should be either numpy.ndarray of torch.tensor
Dimension should be specified with str ('2d', '3d')
"""
if pcds[0].dtype == torch.float:
for (i, pcd) in enumerate(pcds):
pcds[i] = pcd.detach().cpu().numpy()
fig = plt.figure... | 5,286,289 |
def first_or_default(iterable, predicate=None, default=None):
"""First the first value matching a perdicate otherwise a default value.
:param iterable: The items over which to iterate.
:param predicate: A predicate to apply to each item.
:param default: The value to return if no item matches.
:retu... | 5,286,290 |
def bin_bp_sparse(M, positions, bin_len=10000):
"""
Perform binning with a fixed genomic length in
base pairs on a sparse matrix. Fragments will be binned such
that their total length is closest to the specified input.
If a contig list is specified, binning will be performed
such that fragments ... | 5,286,291 |
def process_date(date):
"""
Returns a dictionary with all of the below processes completed,
which can then be imported directly to CalendarDate model.
"""
metadata = {}
metadata["calendar_date"] = date
metadata["calendar_day"] = get_calendar_day(date)
metadata["calendar_month"] = get_ca... | 5,286,292 |
def pulse(
force_field, in_basename, basename, n_step, pulse_fn,
n_step_per_pulse=100, restraint_pdb="", restraint_force=None):
"""
Runs a pulse simulation that uses the restart-file modification
strategy to manage a steered-molecular dynamics simulation.
The pulsed approacha pplies external forces in... | 5,286,293 |
def segment_3D_legacy(fpath, verbose=False,
params={'median_size' : 3,
'thresh_stepsize' : 2,
'thresh_lower' : 4.0,
'clean_small' : 1000,
'clean_big' : 1000000,
... | 5,286,294 |
def until(timeout=10, step=0.5, action=None, silent=False):
"""Yield until timeout"""
yield
started = time.time()
while True:
if action and not silent:
log.info(action)
if time.time() - started > timeout:
if action and not silent:
log.error("Time... | 5,286,295 |
def image_md(image_location, caption="", link=None, tooltip=""):
"""
Returns the html code for the individual plot
"""
image = f"""
<a href="{link}" name="gallery-href">
<img src="{image_location}" name="gallery-image" alt="{tooltip}"
style="width:100%" id="{"".join(image_location.split("-... | 5,286,296 |
def unpacker(*args, **kwargs):
"""Return a MessagePack (with extended types support) Unpacker object."""
return msgpack.Unpacker(*args, ext_hook=_decode_ext_type, raw=False, **kwargs) | 5,286,297 |
def clean_directory(directory, patterns=None):
"""Clean up all generated files from other commands."""
if not patterns:
patterns = [
'dist',
'build',
'.tox',
'*.egg-info',
'*.egg',
'wheelhouse',
'__pycache__',
... | 5,286,298 |
def main(dsList0, dsList1, outputdir, verbose=True):
"""Generate a scatter plot figure."""
#plt.rc("axes", labelsize=24, titlesize=24)
#plt.rc("xtick", labelsize=20)
#plt.rc("ytick", labelsize=20)
#plt.rc("font", size=20)
#plt.rc("legend", fontsize=20)
dictFunc0 = dsList0.dictByFunc()
... | 5,286,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.