content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def unsorted_array(arr: list) -> Tuple[list, int, Tuple[int, int]]:
"""
Time Complexity: O(n)
"""
start, end = 0, len(arr) - 1
while start < end and arr[start] < arr[start + 1]:
start += 1
while start < end and arr[end] > arr[end - 1]:
end -= 1
for el in arr[start : end + ... | 8,100 |
def get_tol_values(places):
# type: (float) -> list
"""List of tolerances to test
Returns:
list[tuple[float, float]] -- [(abs_tol, rel_tol)]
"""
abs_tol = 1.1 / pow(10, places)
return [(None, None), (abs_tol, None)] | 8,101 |
def index(atom: Atom) -> int:
"""Index within the parent molecule (int).
"""
return atom.GetIdx() | 8,102 |
def test_policy_json_one_statement_no_condition(dummy_policy_statement):
"""
GIVEN PolicyCustom and PolicyStatement object.
WHEN Created object with one statement.
THEN Return policy data in JSON format.
"""
test_policy = PolicyDocumentCustom()
test_policy.add_statement( dummy_policy_stateme... | 8,103 |
def specification_config() -> GeneratorConfig:
"""A spec cache of r4"""
return load_config("python_pydantic") | 8,104 |
def _wait_for_stack_ready(stack_name, region, proxy_config):
"""
Verify if the Stack is in one of the *_COMPLETE states.
:param stack_name: Stack to query for
:param region: AWS region
:param proxy_config: Proxy configuration
:return: true if the stack is in the *_COMPLETE status
"""
lo... | 8,105 |
def create_order_number_sequence(
shop_id: ShopID, prefix: str, *, value: Optional[int] = None
) -> OrderNumberSequence:
"""Create an order number sequence."""
sequence = DbOrderNumberSequence(shop_id, prefix, value=value)
db.session.add(sequence)
try:
db.session.commit()
except Integr... | 8,106 |
def move_wheel_files(name, req, wheeldir, user=False, home=None):
"""Install a wheel"""
scheme = distutils_scheme(name, user=user, home=home)
if scheme['purelib'] != scheme['platlib']:
# XXX check *.dist-info/WHEEL to deal with this obscurity
raise NotImplemented("purelib != platlib")
... | 8,107 |
def read_hdulist (fits_file, get_data=True, get_header=False,
ext_name_indices=None, dtype=None, columns=None,
memmap=True):
"""Function to read the data (if [get_data] is True) and/or header (if
[get_header] is True) of the input [fits_file]. The fits file can
be ... | 8,108 |
def calcMFCC(signal, sample_rate=16000, win_length=0.025, win_step=0.01,
filters_num=26, NFFT=512, low_freq=0, high_freq=None, pre_emphasis_coeff=0.97,
cep_lifter=22, append_energy=True, append_delta=False):
"""Calculate MFCC Features.
Arguments:
signal: 1-D numpy array.
... | 8,109 |
def get_user(domain_id=None, enabled=None, idp_id=None, name=None, password_expires_at=None, protocol_id=None, region=None, unique_id=None):
"""
Use this data source to get the ID of an OpenStack user.
"""
__args__ = dict()
__args__['domainId'] = domain_id
__args__['enabled'] = enabled
__ar... | 8,110 |
def start():
"""
Initializes files sharing
"""
(config, is_first_time) = get_config()
run_now = print_config(config, is_first_time)
if is_first_time:
if run_now:
main_job(config)
else:
print('scorpion exited')
return
else:
main_job(config) | 8,111 |
def use(workflow_id, version, client=None):
"""
Use like ``import``: load the proxy object of a published `Workflow` version.
Parameters
----------
workflow_id: str
ID of the `Workflow` to retrieve
version: str
Version of the workflow to retrive
client: `.workflows.client.Cl... | 8,112 |
def logout():
"""
Route for logout page.
"""
logout_user()
return redirect(url_for('index')) | 8,113 |
def ipv4_size_check(ipv4_long):
"""size chek ipv4 decimal
Args:
ipv4_long (int): ipv4 decimal
Returns:
boole: valid: True
"""
if type(ipv4_long) is not int:
return False
elif 0 <= ipv4_long <= 4294967295:
return True
else:
return False | 8,114 |
def _validate_config(config):
"""Validate the StreamAlert configuration contains a valid structure.
Checks for `logs.json`:
- each log has a schema and parser declared
Checks for `sources.json`
- the sources contains either kinesis or s3 keys
- each sources has a list of logs declar... | 8,115 |
def generate_gate_hadamard_mat() -> np.ndarray:
"""Return the Hilbert-Schmidt representation matrix for an Hadamard (H) gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element.
The result is a 4 times 4 real matrix.
Parameters
----------
... | 8,116 |
def dequote(s):
""" Remove outer quotes from string
If a string has single or double quotes around it, remove them.
todo: Make sure the pair of quotes match.
If a matching pair of quotes is not found, return the string unchanged.
"""
if s.startswith(("'", '"', '<')):
return s[1:-1... | 8,117 |
def display_ordinal_value(glyph: str):
"""Displays the integer value of the given glyph
Examples:
>>> display_ordinal_value('🐍')\n
128013
>>> display_ordinal_value('G')\n
71
>>> display_ordinal_value('g')\n
103
"""
return ord(glyph) | 8,118 |
def mixture_HPX( gases, Xs ):
"""
Given a mixture of gases and their mole fractions,
this method returns the enthalpy, pressure, and
composition string needed to initialize
the mixture gas in Cantera.
NOTE: The method of setting enthalpy
usually fails, b/c Cantera uses a Newton
itera... | 8,119 |
def _get_rooms_by_live_id(conn, live_id: int, room_status:WaitRoomStatus = WaitRoomStatus.Waiting) -> Iterator[RoomInfo]:
"""list rooms
Args:
conn ([type]): sql connection
live_id (int):
If 0, get all rooms.
Others, get rooms by live_id.
Yields:
[type]: [de... | 8,120 |
def gameMode():
"""greet the player, shuffle and print the initial board"""
board = Board()
greetings(board)
board.shuffle()
board.print_ascii()
"""while the game has not ended"""
get_arrow = Getch()
while True:
choice = get_arrow()
"""ensure that the choice is valid"""
... | 8,121 |
def merge_files(input_files, output_path, logger):
"""
Performs the merging across N (usually 1 PE and 1 SE)
htseq counts files. When only 1 is provided no changes are made;
however, we use this as a tool to also gzip all outputs.
:param input_files: list of files to merge
:param output_path: p... | 8,122 |
async def async_get_bridges(hass) -> AsyncIterable[HueBridge]:
"""Retrieve Hue bridges from loaded official Hue integration."""
for entry in hass.data[HUE_DOMAIN].values():
if isinstance(entry, HueBridge) and entry.api:
yield entry | 8,123 |
def authorize(config):
"""Authorize in GSheets."""
json_credential = json.loads(config['credentials']['gspread']['credential'])
credentials = ServiceAccountCredentials.from_json_keyfile_dict(json_credential, scope)
return gspread.authorize(credentials) | 8,124 |
def _without_command(results):
"""A helper to tune up results so that they lack 'command'
which is guaranteed to differ between different cmd types
"""
out = []
for r in results:
r = r.copy()
r.pop('command')
out.append(r)
return out | 8,125 |
def b(k, a):
"""
Optimal discretisation of TBSS to minimise error, p. 9.
"""
return ((k**(a+1)-(k-1)**(a+1))/(a+1))**(1/a) | 8,126 |
def changepoint_loc_and_score(
time_series_data_window: pd.DataFrame,
kM_variance: float = 1.0,
kM_lengthscale: float = 1.0,
kM_likelihood_variance: float = 1.0,
k1_variance: float = None,
k1_lengthscale: float = None,
k2_variance: float = None,
k2_lengthscale: float = None,
kC_likel... | 8,127 |
def get_network_interfaces(properties):
""" Get the configuration that connects the instance to an existing network
and assigns to it an ephemeral public IP if specified.
"""
network_interfaces = []
networks = properties.get('networks', [])
if len(networks) == 0 and properties.get('network'... | 8,128 |
def setup(bot):
"""Cog creation"""
bot.add_cog(LinkHelper(bot)) | 8,129 |
def MATCH(*args) -> Function:
"""
Returns the relative position of an item in a range that matches a specified
value.
Learn more: https//support.google.com/docs/answer/3093378
"""
return Function("MATCH", args) | 8,130 |
def set_dict_to_zero_with_list(dictionary, key_list):
""" Set dictionary keys from given list value to zero
Args:
dictionary (dict): dictionary to filter
key_list (list): keys to turn zero in filtered dictionary
Returns:
dictionary (dict): the filtered dictio... | 8,131 |
def terminal_condition_for_minitaur_extended_env(env):
"""Returns a bool indicating that the extended env is terminated.
This predicate checks whether 1) the legs are bent inward too much or
2) the body is tilted too much.
Args:
env: An instance of MinitaurGymEnv
"""
motor_angles = env.robot.motor_ang... | 8,132 |
def save_url_dataset_for_cpp_benchmarks(n_days):
"""Fetches and saves as C++ cereal serialized file the URL dataset
Parameters
----------
n_days : `int`
Number of days kept from the original dataset.
As this dataset is quite big, you might not want to use it in totality.
"""
sav... | 8,133 |
def data_range(dt_start, dt_end):
"""read raw VP data between datetimes"""
filepath_fmt = path.join(DATA_DIR, DATA_FILE_FMT)
fnames = strftime_date_range(dt_start, dt_end, filepath_fmt)
pns = map(vprhimat2pn, fnames)
pns_out = []
for pn in pns:
if not pn.empty:
pns_out.append... | 8,134 |
async def test_call_async_migrate_entry_failure_false(hass):
"""Test migration fails if returns false."""
entry = MockConfigEntry(domain="comp")
entry.version = 2
entry.add_to_hass(hass)
mock_migrate_entry = MagicMock(return_value=mock_coro(False))
mock_setup_entry = MagicMock(return_value=mock... | 8,135 |
def init_ltmanager(conf, db, table, reset_db):
"""Initializing ltmanager by loading argument parameters."""
lt_alg = conf.get("log_template", "lt_alg")
ltg_alg = conf.get("log_template", "ltgroup_alg")
post_alg = conf.gettuple("log_template", "post_alg")
sym = conf.get("log_template", "variable_symb... | 8,136 |
def print_tree(tree, level=0, current=False):
"""Pretty-print a dictionary configuration `tree`"""
pre = ' ' * level
msg = ''
for k, v in tree.items():
if k == 'self':
msg += print_tree(v, level)
continue
# Detect subdevice
if isinstance(v, dict) and 'se... | 8,137 |
def chaine_polynome(poly):
"""Renvoie la représentation dy polynôme _poly_ (version simple)"""
tab_str = [str(coef) + "*X^" + str(i) if i != 0 else str(coef) for i,coef in enumerate(poly)]
return " + ".join(tab_str[::-1]) | 8,138 |
def dump_config(forza: CarInfo, config_version: ConfigVersion = constants.default_config_version):
"""dump config
Args:
forza (CarInfo): car info
"""
try:
forza.logger.debug(f'{dump_config.__name__} started')
config_name = get_config_name(forza, config_version)
forza.log... | 8,139 |
def get_opr_from_dict(dict_of_opr_vals):
"""Takes in a dictionary where the keys are temperatures and values are optical rotation
values. The dictionary is for all the temperatures and optical rotation values extracted
for one molecule. This function determines which of the values in the dictionary to kee... | 8,140 |
def tokens(s):
"""Return a list of strings containing individual words from string s.
This function splits on whitespace transitions, and captures apostrophes
(for contractions).
>>> tokens("I'm fine, how are you?")
["I'm", 'fine', 'how', 'are', 'you']
"""
words = re.findall(r"\b[\w']+\b"... | 8,141 |
def get_variable_value(schema, definition_ast, input):
"""Given a variable definition, and any value of input, return a value which adheres to the variable definition, or throw an error."""
type = type_from_ast(schema, definition_ast.type)
if not type or not is_input_type(type):
raise GraphQLError(
... | 8,142 |
def _convert_3d_crop_window_to_2d(crop_window):
"""Converts a 3D crop window to a 2D crop window.
Extracts just the spatial parameters of the crop window and assumes that those
apply uniformly across all channels.
Args:
crop_window: A 3D crop window, expressed as a Tensor in the format
[offset_heigh... | 8,143 |
def era5_download(years, directory, variable="temp"):
"""Download ERA5 data
:param iterable year: year(s) for which data to be downloaded given as single
value or iterable list
:param str directory: path to root directory for ERA5 downloads
:param str: variable to be downloaded, chosen from:
... | 8,144 |
def _l2_normalise_rows(t: torch.Tensor):
"""l2-normalise (in place) each row of t: float(n, row_size)"""
t.div_(t.norm(p = 2, dim = 1, keepdim = True).clamp(min = EPSILON)) | 8,145 |
def apply_along_axis(func1d, mat, axis):
"""Numba utility to apply reduction to a given axis."""
assert mat.ndim == 2
assert axis in [0, 1]
if axis == 0:
result = np.empty(mat.shape[1], mat.dtype)
for i in range(len(result)):
result[i, :] = func1d(mat[:, i])
else:
... | 8,146 |
def get_all_article():
"""
获取所有 文章资讯
---
tags:
- 资讯文章 API
responses:
200:
description: 文章资讯更新成功
404:
description: 资源不存在
500:
description: 服务器异常
"""
articles = ArticleLibrary.get_all()
return jsonify(articles) | 8,147 |
def cut_fedora_prefix(uri):
"""
Cut the Fedora URI prefix from a URI.
"""
return uri[len(FEDORA_URI_PREFIX):] | 8,148 |
def get_database_login_connection(user,password,host,database):
""" Return database connection object based on user and database details provided """
connection = psycopg2.connect(user = user,
password = password,
host = host,
... | 8,149 |
def getaddrinfo(host,port,family=0,socktype=socket.SOCK_STREAM,proto=0,allow_cname=True):
"""Resolve host and port into addrinfo struct.
Does the same thing as socket.getaddrinfo, but using `pyxmpp.resolver`. This
makes it possible to reuse data (A records from the additional section of
DNS reply) retu... | 8,150 |
def get_layout_for_dashboard(available_pages_list):
"""
Makes the dictionary that determines the dashboard layout page.
Displays the graphic title to represent the graphic.
:param available_pages_list:
:return:
"""
available_pages_list_copy = copy.deepcopy(available_pages_list)
for avail... | 8,151 |
def median(list_in):
"""
Calculates the median of the data
:param list_in: A list
:return: float
"""
list_in.sort()
half = int(len(list_in) / 2)
if len(list_in) % 2 != 0:
return float(list_in[half])
elif len(list_in) % 2 ==0:
value = (list_in[half - 1] + list_in[half... | 8,152 |
def search_file(expr, path=None, abspath=False, follow_links=False):
"""
Given a search path, recursively descend to find files that match a
regular expression.
Can specify the following options:
path - The directory that is searched recursively
executable_extension - This string is used ... | 8,153 |
def delete_gwlbe(gwlbe_ids):
"""
Deletes VPC Endpoint (GWLB-E).
Accepts:
- gwlbe_ids (list of str): ['vpce-svc-xxxx', 'vpce-svc-yyyy']
Usage:
- delete_gwlbe(['vpce-xxxx', 'vpce-yyyy'])
"""
logging.info("Deleting VPC Endpoint Service:")
try:
response = ec2.delete_vpc_endpoin... | 8,154 |
def subdivide_loop(surface:SurfaceData, number_of_iterations: int = 1) -> SurfaceData:
"""Make a mesh more detailed by subdividing in a loop.
If iterations are high, this can take very long.
Parameters
----------
surface:napari.types.SurfaceData
number_of_iterations:int
See Also
------... | 8,155 |
def register():
"""Register a new user.
Validates that the username is not already taken. Hashes the
password for security.
"""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
phone = request.form['full_phone']
cha... | 8,156 |
def gen_key():
"""Function to generate a new access key which does not exist already"""
key = ''.join(choice(ascii_letters + digits) for _ in range(16))
folder = storage + key
# Repeat until key generated does not exist
while(os.path.exists(folder)):
key = ''.join(choice(ascii_letters + dig... | 8,157 |
async def async_setup_platform(opp, config, add_entities, discovery_info=None):
"""Set up binary sensors."""
if discovery_info is None:
return
sensors = []
for host_config in discovery_info["config"][DOMAIN]:
host_name = host_config["host"]
host_name_coordinators = opp.data[DOM... | 8,158 |
def double(x):
"""aqui é onde você coloca um docstring (cadeia de caracteres de documentação)
opcional
que explica o que a função faz.
por exemplo, esta função multiplica sua entrada por 2""" | 8,159 |
def get_url(url, headers=None):
"""
get content from specified URL
"""
reply = requests.get(url, headers=headers)
if reply.status_code != 200:
logging.debug('[get_attribute] Failed to open {0}'.format(url))
return None
else:
return reply.content | 8,160 |
def Read_FImage(Object, Channel, iFlags=0):
"""
Read_FImage(Object, Channel, iFlags=0) -> bool
Read_FImage(Object, Channel) -> bool
"""
return _Channel.Read_FImage(Object, Channel, iFlags) | 8,161 |
def Export(message, stream=None, schema_path=None):
"""Writes a message as YAML to a stream.
Args:
message: Message to write.
stream: Output stream, None for writing to a string and returning it.
schema_path: JSON schema file path. If None then all message fields are
written, otherwise only field... | 8,162 |
def user_locale_get(handle, user_name, name, caller="user_locale_get"):
"""
gets locale for the user
Args:
handle (UcsHandle)
user_name (string): username
name (string): locale name
Returns:
AaaUserLocale: managed object
Raises:
UcsOperationError: if AaaUse... | 8,163 |
def get_set_from_dict_from_dict(
instance: Dict[str, Dict[str, List]], field: str
) -> Set[Any]:
"""
Format of template field within payload
Function gets field from instance-dict, which is a dict again.
The values of these dicts have to be joined in a set.
"""
cml = instance.get(field)
... | 8,164 |
def initiate_os_session(unscoped: str, project: str) -> keystoneauth1.session.Session:
"""
Create a new openstack session with the unscoped token and project id.
Params:
unscoped: str
project: str
Returns:
A usable keystone session object for OS client connections
Return typ... | 8,165 |
def test_bv_bad_format():
"""Test that bad formats cause an error."""
raw = _generate_raw()
tmpdir = _mktmpdir()
vhdr_fname = os.path.join(tmpdir, "philistine.vhdr")
vmrk_fname = os.path.join(tmpdir, "philistine.vmrk")
eeg_fname = os.path.join(tmpdir, "philistine.eeg")
# events = np.array([... | 8,166 |
def delete_topic_collection_items(request_ctx, collection_item_id, topic_id, **request_kwargs):
"""
Deletes the discussion topic. This will also delete the assignment, if it's
an assignment discussion.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
... | 8,167 |
def test_metabolomics_dataset_annotate_peaks(test_db, metabolomics_dataset):
"""Uses find_db_hits to try to annotate all unknown peaks in dataset
GIVEN a metabolomics dataset and MINE db
WHEN trying to find hits for every unknown peak in that dataset
THEN make sure all peaks get the correct # of hits
... | 8,168 |
def xml_section_extract_elsevier(section_root, element_list=None) -> List[ArticleElement]:
"""
Depth-first search of the text in the sections
"""
if element_list is None:
element_list = list()
for child in section_root:
if 'label' in child.tag or 'section-title' in child.tag or 'para... | 8,169 |
def get_data_from_string(string, data_type, key=None):
"""
Getting data from string, type can be either int or float or str.
Key is basically starts with necessary string.
Key is need only when we parse strings from execution file
output (not from test.txt)
"""
data = []
if data_type i... | 8,170 |
async def on_reaction_remove(reaction, user):
"""Remove user from matchmaking queue based on reaction.
Use the unique match_id present in the message of the appropriate format
and only if the reaction being removed is a thumbs up.
"""
print('reaction removed')
message = reaction.message
con... | 8,171 |
def greenline(apikey, stop):
"""
Return processed green line data for a stop.
"""
# Only green line trips
filter_route = "Green-B,Green-C,Green-D,Green-E"
# Include vehicle and trip data
include = "vehicle,trip"
# API request
p = {"filter[route]": filter_route, "include": inclu... | 8,172 |
def Get_Unread_Messages(service, userId):
"""Retrieves all unread messages with attachments, returns list of message ids.
Args:
service: Authorized Gmail API service instance.
userId: User's email address. The special value "me".
can be used to indicate the authenticate... | 8,173 |
def rmse(y_true, y_pred):
"""
rmse
description:
computes RMSE
"""
return sqrt(mean_squared_error(y_true, y_pred)) | 8,174 |
def doxygen(registry, xml_parent, data):
"""yaml: doxygen
Builds doxygen HTML documentation. Requires the Jenkins
:jenkins-wiki:`Doxygen plugin <Doxygen+Plugin>`.
:arg str doxyfile: The doxyfile path (required)
:arg str install: The doxygen installation to use (required)
:arg bool ignore-failur... | 8,175 |
def delete_user(usernames, **boto_options):
"""
Delete specified users, their access keys and their inline policies
s3-credentials delete-user username1 username2
"""
iam = make_client("iam", **boto_options)
for username in usernames:
click.echo("User: {}".format(username))
... | 8,176 |
def read_model_json(path: Path, model: Type[ModelT]) -> ModelT:
"""
Reading routine. Only keeps Model data
"""
return model.parse_file(path=path) | 8,177 |
def details(request, id=None):
"""
Show details about alert
:param request:
:param id: alert ID
:return:
"""
alert = get_object_or_404(Alert, id=id)
context = {
"user": request.user,
"alert": alert,
}
return render(request, "alerts/details.html", context) | 8,178 |
def get_class_id_map():
"""Get mapping between class_id and class_name"""
sql = """
SELECT class_id
, class_name
FROM classes
"""
cur.execute(f"{sql};")
result = [dict(x) for x in cur.fetchall()]
class_map = {}
for r in result:
class_m... | 8,179 |
def test_cancelAllLinking():
"""Test CancelAllLinking."""
msg = CancelAllLinking()
assert msg.hex == hexmsg(0x02, 0x65)
assert not msg.isack
assert not msg.isnak
assert len(msg.hex) / 2 == msg.sendSize
msg = CancelAllLinking(0x06)
assert msg.hex == hexmsg(0x02, 0x65, 0x06)
assert ms... | 8,180 |
def epsilon_nfa_to_nfa(e_nfa: automata.nfa.EpsilonNFA)->automata.nfa.NFA: # todo: add tests
"""
Casts epsilon NFA to NFA.
:param EpsilonNFA e_nfa: original epsilon NFA
:return NFA: cast NFA that takes the same languages.
"""
assert type(e_nfa) is automata.nfa.EpsilonNFA
work = e_nfa.deepco... | 8,181 |
def test_cursor_paginated_searches(collection, session):
"""
Tests that search methods using cursor-pagination are hooked up correctly.
There is no real search logic tested here.
"""
all_runs = [
MaterialRunDataFactory(name="foo_{}".format(i)) for i in range(20)
]
fake_request = make... | 8,182 |
def test_device_ids(get_system):
"""
This method tests the system device's device_ids() method.
"""
system = get_system
devices = system.device_ids()
connected_devices = []
depthcameras = []
for dev in devices:
check_device_types.check_DeviceID(dev)
if dev['name'] != 'uv... | 8,183 |
def potatoes(p0, w0, p1):
"""
- p1/100 = water1 / water1 + (1 - p0/100) * w0
=> water1 = w0 * p1/100 * (1 - p0/100) / (1 - p1/100)
- dry = w0 * (1 - p0/100)
- w1 = water1 + dry = w0 * (100 - p0) / (100 - p1)
Example:
98/100 = water1 / water1 + (1- 99/100) * 100
water1 = 49
w1 = 49... | 8,184 |
def truncate_results_dir(filter_submitter, backup):
"""Walk result dir and
write a hash of mlperf_log_accuracy.json to accuracy.txt
copy mlperf_log_accuracy.json to a backup location
truncate mlperf_log_accuracy.
"""
for division in list_dir("."):
# we are looking at ./$divisio... | 8,185 |
def calc_Cinv_CCGT(CC_size_W, CCGT_cost_data):
"""
Annualized investment costs for the Combined cycle
:type CC_size_W : float
:param CC_size_W: Electrical size of the CC
:rtype InvCa : float
:returns InvCa: annualized investment costs in CHF
..[C. Weber, 2008] C.Weber, Multi-objective design... | 8,186 |
def get_middle_slice_tiles(data, slice_direction):
"""Create a strip of intensity-normalized, square middle slices.
"""
slicer = {"ax": 0, "cor": 1, "sag": 2}
all_data_slicer = [slice(None), slice(None), slice(None)]
num_slices = data.shape[slicer[slice_direction]]
slice_num = int(num_slices / ... | 8,187 |
def test_add_asset_incomplete_for_asset_json(mocker_http_request, client):
"""
When df-add-assets command is provided valid arguments with valid Contact uuid it should pass
"""
from RiskIQDigitalFootprint import add_assets_command
# Fetching expected raw response from file
with open('TestDa... | 8,188 |
def function_name():
"""Check if a is a factor of b"""
pass | 8,189 |
def glewIsSupported(var):
""" Return True if var is valid extension/core pair
Usage: glewIsSupported("GL_VERSION_1_4 GL_ARB_point_sprite")
Note: GLEW API was not well documented and this function was
written in haste so the actual GLEW format for glewIsSupported
might be different.
TODO:
-... | 8,190 |
def check_file(file_input, is_json=False, ignore=None):
"""Creates a machine object to process a file of URLs"""
if is_json:
url_machine = url_class.urlAutomationMachine(file_input, is_json, ignore)
url_machine.processFile()
else:
url_machine = url_class.urlAutomationMachine(file_inp... | 8,191 |
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info('making data set.')
if not os.path.exists(os.path.join(input_filepat... | 8,192 |
def example_two():
"""Serve example two page."""
return render_template('public/examples/two.j2') | 8,193 |
def omegaTurn(r_min, w_row, rows):
"""Determines a path (set of points) representing a omega turn.
The resulting path starts at 0,0 with a angle of 0 deg. (pose = 0,0,0). It
will turn left or right depending on if rows is positive (right turn) or
negative (left turn). Path should be translated and... | 8,194 |
def atomic_call(*funcs):
"""
Call function atomicly
"""
for func in funcs:
if not callable(func):
raise TypeError(f"{func} must be callable!")
func() | 8,195 |
def sparse_ones(indices, dense_shape, dtype=tf.float32, name="sparse_ones"):
""" Creates a new `SparseTensor` with the given indices having value 1
Args:
indices (`Tensor`): a rank 2 tensor with the `(row,column)` indices for the resulting sparse tensor
dense_shape (`Tensor` or `TensorShape`): ... | 8,196 |
def ask(*args: Any, **kwargs: Any) -> Any:
"""Ask a modular question in the statusbar (blocking).
Args:
message: The message to display to the user.
mode: A PromptMode.
default: The default value to display.
text: Additional text to show
option: The option for always/nev... | 8,197 |
def get_sale(this_line, cattle, category):
"""Convert the input into a dictionary, with keys matching
the CSV column headers in the scrape_util module.
"""
cattle = cattle.replace("MARKET","")
cattle = cattle.replace(":","")
cattle = cattle.strip().title()
sale = {'cattle_cattle': cattle}
... | 8,198 |
def get_request(term, destination, days_input, price_limit, food_preference):
"""
Fetches restaurant information from the Yelp API for a given meal term, meal attribute, destination, number of days of vacation, price limit, and food preference.
Params:
term (str) the specific meal, like "breakfast"... | 8,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.