content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def change_service(**kwargs):
"""Makes a given change to a MRS service
Args:
**kwargs: Additional options
Keyword Args:
service_id (int): The id of the service
change_type (int): Type of change
url_context_root (str): The context root for this service
url_host_name ... | 37,300 |
def text_3d(string, depth=0.5):
"""Create 3D text."""
vec_text = _vtk.vtkVectorText()
vec_text.SetText(string)
extrude = _vtk.vtkLinearExtrusionFilter()
extrude.SetInputConnection(vec_text.GetOutputPort())
extrude.SetExtrusionTypeToNormalExtrusion()
extrude.SetVector(0, 0, 1)
extrude.Se... | 37,301 |
def get_secret_version(project: Optional[str] = None,
secret: Optional[str] = None,
version: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSecretVersionResult:
"""
Get a Secret Manager secret's version. For ... | 37,302 |
def logged_class(cls):
"""Class Decorator to add a class level logger to the class with module and
name."""
cls.logger = logging.getLogger("{0}.{1}".format(cls.__module__, cls.__name__))
return cls | 37,303 |
def set_beam_dimensions_from_yield_moment_and_strain(df, eps_yield, e_mod, f_crack=0.4, d_fact=2.1):
"""d_fact=2.1 from Priestley book"""
import sfsimodels as sm
assert isinstance(df, sm.FrameBuilding)
for ns in range(df.n_storeys):
beams = df.get_beams_at_storey(ns)
for beam in beams:
... | 37,304 |
def display_grid(rows, cols, xs, y_true, y_pred=None,
y_true_color='b', y_pred_color='g', figsize=(14, 7)):
"""Despliega ejemplos en una cuadrícula."""
fig, ax = plt.subplots(rows, cols, figsize=figsize)
i = 0
for r in range(rows):
for c in range(cols):
img = xs[i]
... | 37,305 |
def get_available_plugin_screens():
"""
Gets the available screens in this package for dynamic instantiation.
"""
ignore_list = ['__init__.py']
screens = []
for plugin in os.listdir(os.path.join(os.path.dirname(__file__))):
if (os.path.isdir(os.path.join(os.path.dirname(__file__), plugin... | 37,306 |
def crop_point(image, height_rate, width_rate):
"""Crop the any region of the image.
Crop region area = height_rate * width_rate *image_height * image_width
Args:
image: a Image instance.
height_rate: flaot, in the interval (0, 1].
width_rate: flaot, in the interval (0, 1].... | 37,307 |
def test_name_rename():
"""
Test a simple transformer to rename
"""
class Renamer(NodeTransformer):
def visit_Name(self, node, meta):
node.id = node.id + '_visited'
return node
renamer = Renamer()
mod = ast.parse("bob = frank")
transform(mod, renamer)
bob... | 37,308 |
def endiff(directory):
"""
Calculate the energy difference for a transition.
"""
from pybat.cli.commands.get import get_endiff
get_endiff(directory) | 37,309 |
def fileobj_video(contents=None):
"""
Create an "mp4" video file on storage and return a File model pointing to it.
if contents is given and is a string, then write said contents to the file.
If no contents is given, a random string is generated and set as the contents of the file.
"""
if conte... | 37,310 |
def delete_old_stock_items():
"""
This function removes StockItem objects which have been marked for deletion.
Bulk "delete" operations for database entries with foreign-key relationships
can be pretty expensive, and thus can "block" the UI for a period of time.
Thus, instead of immediately deleti... | 37,311 |
def test_smoke_parse_merpfile():
"""just parse"""
for mcf in good_mcfs + softerror_mcfs:
merp2tbl.parse_merpfile(mcf)
for mcf in harderror_mcfs:
with pytest.raises(NotImplementedError):
merp2tbl.parse_merpfile(mcf) | 37,312 |
def _toIPv4AddrString(intIPv4AddrInteger):
"""Convert the IPv4 address integer to the IPv4 address string.
:param int intIPv4AddrInteger: IPv4 address integer.
:return: IPv4 address string.
:rtype: str
Example::
intIPv4AddrInteger Return
---------------------------------
... | 37,313 |
def expand_case_matching(s):
"""Expands a string to a case insensitive globable string."""
t = []
openers = {"[", "{"}
closers = {"]", "}"}
nesting = 0
drive_part = WINDOWS_DRIVE_MATCHER.match(s) if ON_WINDOWS else None
if drive_part:
drive_part = drive_part.group(0)
t.appe... | 37,314 |
def look_behind(s: str, end_idx: int) -> str:
"""
Given a string containing semi-colons, find the span of text after the last
semi-colon.
"""
span = s[: (end_idx - 1)]
semicolon_matches = [
(m.group(), m.start(), m.end()) for m in re.finditer(r"(?<=(;))", span)
]
if len(semicolon... | 37,315 |
def sum_fspec(files, outname=None):
"""Take a bunch of (C)PDSs and sums them."""
# Read first file
ftype0, contents = get_file_type(files[0])
pdstype = ftype0.replace("reb", "")
outname = _assign_value_if_none(
outname, "tot_" + ftype0 + HEN_FILE_EXTENSION
)
def check_and_distribute... | 37,316 |
def make_aware(dt, tz=None):
"""
Convert naive datetime object to tz-aware
"""
if tz:
if isinstance(tz, six.string_types):
tz = pytz.timezone(tz)
else:
tz = pytz.utc
if dt.tzinfo:
return dt.astimezone(dt.tzinfo)
else:
return tz.localize(dt) | 37,317 |
def decrypt(ctxt, kx, spice, blocksize):
""" Main decryption function
Args:
ctxt: ciphertext
kx: key expansion table
spice: spice
blocksize: size of block
Returns:
Decrypted ciphertext
"""
spice = int_to_arr(spice, 512)
c... | 37,318 |
def test_list(app):
""" test list folder """
LOGGER.debug("sample: %r, %r", SAMPLE_FOLDER, SAMPLE_FILE)
site = app.get_site()
file = site.list_folder(f"{SAMPLE_FOLDER}/")["files"][0]
assert file["path"] == SAMPLE_KEY
assert file["name"] == SAMPLE_FILE | 37,319 |
def listCombination(lists) -> list:
"""
输入多个列表组成的列表,返回多列表中元素的所有可能组合
:param lists: 多个列表组成的列表
:return: 所有元素可能的组合
"""
result = []
resultAppend = result.append
from itertools import product
for i in product(*lists):
resultAppend(i)
return result | 37,320 |
def DoChopTraj(trajf, chopf, startns, stopns, translate=False):
"""
Chops a provided trajectory file based on a given
start time and end time in nanoseconds. Assuming
2 fs time step and writing results every 1000 steps.
Helpful for seeing how PMF evolves over time.
Parameters
-----... | 37,321 |
def test_single_link_is_dead(client):
"""Ensure a dead link is flagged as rotten status of 'yes'."""
creation = client.post(
helpers.authed_request("/", auth=helpers.VALID_AUTH),
json=helpers.item_dead_url(),
)
item_id = helpers.from_json(creation.data)["id"]
for _ in range(3):
... | 37,322 |
def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs):
"""DEPRECIATED - use to_sql
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame
name : string
con : DBAPI2 connection
flavor : {'sqlite', 'mysql'}, default 'sqlite... | 37,323 |
def edge_slope(e):
"""Calculate the slope of an edge, 'inf' for vertical edges"""
v = edge_vector(e)
try:
return v.z / round(v.xy.length, 4)
except ZeroDivisionError:
return float("inf") | 37,324 |
def test_reg_user_cannot_view_users_org_dne(reg_user_headers):
""" regular users cannot view users of an organization that doesn't exist """
org = str(uuid.uuid4())
res = requests.get(
f'{env.AWG_BASE_URL}{ORG_URL}/{org}/users',
headers=reg_user_headers
)
assert res.status_code == 40... | 37,325 |
def modify_table():
"""Delete old table from README.md, and put new one."""
delete_next_lines = False
with open("docs/README.md", "r", encoding="utf-8") as old_file:
lines = old_file.readlines()
with open("docs/README.md", "w", encoding="utf-8") as new_file:
for line in lines:
... | 37,326 |
def pkt_addrs(addr_fragment: str) -> tuple[Address, Address, Address, Address, Address]:
"""Return the address fields from (e.g): '01:078710 --:------ 01:144246'.
Will raise an InvalidAddrSetError is the address fields are not valid.
"""
# for debug: print(pkt_addrs.cache_info())
try:
addr... | 37,327 |
def token_downup(target_dict, source_dict):
"""Transform token features between different distribution.
Returns:
x_out (Tensor[B, N, C]): token features.
Args:
target_dict (dict): dict for target token information
source_dict (dict): dict for source token information.
"""
... | 37,328 |
def get_score(train_data,train_labels,test_data,test_labels,problem_type):
"""
Returns the f1 score resulting from 3NN classification if problem_type = 'classification',
or the mse from regression if problem_type = 'regression'
"""
if (problem_type=="classification"):
predictor = KNeighborsClassifier(n_neighb... | 37,329 |
def build_client_datasets_fn(train_dataset, train_clients_per_round):
"""Builds the function for generating client datasets at each round.
Args:
train_dataset: A `tff.simulation.ClientData` object.
train_clients_per_round: The number of client participants in each round.
Returns:
A function which re... | 37,330 |
def get_simple_grid(xbounds, ybounds, shift_origin=None):
""" """
xbounds = np.atleast_1d(xbounds)
if len(xbounds)==1:
xmin,xmax = 0,xbounds[0]
else:
xmin,xmax = xbounds
ybounds = np.atleast_1d(ybounds)
if len(ybounds)==1:
ymin,ymax = 0,ybounds[0]
else:
... | 37,331 |
def log_message(update, context):
"""Log the message that caused the update
Args:
update (Update): update event
context (CallbackContext): context passed by the handler
"""
if update.message:
try:
with open(get_abs_path("logs", "messages.log"), "a", encoding="utf8") ... | 37,332 |
def query_hecate(session, ra, dec, _radius, _verbose: bool = True):
""" Query the HECATE catalog """
m=0
gal_offset = []; mag = []; filt = []; dist = []; dist_err = []; gal_ra = []; gal_dec = []; distflag = []; source = []
# set up query
try:
query = session.query(HecateQ3cRecord)
... | 37,333 |
def all_main_characters(raw_data: AniListRawResponse) -> list[Character]:
"""Returns all of the main characters from the data."""
characters: list[Character] = anime_media(raw_data)["mainCharacters"]["nodes"]
return characters | 37,334 |
def sequence_to_ngram(sequence: str, N: int) -> List[str]:
"""
Chops a sequence into overlapping N-grams (substrings of length N)
:param sequence: str Sequence to convert to N-garm
:type sequence: str
:param N: Length ofN-grams (int)
:type N: int
:return: List of n-grams
:rtype: List[st... | 37,335 |
def _convert_for_receive(profile):
"""Convert profile to be fed into the receive model.
Args:
profile (pandas.DataFrame): Profile to convert.
Returns:
pandas.DataFrame: Converted profile.
"""
without_profile = profile[profile.age.isna()].reset_index(drop=True)
profile = profil... | 37,336 |
def _format_path(path):
"""Format path to data for which an error was found.
:param path: Path as a list of keys/indexes used to get to a piece of data
:type path: collections.deque[str|int]
:returns: String representation of a given path
:rtype: str
"""
path_with_brackets = (
''.j... | 37,337 |
def common_mean_watson(Data1, Data2, NumSims=5000, print_result=True, plot='no', save=False, save_folder='.', fmt='svg'):
"""
Conduct a Watson V test for a common mean on two directional data sets.
This function calculates Watson's V statistic from input files through
Monte Carlo simulation in order to... | 37,338 |
def empty_method(context):
"""
Even if it may not be used, context argument is required for step
implementation methods. It is an instance of behave.runner.Context
"""
pass | 37,339 |
def GetLayouts():
"""Returns the layout proxies on the active session.
Layout proxies are used to place views in a grid."""
return servermanager.ProxyManager().GetProxiesInGroup("layouts") | 37,340 |
def p_constdef(p):
"""constdef : DEFINE IDENTIFIER EQ argument"""
constdef = {p[2]: p[4]}
p[0] = constdef | 37,341 |
def fail(message: str) -> NoReturn:
"""
Shortcut for throwing a `DescriptiveError`. See its docs for details.
"""
raise DescriptiveError(dedent(message).strip()) | 37,342 |
def register(event: str, handler: Callable, exchange=""):
"""
为`event`注册一个事件处理器。如果
:param event:
:param handler:
:param exchange:
:return:
"""
global _registry
event = f"{exchange}/{event}"
item = _registry.get(event, {"handlers": set()})
item['handlers'].add(handler)
_r... | 37,343 |
def test_one_node_net():
"""
:return:
:rtype:
"""
net = create_empty_network(fluid='water')
j = create_junction(net, 1, 298.15)
create_ext_grid(net, j, 1, 298.15)
create_sink(net, j, 0.01)
create_source(net, j, 0.02)
pp.pipeflow(net)
assert np.isclose(net.res_ext_grid.valu... | 37,344 |
def GetRelativePath(starting_dir, dest):
"""Creates a relative path from the starting_dir to the dest."""
assert starting_dir
assert dest
starting_dir = os.path.realpath(starting_dir).rstrip(os.path.sep)
dest = os.path.realpath(dest).rstrip(os.path.sep)
common_prefix = GetCommonPath(... | 37,345 |
def _calculate_mean_cvss():
"""Calcuate the mean CVSS score across all known vulnerabilities"""
results = db.osvdb.aggregate([
{"$unwind": "$cvss_metrics"},
{"$group": {
"_id": "null",
"avgCVSS": {"$avg": "$cvss_metrics.calculated_cvss_base_score"}
}}
])
l... | 37,346 |
def decomposition_super1(centroid, highway, coherence,coordinates,input):
"""
Function to perform Experiment 2: Differential Decomposition with level-specific weight
Args:
centroid: Cluster centroid of super pixels
highway: Super pixels after Stage I Super pixeling
coherence: Coherence value a... | 37,347 |
async def webhook_ack():
"""
{
"application_code" : "<e.g. uuid4>"
}
"""
pass | 37,348 |
def drop_duplicate_titles(df_bso):
"""Drop lines whose titles are not unique.
The most common 'title' is "Introduction", appearing eg. in books and
journal issues.
The 'source_title' is the name of the journal or book series, which is
often not very helpful for very general collections that cover m... | 37,349 |
def get_deck_xs(bridge: Bridge, ctx: BuildContext) -> List[float]:
"""X positions of nodes on the bridge deck.
First the required X positions 'RX' are determined, positions of loads and
abutments etc.. After that a number of X positions are calculated between
each pair of adjacent X positions 'RX_i' an... | 37,350 |
def helicsGetFederateByName(fed_name: str) -> HelicsFederate:
"""
Get an existing `helics.HelicsFederate` from a core by name.
The federate must have been created by one of the other functions and at least one of the objects referencing the created federate must still be active in the process.
**Parame... | 37,351 |
def persistant_property(*key_args):
"""Utility decorator for Persistable-based objects. Adds any arguments as properties
that automatically loads and stores the value in the persistence table in the database.
These arguments are created as permanent persistent properties."""
def _decorator(cls):
... | 37,352 |
def _initialize_ort_devices():
"""
Determine available ORT devices, and place info about them to os.environ,
they will be available in spawned subprocesses.
Using only python ctypes and default lib provided with NVIDIA drivers.
"""
if int(os.environ.get('ORT_DEVICES_INITIALIZED', 0)) == 0:
... | 37,353 |
def states():
"""
Get a dictionary of Backpage city names mapped to their respective states.
Returns:
dictionary of Backpage city names mapped to their states
"""
states = {}
fname = pkg_resources.resource_filename(__name__, 'resources/City_State_Pairs.csv')
with open(fname, 'rU') as csvfile:
rea... | 37,354 |
def matrix_set_diag(input_x, diagonal, k=0, alignment="RIGHT_LEFT"):
"""
Calculate a batched matrix tensor with new batched diagonal values.
Args:
input_x (Tensor): a :math:`(..., M, N)` matrix to be set diag.
diagonal (Tensor): a :math`(..., max_diag_len)`, or `(..., num_diags, max_diag_le... | 37,355 |
def execute_payment(pp_req):
"""Executes a payment authorized by the client."""
payment = paypalrestsdk.Payment.find(pp_req['paymentId'])
if payment.execute({"payer_id": pp_req['PayerID']}):
return True
return False | 37,356 |
def FillSegmentWithNops(x):
"""
Sets every byte in the segment that contains 'x' to a
NOP by changing its value to 0x90 and marking it as code.
"""
for Byte in segment.SegmentAddresses(x):
ida.patch_byte(Byte, 0x90)
ida.MakeCode(Byte) | 37,357 |
def create_structural_eqs(X, Y, G, n_nodes_se=40, n_nodes_M=100, activation_se='relu'):
"""
Method to create structural equations (F:U->X) and the original prediction model (M:X->Y). This also calculates and stores residuals.
Parameters
----------
X : pandas DataFrame
input features of the ... | 37,358 |
def twitch_checkdspstatus(_double_check: bool) -> bool:
"""
Uses current Selenium browser to determine if DSP is online on Twitch.
:param _double_check: Internally used to recursively call function again to double check if DSP is online
:return: True if DSP is online. False is DSP is offline.
"""
... | 37,359 |
def test_cold_start(sdc_builder, sdc_executor, cluster, db, stored_as_avro, external_table, partitioned):
"""Validate Cold Start no table and no data. This test also tests different types of table and methods of creation.
The pipeline looks like:
dev_raw_data_source >> expression_evaluator >> hive_m... | 37,360 |
def random_walk(humans, dt, energy, temperature):
"""
calculates location, speed and acceleration by adding random values to the speed
Args:
humans (list): list of all humans
dt (float): time step in which the movement is calculated
energy (float): amount of movement
Returns:
... | 37,361 |
def format_name(name_format: str, state: State):
"""Format a checkpoint filename according to the ``name_format`` and the training :class:`~.State`.
The following format variables are available:
+------------------------+-------------------------------------------------------+
| Variable ... | 37,362 |
def build_arglist(builder, nb):
"""
arglist: (argument ',')* ( '*' test [',' '**' test] |
'**' test |
argument |
[argument ','] )
"""
atoms = get_atoms(builder, nb)
arguments, stararg, dstararg = parse_arg... | 37,363 |
def allsync(local_values, comm=None, op=None):
"""Perform allreduce if MPI comm is provided."""
if comm is None:
return local_values
if op is None:
from mpi4py import MPI
op = MPI.MAX
return comm.allreduce(local_values, op=op) | 37,364 |
def output_variant_tsv(interpretation_request, force_update=False):
"""Output a variant TSV to match Alamut Batch format for annotation.
If a variant TSV for the given interpretation_request (version, and genome
build) exists then pass. If a matching file does not exist or the
force_update boolean is T... | 37,365 |
def vec_bin_array(arr, m):
"""
Arguments:
arr: Numpy array of positive integers
m: Number of bits of each integer to retain
Returns a copy of arr with every element replaced with a bit vector.
Bits encoded as int8's.
"""
to_str_func = np.vectorize(lambda x: np.binary_repr(x).zfill(m))
... | 37,366 |
def make_api_links(file_path, file_type):
"""Build links to automodapi documentation."""
start_link = "../"
re_api = re.compile(r'<span class="pre">~gammapy\.(.*?)</span>')
if file_type == "ipynb":
start_link = URL_DOCS
re_api = re.compile(r"`~gammapy\.(.*?)`")
txt = file_path.read_... | 37,367 |
def parse_bafs(stream: Iterator[str]) -> List[BAF]:
"""Parses allelic counts output from GATK ModelSegments, which is a SAM-style
header comprising lines starting with @ followed by single line with column
names (CONTIG, POSITION, REF_COUNT, ALT_COUNT, REF_NUCLEOTIDE, ALT_NUCLEOTIDE)."""
skip_header(... | 37,368 |
def logpdf(x, chi, c):
"""
Logarithm of the PDF of the ARGUS probability distribution.
"""
if c <= 0:
raise ValueError('c must be positive')
if chi <= 0:
raise ValueError('chi must be positive')
if x < 0 or x > c:
return mpmath.mp.ninf
with mpmath.extradps(5):
... | 37,369 |
def sample(colors: list, max_colors: int = 8, sensitivity: int = 75) -> list:
"""
Sample most common colors from a PIL Image object.
:param colors: list of RGB color tuples eg. [(0, 0, 0), (255, 255, 255)]
:param max_colors: maximum number of colors to return
:param sensitivity: how perceptively di... | 37,370 |
def tf_example_to_feature_description(example,
num_timesteps=DEFAULT_NUM_TIMESTEPS):
"""Takes a string tensor encoding an tf example and returns its features."""
if not tf.executing_eagerly():
raise AssertionError(
'tf_example_to_reverb_sample() only works under eag... | 37,371 |
def setupmethod(f: F) -> F:
"""Wraps a method so that it performs a check in debug mode if the
first request was already handled.
"""
def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
if self._is_setup_finished():
raise AssertionError(
"A setup function... | 37,372 |
def generateStructuredGridPoints(nx, ny, v0, v1, v2, v3):
"""
Generate structured grid points
:param nx: number of x cells
:param ny: number of y cells
:param v0: south west corner
:param v1: south east corner
:param v2: north east corner
:param v3: north west corner
:returns array o... | 37,373 |
def Keywords(lang_id=0):
"""Returns Specified Keywords List
@param lang_id: used to select specific subset of keywords
"""
return [PY_KW, PY_BIN] | 37,374 |
def cli() -> None:
"""
Command line interface for TESMART device RT-05
If none options are defined, it uses config.toml
""" | 37,375 |
def clear(keyword):
"""``clear`` property validation."""
return keyword in ('left', 'right', 'both', 'none') | 37,376 |
def PermissionsListOfUser(perm_list: List[str]) -> List[str]:
"""
Takes a list of items and asserts that all of them are in the permissions list of
a user.
:param perm_list: A list of permissions encoded as ``str``
:return: The input perm_list
:raises Invalid: If the user does not ha... | 37,377 |
def PrepareForBuild(input_proto, output_proto, _config):
"""Prepare to build toolchain artifacts.
The handlers (from _TOOLCHAIN_ARTIFACT_HANDLERS above) are called with:
artifact_name (str): name of the artifact type.
chroot (chroot_lib.Chroot): chroot. Will be None if the chroot has not
yet... | 37,378 |
def for_properties(path: Path = Path('config.json')):
"""
Simple externalized configuration loader. Properties are loaded from a file containing a JSON object.
:param path: Path to the file.
:return: Simple namespace with the key/value pairs matching the loaded json object.
"""
if not path or no... | 37,379 |
async def discordHandleGameChange(cls:"PhaazebotDiscord", event_list:List["StatusEntry"]) -> None:
"""
With a list status entry's from twitch,
we format and send all gamechange announcements to all discord channels
"""
if not cls: return # Discord Client not ready or off
event_channel_list:str = ",".join(Event.... | 37,380 |
def guess_components(paths, stop_words=None, n_clusters=8):
"""Guess components from an iterable of paths.
Args:
paths: list of string containing file paths in the project.
stop_words: stop words. Passed to TfidfVectorizer.
n_clusters: number of clusters. Passed to MiniBatchKMeans.
... | 37,381 |
def get_instance_tags(ec2_client: boto3.Session.client, instance_id: str):
"""Get instance tags to parse through for selective hardening"""
tag_values = []
tags = ec2_client.describe_tags(
Filters=[
{
"Name": "resource-id",
"Values": [
... | 37,382 |
def create_app(config_name=None) -> Flask:
"""Create a flask app instance."""
app = Flask("__name__")
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# import blueprints
from scorer.controller import prediction_app
app.register_blueprint(prediction_app)
... | 37,383 |
def getmasterxpub(client: HardwareWalletClient, addrtype: AddressType = AddressType.WIT, account: int = 0) -> Dict[str, str]:
"""
Get the master extended public key from a client
:param client: The client to interact with
:return: A dictionary containing the public key at the ``m/44'/0'/0'`` derivation... | 37,384 |
def test_FilterAnalyzer():
"""Testing the FilterAnalyzer """
t = np.arange(np.pi/100,10*np.pi,np.pi/100)
fast = np.sin(50*t)+10
slow = np.sin(10*t)-20
fast_mean = np.mean(fast)
slow_mean = np.mean(slow)
fast_ts = ts.TimeSeries(data=fast,sampling_rate=np.pi)
slow_ts = ts.TimeSeries(data... | 37,385 |
def serialize(
obj: Any,
annotation: Any,
config: SerializerConfig
) -> str:
"""Convert the object to JSON
Args:
obj (Any): The object to convert
annotation (Annotation): The type annotation
config (SerializerConfig): The serializer configuration
Returns:
... | 37,386 |
def validate_dvprel(prop_type, pname_fid, validate):
"""
Valdiates the DVPREL1/2
.. note:: words that start with integers (e.g., 12I/T**3) doesn't
support strings
"""
if validate:
msg = 'DVPREL1: prop_type=%r pname_fid=%r is invalid' % (prop_type, pname_fid)
#if prop... | 37,387 |
def generate_thrift():
"""Generates the thrift metric definitions file used by Impala."""
metrics = load_metrics(options.input_schema_path)
metrics_json = json.dumps(metrics, sort_keys=True, indent=2)
# dumps writes the TMetricKind and TUnit as quoted strings which is not
# interpreted by the thrift compiler... | 37,388 |
def is_ligature(archar):
"""Checks for Arabic Ligatures like LamAlef.
(LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_HAMZA_BELOW, LAM_ALEF_MADDA_ABOVE)
@param archar: arabic unicode char
@type archar: unicode
@return:
@rtype:Boolean
"""
return archar in LIGUATURES | 37,389 |
def write_config_file(config: ClientConfig, path: str) -> None:
"""
Writes a config object to a config file
:param config: the config to write
:param path: the path to write the file
:return: None
"""
json_str = json.dumps(json.loads(jsonpickle.encode(config)), indent=4, sort_keys=True)
... | 37,390 |
def _get_embl_key(line):
"""Return first part of a string as a embl key (ie 'AC M14399;' -> 'AC')"""
# embl keys have a fixed size of 2 chars
return line[:2] | 37,391 |
def poke(event=None):
"""Poke event, checks if the user is still there... currently just bugs the user"""
msg_list.insert(END, "Bot -> Are you still there?")
CONTEXT[USERNAME] = 'here' | 37,392 |
def size_too_big(path):
"""Returns true is file is too large (5MB)
"""
five_mb = 5242880
return os.path.getsize(path) > five_mb | 37,393 |
def store_h2o_frame(data, directory, filename, force=False, parts=1):
"""
Export a given H2OFrame to a path on the machine this python session is currently connected to.
:param data: the Frame to save to disk.
:param directory: the directory to the save point on disk.
:param filename: the name to s... | 37,394 |
def get_region_data(region, lastday=-1, printrows=0, correct_anomalies=True,
correct_dow='r7'):
"""Get case counts and population for one municipality.
It uses the global DFS['mun'], DFS['cases'] dataframe.
Parameters:
- region: region name (see below)
- lastday: last day to i... | 37,395 |
def write(path: Union[str, Path], entity_key: str, data: Any):
"""Writes data to the HDF file at the given path to the given key.
Parameters
----------
path
The path to the HDF file to write to.
entity_key
A string representation of the internal HDF path where we want to
wri... | 37,396 |
def MONTH(*args) -> Function:
"""
Returns the month of the year a specific date falls in, in numeric format.
Learn more: https//support.google.com/docs/answer/3093052
"""
return Function("MONTH", args) | 37,397 |
def local_tmp_dir():
"""tmp directory for tests"""
tmp_dir_path = "./tmp"
if not os.path.isdir(tmp_dir_path):
os.mkdir(tmp_dir_path)
return tmp_dir_path | 37,398 |
def Install(browser):
"""Installs |browser|, if necessary. It is not possible to install
an older version of the already installed browser currently.
Args:
browser: specific browst to install.
Returns:
whether browser is installed.
"""
# Only dynamic installation of browsers for Windows now.
... | 37,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.