content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def draw_boxes_on_image(img, boxes, labels_index, labelmap_dict,
**kwargs):
"""Short summary.
Parameters
----------
img : ndarray
Input image.
boxes : ndarray-like
It must has shape (n ,4) where n is the number of
bounding boxes.
labels_index : nd... | 5,334,800 |
def guess_locations(location):
"""Convenience function to guess where other Strongholds are located."""
location = Point(*location)
return (location,
rotate(location, CLOCKWISE),
rotate(location, COUNTERCLOCKWISE)) | 5,334,801 |
def get_centroid(mol, conformer=-1):
"""
Returns the centroid of the molecule.
Parameters
---------
conformer : :class:`int`, optional
The id of the conformer to use.
Returns
-------
:class:`numpy.array`
A numpy array holding the position of the centroid.
"""
cen... | 5,334,802 |
def git_clone(target_dir, url, branch="master"):
"""
Clone projects to build/conanfile.name dir. This is import because the following file structure is base on it.
:param target_dir:
:param url:
:param branch:
:return:
"""
os.system(f"git clone --depth 1 --single-branch --branch {branch}... | 5,334,803 |
def idct(X, norm=None):
"""
The inverse to DCT-II, which is a scaled Discrete Cosine Transform, Type III
Our definition of idct is that idct(dct(x)) == x
For the meaning of the parameter `norm`, see:
https://docs.scipy.org/doc/ scipy.fftpack.dct.html
:param X: the input signal
:param norm: t... | 5,334,804 |
def version(only_number: bool = False) -> None:
"""Show the version info of MocaSystem."""
if only_number:
mzk.tsecho(core.VERSION)
else:
mzk.tsecho(f'MocaVirtualDM ({core.VERSION})') | 5,334,805 |
def div25():
"""
Returns the divider 44444444444444444444444
:return: divider25
"""
return divider25 | 5,334,806 |
def comp_periodicity(self, wind_mat=None):
"""Computes the winding matrix (anti-)periodicity
Parameters
----------
self : Winding
A Winding object
wind_mat : ndarray
Winding connection matrix
Returns
-------
per_a: int
Number of spatial periods of the winding
... | 5,334,807 |
def _is_valid_target(target, target_name, target_ports, is_pair):
"""Return True if the specified target is valid, False otherwise."""
if is_pair:
return (target[:utils.PORT_ID_LENGTH] in target_ports and
target_name == _PAIR_TARGET_NAME)
if (target[:utils.PORT_ID_LENGTH] not in targ... | 5,334,808 |
def _get_span_name(servicer_context):
"""Generates a span name based off of the gRPC server rpc_request_info"""
method_name = servicer_context._rpc_event.call_details.method[1:]
if isinstance(method_name, bytes):
method_name = method_name.decode('utf-8')
method_name = method_name.replace('/', '.... | 5,334,809 |
def save_flags(msfile,name,logger):
"""
Save the current flag version as "name".
Input:
msfile = Path to the MS. (String)
name = Root of filename for the flag version. (String)
"""
logger.info('Saving flag version as: {}.'.format(name))
command = "flagmanager(vis='{0}', mode='save'... | 5,334,810 |
def calculateNDFairnessPara(_ranking, _protected_group, _cut_point, _gf_measure, _normalizer, items_n, proItems_n ):
"""
Calculate group fairness value of the whole ranking.
Calls function 'calculateFairness' in the calculation.
:param _ranking: A permutation of N numbers (0..N-1) that repre... | 5,334,811 |
def getCategories(blog_id, username, password):
"""
Parameters
int blog_id
string username
string password
Return Values
array
struct
int categoryId
int parentId
string description
string categoryName... | 5,334,812 |
def change_server(name: str = None, description: str = None, repo_url: str = None, main_status: int = None, components: dict = None, password: str = None):
"""Change server according to arguments (using package config).
This will automatically change the config so it has the right credentials."""
check_con... | 5,334,813 |
def tokenize(lines, token='word'):
"""Split text lines into word or character tokens."""
if token == 'word':
return [line.split() for line in lines]
elif token == 'char':
return [list(line) for line in lines]
else:
print('ERROR: unknown token type: ' + token) | 5,334,814 |
def get_versioned_persist(service):
"""Get a L{Persist} database with upgrade rules applied.
Load a L{Persist} database for the given C{service} and upgrade or
mark as current, as necessary.
"""
persist = Persist(filename=service.persist_filename)
upgrade_manager = UPGRADE_MANAGERS[service.serv... | 5,334,815 |
def client_commands():
"""Client commands group.""" | 5,334,816 |
def gravatar(environ):
"""
Generate a gravatar link.
"""
email = environ.get('tank.user_info', {}).get('email', '')
return GRAVATAR % md5(email.lower()).hexdigest() | 5,334,817 |
def _prepare_topomap(pos, ax, check_nonzero=True):
"""Prepare the topomap axis and check positions.
Hides axis frame and check that position information is present.
"""
_hide_frame(ax)
if check_nonzero and not pos.any():
raise RuntimeError('No position information found, cannot compute '
... | 5,334,818 |
def keyrep(kspec, enc="utf-8"):
"""
Instantiate a Key given a set of key/word arguments
:param kspec: Key specification, arguments to the Key initialization
:param enc: The encoding of the strings. If it's JSON which is the default
the encoding is utf-8.
:return: Key instance
"""
if en... | 5,334,819 |
def aa2matrix(axis, angle, radians=True, random=False):
"""
Given an axis and an angle, return a 3x3 rotation matrix.
Based on:
https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle
Args:
axis: a vector about which to perform a rotation
angle: the angle of rotation
ra... | 5,334,820 |
def expand_value_range(value_range_expression):
"""Expand the value range expression.
Args:
value_range_expression: Value range or expression to expand.
Return:
iterable.
"""
if type(value_range_expression) is str:
# Grid search
if value_range_expression.startswith('... | 5,334,821 |
def date_range(df):
"""Takes the dataframe returns date range.
Example here:
http://pandas.pydata.org/pandas-docs/stable/timeseries.html
Returns as Days
"""
start_date = df.tail(1)['date']
start = pd.Timestamp.date(list(start_date.to_dict().values())[0])
end_date = df.head(1)['date'... | 5,334,822 |
def last_hit_timestamp(hit_count_rules, month):
"""
Get list of last hit timestamp to rule
:param hit_count_rules:
dictionary which contain json response with all hit count rules
:param month:
number of month elapsed since the rule was triggered last
:return:
... | 5,334,823 |
def compare_gatenum_distribution (path, constraint):
"""
compare the gate number distribution in each run
"""
bm_path = path + 'runs/benchmark/electronic-circuits/md5Core/'
# for npart in os.listdir(sol_path):
# if npart.startswith('.') == False and npart != 'best_solns.txt':
# print ('npart', npart)
# lo... | 5,334,824 |
def url(should_be=None):
"""Like the default ``url()``, but can be called without arguments,
in which case it returns the current url.
"""
if should_be is None:
return get_browser().get_url()
else:
return twill.commands.url(should_be) | 5,334,825 |
def propmap(numframe, denomframe, numdim, denomdim, numcause, denomcause,
startage, endage, sex, shapefname, percfunc = threep, mean = False):
"""Draw a map with percentiles of deaths of one cause relative to another."""
plt.close()
ages = ageslice(startage, endage, mean)
agealias = ages['alias'... | 5,334,826 |
def test_order_book_can_cancel_sell():
""" Here there are more asks than bids, so the bids will fill"""
instrument_id = "AAPL"
quantity = 100
price = 10
limit_orders = [LimitOrder(instrument_id=instrument_id,
order_direction=OrderDirection.buy if i % 2 else OrderDirect... | 5,334,827 |
def remove_outliers(X_train,y_train):
"""
This function deletes outliers on the given numpy arrays,
and returns clean version of them.
Parameters
----------
X_train: dataset to remove outliers with k features
y_train: dataset to remove outliers with k f... | 5,334,828 |
def query_data(regions, filepath_nl, filepath_lc, filepath_pop):
"""
Query raster layer for each shape in regions.
"""
shapes = []
csv_data = []
for region in tqdm(regions):
geom = shape(region['geometry'])
population = get_population(geom, filepath_pop)
pop_density_... | 5,334,829 |
def scrape_urls(html_text, pattern):
"""Extract URLs from raw html based on regex pattern"""
soup = BeautifulSoup(html_text,"html.parser")
anchors = soup.find_all("a")
urls = [a.get("href") for a in anchors]
return [url for url in urls if re.match(pattern, url)!=None] | 5,334,830 |
def get_num_weight_from_name(model: nn.Module, names: List[str]) -> List[int]:
"""Get list of number of weights from list of name of modules."""
numels = []
for n in names:
module = multi_getattr(model, n)
num_weights = module.weight.numel()
numels.append(num_weights)
return nume... | 5,334,831 |
def tokenizeGenePredStream(genePredStream):
"""
Iterator through gene pred file, returning lines as list of tokens
"""
for line in bedStream:
if line != '':
tokens = line.split("\t")
tokens[-1].rstrip()
yield tokens | 5,334,832 |
def _categories_level(keys):
"""use the Ordered dict to implement a simple ordered set
return each level of each category
[[key_1_level_1,key_2_level_1],[key_1_level_2,key_2_level_2]]
"""
res = []
for i in zip(*(keys)):
tuplefied = _tuplify(i)
res.append(list(OrderedDict([(j, Non... | 5,334,833 |
def to_usd(my_price):
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
"""
return f"${my_price:,.2f}" | 5,334,834 |
def test_init_dictionary_initial_D_init(X, D_init, solver_d, window,
uv_constraint, shape):
"""Tests if init_dictionary is doing what is expected when rank1 is False and
initial D_init is provided."""
d_solver = get_solver_d(N_CHANNELS,
N_... | 5,334,835 |
def computeNodeDerivativeHermiteLagrange(cache, coordinates, node1, derivative1, scale1, node2, scale2):
"""
Computes the derivative at node2 from quadratic Hermite-Lagrange interpolation of
node1 value and derivative1 to node2 value.
:param cache: Field cache to evaluate in.
:param coordinates: Coo... | 5,334,836 |
def _step5(state):
"""
Construct a series of alternating primed and starred zeros as follows.
Let Z0 represent the uncovered primed zero found in Step 4.
Let Z1 denote the starred zero in the column of Z0 (if any).
Let Z2 denote the primed zero in the row of Z1 (there will always be one).
... | 5,334,837 |
def download():
"""Download data from zenodo.
The NeonTreeEvaluation benchmark consists of two parts:
1) package code to run evaluation workflows
2) evaluation data. Evaluation data is ~ 2GB in size and will be downloaded to package contents.
"""
basedir = os.path.dirname(os.path.dirname(__file__))... | 5,334,838 |
def test_support_created_case_can_be_described_without_params():
"""
On creating a support request it can be described
"""
client = boto3.client("support", "us-east-1")
describe_cases_response = client.describe_cases()
describe_cases_response["cases"].should.equal([])
client.create_case(
... | 5,334,839 |
def encode_ascii_xml_array(data):
"""Encode an array-like container of strings as fixed-length 7-bit ASCII
with XML-encoding for characters outside of 7-bit ASCII.
"""
if isinstance(data, np.ndarray) and \
data.dtype.char == STR_DTYPE_CHAR and \
data.dtype.itemsize > 0:
return data... | 5,334,840 |
def test_ap_wps_auto_setup_with_config_file(dev, apdev):
"""WPS auto-setup with configuration file"""
conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
ifname = apdev[0]['ifname']
try:
with open(conffile, "w") as f:
f.write("driver=nl80211\n")
f.write("hw_mode=g\n... | 5,334,841 |
def download_dataset(
period: str, output_dir: Union[Path, str], fewer_threads: bool, datasets_path: Optional[Union[Path, str]] = None
) -> List[Path]:
"""Download files from the given dataset with the provided selections.
Args:
period: Name of the period to be downloaded.
output_dir: Path ... | 5,334,842 |
def test_say_trailing(bot):
"""Test optional trailing string."""
text = '"This is a test quote.'
bot.say(text, '#sopel', trailing='"')
assert bot.backend.message_sent == rawlist(
# combined
'PRIVMSG #sopel :%s' % text + '"'
) | 5,334,843 |
def monospaced(fields, context):
"""
Make text monospaced.
In HTML: use tags
In Markdown: use backticks
In Text: use Unicode characters
"""
content = fields[0]
target = context['target']
if target == 'md':
return wrapper('`')([content], context)
if target == 'html':
... | 5,334,844 |
def indexview(request):
"""
initial page
shows all the domains in columns
"""
domdb = Domain.objects
if not request.user.has_perm('editapp.see_all'): # only see mine
domdb = domdb.filter(owner__username=request.user.username)
domains = [ d.domain for d in domdb.order_by('domain') ]
... | 5,334,845 |
def print_helper(base_str, dbg):
""" print helper applied to test dbg type and take correct print action """
print_dbg = test_dbg(dbg)
if print_dbg:
if isinstance(dbg, bool):
print(
" ".join([dt.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), base_str])
)
... | 5,334,846 |
def _search_solutions(snake: Snake,
board: Board,
depth: int) -> None:
"""
Recursive function used to perform the backtracking algorithm
Args:
snake: representation of the positions of a snake in the board.
board: two-dimensional space where the ... | 5,334,847 |
def MC_swap(alloy, N, E, T):
"""
Randomly selects an atom and one of its neighbours in a
matrix and calculates the change in energy if the two atoms were swapped.
The following assignment is used to represent the neighbouring directions:
1 = up
2 = right
3 = down
4 = left
"""
... | 5,334,848 |
def _try_type(value, dtype):
"""
Examples
--------
>>> _try_type("1", int)
1
>>> _try_type(1.0, int)
1
>>> _try_type("ab", float)
'ab'
"""
try:
return dtype(value)
except ValueError:
return value | 5,334,849 |
def get_all_codes(date=None):
"""
获取某个交易日的所有股票代码列表,如果没有指定日期,则从当前日期一直向前找,直到找到有
数据的一天,返回的即是那个交易日的股票代码列表
:param date: 日期
:return: 股票代码列表
"""
datetime_obj = datetime.now()
if date is None:
date = datetime_obj.strftime('%Y-%m-%d')
codes = []
while len(codes) == 0:
c... | 5,334,850 |
def cluster_config(request_data, op_ctx: ctx.OperationContext):
"""Request handler for cluster config operation.
Required data: cluster_name
Optional data and default values: org_name=None, ovdc_name=None
(data validation handled in broker)
:return: Dict
"""
_raise_error_if_pks_not_enable... | 5,334,851 |
def compute_pad_value(input_dir, list_IDs):
"""
Computes the minimum pixel intensity of the entire dataset for the pad value (if it's not 0)
Args:
input_dir: directory to input images
list_IDs: list of filenames
"""
print("Computing min/pad value...")
# iterating through entire d... | 5,334,852 |
def image_marker_layout(box):
"""Layout the :class:`boxes.ImageMarkerBox` ``box``.
:class:`boxes.ImageMarkerBox` objects are :class:`boxes.ReplacedBox`
objects, but their used size is computed differently.
"""
_, width, height = box.replacement
ratio = width / height
one_em = box.style.fon... | 5,334,853 |
def iotcentral_cli_handler(args):
"""
CLI entry point for command: iotcentral
"""
logger = getLogger(__name__)
from .pyazureutils_errors import PyazureutilsError
try:
if args.action == "register-device":
status = _action_register_device(args)
except PyazureutilsError as e... | 5,334,854 |
def cross_validation_wrapper(learner, dataset, k=10, trials=1):
"""[Fig 18.8]
Return the optimal value of size having minimum error
on validation set.
err_train: A training error array, indexed by size
err_val: A validation error array, indexed by size
"""
err_val = []
err_train = []
... | 5,334,855 |
def kelly_kapowski(s, g, w, its=45, r=0.025, m=1.5, **kwargs):
"""
Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : ANTsim... | 5,334,856 |
def test_tree_node_section() -> None:
"""Given a path to a ``stories.py``, extract needed info."""
from examples.minimal.components import stories
stories_path = Path(stories.__file__)
tree_node = TreeNode(
root_path="examples.minimal",
stories_path=stories_path,
)
assert isinst... | 5,334,857 |
def loadPlugin(ac="script",a=1,n="string",qt=1,rc="script"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/loadPlugin.html
-----------------------------------------
loadPlugin is undoable, NOT queryable, and NOT editable.
Load plug-ins into Maya. The parameter(s) to this command... | 5,334,858 |
def test_file_with_connection():
"""Test File class with connection to 2ch."""
catalog = Catalog('test')
thread = catalog.threads[0]
post = thread.posts[0]
# Download file
files_list = post.files
for file_descr in files_list:
assert isinstance(file_descr, File)
file_descr.do... | 5,334,859 |
def get_word_count(frame, pattern_list, group_by_name):
"""
Compute word count and return a dataframe
:param frame:
:param pattern_list:
:param column_name:
:return: frame with count or None if pattern_list is empty
"""
if not pattern_list or len(pattern_list) == 0:
return None
... | 5,334,860 |
def test_aggregate_across_levels_perslice(dummy_metrics, dummy_vert_level):
"""Test extraction of metrics aggregation within selected vertebral levels and per slice"""
agg_metric = aggregate_slicewise.aggregate_per_slice_or_level(dummy_metrics['with float'], levels=[2, 3],
... | 5,334,861 |
def parse(text, from_timezone=None):
"""
:rtype: TimeeDT
"""
timee_dt = None
if from_timezone:
timee_dt = parse_with_maya(text, timezone=from_timezone)
return timee_dt
else:
for parse_method in parsing_methods():
result = parse_method(text)
i... | 5,334,862 |
def _command_line_objc_copts(objc_fragment):
"""Returns copts that should be passed to `clang` from the `objc` fragment.
Args:
objc_fragment: The `objc` configuration fragment.
Returns:
A list of `clang` copts, each of which is preceded by `-Xcc` so that they can be passed
through ... | 5,334,863 |
def test_set_slice_reorder():
"""
Sets a slice across one of the axes. The source data is not in the same order as the axes in
ImageStack, but set_slice should reorder the axes and write it correctly.
"""
stack = ImageStack.synthetic_stack()
round_ = 1
y, x = stack.tile_shape
index = {A... | 5,334,864 |
def reversal_test_bootstrap(dec=None, inc=None, di_block=None, plot_stereo=False, save=False, save_folder='.', fmt='svg'):
"""
Conduct a reversal test using bootstrap statistics (Tauxe, 2010) to
determine whether two populations of directions could be from an antipodal
common mean.
Parameters
-... | 5,334,865 |
def handle_incoming_mail(addr=None):
"""Handle an incoming email by making a task to examine it.
This code checks some basic properties of the incoming message
to make sure that it is worth examining. Then it puts all the
relevent fields into a dict and makes a new Cloud Task which
is futher processed in py... | 5,334,866 |
def test_we_have_some_config_values():
"""Check to see we have some config values."""
assert len(Config) > 0 | 5,334,867 |
def test_cascade_delete(settings):
"""
Verify that if we delete a model with the ArchiveMixin, then the
delete cascades to its "parents", i.e. the models with foreign keys
to it.
"""
settings.SOFT_DELETE_SAFE_MODE = False
base = models.BaseArchiveModel.objects.create(name='test')
related... | 5,334,868 |
def split(df, partition, column):
"""
:param df: The dataframe to split
:param partition: The partition to split
:param column: The column along which to split
: returns: A tuple containing a split of the original partition
"""
dfp = df[column][partition]
if column in ca... | 5,334,869 |
def get_gaussian_kernel(l=5, sig=1.):
"""
creates gaussian kernel with side length l and a sigma of sig
"""
ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l)
xx, yy = np.meshgrid(ax, ax)
kernel = np.exp(-0.5 * (np.square(xx) + np.square(yy)) / np.square(sig))
return kernel / np.sum(kernel) | 5,334,870 |
def save_context_test() -> None:
"""Test printing out context data.
:return: None
:rtype: None
"""
a = save_context('a')
raise NotImplemented | 5,334,871 |
def get_data_tbl(path, tblname):
"""Wrapper function around @merge_json
"""
files = get_annon_db_file(path, tblname)
log.info("files: {}".format(files))
K,V = common.merge_json(files)
return K,V | 5,334,872 |
def costes_coloc(im_1, im_2, psf_width=3, n_scramble=1000, thresh_r=0.0,
roi=None, roi_method='all', do_manders=True):
"""
Perform Costes colocalization analysis on a pair of images.
Parameters
----------
im_1: array_like
Intensity image for colocalization. Must be the
... | 5,334,873 |
def test_creating_extra_byte_with_invalid_type(simple_las_path):
"""
Test the error message when creating extra bytes with invalid type
"""
las = laspy.read(simple_las_path)
with pytest.raises(TypeError):
las.add_extra_dim(laspy.ExtraBytesParams("just_a_test", "i16")) | 5,334,874 |
def get_induced_dipole_count(efpobj):
"""Gets the number of polarization induced dipoles in `efpobj` computation.
Returns
-------
int
Total number of polarization induced dipoles.
"""
(res, ndip) = efpobj._efp_get_induced_dipole_count()
_result_to_error(res)
return ndip | 5,334,875 |
def _gen_parabola(phase: float, start: float, mid: float, end: float) -> float:
"""Gets a point on a parabola y = a x^2 + b x + c.
The Parabola is determined by three points (0, start), (0.5, mid), (1, end) in
the plane.
Args:
phase: Normalized to [0, 1]. A point on the x-axis of the parabola.
start... | 5,334,876 |
def grant_perms(obj: element, mast: element, read_only: bool, meta):
"""
Grants another user permissions to access a Jaseci object
Param 1 - target element
Param 2 - master to be granted permission
Param 3 - Boolean read_only flag
Return - Sorted list
"""
mast = meta['h'].get_obj(meta['... | 5,334,877 |
def get_instance_ids_compute_hostnames_conversion_dict(instance_ids, id_to_hostname, region=None):
"""Return instanceIDs to hostnames dict if id_to_hostname=True, else return hostname to instanceID dict."""
try:
if not region:
region = os.environ.get("AWS_DEFAULT_REGION")
conversion_... | 5,334,878 |
def pkgdir(tmpdir, monkeypatch):
"""
temp directory fixture containing a readable/writable ./debian/changelog.
"""
cfile = tmpdir.mkdir('debian').join('changelog')
text = """
testpkg (1.1.0-1) stable; urgency=medium
* update to 1.1.0
* other rad packaging updates
* even more cool packaging up... | 5,334,879 |
def read_plot_config(filename):
"""Read in plotting config file.
Args:
filename (str): Full path and name of config file.
Returns:
dict: Contents of config file.
"""
config = configparser.ConfigParser()
config.read(filename)
out = {}
for section in config.sections():
... | 5,334,880 |
def parse(file_path, prec=15):
"""
Simple helper
- file_path: Path to the OpenQASM file
- prec: Precision for the returned string
"""
qasm = Qasm(file_path)
return qasm.parse().qasm(prec) | 5,334,881 |
def sinusoid(amplitude=1.0, frequency=1.0, phase=0.0, duration=60.0, samplerate=100.0):
"""Generate a sinusoid"""
t = np.arange(0, duration, 1.0/samplerate)
d = np.sin(2.0 * np.pi * frequency * t)
return t, d | 5,334,882 |
def get_model():
"""
Returns a compiled convolutional neural network model. Assume that the
`input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
The output layer should have `NUM_CATEGORIES` units, one for each category.
"""
model = tf.keras.models.Sequential()
model.add(
... | 5,334,883 |
def check_datetime_str(datetime_str):
"""
Tries to parse the datetime string to a datetime object. If it fails,
it will return False
:param str datetime_str:
:return: returns True or False depending on the validity of the datetime string
:rtype: bool
"""
try:
parse_datetime_str(... | 5,334,884 |
def train(args, train_exe, build_res, place):
"""[train the net]
Arguments:
args {[type]} -- [description]
train_exe {[type]} -- [description]
compiled_prog{[type]} -- [description]
build_res {[type]} -- [description]
place {[type]} -- [description]
"""
globa... | 5,334,885 |
def _df_pitch(df: pd.DataFrame, xcol: str = 'x',
ycol: str = 'y', zcol: str = 'z'):
"""Find angular pitch for each row in an accelerometer dataframe.
Args:
df (pd.DataFrame): accelerometer dataframe
xcol, ycol, zcol (str): column names for x, y, and z acceleration
Returns:
... | 5,334,886 |
def gan_masked_generate_face(generator_fun, face_img: np.array):
"""
Generated a face from the seed one considering a generator_fun which should output alpha mask and bgr results
:param generator_fun: takes an image and returns alpha mask concatenated with bgr results
:param face_img: img to feed to the... | 5,334,887 |
def manual_auth(transport, username, hostname):
"""
Attempt to authenticate to the given transport using manual
login/password method
"""
default_auth = 'p'
# auth = raw_input(\
# 'Authenticate by (p)assword, (r)sa key, or (d)sa key? [%s] ' % default_auth)
# if len(auth) == 0:
# ... | 5,334,888 |
def get_namespace_from_path(path):
"""get namespace from file path
Args:
path (unicode): file path
Returns:
unicode: namespace
"""
return os.path.splitext(os.path.basename(path))[0] | 5,334,889 |
def feat_row_sum_inv_normalize(x):
"""
:param x: np.ndarray, raw features.
:return: np.ndarray, normalized features
"""
x_feat = x.astype(dtype=np.float64)
inv_x_rowsum = np.power(x_feat.sum(axis=1), -1).flatten()
inv_x_rowsum[np.isinf(inv_x_rowsum)] = 0.
x_diag_mat = np.diag(inv_x_rows... | 5,334,890 |
def cross3(v1, v2):
"""
cross3
"""
return (v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0]) | 5,334,891 |
def api_request(request, viewset, method, url_kwargs={}, get_params={}):
"""
Call an API route on behalf of the user request. Examples:
data = api_request(request, CaseDocumentViewSet, 'list', get_params={'q': 'foo'}).data
data = api_request(request, CaseDocumentViewSet, 'retrieve', ... | 5,334,892 |
def ca_restart(slot):
"""
:param slot:
"""
LOG.info("CA_Restart: attempting to restart")
ret = CA_Restart(CK_ULONG(slot))
LOG.info("CA_Restart: Ret Value: %s", ret)
return ret | 5,334,893 |
def test_provider_system_hook_command_exit(change_dir):
"""Verify the hook call works properly."""
with pytest.raises(HookCallException):
tackle(context_file='command-exit.yaml', no_input=True) | 5,334,894 |
def naturally_select_features(train, valid, X, Y, frame_type='h2o'):
"""
"""
train_frame = train.as_data_frame()
rounds_till_death = 3
number_of_features_to_make_the_cut = 0.2
n_folds = 20
features_made_the_cut = []
features_passing_to_next_round = []
features_passed_previous_r... | 5,334,895 |
def test_update_team_password(mongo_proc, redis_proc, client): # noqa (fixture)
"""Test the /team/update_password endpoint."""
clear_db()
register_test_accounts()
res = client.post(
"/api/v1/user/login",
json={
"username": STUDENT_DEMOGRAPHICS["username"],
"passw... | 5,334,896 |
def pickup_target(
path: ShortestPath,
target_id: str
) -> None:
"""Update the given path to pickup the target with the given ID."""
path.action_list.append({
'action': 'PickupObject',
'params': {
'objectId': target_id
}
}) | 5,334,897 |
def ogr_wkts(src_ds):
"""return the wkt(s) of the ogr dataset"""
these_regions = []
src_s = src_ds.split(':')
if os.path.exists(src_s[0]):
poly = ogr.Open(src_s[0])
if poly is not None:
p_layer = poly.GetLayer(0)
for pf in p_layer:
pgeom = pf.... | 5,334,898 |
def load_word2vec_matrix(embedding_size):
"""
Return the word2vec model matrix.
Args:
embedding_size: The embedding size
Returns:
The word2vec model matrix
Raises:
IOError: If word2vec model file doesn't exist
"""
word2vec_file = '../data/word2vec_' + str(embedding_s... | 5,334,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.