content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def attribute_rename_cmd(oldattr, newattr):
"""
Rename an attribute.
If it's not present nothing is done, and its value is kept.
That's it.
$ cjio myfile.city.json attribute_rename oldAttr newAttr info
"""
def processor(cm):
utils.print_cmd_status('Rename attribute: "%s" =>... | 5,320,800 |
def editItemInCategory(item_id):
""" Edit an item in a given category."""
if 'username' not in login_session:
sMsg = "You are not authorized to perform this '%s' " % ('edit item category')
sMsg += "action because you are not logged in. You are being redirected to login."
flash(sMsg)
return redirect('/login... | 5,320,801 |
def run(event_type, data):
"""Everything starts here."""
installation_id = data["installation"]["id"]
installation_token = utils.get_installation_token(installation_id)
if not installation_token:
return
g = github.Github(
installation_token, base_url="https://api.%s" % config.GITHUB... | 5,320,802 |
def factorial(n, show=False):
"""
-> Calcula o Fatorial de um número.
:param n: O número a ser calculado.
:param show: (opcional) Mostra ou não a conta.
:return: O valor do Fatorial de um número n.
"""
f = 1
for c in range(n, 0, -1):
if show:
print(c, end='')
... | 5,320,803 |
def parse_commands(log_content):
"""
parse cwl commands from the line-by-line generator of log file content and
returns the commands as a list of command line lists, each corresponding to a step run.
"""
command_list = []
command = []
in_command = False
line = next(log_content)
wh... | 5,320,804 |
def wait_for_operation(client,
project,
op_id,
timeout=datetime.timedelta(hours=1),
polling_interval=datetime.timedelta(seconds=5),
status_callback=log_operation_status):
"""Wait for the specified operat... | 5,320,805 |
def regex_closest_match(regex: str, string: str) -> str:
"""Find the longest version of regex that matches something in string."""
no_match = True
modified_regex = regex
while no_match:
# TODO: there may be a better way to do this rather than a try-except (perhaps using sre_parse to strategical... | 5,320,806 |
def themes():
"""
Usage:
catsup themes
Options:
-h --help Show this screen and exit.
"""
from catsup.parser.themes import list_themes
list_themes() | 5,320,807 |
def bij_connected_comps(components):
"""Set of connected planar graphs (possibly derived) to nx.PlanarEmbedding."""
res = nx.PlanarEmbedding()
for g in components:
g = g.underive_all()
g = g.to_planar_embedding()
res = nx.PlanarEmbedding(nx.compose(res, g))
return res | 5,320,808 |
def render_responses(intent: Intent, language_data: IntentLanguageData) -> Tuple[IntentResponseDict, str]:
"""
Return a copy of responses in `language_data` where intent parameter references are
replaced with their values from the given :class:`Intent` instance.
Args:
intent: The intent to read... | 5,320,809 |
def sp_cpu(file):
"""Read single-point output for cpu time."""
spe, program, data, cpu = None, None, [], None
if os.path.exists(os.path.splitext(file)[0] + '.log'):
with open(os.path.splitext(file)[0] + '.log') as f:
data = f.readlines()
elif os.path.exists(os.path.splitext(file)[0]... | 5,320,810 |
def cropseq(indexes, l, stride):
"""generate chunked silencer sequence according to loaded index"""
print('Generating silencer samples with length {} bps...'.format(l))
silencers = list()
i = 0
for index in indexes:
try:
[sampleid, chrkey, startpos, endpos, _] = index
exc... | 5,320,811 |
def generate_claims(model, gen_dset, dl, tokenizer, device):
"""
Run generation using the given model on the given dataset
:param model: BART model to use for generation
:param gen_dset: The original dataset
:param dl: A dataloader to use for generation
:param tokenizer: A tokenizer for the give... | 5,320,812 |
def to_geojson(series):
"""Return a GeoJSON geometry collection from the series (must be in EPSG:4326).
Did not use the builtin for the series since it introduces a lot of bloat.
"""
return {
"type": "GeometryCollection",
"geometries": series.apply(lambda x: x.__geo_interface__).to_list... | 5,320,813 |
def check_kafka_ready(expected_brokers, timeout, config, bootstrap_broker_list=None, zookeeper_connect=None, security_protocol=None):
"""Waits for a Kafka cluster to be ready and have at least the
expected_brokers to present. This commands uses the Java docker-utils
library to get the Kafka status.
... | 5,320,814 |
async def copy_context(ctx: commands.Context, *, author=None, channel=None, **kwargs):
"""
Returns a new Context with changed message properties.
"""
# copy the message and update the attributes
alt_message: discord.Message = copy.copy(ctx.message)
alt_message._update(kwargs)
if author is n... | 5,320,815 |
def test_read_at(curve):
"""
Test reading at index value for single number and array of numbers.
"""
assert curve.read_at(1000) - 109.414177 < 0.001
actual = curve.read_at([500, 1000, 1500])
desired = np.array([91.29946709, 109.4141766, 64.55931458])
np.testing.assert_allclose(actual, desir... | 5,320,816 |
def getConstraintWeightAttr(leader, constraint):
"""
Return the weight attribute from a constraint that
corresponds to a specific leader node.
Args:
leader (PyNode): A node that is one of the leaders of a constraint
constraint (PyNode): A constraint node
"""
for i, target in enu... | 5,320,817 |
def show_slices(slices):
""" Function to display a row of image slices """
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower") | 5,320,818 |
def load_data(dataset_str):
"""
Loads input data from gcn/data directory
ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object;
ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object;
ind.dataset_str.a... | 5,320,819 |
def approximate_mds(dists):
"""Approximate multidimensional scaling (MDS)
Estimate the inter-node distance matrix from source node distances as
described in "Iterative Geometry Calibration from Distance Estimates for
Wireless Acoustic Sensor Networks" (https://arxiv.org/abs/2012.06142).
Subsequentl... | 5,320,820 |
def build_resnet_fpnindi_backbone(cfg, input_shape: ShapeSpec):
"""
Args:
cfg: a detectron2 CfgNode
Returns:
backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
"""
bottom_up = build_resnet_backbone(cfg, input_shape)
in_features = cfg.MODEL.FPN.IN_FEAT... | 5,320,821 |
def get_cloud_front_origin_access_identity(Id=None):
"""
Get the information about an origin access identity.
See also: AWS API Documentation
Exceptions
:example: response = client.get_cloud_front_origin_access_identity(
Id='string'
)
:type Id: string
:param I... | 5,320,822 |
def _get_min_max_outputs(node: BaseNode,
fw_info: FrameworkInfo) -> Tuple[Any, Any]:
"""
Return the min/max output values of a node if known.
If one of them (or both of them) is unknown - return None instead of a value.
Args:
node: Node to create its prior info.
... | 5,320,823 |
def remove_stop_words(document):
"""Returns document without stop words"""
document = ' '.join([i for i in document.split() if i not in stop])
return document | 5,320,824 |
def no_blank_line_after_last_section(): # noqa: D416
"""Toggle the gizmo.
Returns
-------
A value of some sort.
""" | 5,320,825 |
def insert_to_api(conn, username, api_name, api_elapse, api_call_datetime, terminal_type, img_path, skin_disease):
"""
insert a record to API TABLE
:param conn:
:return:
"""
cursor = conn.cursor()
sql = "INSERT INTO api(username, api_name, api_elapse, api_call_datetime, terminal_type, img_pa... | 5,320,826 |
def Ion_Flux_Relabeling(h,q):
"""
Oh no! Commander Lambda's latest experiment to improve the efficiency of her LAMBCHOP
doomsday device has backfired spectacularly. She had been improving the structure of
the ion flux converter tree, but something went terribly wrong and the flux chains
exploded. ... | 5,320,827 |
def process_line(line, previous_state):
"""
Read line, split it before opening brackets if not in quotes nor escaped
and add '\n' in the end of new lines.
"""
# opening bracket and/or quote can start in other line
brackets = previous_state.brackets
in_quotes = pr... | 5,320,828 |
def parse_tape6(tape6="TAPE6.OUT"):
"""Parses an ORIGEN 2.2 TAPE6.OUT file.
Parameters
----------
tape6 : str or file-like object
Path or file to read the tape6 file from.
Returns
-------
results : dict
Dictionary of parsed values.
Warnings
--------
This method... | 5,320,829 |
def cleanup_before_exit(tmp_dir):
"""
Remove temporary files and directories.
"""
if tmp_dir and os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir) | 5,320,830 |
def property_values_to_string(pv,extra_indentation = 0):
"""
Parameters
----------
pv : OrderedDict
Keys are properties, values are values
"""
# Max length
keys = pv[::2]
values = pv[1::2]
values = ['"%s"' %x if isinstance(x,_Quotes) else x for x in values]
key_lengths... | 5,320,831 |
def test_list_non_positive_integer_enumeration_nistxml_sv_iv_list_non_positive_integer_enumeration_1_1(mode, save_output, output_format):
"""
Type list/nonPositiveInteger is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/nonPositiveInteger/Schema+Instance/NISTSchema-... | 5,320,832 |
def parse_cmdline():
"""parse command line arguments"""
parser = ArgumentParser(
description="dtbTool version " + str(QCDT_VERSION))
parser.add_argument("input_dir",
help="Input directory")
parser.add_argument("-o", "--output-file", type=FileType('wb'), required=True,
... | 5,320,833 |
def __build_vocab(nlp, datasets):
"""
Generates the encoder vocabulary (natural language tokens),
decoder vocabulary (programming language tokens) and stack
vocabulary (terminal and non-terminal symbols, tokens) by
parsing each source and target example in each split.
:param nlp: nl pro... | 5,320,834 |
def file_contains_exact_text(filename, text):
"""Returns True iff the file exists and it already contains the given text."""
if not os.path.isfile(filename):
return False
with open(filename, "r") as infile:
intext = infile.read()
return text == intext
return False | 5,320,835 |
def get_profile(key: str) -> Optional[Dict]:
"""Fetch user profile.
Arguments:
---------
key: User's database key.
Returns:
---------
Profile dictionary if exists else None.
"""
return BASE_PROFILE.get(key=key) | 5,320,836 |
def plot_domain_2D(prefix:str,x:np.ndarray,y:np.ndarray,u:np.ndarray,v:np.ndarray,i:int):
"""Saves an image containing the value of u and v for burger's equation
Args:
prefix (str): filename prefix
x (np.ndarray): matrix x direction
y (np.ndarray): matrix y direction
u (np.ndarr... | 5,320,837 |
def print_response(response):
"""Parses and prints the Analytics Reporting API V4 response.
Args:
response: An Analytics Reporting API V4 response.
"""
for report in response.get('reports', []):
columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
... | 5,320,838 |
def test_handles_exceptions(client):
"""
Test that a raised exception will be handled correctly
"""
data = '{"message": "throw"}'
rv = client.post(
"/",
data=data,
headers={"Content-Type": "application/json"})
assert rv.data == b"Function raised Whoops!"
assert rv.sta... | 5,320,839 |
def render_single(pathway_info, trees, rounding):
""" Render the percentage of participation per entry for a single pathway """
# Use first report for group list
groups = trees[0]["children"].keys()
# Render column headers
row_headers = ["EC"]
for group in groups:
for tsv_tree in enumer... | 5,320,840 |
def rectangle_centered(
w: int = 1, h: int = 1, x: None = None, y: None = None, layer: int = 0
) -> Component:
""" a rectangle size (x, y) in layer
bad naming with x and y. Replaced with w and h. Keeping x and y
for now for backwards compatibility
.. plot::
:include-source:
imp... | 5,320,841 |
def sched_time_to_dt(timeStr, targetDate):
"""Converts a GTFS schedule time string to a datetime
Note that a GTFS time may be more than 24 hours, in which case
the function removes 24 from the hours part of the time and increases
the date part of the datetime by 1
Args:
timeStr: time part of the datetim... | 5,320,842 |
def test_io_boilerplate():
"""Importing from ``pyglotaran_extras.io.boilerplate`` raises deprecation warning."""
with pytest.warns(PyglotaranExtrasApiDeprecationWarning) as record:
from pyglotaran_extras.io.boilerplate import setup_case_study # noqa:F401
assert len(record) == 1
assert ... | 5,320,843 |
def get_arxiv_csl(*, arxiv_id):
"""
Generate a CSL Item for an unversioned arXiv identifier
using arXiv's OAI_PMH v2.0 API <https://arxiv.org/help/oa>.
This endpoint does not support versioned `arxiv_id`.
"""
# XML namespace prefixes
ns_oai = "{http://www.openarchives.org/OAI/2.0/}"
ns_a... | 5,320,844 |
def _equivalent_data_structures(reference, struct_2):
"""Compare arbitrary data structures for equality.
``reference`` is expected to be the reference data structure. Cannot handle
set like data structures.
"""
if isinstance(reference, np.ndarray):
return np.allclose(reference, struct_2)
... | 5,320,845 |
async def test_state_value(hass: HomeAssistant) -> None:
"""Test with state value."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "cover_status")
await setup_test_entity(
hass,
{
"test": {
"comman... | 5,320,846 |
def _clear():
"""Clear the cache"""
time.sleep(random.randint(0, 2))
debug_print("clearing")
c.clear()
assert True | 5,320,847 |
def _find_line_bounding_boxes(line_segmentation: np.ndarray):
"""Given a line segmentation, find bounding boxes for connected-component regions corresponding to non-0 labels."""
def _find_line_bounding_boxes_in_channel(line_segmentation_channel: np.ndarray) -> np.ndarray:
line_activation_image = cv2.di... | 5,320,848 |
def split_items(items, num_groups):
"""Splits a list of items into ``num_groups`` groups fairly (i.e. every
item is assigned to exactly one group and no group is more than one item
larger than any other)."""
per_set = len(items) / float(num_groups)
assert per_set >= 1, "At least one set will be empt... | 5,320,849 |
def generate_tool_flow(tool: GladierBaseTool, modifiers):
"""Generate a flow definition for a Gladier Tool based on the defined ``funcx_functions``.
Accepts modifiers for funcx functions"""
flow_moder = FlowModifiers([tool], modifiers, cls=tool)
flow_states = OrderedDict()
for fx_func in tool.func... | 5,320,850 |
def do_user_delete(kc, args):
"""Delete user"""
user = utils.find_resource(kc.users, args.user)
kc.users.delete(user) | 5,320,851 |
def paralellLines(M,axis=1,labels=(), interactive=True, title="",show=True):
"""
Makes an optionally interactive paralell Lines plot.
M: Matrix to visualise.
axis: Axis of data values to plot. Needs to be either 1 or 0. Defaults to 1.
labels: Labels of the axes to plot.
inte... | 5,320,852 |
def hpat_pandas_series_dropna(self, axis=0, inplace=False):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.dropna
Limitations
-----------
- Parameter ``inplace`` is currently unsupported by Intel Scalable Dataframe Co... | 5,320,853 |
def sort_characters(text, alphabet):
"""Counting Sort"""
dim = len(text)
order = [0] * dim
count = {k: 0 for v, k in enumerate(alphabet)}
for char in text:
count[char] += 1
for j in range(1, len(alphabet)):
count[alphabet[j]] += count[alphabet[j-1]]
for i, char in reversed... | 5,320,854 |
def extract_layers_from_images(project, images):
"""
Extract all the layers from provided `images` into the `project` codebase/ work
directory.
Return the `errors` that may have happen during the extraction.
"""
errors = []
for image in images:
image_dirname = Path(image.base_locati... | 5,320,855 |
def test_get_orders_success(client):
"""Test if admin can get all orders"""
rv = client.get('/api/v1/orders/')
assert rv.status_code == 200 | 5,320,856 |
def get_rp_throughput_summary(isamAppliance, date, duration, aspect, summary=True, check_mode=False, force=False):
"""
Retrieving a summary of throughput for all Reverse Proxy instances
"""
return isamAppliance.invoke_get("Retrieving a summary of throughput for all Reverse Proxy instances",
... | 5,320,857 |
def do_regress(
test_features: np.ndarray,
train_features: np.ndarray,
train_targets: np.ndarray,
nn_count: int = 30,
batch_count: int = 200,
loss_method: str = "mse",
sigma_method: Optional[str] = "analytic",
variance_mode: Optional[str] = None,
kern: Optional[str] = None,
k_kwa... | 5,320,858 |
def set_computer_policy(
name, setting, cumulative_rights_assignments=True, adml_language="en-US"
):
"""
Set a single computer policy
Args:
name (str):
The name of the policy to configure
setting (str):
The setting to configure the named policy with
cum... | 5,320,859 |
def eStop_callback(state):
"""
Update state with new value of eStop_callback
"""
state.vars[eStop] | 5,320,860 |
def test_return_value():
"""
Test that parseVocabularySources returns a list of the correct length
where all elements are tuples.
"""
read_data = json.dumps({
'terms': [
{'name': 'foo', 'label': 'Foo'},
{'name': 'bar', 'label': 'Bar'},
{'name': 'baz', 'lab... | 5,320,861 |
def test_pressure():
"""Test module pressure.py by downloading
pressure.csv and testing shape of
extracted data has 19 rows and 2 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = pressure(test_path)
try:
assert x_train.shape == (19, 2)
except:
shutil.rmtree(test_path)
raise() | 5,320,862 |
def get_api_result(url):
"""
Retrieve JSON data from API via a supplied URL
"""
s = requests.Session()
r = s.get(url)
return r.json() | 5,320,863 |
def lens_compose(big_lens, *smaller_lenses):
"""
Compose many lenses
"""
return reduce(_lens_compose2, smaller_lenses, big_lens) | 5,320,864 |
def create_left_maskval_to_projmat_dict(seed, whimsy_server_weights,
whimsy_client_weights, left_mask,
right_mask, build_projection_matrix):
"""Creates a dictionary mapping the values of `left_mask` and `right_mask` to projection matrices... | 5,320,865 |
def renew_defs(func: PrimFunc):
"""Re-generate the definition nodes for a TIR, including VarDef, BufferDef.
This pass works as a simple DeepCopy to duplicate a function with different Vars and
Buffers but the same behavior
Parameters
----------
func: PrimFunc
The input function
Ret... | 5,320,866 |
def drop_tables(models: Optional[Iterable[str]] = None) -> None:
"""Drops all existing tables"""
if models is None:
models = get_all_models()
try:
db.drop_tables(models, safe=True, cascade=True)
# for model in models:
# m2ms = getattr(model._meta, "many_to_many", None)
... | 5,320,867 |
def predecessors(g: Mapping, node):
"""Iterator of nodes that have directed paths TO node
>>> g = {
... 0: [1, 2],
... 1: [2, 3, 4],
... 2: [1, 4],
... 3: [4]}
>>> set(predecessors(g, 4))
{0, 1, 2, 3}
>>> set(predecessors(g, 2))
{0, 1, 2}
>>> set(predecessors... | 5,320,868 |
def requires_common_raster(method):
"""
A decorator for spectrum methods that require that another spectrum as an input and require it to be sampled on the
same wavelength raster as us.
:param method:
A method belonging to a sub-class of Spectrum.
"""
def wrapper(spectrum, other, *args... | 5,320,869 |
def k8s_conf_dict(boot_conf, hb_conf):
"""
Generates and returns a dict of the k8s deployment configuration
:param boot_conf: the snaps-boot config dict
:param hb_conf: the adrenaline config dict
:return: dict with one key 'kubernetes' containing the rest of the data
"""
k8s_dict = __generat... | 5,320,870 |
def autodetect_mode(a, b):
"""
Return a code identifying the mode of operation (single, mixed, inverted mixed and
batch), given a and b. See `ops.modes` for meaning of codes.
:param a: Tensor or SparseTensor.
:param b: Tensor or SparseTensor.
:return: mode of operation as an integer code.
""... | 5,320,871 |
def f_unc(x, k, weight):
"""
similar to the raw function call, but uses unp instead of np for uncertainties calculations.
:return:
"""
term = 1
# calculate the term k^x / x!. Can't do this directly, x! is too large.
for n in range(0, int(x)):
term *= k / (x - n) * unp.exp(-k/int(x))
... | 5,320,872 |
def check_keys(gvar, mp, rp, op, not_optional=[], key_map=None, requires_server=True):
"""
Modify user settings.
"""
import csv2_help
from os import getenv
# Summarize the mandatory, required, and optional parameters for the current command.
mandatory = []
required = []
options = [... | 5,320,873 |
def get_data(n_clients):
"""
Import the dataset via sklearn, shuffle and split train/test.
Return training, target lists for `n_clients` and a holdout test set
"""
print("Loading data")
diabetes = load_diabetes()
y = diabetes.target
X = diabetes.data
# Add constant to emulate interce... | 5,320,874 |
def fn(r):
"""
Returns the number of fields based on their radial distance
:param r: radial distance
:return: number of fields at radial distance
"""
return 4 * r + 4 | 5,320,875 |
def delete_function(FunctionName=None, Qualifier=None):
"""
Deletes a Lambda function. To delete a specific function version, use the Qualifier parameter. Otherwise, all versions and aliases are deleted.
To delete Lambda event source mappings that invoke a function, use DeleteEventSourceMapping . For AWS s... | 5,320,876 |
def do_icon(name, *args, **kwargs):
"""
Render an icon
This template is an interface to the `icon` function from `django_icons`
**Tag name**::
icon
**Parameters**:
name
The name of the icon to be rendered
title
The title attribute for the icon
... | 5,320,877 |
def docs(c):
"""Build documentation."""
print("Rendering README...")
OUT_DIR.mkdir(parents=True, exist_ok=True)
cmd = ["rst2html", "README.rst", f"-d {OUT_DIR}/README.html"]
with c.cd(str(TOP_DIR)):
c.run(" ".join(cmd), pty=True)
print() | 5,320,878 |
def ED_BldGag(ED):
""" Returns the radial position of ElastoDyn blade gages
INPUTS:
- ED: either:
- a filename of a ElastoDyn input file
- an instance of FileCl, as returned by reading the file, ED = weio.read(ED_filename)
OUTPUTS:
- r_gag: The radial positions of the ga... | 5,320,879 |
def multiclass_confusion_matrix_metrics(
cm: np.ndarray, labels: List[str]
) -> Dict[str, int]:
"""
Create a dictionary of multiple class labels and their TP, TN, FP, FN values
:param cm: Confusion matrix
:param labels: string labels corresponding to the Confusion Matrix rows and columns
:return... | 5,320,880 |
def parse_arguments():
"""
Parse the command line arguments
"""
ap = argparse.ArgumentParser()
ap.add_argument("-ann", "--annotations_path", required=True,
help="Path to the directory containing the annotation files or path to the single annotation file.")
ap.add_argument("-a... | 5,320,881 |
def is_perf_benchmarks_scheduling_valid(
perf_waterfall_file, outstream):
"""Validates that all existing benchmarks are properly scheduled.
Return: True if all benchmarks are properly scheduled, False otherwise.
"""
scheduled_non_telemetry_tests = get_scheduled_non_telemetry_benchmarks(
perf_waterfal... | 5,320,882 |
def audit_postcode_type(postcode_types, postcode):
""" Process addr:postcode tag
Args:
postcode_types - Dictionary of keys not compliant to Singapore postcode format
postcode - Postcode; 'v' attribute of addr:postcode
"""
postcode_type_re = re.compile(r'^\d{6}$')
match_result = post... | 5,320,883 |
def download_link(object_to_download, download_filename, download_link_text):
"""Generates a link from which the user can download object_to_download
Method from https://discuss.streamlit.io/t/heres-a-download-function-that-works-for-dataframes-and-txt/4052
Args: object_to_download (str, pd.DataFra... | 5,320,884 |
def run_epoch(sess, cost_op, ops, reset, num_unrolls):
"""Runs one optimization epoch."""
sess.run(reset)
for _ in range(num_unrolls):
results = sess.run([cost_op] + ops)
return results[0], results[1:] | 5,320,885 |
def transformToUTM(gdf, utm_crs, estimate=True, calculate_sindex=True):
"""Transform GeoDataFrame to UTM coordinate reference system.
Arguments
---------
gdf : :py:class:`geopandas.GeoDataFrame`
:py:class:`geopandas.GeoDataFrame` to transform.
utm_crs : str
:py:class:`rasterio.crs.C... | 5,320,886 |
def exporttaskresult_delete_exports(sender, instance, *args, **kwargs):
"""
Delete associated files when deleting the FileProducingTaskResult.
"""
# The url should be constructed as [download context, run_uid, filename]
if getattr(settings, "USE_S3", False):
delete_from_s3(download_url=insta... | 5,320,887 |
def test_new_nice_naughty_strings(naughty_string):
"""Strings that don't match the new nice rules return False"""
# Explicit `is not None` check because `not (None)` returns True
assert is_new_nice(naughty_string) is not None
assert not is_new_nice(naughty_string) | 5,320,888 |
def remove_prohibited_characters(prompt_str: str) -> str:
"""
Remove prohibited characters.
"""
prohibited_chars = ["[", "]", "<", ">", "#", "%", "$", ":", ";", "~", "\r", " ", "\n"]
result_str = prompt_str
for ch in prohibited_chars:
result_str = result_str.replace(ch, "")
if "\x1b... | 5,320,889 |
def correction_factors(kappa, eta, gamma, b0, use_eta=True):
"""Computes correction factors for MLE of high dimensional logistic reg."""
system_ = get_system(kappa, eta, gamma, b0, use_eta)
if use_eta:
init = np.array([2, 2, np.sqrt(eta / 2), b0 / 2])
else:
init = np.array([2, 2, np.sqrt(gamma**2 + 1), ... | 5,320,890 |
def run_windows_build_process(*args, **kwargs):
"""
Runs the subprocess with the correct environment variables for building
"""
# Add call to set VC variables
cmd_input = ['call "%s" >nul' % _get_vcvars_path()]
cmd_input.append('set DEPOT_TOOLS_WIN_TOOLCHAIN=0')
cmd_input.append(' '.join(map... | 5,320,891 |
def remove_user_privilege(name):
"""Removes role
:param name: Rolre name
:type file: String
"""
try:
subprocess.check_output(["etcdctl", "role", "remove", name], stderr=subprocess.STDOUT)
logging.info("Role {} has been removed.".format(name))
except subprocess.CalledProcessError ... | 5,320,892 |
def bzr_find_files(dirname):
"""Find versioned files using bzr, for use in 'setuptools.file_finders'
entry point in setup.py."""
cmd = 'bzr ls --versioned ' + dirname
proc = subprocess.Popen(
cmd.split(), stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, ... | 5,320,893 |
def make_style_prompt(choices: list, default: str = None, prompt_msg: str = "Would you like to:",
main_style: str = "none",
frame_style: str = "none",
frame_border_style: str = "none") -> str:
"""
Prompts user in a cool way and retrieves what the... | 5,320,894 |
def test_storage_open(param, expected, empty_storage: MemoryStorage):
"""
При открытии стораджа только устанавливается префикс
:param storage:
:return:
"""
empty_storage.open({'prefix': param})
assert empty_storage._prefix == expected | 5,320,895 |
async def copy_branch(git_repo: Union[Path, str], branch_name: str, new_branch: str):
"""
Copy an existing branch to a new branch in repo (uses --force)
:param git_repo: Path to the repo
:param branch_name: Branch name
:param new_branch: The new branch name
:raises NoBranchesExc... | 5,320,896 |
def test_answer():
""" Load different .cnv versions with fCNV
"""
datafiles = glob(os.path.join(seabird_dir(), 'data/*', "*.cnv"))
assert len(datafiles) > 0, \
"No files available for testing at: %s" % datafiles
for f in datafiles:
print("Loading file: %s"... | 5,320,897 |
def jsonfile_1():
""" A JSON File object """
return thresh.TabularFile(
content=OrderedDict({"bar": 4, "foo": 3}), alias="JSON_", length_check=False, namespace_only=True
) | 5,320,898 |
def test_sort_dict():
"""Test the Helpers.sort_dict method"""
helpers = Helpers()
d1 = {}
assert helpers.sort_dict(d1) == {}
d2 = {"test": 1}
assert helpers.sort_dict(d2) == {"test": 1}
d3 = {"a": 1, "b": 2}
assert helpers.sort_dict(d3) == {"a": 1, "b": 2}
d4 = {"b": 2, "a": 1}
... | 5,320,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.