content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_get_sensitive_hits_object_detail_when_invalid_values_are_provided(client, snapshot_id, snappable_id):
"""
Tests get_sensitive_hits_object_detail method of PolarisClient when invalid values are provided
"""
from rubrik_polaris.sonar.object import get_sensitive_hits_object_detail, ERROR_MESSAGES
... | 5,329,800 |
def qc():
"""quick-command: a cli for remembering commands"""
pass | 5,329,801 |
def credentials():
"""
Fixture to extract the user credentials for logging into the Tark database.
Requires that there is a crd.json file in the root directory of the module.
Returns
-------
crd : dict
Dictionary object of the user, password, host, port and db
"""
with open('cr... | 5,329,802 |
def gunzip(content):
"""
Decompression is applied if the first to bytes matches with
the gzip magic numbers.
There is once chance in 65536 that a file that is not gzipped will
be ungzipped.
"""
if len(content) == 0:
raise DecompressionError('File contains zero bytes.')
gzip_magic_numbers = [ 0x1f... | 5,329,803 |
def write_to_fits(file_name, data):
"""Write FITS file
This method writes the output image array data to a FITS file.
Parameters
----------
file_name : str
Name of file with path
data : np.ndarray
Image data array
"""
fits.PrimaryHDU(data).writeto(file_name) | 5,329,804 |
def get_rigid_elements_with_node_ids(model: BDF, node_ids):
"""
Gets the series of rigid elements that use specific nodes
Parameters
----------
node_ids : List[int]
the node ids to check
Returns
-------
rbes : List[int]
the set of self.rigid_elements
"""
try:
... | 5,329,805 |
def genFileBase(f):
""" Given a filename, generate a safe 'base' name for
HTML and PNG filenames """
baseName = w2res.getBaseMulti(f)
baseName = "R"+w2res.removeGDBCharacters(baseName)
return baseName | 5,329,806 |
def retrieve_results_average(query, index, k=10, verbose=False, tfidf=False):
"""
(NOT USED) Given a query, return most similar papers from the specified FAISS index.
Also prunes the resulting papers by filtering out papers whose authors do not have tags.
This uses the average paper representations per ... | 5,329,807 |
def part1(data):
"""
""" | 5,329,808 |
def _json_custom_hook(d):
"""Serialize NumPy arrays."""
if isinstance(d, dict) and '__ndarray__' in d:
data = base64.b64decode(d['__ndarray__'])
return np.frombuffer(data, d['dtype']).reshape(d['shape'])
elif isinstance(d, dict) and '__qbytearray__' in d:
return _decode_qbytearray(d[... | 5,329,809 |
def basic_pyxll_function_3(x):
"""docstrings appear as help text in Excel"""
return x | 5,329,810 |
def log_mean_exp(x, dim=1):
"""
log(1/k * sum(exp(x))): this normalizes x.
@param x: PyTorch.Tensor
samples from gaussian
@param dim: integer (default: 1)
which dimension to take the mean over
@return: PyTorch.Tensor
mean of x
"""
m = torch.max(x, d... | 5,329,811 |
def get_shot_end_frame(shot_node):
"""
Returns the end frame of the given shot
:param shot_node: str
:return: int
"""
return maya.cmds.getAttr('{}.endFrame'.format(shot_node)) | 5,329,812 |
def query_iterator(query, limit=50):
"""Iterates over a datastore query while avoiding timeouts via a cursor.
Especially helpful for usage in backend-jobs."""
cursor = None
while True:
bucket, cursor, more_objects = query.fetch_page(limit, start_cursor=cursor)
if not bucket:
... | 5,329,813 |
def test_poll_for_activity_identity(monkeypatch, poll=poll):
"""Test that identity is passed to poll_for_activity.
"""
current_activity = activity_run(monkeypatch, poll)
current_activity.poll_for_activity(identity='foo')
current_activity.poll.assert_called_with(identity='foo') | 5,329,814 |
def is_integer():
""" Generates a validator to validate if the value
of a property is an integer.
"""
def wrapper(obj, prop):
value = getattr(obj, prop)
if value is None:
return (True, None)
try:
int(value)
except ValueError:
return... | 5,329,815 |
def int_inputs(n):
"""An error handling function to get integer inputs from the user"""
while True:
try:
option = int(input(Fore.LIGHTCYAN_EX + "\n >>> "))
if option not in range(1, n + 1):
i_print_r("Invalid Entry :( Please Try Again.")
contin... | 5,329,816 |
def test_label_dict():
"""@TODO: Docs. Contribution is welcome."""
dataset = TextClassificationDataset(texts, labels)
label_dict = dataset.label_dict
assert label_dict == {"negative": 0, "positive": 1} | 5,329,817 |
def load_cElementTree(finder, module):
"""the cElementTree module implicitly loads the elementtree.ElementTree
module; make sure this happens."""
finder.IncludeModule("elementtree.ElementTree") | 5,329,818 |
def gen_binder_rst(fname, binder_conf):
"""Generate the RST + link for the Binder badge.
Parameters
----------
fname: str
The path to the `.py` file for which a Binder badge will be generated.
binder_conf: dict | None
If a dictionary it must have the following keys:
'url': ... | 5,329,819 |
def downgrade():
"""Make refresh token field not nullable."""
bind = op.get_bind()
session = Session(bind=bind)
class CRUDMixin(object):
"""Mixin that adds convenience methods for CRUD (create, read, update, delete) ops."""
@classmethod
def create_as(cls, current_user, **kwargs... | 5,329,820 |
def height(grid):
"""Gets the height of the grid (stored in row-major order)."""
return len(grid) | 5,329,821 |
def test_blank_index_upload_missing_indexd_credentials_unable_to_load_json(
app, client, auth_client, encoded_creds_jwt, user_client
):
"""
test BlankIndex upload call but unable to load json with a ValueError
"""
class MockArboristResponse:
"""
Mock response for requests lib for Ar... | 5,329,822 |
def parameterize(url):
"""Encode input URL as POST parameter.
url: a string which is the URL to be passed to ur1.ca service.
Returns the POST parameter constructed from the URL.
"""
return urllib.urlencode({"longurl": url}) | 5,329,823 |
def sum_ints(*args, **kwargs):
""" This function is contrived to illustrate args in a function.
"""
print args
return sum(args) | 5,329,824 |
def set_have_mods(have_mods: bool) -> None:
"""set_have_mods(have_mods: bool) -> None
(internal)
"""
return None | 5,329,825 |
def test_from_db_file(datapath):
"""Test instantiate SearchDB from a yaml file"""
searchdb = SearchDB.from_db_file(datapath / 'disp_db.yaml')
assert searchdb.user is None
assert searchdb.host == 'localhost'
assert searchdb.database | 5,329,826 |
def log(ui, repo, *pats, **opts):
"""show revision history of entire repository or files
Print the revision history of the specified files or the entire
project.
If no revision range is specified, the default is ``tip:0`` unless
--follow is set, in which case the working directory parent is
us... | 5,329,827 |
def user_required(handler):
"""
Decorator for checking if there's a user associated
with the current session.
Will also fail if there's no session present.
"""
def check_login(self, *args, **kwargs):
"""
If handler has no login_url specified invoke a 403 error... | 5,329,828 |
def checkGlyphExistsInLayer(project):
"""Check whether a glyph in a layer exists, if the parent glyph specifies a
layerName for a variation.
"""
for glyphSetName, glyphSet, glyphName, glyph in iterGlyphs(project):
for layerName in getattr(glyph, "glyphNotInLayer", ()):
yield f"'{glyp... | 5,329,829 |
def student_editapplication(request):
"""View allowing a student to edit and/or submit their saved application"""
FSJ_user = get_FSJ_user(request.user.username)
award_id = request.GET.get('award_id', '')
try:
award = Award.objects.get(awardid = award_id)
application = A... | 5,329,830 |
def create_and_calibrate(servers=None, nserver=8, npipeline_per_server=4, cal_directory='/home/ubuntu/mmanders'):
"""
Wraper to create a new BeamPointingControl instance and load bandpass
calibration data from a directory.
"""
# Create the instance
control_instance = BeamPointingControl(ser... | 5,329,831 |
def test_geometry_contains(feature_list, field_list):
"""
Assertions for 'contains' comparison operation
:param feature_list: feature collection list
:param field_list: feature field names
"""
cql_ast = get_ast('CONTAINS(geometry,POINT(-75 45))')
assert cql_ast == SpatialPredicateNode(
... | 5,329,832 |
def get_haps_from_variants(translation_table_path: str, vcf_data: str,
sample_id: str, solver: str = "CBC",
config_path: str = None, phased = False) -> tuple:
"""
Same as get_haps_from_vcf, but bypasses the VCF file so that you can provide formatted vari... | 5,329,833 |
def _populate_number_fields(data_dict):
"""Returns a dict with the number fields N_NODE, N_EDGE filled in.
The N_NODE field is filled if the graph contains a non-`None` NODES field;
otherwise, it is set to 0.
The N_EDGE field is filled if the graph contains a non-`None` RECEIVERS field;
otherwise, it is set ... | 5,329,834 |
def to_graph(e,
recursive=True,
verbose=False,
arg_values=None,
arg_types=None,
partial_types=None):
"""Compile a Python entity into equivalent TensorFlow code.
Currently supported entities:
* functions
* classes
Classes are handled by con... | 5,329,835 |
def test_nullable_field_validation(e, m):
"""Detect if data source field breaks the contract.
Data source cannot have nullable field if corresponding entity
attribute is not annotated with Optional type.
"""
expected = ""
with pytest.raises(MapperError) as exc_info:
Mapper(e.Group, m.G... | 5,329,836 |
def to_frame(nc):
"""
Convert netCDF4 dataset to pandas frames
"""
s_params = ["time", "bmnum", "noise.sky", "tfreq", "scan", "nrang", "intt.sc", "intt.us", "mppul", "scnum"]
v_params = ["v", "w_l", "gflg", "p_l", "slist", "gflg_conv", "gflg_kde", "v_mad", "cluster_tag", "ribiero_gflg"]
_dict_ =... | 5,329,837 |
def gather_grade_info(fctx, flow_session, answer_visits):
"""
:returns: a :class:`GradeInfo`
"""
all_page_data = (FlowPageData.objects
.filter(
flow_session=flow_session,
ordinal__isnull=False)
.order_by("ordinal"))
points = 0
provisional... | 5,329,838 |
def test_bool_str():
"""Test to string of bool literal renders inmanta true/false and not python"""
statements = parse_code(
"""
val1 = true
val2 = false
"""
)
assert len(statements) == 2
assert isinstance(statements[0], Assign)
assert isinstance(statements[1], Assign)
assert str(sta... | 5,329,839 |
def numericalSort(value):
"""
複数ファイルの入力の際、ファイル名を昇順に並べる。
Input
------
value : 読み込みたいファイルへのパス
Output
------
parts : ファイル中の数字
"""
numbers = re.compile(r'(\d+)')
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts | 5,329,840 |
def load_and_validate(response):
""" Loads JSON data from an HTTP response, then validates it. """
validate_response(response.json()) | 5,329,841 |
def add_markings(obj, marking, selectors):
"""
Append a granular marking to the granular_markings collection. The method
makes a best-effort attempt to distinguish between a marking-definition
or language granular marking.
Args:
obj: An SDO or SRO object.
marking: identifier or list... | 5,329,842 |
def test_custom_font():
"""Test figure using a custom font with fontspec in config file..."""
with build_pypgf(srcdir, "custom_font.py") as res:
assert res.returncode == 0, "Failed to build tests/sources/fonts/custom_font.py" | 5,329,843 |
def add_to_list(str_to_add, dns_names):
"""
This will add a string to the dns_names array if it does not exist.
It will then return the index of the string within the Array
"""
if str_to_add not in dns_names:
dns_names.append(str_to_add)
return dns_names.index(str_to_add) | 5,329,844 |
def check_icmp_path(sniffer, path, nodes, icmp_type = ipv6.ICMP_ECHO_REQUEST):
"""Verify icmp message is forwarded along the path.
"""
len_path = len(path)
# Verify icmp message is forwarded to the next node of the path.
for i in range(0, len_path):
node_msg = sniffer.get_messages_sent_by(p... | 5,329,845 |
def ping():
"""Determine if the container is working and healthy. In this sample container, we declare
it healthy if we can load the model successfully."""
health = scoring_service.get_model() is not None # You can insert a health check here
status = 200 if health else 404
return flask.Response(re... | 5,329,846 |
def cyber_pose_to_carla_transform(cyber_pose):
"""
Convert a Cyber pose a carla transform.
"""
return carla.Transform(
cyber_point_to_carla_location(cyber_pose.position),
cyber_quaternion_to_carla_rotation(cyber_pose.orientation)) | 5,329,847 |
def _is_predator_testcase(testcase):
"""Return bool and error message for whether this testcase is applicable to
predator or not."""
if build_manager.is_custom_binary():
return False, 'Not applicable to custom binaries.'
if testcase.regression != 'NA':
if not testcase.regression:
return False, 'N... | 5,329,848 |
def main():
"""
How to run this script:
python dump_tf_graph.py protxt_file_path
"""
with gfile.FastGFile(argv[1],'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name='... | 5,329,849 |
def _a_ij_Aij_Dij2(A):
"""A term that appears in the ASE of Kendall's tau and Somers' D."""
# See `somersd` References [2] section 4: Modified ASEs to test the null hypothesis...
m, n = A.shape
count = 0
for i in range(m):
for j in range(n):
count += A[i, j]*(_Aij(A, i, j) - _Dij... | 5,329,850 |
def check_metadata_format(paramfile, is_file=True):
"""
Checks HLSP files for compliance. Logs errors and warnings to log file.
:param paramfile: The parameter file created by 'precheck_data_format' and
'select_data_templates'.
:type paramfile: str
"""
# Read in all the YAML standard... | 5,329,851 |
def getWeekHouseMsg():
"""
获取一周的房产信息
:return:
"""
response = requests.get(url=week_host, headers=headers).text
soup = BeautifulSoup(response, 'lxml')
house_raw = soup.select('div[class=xfjj]')
# 二手房均价
second_hand_price = house_raw[0].select('.f36')[0].string
# 二手房成交数目
second_hand_num = house_raw[1].select('.... | 5,329,852 |
def _match(x, y):
"""Returns an array of the positions of (first) matches of y in x
This is similar to R's `match` or Matlab's `[Lia, Locb] = ismember`
See https://stackoverflow.com/a/8251757
This assumes that all values in y are in x, but no check is made
Parameters
--------... | 5,329,853 |
def add_type(s, validator):
"""Add a type. May override most existing types.
Raises ConfigValueError if type is reserved or invalid,
and ConfigTypeError if it's not a string.
The validator is not, umm, validated."""
if not isinstance(s, basestring):
raise ConfigTypeError('type must be a string')
... | 5,329,854 |
def create_default_support_dir():
""" create a empty panzer support directory """
# - create .panzer
os.mkdir(const.DEFAULT_SUPPORT_DIR)
info.log('INFO', 'panzer', 'created "%s"' % const.DEFAULT_SUPPORT_DIR)
# - create subdirectories of .panzer
subdirs = ['preflight',
'filter',
... | 5,329,855 |
def download_mnist_tfrecords() -> str:
"""
Return the path of a directory with the MNIST dataset in TFRecord format.
The dataset will be downloaded into WORK_DIRECTORY, if it is not already
present.
"""
if not tf.gfile.Exists(WORK_DIRECTORY):
tf.gfile.MakeDirs(WORK_DIRECTORY)
filepa... | 5,329,856 |
def buildMeanAndCovMatFromRow(row):
"""
Build a covariance matrix from a row
Paramters
---------
row : astropy Table row
Entries: {X, Y, Z, U, V, W, dX, dY, ..., cXY, cXZ, ...}
Return
------
cov_mat : [6,6] numpy array
Diagonal elements are dX^2, dY^2, ...
Off-d... | 5,329,857 |
def getNumArgs(obj):
"""Return the number of "normal" arguments a callable object takes."""
sig = inspect.signature(obj)
return sum(1 for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_ONLY or
p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD) | 5,329,858 |
def test_get_firmware_version() -> None:
"""Test that we can get the firmware version from the serial interface."""
backend = SRV4MotorBoardHardwareBackend("COM0", serial_class=MotorSerial)
serial = cast(MotorSerial, backend._serial)
serial.check_data_sent_by_constructor()
assert backend.firmware_ve... | 5,329,859 |
def min_distance_from_point(vec, p):
"""
Minimial distance between a single point and each point along a vector (in N dimensions)
"""
return np.apply_along_axis(np.linalg.norm, 1, vec - p).min() | 5,329,860 |
def create_environment(env_config):
"""Creates an simple sequential testing environment."""
if env_config['num_candidates'] < 4:
raise ValueError('num_candidates must be at least 4.')
SimpleSequentialResponse.MAX_DOC_ID = env_config['num_candidates'] - 1
user_model = SimpleSequentialUserModel(
env_co... | 5,329,861 |
def nb_to_python(nb_path):
"""convert notebook to python script"""
exporter = python.PythonExporter()
output, resources = exporter.from_filename(nb_path)
return output | 5,329,862 |
def add(data_source: DataSource) -> DataSource:
"""
Add a new data source to AuroraX
Args:
data_source: the data source to add (note: it must be a fully-defined
DataSource object)
Returns:
the newly created data source
Raises:
pyaurorax.exceptions.AuroraXMaxRet... | 5,329,863 |
def list_installed(args):
"""List the installed models."""
# Find installed models, ignoring special folders like R.
if os.path.exists(MLINIT):
msg = " in '{}'.".format(MLINIT)
models = [f for f in os.listdir(MLINIT)
if os.path.isdir(os.path.join(MLINIT, f)) and f != "R" ... | 5,329,864 |
def initialize():
"""Do all necessary actions before input loop starts"""
isbench = False
# udp,register,server,room
arg_dict = get_args()
if "udp" in arg_dict and arg_dict["udp"].isdigit():
StateHolder.udp_listen_port = int(arg_dict["udp"])
else:
StateHolder.udp_listen_port = 50... | 5,329,865 |
def jacobian_numba(coordinates, points, jac, greens_function):
"""
Calculate the Jacobian matrix using numba to speed things up.
It works both for Cartesian and spherical coordiantes.
We need to pass the corresponding Green's function through the
``greens_function`` argument.
"""
east, nort... | 5,329,866 |
def read_text(file, num=False):
""" Read from txt [file].
If [num], then data is numerical data and will need to convert each
string to an int.
"""
with open(file,'r') as f:
data = f.read().splitlines()
if num:
data = [int(i) for i in data]
return data | 5,329,867 |
def p_base_access(p):
"""base_access : BASE MEMBERACCESS IDENTIFIER
| BASE LBRACKET expression_list RBRACKET
""" | 5,329,868 |
def interpolate_rbf(x, y, z, x_val, y_val, z_val):
"""Radial basis function interpolation.
Parameters
----------
x : np.ndarray
x-faces or x-edges of a mesh
y : np.ndarray
y-faces or y-edges of a mesh
z : np.ndarray
z-faces or z-edges of a mesh
x_val : np.ndarray
... | 5,329,869 |
def svm_loss_naive(W, X, y, reg):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a... | 5,329,870 |
def _chambollepock_tv2d(x, w, y, max_iters, info, **kwargs):
"""Chambolle and Pock's method for 2D TV proximity"""
_condatchambollepock_tv2d(x, w, y, max_iters, info, algorithm=1) | 5,329,871 |
def get_batch(image_files, width, height, mode='RGB'):
"""
Get a single batch of data as an NumPy array
"""
data_batch = np.array(
[get_image(sample_file, width, height, mode) for sample_file in image_files]).astype(np.float32)
# Make sure the images are in 4 dimensions
if len(data_batc... | 5,329,872 |
def ScriptProvenanceConst_get_decorator_type_name():
"""ScriptProvenanceConst_get_decorator_type_name() -> std::string"""
return _RMF.ScriptProvenanceConst_get_decorator_type_name() | 5,329,873 |
def load(dataset, trainset_name = ''):
"""Load training sets
======
Add a new dataset to graph learning by saving the data and labels.
Parameters
----------
dataset : string
Name of dataset.
trainset_name : string (optional), default=''
A modifier to uniquely identify di... | 5,329,874 |
def parse_annotation(parameter):
"""
Tries to parse an internal annotation referencing ``Client`` or ``InteractionEvent``.
Parameters
----------
parameter : ``Parameter``
The respective parameter's representation.
Returns
-------
choices : `None` or `dict` of (`str` or ... | 5,329,875 |
def search(request):
"""
Search results
"""
query = request.GET.get('query')
res = MsVerse.objects.filter(raw_text__icontains=query).order_by(
'verse__chapter__book__num',
'verse__chapter__num',
'verse__num',
'hand__manuscript__liste_id')
return default_response... | 5,329,876 |
def _compare(pair: Tuple[List[int], List[int]]) -> float:
"""Just a wrapper for fingerprints.compare, that unpack its first argument"""
return fingerprints.compare(*pair) | 5,329,877 |
def output_onto(conll_tokens, markstart_dict, markend_dict, file_name):
"""
Outputs analysis results in OntoNotes .coref XML format
:param conll_tokens: List of all processed ParsedToken objects in the document
:param markstart_dict: Dictionary from markable starting token ids to Markable objects
:param markend_d... | 5,329,878 |
def create_collection(zookeeper_quorum, solr_znode, collection, config_set, java64_home, user, group,
shards = 1, replication_factor = 1, max_shards = 1, retry = 5, interval = 10):
"""
Create Solr collection based on a configuration set in zookeeper.
If this method called again the with high... | 5,329,879 |
def vertical() -> np.array:
"""Returns the Jones matrix for a horizontal linear polarizer."""
return np.asarray([[0, 0], [0, 1]]) | 5,329,880 |
def resource_id(d, i, r):
"""Get resource id from meter reading.
:param d: Report definition
:type: d: Dict
:param i: Item definition
:type i: Dict
:param r: Meter reading
:type r: usage.reading.Reading
"""
return _get_reading_attr(r, 'resource_id') | 5,329,881 |
def create_provider_router(neutron_client, project_id):
"""Create the provider router.
:param neutron_client: Authenticated neutronclient
:type neutron_client: neutronclient.Client object
:param project_id: Project ID
:type project_id: string
:returns: Router object
:rtype: dict
"""
... | 5,329,882 |
def prompt_roles_to_delete(role_for_the_profile_list:List[ProfileTuple]):
"""ロール削除時に選択番号をプロンプト"""
print("\n削除するロールを選んでください")
count = 1
for role in role_for_the_profile_list:
print("{}) {}".format(count, role.name))
count += 1 | 5,329,883 |
def split(string: str) -> List[str]:
"""
Split string (which represents a command) into a list.
This allows us to just copy/paste command prefixes without having to define a full list.
"""
return shlex.split(string) | 5,329,884 |
def compute_prevalence_percentage(df, groupby_fields):
"""
base: ['topic_id', 'year']
"""
# agg_df = df.groupby(groupby_fields)['topic_weight'].sum().reset_index()
# groupby_fields.append('topic_weight')
# wide_df = agg_df[groupby_fields].copy().pivot(index=groupby_fields[0],columns=groupby_fiel... | 5,329,885 |
def get_token_history(address) -> pd.DataFrame:
"""Get info about token historical transactions. [Source: Ethplorer]
Parameters
----------
address: str
Token e.g. 0xf3db5fa2c66b7af3eb0c0b782510816cbe4813b8
Returns
-------
pd.DataFrame:
DataFrame with token historical transa... | 5,329,886 |
def top1_accuracy(pred, y):
"""Main evaluation metric."""
return sum(pred.argmax(axis=1) == y) / float(len(y)) | 5,329,887 |
def lookup_default_client_credentials_json() -> Optional[str]:
"""
Try to look up the default Json file containing the Mix client credentials
:return: str or None, the path to the default Json file, or none if not found
"""
path_client_cred_json = os.path.realpath(os.path.join(os.getcwd(), DEFAULT_... | 5,329,888 |
def dividend_history (symbol):
"""
This function returns the dividend historical data of the seed stock symbol.
Args:
symbol (:obj:`str`, required): 3 digits name of the desired stock.
"""
data = requests.get('https://apipubaws.tcbs.com.vn/tcanalysis/v1/company/{}/dividend-payment-histories?... | 5,329,889 |
def run():
"""Requirements for Task 1E"""
# Build list of stations
stations = build_station_list()
# Build set of rivers with stations
rivers = rivers_with_station(stations)
print("List of 9 rivers with most monitoring stations: ", rivers_by_station_number(stations, 9)) | 5,329,890 |
def reftype_to_pipelines(reftype, cal_ver=None, context=None):
"""Given `exp_type` and `cal_ver` and `context`, locate the appropriate SYSTEM CRDSCFG
reference file and determine the sequence of pipeline .cfgs required to process that
exp_type.
"""
context = _get_missing_context(context)
cal_ve... | 5,329,891 |
def get_forecast(filename):
"""
"""
folder = os.path.join(DATA_RAW, 'population_scenarios')
with open(os.path.join(folder, filename), 'r') as source:
reader = csv.DictReader(source)
for line in reader:
yield {
'year': line['timestep'],
'lad':... | 5,329,892 |
def levy(x: np.ndarray):
"""
The function is usually evaluated on the hypercube xi ∈ [-10, 10], for all i = 1, …, d.
:param x: c(x1, x2, ..., xd)
:return: the y-value (float)
"""
w = 1 + (x - 1) / 4 # same shape as x
term1 = (np.sin(np.pi * w.T[0])) ** 2
term3 = (w.T[-1] - 1) ... | 5,329,893 |
def play(sequence, rate=30, bitrate=None,
width=None, height=None, autoscale=True):
"""In an IPython notebook, display a sequence of images as
an embedded video.
N.B. If the quality and detail are insufficient, increase the
bit rate.
Parameters
----------
sequence : any iterator o... | 5,329,894 |
def setup_plot_defaults():
"""
Sets up default plot settings for figures.
Parameters
----------
Returns
-------
"""
plt.rcParams['ps.useafm'] = True
plt.rcParams['pdf.use14corefonts'] = True
plt.rcParams['text.usetex'] = True
plt.rcParams['font.size'] = 14
plt.rcPar... | 5,329,895 |
def _select_programme(state, audio_programme=None):
"""Select an audioProgramme to render.
If audio_programme_id is provided, use that to make the selection,
otherwise select the only audioProgramme, or the one with the lowest id.
Parameters:
state (_ItemSelectionState): 'adm' must be set.
... | 5,329,896 |
def puzzles():
"""
Pick one of the TOP95 puzzle strings
"""
return [l for l in TOP95.split("\n") if l] | 5,329,897 |
def remove_shortcut(name: str):
"""Removes a shortcut that is given by its name."""
current = query_all_shortcuts()
to_keep = list(filter(lambda p: p.split('/')[-2] != name, current))
overwrite_shortcut_list(to_keep) | 5,329,898 |
def test_declarative_sfc_obs_full(ccrs):
"""Test making a full surface observation plot."""
data = pd.read_csv(get_test_data('SFC_obs.csv', as_file_obj=False),
infer_datetime_format=True, parse_dates=['valid'])
obs = PlotObs()
obs.data = data
obs.time = datetime(1993, 3, 12, ... | 5,329,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.