content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def st_oid(draw, max_value=2**512, max_size=50):
"""
Hypothesis strategy that returns valid OBJECT IDENTIFIERs as tuples
:param max_value: maximum value of any single sub-identifier
:param max_size: maximum length of the generated OID
"""
first = draw(st.integers(min_value=0, max_value=2))
... | 36,300 |
def predict(model, image_pth=None, dataset=None):
"""
Args:
model : model
image (str): path of the image >>> ".../image.png"
dataset [Dataset.Tensor]:
Returns:
--------
predicted class
"""
transform = transforms.Compose([
transforms.Resize([28, 28]),
... | 36,301 |
def to_centers(sids):
""" Converts a (collection of) sid(s) into a (collection of) trixel center longitude, latitude pairs.
Parameters
----------
sids: int or collection of ints
sids to covert to vertices
Returns
--------
Centers: (list of) tuple(s)
List of centers. A cente... | 36,302 |
def get_atlas_by_id(atlas_id: str, request: Request):
"""
Get more information for a specific atlas with links to further objects.
"""
for atlas in siibra.atlases:
if atlas.id == atlas_id.replace('%2F', '/'):
return __atlas_to_result_object(atlas, request)
raise HTTPException(
... | 36,303 |
def gen_header_types(out, schema):
"""
Generates the types in the header file.
"""
#
# The list of types to generate is currently hard-coded below to match
# exactly with the legacy version produced by the C# tool. We can later
# make it shorter by iterating only on the top-level types (gen... | 36,304 |
def load_etod(event):
"""Called at startup or when the Reload Ephemeris Time of Day rule is
triggered, deletes and recreates the Ephemeris Time of Day rule. Should be
called at startup and when the metadata is added to or removed from Items.
"""
# Remove the existing rule if it exists.
if not d... | 36,305 |
def extract_title(html):
"""Return the article title from the article HTML"""
# List of xpaths for HTML tags that could contain a title
# Tuple scores reflect confidence in these xpaths and the preference
# used for extraction
xpaths = [
('//header[@class="entry-header"]/h1[@class="entry-ti... | 36,306 |
def re_send_mail(request, user_id):
"""
re-send the email verification email
"""
user = User.objects.get(pk=user_id)
try:
verify = EmailVerify.objects.filter(user = user).get()
verify.delete()
except EmailVerify.DoesNotExist:
pass
email_verify = EmailVerify(user=... | 36,307 |
def get_snap_filenames(base, snap_prefix, num):
"""Return a list of paths (without file extensions) to snapshot files
corresponding to the snapshot indicated by num. The list may consist of
one or multiple files, depending on how the snapshot was written.
"""
num_pad = str(num).zfill(3)
path = ... | 36,308 |
def apply_playbook(playbook_path, hosts_inv=None, host_user=None,
ssh_priv_key_file_path=None, password=None, variables=None,
proxy_setting=None, inventory_file=None, become_user=None):
"""
Executes an Ansible playbook to the given host
:param playbook_path: the (relati... | 36,309 |
def test_list_projects(mocker):
"""Test projects being outputed to the shell."""
runner = CliRunner()
mocked_login = mocker.patch.object(APIClient, "login", return_value=None)
mocked_get_projects = mocker.patch.object(
APIClient, "list_projects", return_value=Projects(**MOCKED_PROJECTS)
)
... | 36,310 |
def add_map_widget(
width: int,
height: int,
center: tuple[float, float],
zoom_level: int,
tile_server: TileServer,
) -> int | str:
"""Add map widget
Args:
width (int): Widget width
height (int): Widget height
center (tuple[float, float]): Center point coordinates:
... | 36,311 |
def _index_within_range(query: List[int], source: List[int]) -> bool:
"""Check if query is within range of source index.
:param query: List of query int
:param source: List of soure int
"""
dim_num = len(query)
for i in range(dim_num):
if query[i] > source[i]:
raise IndexErro... | 36,312 |
def path_sender():
"""
Sends computed path to drones
"""
#TODO
return json.dumps({"result":2}) | 36,313 |
def test_transactions() -> List[TransactionObject]:
"""
Load some example transactions
"""
transaction_dict_1 = {
"amount": 1.0,
"asset_id": 23043,
"category_id": 229134,
"currency": "usd",
"date": "2021-09-19",
"external_id": None,
"fees": None,
... | 36,314 |
def modified(mctx, x):
"""``modified()``
File that is modified according to status.
"""
# i18n: "modified" is a keyword
getargs(x, 0, 0, _("modified takes no arguments"))
s = mctx.status()[0]
return [f for f in mctx.subset if f in s] | 36,315 |
def parse_declarations(lang, state, code_only=False, keep_tokens=True):
"""
Return the comments or code of state.line.
Unlike parse_line, this function assumes the parser is *not*
in the context of a multi-line comment.
Args:
lang (Language):
Syntax description for the language being... | 36,316 |
def rads_to_degs(rad):
"""Helper radians to degrees"""
return rad * 180.0 / math.pi | 36,317 |
def properties_entity(entity_a, properties_resource):
"""
An entity from properties_resource.
"""
entity_a.translation_set.all().delete()
entity_a.string = "something %s"
entity_a.save()
yield entity_a | 36,318 |
def test_post():
"""Test the post with a basic program"""
robot = RobotPost('Motomantest', 'Motoman robot', 6)
robot.ProgStart("Program")
robot.RunMessage("Program generated by RoboDK", True)
robot.setFrame(Pose([807.766544, -963.699898, 41.478944, 0, 0, 0]), None, 0)
robot.setTool(Pos... | 36,319 |
def get_employer_jobpost(profile):
""" """
jobs = None
if profile.is_employer:
jobs = JobPost.objects.filter(user=profile.user).order_by('title', 'employment_option', 'is_active')
return jobs | 36,320 |
def _paginate_issues_with_cursor(page_url,
request,
query,
cursor,
limit,
template,
extra_nav_parameters=None,
... | 36,321 |
def raise_blame_caller(level_up, ex):
"""Raises an exception, changing the stack trace to point to the caller."""
new_st = get_stack_trace_of_caller(level_up + 2)
raise type(ex), ex, new_st | 36,322 |
def test_delay():
"""
>>> db = get_connection('sqlite://')
>>> db.metadata.drop_all()
>>> class Test(Model):
... username = Field(unicode)
... year = Field(int, default=0)
... birth = Field(datetime.date)
>>> c = Test(username='limodou', birth='2011-03-04', year=2012)
>>>... | 36,323 |
def overlapping(startAttribute, # X
endAttribute, # Y
startValue, # A
endValue, # B
):
"""
Return an L{axiom.iaxiom.IComparison} (an object that can be passed as the
'comparison' argument to Store.query/.sum/.count) which will const... | 36,324 |
def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
many_series : list[pd.Series]
Returns
-------
aligned_series : list[pd.Series... | 36,325 |
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None): # pylint: disable=w0613
"""Set up the Car Wash sensor."""
# Print startup message
_LOGGER.info('Version %s', VERSION)
_LOGGER.info('If you have ANY issues with this,'
... | 36,326 |
def structConfMat(confmat, index=0, multiple=False):
"""
Creates a pandas dataframe from the confusion matrix. It distinguishes
between binary and multi-class classification.
Parameters
----------
confmat : numpy.ndarray
Array with n rows, each of one being a flattened confusion matrix... | 36,327 |
async def test_user(opp, spider):
"""Test user config."""
await setup.async_setup_component(opp, "persistent_notification", {})
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FO... | 36,328 |
def get_img(ds):
"""Get a standard image file as a Niimg
Parameters
----------
ds : str
Name of image to get.\n
Volume Masks:\n
"MNI152_T1_2mm_brain"\n
"MNI152_T1_2mm_brain_mask"\n
"MNI152_T1_2mm_brain_mask_dil"\n
"MNI152_T1_1mm_brain"\n
"MNI152_T... | 36,329 |
def print_environ_usage():
"""Dump a list of environment variables used by CGI jako HTML."""
print("""
<H3>These environment variables could have been set:</H3>
<UL>
<LI>AUTH_TYPE
<LI>CONTENT_LENGTH
<LI>CONTENT_TYPE
<LI>DATE_GMT
<LI>DATE_LOCAL
<LI>DOCUMENT_NAME
<LI>DOCUMENT_ROOT
<LI>DOCUMENT_URI
<LI>GATEWAY_INT... | 36,330 |
def ajax_log(message):
""" Write a message for debugging ajax calls """
message = "%s : %s" % (datetime.datetime.today(), message)
open(os.path.join(settings.MEDIA_ROOT, "ajax_log.txt"), 'a').write("%s\n" % message)
if settings.DEBUG and settings.IS_LOCAL:
print message
#if Preferences.... | 36,331 |
def load_fish(return_X_y: bool = False, as_frame: bool = False):
"""
Loads in a subset of the Fish market dataset. You can find the full dataset [here](https://www.kaggle.com/aungpyaeap/fish-market).
Arguments:
return_X_y: return a tuple of (`X`, `y`) for convenience
as_frame: return all th... | 36,332 |
def check_for_missing_kmers(is_fastq: bool,
subtype_result: str,
scheme: str,
df: pd.DataFrame,
exp: int,
obs: int,
p: SubtypingParams) -> Tuple[Optiona... | 36,333 |
def splat_feat_nd(init_grid, feat, coords):
"""
Args:
init_grid: B X nF X W X H X D X ..
feat: B X nF X nPt
coords: B X nDims X nPt in [-1, 1]
Returns:
grid: B X nF X W X H X D X ..
"""
wts_dim = []
pos_dim = []
grid_dims = init_grid.shape[2:]
B = init_gr... | 36,334 |
def q_nstep_td_error_ngu(
data: namedtuple,
gamma: Any, # float,
nstep: int = 1,
cum_reward: bool = False,
value_gamma: Optional[torch.Tensor] = None,
criterion: torch.nn.modules = nn.MSELoss(reduction='none'),
) -> torch.Tensor:
"""
Overview:
Multistep (... | 36,335 |
def unzip(filename):
"""Generator that yields files in the given zip archive."""
with zipfile.ZipFile(filename, 'r') as archive:
for zipinfo in archive.infolist():
yield archive.open(zipinfo, 'r'), {
'name': zipinfo.filename,
} | 36,336 |
def list_datasets(*, direc=None, kind=None, hsh=None, seed=None, redshift=None):
"""Yield all datasets which match a given set of filters.
Can be used to determine parameters of all cached datasets, in conjunction with :func:`readbox`.
Parameters
----------
direc : str, optional
The direct... | 36,337 |
def thermal_error_estimation(experimental_data):
"""
To identify any anomalies in the thermographic data and identify the indices of those thermograms
Args:
experimental_data (3d array): thermographi data
"""
# calculating the mean tempeature of each thermogram
avg_temp = np.mean(experim... | 36,338 |
def app_with_mail(app):
"""App with email test templates."""
app.register_blueprint(
Blueprint(
"invenio_app_ils_tests", __name__, template_folder="templates"
)
)
# add extra test templates to the search app blueprint, to fake the
# existence of `invenio-theme` base templ... | 36,339 |
def part1():
"""Solution to day 3, part 1."""
data = load_input()
moves = (3, 1)
initial_position = (0, 0)
tobbogan = Tobbogan(data, moves, initial_position)
n_trees = tobbogan.unhappy_encounters()
print(f"{n_trees} trees were encountered.") | 36,340 |
def generate_activation_code(email : str) -> str:
"""
Takes email address and combines it with a timestamp before encrypting everything with the ACTIVATION_LINK_SECRET
No database storage required for this action
:param email: email
:type email: unicode
:return: activation_code
:rtype: str
... | 36,341 |
def fmin_sgd(*args, **kwargs):
"""
See FMinSGD for documentation. This function creates that object, exhausts
the iterator, and then returns the final self.current_args values.
"""
print_interval = kwargs.pop('print_interval', sys.maxint)
obj = FMinSGD(*args, **kwargs)
while True:
t ... | 36,342 |
async def test_thermostat_power_state(hass, hk_driver, events):
"""Test if accessory and HA are updated accordingly."""
entity_id = "climate.test"
# SUPPORT_ON_OFF = True
hass.states.async_set(
entity_id,
HVAC_MODE_HEAT,
{
ATTR_SUPPORTED_FEATURES: 4096,
A... | 36,343 |
def normalize_timestamp(date_time):
"""
TODO: get rid of this function and all references to it / uses of it.
Attempt to convert a string timestamp in to a TruSTAR compatible format for submission.
Will return current time with UTC time zone if None
:param date_time: int that is seconds or milliseco... | 36,344 |
def round_rect(surface, rect, color, rad=20, border=0, inside=(0,0,0,0)):
"""
Draw a rect with rounded corners to surface. Argument rad can be specified
to adjust curvature of edges (given in pixels). An optional border
width can also be supplied; if not provided the rect will be filled.
Both the ... | 36,345 |
def strings_from_apk(app_file, app_dir, elf_strings):
"""Extract the strings from an app."""
try:
logger.info('Extracting Strings from APK')
dat = []
secrets = []
urls = []
urls_nf = []
emails_nf = []
apk_file = os.path.join(app_dir, app_file)
and_... | 36,346 |
def scan(this, accumulator, seed=None):
"""Applies an accumulator function over an observable sequence and
returns each intermediate result. The optional seed value is used as
the initial accumulator value.
For aggregation behavior with no intermediate results, see OutputThing.aggregate.
1 - scanne... | 36,347 |
def get_efficient_pin_order_scramble():
""" Gets an efficient pin order scramble for a Rubik's Clock. """
return _UTIL_SCRAMBLER.call("util_scramble.getClockEfficientPinOrderScramble") | 36,348 |
def fixed_padding(inputs, kernel_size):
"""Pad the input along the spatial dimensions independently of input size.
This function is copied/modified from original repo:
https://github.com/tensorflow/tpu/blob/acb331c8878ce5a4124d4d7687df5fe0fadcd43b/models/official/resnet/resnet_model.py#L357
Args:
... | 36,349 |
def _is_si_object(storage_instance):
"""
Helper method for determining if a storage instance is object.
Args:
storage_instance:
Returns: (Bool) True if object, False if not.
"""
si_type = storage_instance.get("service_configuration", None)
if si_type is None:
# object not su... | 36,350 |
def wgs84_to_bd09(lng, lat):
"""WGS84 -> BD09"""
lng, lat = wgs84_to_gcj02(lng, lat)
lng, lat = gcj02_to_bd09(lng, lat)
return lng, lat | 36,351 |
def spin_images(pc1, pc2, opt = spin_image_options()):
"""Compute spin image descriptors for a point cloud
Parameters
----------
pc1 : pcloud
The function computes a spin image descriptor for each point in
the point cloud pc1
pc2 : pcloud
The points in the point cloud pc2 a... | 36,352 |
def clone_file_info(input, output):
"""clone_file_info(FileConstHandle input, FileHandle output)"""
return _RMF.clone_file_info(input, output) | 36,353 |
def queries_to_retract_from_dataset(client,
project_id,
dataset_id,
person_id_query,
retraction_type=None):
"""
Get list of queries to remove all records in all tables ... | 36,354 |
def calc_moments(imcube, rmscube, mask=None):
"""
Calculate moments of a masked cube and their errors
Parameters
----------
imcube : SpectralCube
The image cube for which to calculate the moments and their errors.
rmscube : SpectralCube
A cube representing the noise estimate at ... | 36,355 |
def value(*, source: str, current_location: types.Location) -> types.TSourceMapEntries:
"""
Calculate the source map of any value.
Args:
source: The JSON document.
current_location: The current location in the source.
Returns:
A list of JSON pointers and source map entries.
... | 36,356 |
def greplines(lines, regexpr_list, reflags=0):
"""
grepfile - greps a specific file
TODO: move to util_str, rework to be core of grepfile
"""
found_lines = []
found_lxs = []
# Ensure a list
islist = isinstance(regexpr_list, (list, tuple))
islist2 = isinstance(reflags, (list, tuple))... | 36,357 |
def get_class_cnts_by_feature_null(df, class_col, feature, normalize=True):
"""
Break out class fequencies (in `df[class_col]`) by whether or not
`df[feature]` is null.
Parameters
----------
df : pandas.DataFrame
DataFrame on which this function will operate.
class_col : str
... | 36,358 |
def systemic_vel_est(z,param_dict,burn_in,run_dir,plot_param_hist=True):
"""
Estimates the systemic (stellar) velocity of the galaxy and corrects
the SDSS redshift (which is based on emission lines).
"""
c = 299792.458
# Get measured stellar velocity
stel_vel = np.array(param_dict['stel_vel']['chain'])
# ... | 36,359 |
def bookmark_fn(outdir):
"""Single line text file storing the epoch,brick,batch number of last ckpt"""
return os.path.join(outdir,'ckpts',
'last_epoch_brick_batch.txt') | 36,360 |
def aps_pause():
"""
:return:
"""
scheduler.pause_job('interval_task') | 36,361 |
def give_register_permission(username, base_uri):
"""Give a user register permission on a base URI."""
if not base_uri_exists(base_uri):
click.secho(
"Base URI '{}' not registered".format(base_uri),
fg="red",
err=True
)
sys.exit(1)
if not user_ex... | 36,362 |
def set_model_weights(model, weights):
"""Set the given weights to keras model
Args:
model : Keras model instance
weights (dict): Dictionary of weights
Return:
Keras model instance with weights set
"""
for key in weights.keys():
model.get_layer(key).set_weights(wei... | 36,363 |
def test_reference_links_extra_03e():
"""
Test case extra 03e: variation of 3 with autolink
"""
# Arrange
source_markdown = """[bar<http://autolink.com>foo]: /uri
[bar<http://autolink.com>foo]"""
expected_tokens = [
"[link-ref-def(1,1):True::bar<http://autolink.com>foo:: :/uri:::::]",... | 36,364 |
def check_history(history_file, inputList):
"""
Method to check in the given history file if
data files have been already processed.
"""
unprocessed = list(inputList)
if not (os.path.isfile(history_file)):
LOG.warning(history_file + " does not exist yet!")
return unprocessed
... | 36,365 |
def extract_manage_vlan(strValue):
"""处理show manage-vlan得到的信息
Args:
strValue(str): show manage-vlan得到的信息
Returns:
list: 包含管理Vlan字典的列表
"""
# ------------------------------------
# Manage name : xx
# ------------------------------------
# Svlan : 100... | 36,366 |
def train_and_evaluate(model, train_dataloader, val_dataloader, optimizer, loss_fn, metrics, params, model_dir,
restore_file=None, lr_scheduler=None):
"""Train the model and evaluate every epoch.
Args:
model: (torch.nn.Module) the neural network
train_dataloader: (DataLoad... | 36,367 |
def etree_demo2():
"""
2. //选取所有节点
"""
html = etree.parse('./lxml_test.html', etree.HTMLParser())
result = html.xpath('//*') # 返回的是list,包含每一个节点,*代表任意节点
print(type(result))
print(result, '\n\n')
# 当只获取指点的节点时,只需指定名称
result2 = html.xpath('//ul')
print(result2) | 36,368 |
def generate_sample_space_plot_detailed(
run_directory: str,
step: int = 0,
agent_ids: List[int] = [0],
contour_z: str = "action_value",
circle_size: str = "action_visits",
) -> List[dcc.Graph]:
"""Generates detailed sample space plots for the given agents.
Parameters
----------
run... | 36,369 |
def raw_path_basename(path):
"""Returns basename from raw path string"""
import ntpath
path = raw(path)
return ntpath.basename(path) | 36,370 |
def prepare_request(
url: str,
access_token: str = None,
user_agent: str = None,
ids: MultiInt = None,
params: RequestParams = None,
headers: Dict = None,
json: Dict = None,
) -> Tuple[str, RequestParams, Dict, Optional[Dict]]:
"""Translate some ``pyinaturalist``-specific params into sta... | 36,371 |
def send_folio_detail(channel):
"""FOLIO グラフ画像の通知
Arguments:
channel {str} -- チャンネルID
"""
print('[info] called service method. name=[send_folio_detail]')
# 投稿する画像をそれぞれ取得して保存する
# ファイルパスを辞書型で返してもらう
result = folio_repository.fetch_graph_images()
if result['status'] == 'NG':
... | 36,372 |
def require_permission(permission):
"""Pyramid decorator to check permissions for a request."""
def handler(f, *args, **kwargs):
request = args[0]
if check_permission(request, request.current_user, permission):
return f(*args, **kwargs)
elif request.current_user:
... | 36,373 |
def _collapse_subgraph(graph_def, inputs, outputs, op_definition):
"""Substitute a custom op for the subgraph delimited by inputs and outputs."""
name = _uuid.uuid1().hex
# We need a default type, but it can be changed using 'op_definition'.
default_type = types_pb2.DT_FLOAT
new_graph = fuse_op(
graph_d... | 36,374 |
def downsample_filter_simple(data_in, n_iter=1, offset=0):
"""
Do nearest-neighbor remixing to downsample data_in (..., nsamps)
by a power of 2.
"""
if n_iter <= 0:
return None
ns_in = data_in.shape[-1]
ns_out = ns_in // 2
dims = data_in.shape[:-1] + (ns_out,)
data_out = np.e... | 36,375 |
def _session_setup(calling_function_name='[FUNCTION NAME NOT GIVEN]'):
""" Typically called at the top of lightcurve workflow functions, to collect commonly required data.
:return: tuple of data elements: context [tuple], defaults_dict [py dict], log_file [file object].
"""
context = _get_session_contex... | 36,376 |
def find_center(image, center_guess, cutout_size=30, max_iters=10):
"""
Find the centroid of a star from an initial guess of its position. Originally
written to find star from a mouse click.
Parameters
----------
image : numpy array or CCDData
Image containing the star.
... | 36,377 |
def zGetTraceArray(numRays, hx=None, hy=None, px=None, py=None, intensity=None,
waveNum=None, mode=0, surf=-1, want_opd=0, timeout=5000):
"""Trace large number of rays defined by their normalized field and pupil
coordinates on lens file in the LDE of main Zemax application (not in the DDE ser... | 36,378 |
def bin2bytes(binvalue):
"""Convert binary string to bytes.
Sould be BYTE aligned"""
hexvalue = bin2hex(binvalue)
bytevalue = unhexlify(hexvalue)
return bytevalue | 36,379 |
def bind_and_listen_on_posix_socket(socket_name, accept_callback):
"""
:param accept_callback: Called with `PosixSocketConnection` when a new
connection is established.
"""
assert socket_name is None or isinstance(socket_name, six.text_type)
assert callable(accept_callback)
# Py2 uses 0... | 36,380 |
def _report_maker(
*,
tback: str,
func_name: Optional[str] = None,
header: Optional[str] = None,
as_attached: bool = False,
) -> Report:
"""
Make report from
Args:
tback(str): traceback for report.
func_name(str, optional): name of function when raised... | 36,381 |
def moments(data,x0=None,y0=None):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = data.sum()
X, Y = np.indices(data.shape)
x = (X*data).sum()/total
y = (Y*data).sum()/total
col = data[:, int(y)]
width_x ... | 36,382 |
def draw_trajectory(tr):
""" ss << "(" << tr.final_pose.tra.x() << ", " << tr.final_pose.tra.y()
<< ", " << tr.final_pose.rot << ", " << tr.rotate_circle_center.x()
<< ", " << tr.rotate_circle_center.y() << ", "
<< tr.rotate_circle_radius << ", " << tr.achieved_vel_pose.tra.x()
<... | 36,383 |
def string_to_bytes(size, assume_binary=False):
"""Convert human-readable size str to bytes and return an int."""
LOG.debug('size: %s, assume_binary: %s', size, assume_binary)
scale = 1000
size = str(size)
tmp = REGEX_SIZE_STRING.search(size.upper())
# Raise exception if string can't be parsed as a size
... | 36,384 |
def set_online(rg = None):
"""
Sets the desired CPU cores online.
Parameters
----------
rg : int, list
An integer or list of integers with the indices of CPU cores that
will be set online. If None, all CPU cores will be set online.
"""
if isinstance(r... | 36,385 |
def VecStack(vector_list, axis=0):
""" This is a helper function to stack vectors """
# Determine output size
single_vector_shape = [max([shape(vector)[0] for vector in vector_list]), max([shape(vector)[1] for vector in vector_list])]
vector_shape = dcopy(single_vector_shape)
vector_shape[axis] *= ... | 36,386 |
def precook(s, n=4, out=False):
"""
Takes a string as input and returns an object that can be given to
either cook_refs or cook_test. This is optional: cook_refs and cook_test
can take string arguments as well.
:param s: string : sentence to be converted into ngrams
:param n: int : number of ... | 36,387 |
def get_full_path(path, nx_list_subgraph):
"""Creates a numpy array of the line result.
Args:
path (str): Result of ``nx.shortest_path``
nx_list_subgraph (list): See ``create_shortest path`` function
Returns:
ndarray: Coordinate pairs along a path.
"""
p_list = []
curp ... | 36,388 |
def get_compliance_site_case_notifications(data, request):
"""
returns the count of notification for a compliance site case and all visit cases under it.
"""
ids = [item["id"] for item in data]
notifications = (
ExporterNotification.objects.filter(
user_id=request.user.pk, organ... | 36,389 |
def copy(src, dst):
"""
If the source is a folder, it will copy the contentes of the folder.
Otherwise, Windows will error out due to permissions problems.
"""
dst = expand(dst)
mkdir(dirname(dst))
if is_dir(src):
src = list_files(src)
else:
src = [src]
for ... | 36,390 |
def _call_function(self, *args, **kwargs):
"""
Monkey patching method. Odoo 11.0
Hiện tại request webhook của facebook gửi cả 2 type là 'http' và 'json' nên rơi vào exception BadRequest.
Phương thức này ghi đè lên method ban đầu.
TODO: Cần tìm giải pháp tối ưu hơn, ví dụ tạo một server riêng để nhận... | 36,391 |
def compare_two_data_lists(data1, data2):
"""
Gets two lists and returns set difference of the two lists.
But if one of them is None (file loading error) then the return value is None
"""
set_difference = None
if data1 is None or data2 is None:
set_difference = None
else:
set... | 36,392 |
def get_on_request(field: Any, default_value: Any) -> Any:
"""
Функция получения значений
Args:
field: поле
default_value: если пустое то подставим это значение
Return:
значение поля или дефолтное
"""
if isinstance(field, datetime):
if field.timestamp() < 10:
... | 36,393 |
def aptamer(ligand, piece='whole', liu=False):
"""
Construct aptamer sequences.
Parameters
----------
ligand: 'theo'
Specify the aptamer to generate. Right now only the theophylline
aptamer is known.
piece: 'whole', '5', '3', or 'splitter'
Specify which part of the ap... | 36,394 |
def bootstrap_ci(dataframe, kind='basic'):
"""Generate confidence intervals on the 1-sigma level for bootstrapped data
given in a DataFrame.
Parameters
----------
dataframe: DataFrame
DataFrame with the results of each bootstrap fit on a row. If the
t-method is to be used, a Panel i... | 36,395 |
def get_Trinity_gene_name(transcript_name):
"""
extracts the gene name from the Trinity identifier as the prefix
"""
(gene_name, count) = re.subn("_i\d+$", "", transcript_name)
if count != 1:
errmsg = "Error, couldn't extract gene_id from transcript_id: {}".format(transcript_name)
l... | 36,396 |
def k_means(k):
"""
K-Means clustering algorithm
"""
global dataset
print("Running k-Means for {} clusters..".format(k))
X = np.array(dataset)
init_centroids = random.sample(range(0, len(dataset)), k)
centroids, cluster_labels = [], []
for i in init_centroids:
centroids.append(dataset[i])
# converting ... | 36,397 |
def exclude_block_notation(pattern: str, text: str) -> str:
"""
行を表現するテキストから、ブロック要素の記法を除外\n
除外した結果をInline Parserへ渡すことで、Block/Inlineの処理を分離することができる
:param pattern: 記法パターン
:param text: 行テキスト
:return: 行テキストからブロック要素の記法を除外した文字列
"""
return regex.extract_from_group(pattern, text, [INDEX_TEXT]) | 36,398 |
def envfile_to_params(data):
"""
Converts environment file content into a dictionary with all the parameters.
If your input looks like:
# comment
NUMBER=123
KEY="value"
Then the generated dictionary will be the following:
{
"NUMBER": "123",
"KEY": "value"
}
"""
params = filter(lambda x: len(x) == 2,... | 36,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.