content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def historical_daily_discounted_cash_flow(
apikey: str, symbol: str, limit: int = DEFAULT_LIMIT
) -> typing.List[typing.Dict]:
"""
Query FMP /historical-daily-discounted-cash-flow/ API.
:param apikey: Your API key.
:param symbol: Company ticker.
:param limit: Number of rows to return.
:retu... | 5,315,700 |
def split_exon(exon, cds):
"""Takes an exon and a CDS, and returns a map of regions for each
feature (UTR5/3, CDS) that may be inferred from the arguments.
Note that the CDS is simply returned as is, to simplify
downstream handling of these features."""
results = [cds]
if exon["start"] < cds["s... | 5,315,701 |
def state_dict_to_cpu(state_dict):
"""Make a copy of the state dict onto the cpu."""
# .state_dict() references tensors, so we detach and copy to cpu
return {key: par.detach().cpu() for key, par in state_dict.items()} | 5,315,702 |
def draw_locations(locations, fileName, path="./"):
"""
基于folium生成地域分布的热力图的html文件.
:param locations: 样本的省市区, pandas的dataframe类型.
:param fileName: 生成的html文件的文件名.
:param path: 生成的html文件的路径.
"""
_base_input_check(locations)
import folium
from folium.plugins import HeatMap
from chine... | 5,315,703 |
def NpapiFromNPVariant(scope, type_defn, input_expr, variable, success,
exception_context, npp):
"""Gets the string to get a value from a NPVariant.
This function creates a string containing a C++ code snippet that is used to
retrieve a value from a NPVariant. If an error occurs, like if the NPVariant
is n... | 5,315,704 |
def find_lane_lines():
"""
FindLines used in Udacity self-driving-car nanodegree.
:return: FindLines
"""
from lane_lines_finder.lane_lines_detector import FindLines
return FindLines(window_number=10, window_width=150, window_min_n_pixels=50, search_width=150,
pixels_to_meter... | 5,315,705 |
def CollectBmpTermination(sock, msg_length, verbose=False):
"""Collect a BMP Termination message.
Args:
sock: socket from which to read.
Returns:
A list of strings.
Raises:
ValueError: an unexpected value was found in the message
"""
print_msg = []
indent_str = indent.IndentLevel(indent.BM... | 5,315,706 |
def near_field_map_vect_vjp(params: NearFieldParams,
nu_vect: jnp.ndarray) -> jnp.ndarray:
"""function to comput the near field in a circle of radious 1,
in this case we use the ls_solver_batched_sigma, which already has
a custom vjp """
Rhs = -(params.ls_params.omega**2)\
... | 5,315,707 |
def save_model(state, is_best, filename='checkpoint.pth.tar'):
"""
Saves a model to a checkpoint.
"""
torch.save(state, filename)
if is_best:
print("\tSaving new best model")
shutil.copyfile(filename, 'model_best.pth.tar') | 5,315,708 |
def normalize_str(text):
"""
Normalizes unicode input text (for example remove national characters)
:param text: text to normalize
:type text: unicode
"""
# unicodedata NFKD doesn't convert properly polish ł
trans_dict = {
u'ł': u'l',
u'Ł': u'L'
}
trans = dict((ord(k... | 5,315,709 |
def start():
"""Route for starting the server."""
try:
if not session.get('logged_in'):
return redirect(url_for('login'))
else:
do_start_server()
return redirect(url_for('home'))
except Exception as e:
abort(500, {'message': str(e)}) | 5,315,710 |
def streaming_bulk(client, actions, chunk_size=500, raise_on_error=False, expand_action_callback=expand_action, **kwargs):
"""
Streaming bulk consumes actions from the iterable passed in and yields
results per action. For non-streaming usecases use
:func:`~elasticsearch.helpers.bulk` which is a wrapper ... | 5,315,711 |
def get_context_data(data) -> dict:
"""Look for 'context' item in 'queries' item."""
if "queries" in data:
if "context" in data["queries"]:
if isinstance(data["queries"], list):
return data["queries"][0]["context"]
else:
return data["queries"]["con... | 5,315,712 |
def GrepForActions(path, actions):
"""Grep a source file for calls to UserMetrics functions.
Arguments:
path: path to the file
actions: set of actions to add to
"""
action_re = re.compile(r'[> ]UserMetrics:?:?RecordAction\(L"(.*)"')
other_action_re = re.compile(r'[> ]UserMetrics:?:?RecordAction\(')
... | 5,315,713 |
def dttm_to_epoch(date_str, frmt='%Y-%m-%dT%H:%M:%SZ'):
"""Convert a date string to epoch seconds."""
return int((datetime.datetime.strptime(date_str, frmt) -
datetime.datetime(1970, 1, 1)).total_seconds()) | 5,315,714 |
def merge(src: list, dst: list) -> list:
"""Merge `src` into `dst` and return a copy of `dst`."""
# Avoid side effects.
dst = copy.deepcopy(dst)
def find_dict(data: list, key: str) -> dict:
"""Find and return the dictionary in `data` that has the `key`."""
tmp = [_ for _ in data if isin... | 5,315,715 |
def select_dice(score, opponent_score):
"""Select six-sided dice unless the sum of SCORE and OPPONENT_SCORE is a
multiple of 7, in which case select four-sided dice (Hog Wild).
"""
# BEGIN PROBLEM 3
"*** REPLACE THIS LINE ***"
# END PROBLEM 3 | 5,315,716 |
def restart_component(service_name, template_name):
"""Stop an component, then start it."""
ret = RefCPSServiceExtent.host_template_instance_operate(service_name,
template_name,
'stop')
... | 5,315,717 |
def handle_unknown_errors(exc):
"""All not HTTP errors should result in a formatted server error."""
return jsonify(dict(
traceback=traceback.format_exc(),
message=str(exc),
)), 500 | 5,315,718 |
def to_device(device, x):
"""Send an array to a given device.
This method sends a given array to a given device. This method is used in
:func:`~chainer.dataset.concat_examples`.
You can also use this method in a custom converter method used in
:class:`~chainer.training.Updater` and :class:`~chainer... | 5,315,719 |
def grab_receivers(apk) :
"""
@param apk : an APK instance
@rtype : the android:name attribute of all receivers
"""
return apk.get_elements("receiver", "android:name") | 5,315,720 |
def abstract_integrator(
position: np.ndarray, momentum: np.ndarray, time_step: float,
state_derivatives_fn: StateDerivativesFnType,
) -> Tuple[np.ndarray, np.ndarray]:
"""Signature of an abstract integrator.
An integrator is a function, that given the the current state, a time step,
and a `state_der... | 5,315,721 |
def itos(x):
"""Converts intergers to strings"""
if type(x) != int:
raise ValueError("Input value not an integer!")
return '{}'.format(x) | 5,315,722 |
def updateStderr():
"""In case the definition of sys.stderr changes, this function
retrieves its new definition for use by the console output log
handler (if that has been defined)."""
# The locking here prevents another thread from putting some
# more output to the console handler after we fl... | 5,315,723 |
def translate_reference_entities(ref_entities, mappings=None):
"""Transform MaaS reference data for comparison with test deployment.
Positional arguments:
ref_entities -- the reference entity data
Keyword arguments:
mappings -- describe the relationship between the reference and the test
To c... | 5,315,724 |
def get_data_base(arr):
"""For a given array, finds the base array that "owns" the actual data."""
base = arr
while isinstance(base.base, np.ndarray):
base = base.base
return base | 5,315,725 |
def backLogIn():
"""backLogIn()
Args:
N/A
Output:
.docx editable file
"""
window.destroy()
contra_goapp.CONTRAGO_GUI.contra_go_log_in_GUI.contrago_log_in() | 5,315,726 |
def file_size_feed(filename):
"""file_size_feed(filename) -> function that returns given file's size"""
def sizefn(filename=filename,os=os):
try:
return os.stat(filename)[6]
except:
return 0
return sizefn | 5,315,727 |
def start_uno(ctx, set=None):
"""
Start game.
Start a game of Uno.
"""
k = (ctx.client.name, ctx.target)
if k in ctx.storage.games:
ctx.respond(ctx._("A game is already in progress."))
return
if set is not None:
try:
set = Game.SETS[set.lower()]
... | 5,315,728 |
def compute_discriminator_loss(real_logit, fake_logit):
"""Computes the discriminator hinge loss given logits.
Args:
real_logit: A list of logits produced from the real image
fake_logit: A list of logits produced from the fake image
Returns:
Scalars discriminator loss, adv_loss, patchwise accuracy o... | 5,315,729 |
def generate_using_rnn(request, first_word):
"""
Method which run RNN generating algorithm
"""
rnn = RNN_generator(first_word)
result = rnn.run()
messages.info(request, result) | 5,315,730 |
def test_config_dnsmasq():
"""
Test configuration of dnsmasq where we specify an interface
"""
write_file(CONFIG_FILE, DNSMASQ_CONFIG)
manager = ConfigManager(WRITE_DIR)
manager.loadConfig(search=CONFIG_FILE, execute=False)
commands = manager.previousCommands
assert len(commands) > 0
... | 5,315,731 |
def plotVarImportance(data, pdf, var):
"""
Runs LDA over a wide formated dataset
:Arguments:
:type scores: pandas.DataFrame
:param scores: Scores of the LDA.
:type pdf: pdf object
:param pdf: PDF object to save all the generated figures.
:type var: int
:par... | 5,315,732 |
def get_ade20_vqa_data(file_name="ade20k_vqa.jsonl"):
"""
Get the general project configpretrained_dir = conf["captioning"]["pretrained_dir"]
:return:
"""
conf = get_config()
vqa_file = conf["ade20k_vqa_dir"]
file = os.path.join(vqa_file, file_name)
print(f"Reading {file}")
with json... | 5,315,733 |
def insert_table(connection, query, df):
"""
Performs queries, e.g. INSERT, in the "vehicles" database.
"""
cursor = connection.cursor()
try:
for i in range(0, df.shape[0]):
cursor.execute(query, tuple(df.iloc[i].values.flatten().tolist()))
connection.commit()
... | 5,315,734 |
def gap_calculator(condition_vector):
"""
This function calculates max gaps between daily activites in a time series.
Requires only a single binary vector describing whether a condition was met.
"""
# Find the index of all days in which the condition is true
max_gap = None
indices = np.wher... | 5,315,735 |
def _create_bridges(config, dpdk_bridges):
"""
Create bridges with their ports
"""
for bridge in config:
bridge_name = bridge["name"]
logging.info("Create the DPDK bridge: " + bridge_name)
if bridge_name in dpdk_bridges:
helpers.run_command(
"/usr/bin/... | 5,315,736 |
def SetUserCredentials(
user_id, refresh_token=None, access_token=None, expires_in=3600):
"""Saves OAuth credentials for a user. Creates user if it does not exist.
If only a user id is provided then credentials for a user will be cleared.
Args:
user_id: The id of the user to store credentials for.
r... | 5,315,737 |
def inverse_warp(img, depth, pose, intrinsics, intrinsics_inv, target_image):
"""Inverse warp a source image to the target image plane
Part of the code modified from
https://github.com/tensorflow/models/blob/master/transformer/spatial_transformer.py
Args:
img: the source image (where to ... | 5,315,738 |
def _get_session_keystone_v2():
"""
Returns a keystone session variable.
"""
from keystoneauth1 import session
from keystoneauth1.identity import v2
user, password, auth_uri, project_name, project_id, user_domain_name = _get_connection_info('2')
auth = v2.Password(username=user, password=pas... | 5,315,739 |
def s3_resource(session):
#print type(session)
"""continue form multithread call
returns an s3 resource
Args:
session (session.Session()):
"""
s3 = session.resource('s3') | 5,315,740 |
def fetch_afl_data(path: str, params: Dict[str, Any] = {}) -> List[Dict[str, Any]]:
"""
Fetch data from the afl_data service.
Params
------
path (string): API endpoint to call.
params (dict): Query parameters to include in the API request.
Returns
-------
list of dicts, representin... | 5,315,741 |
def write_version_file(filepath):
"""Write the version number to the file designated by filepath. Returns
nothing."""
comments = [
'The version noted below is used throughout InVEST as a static version',
'that differs only from build to build. Its value is determined by ',
'setup.p... | 5,315,742 |
def mock_diffuser_v1_battery_cartridge():
"""Create and return a mock version 1 Diffuser with battery and a cartridge."""
return mock_diffuser(hublot="lot123v1") | 5,315,743 |
def test_no_input_video_no_output_video():
"""Camera video stream processing test without output video.""" | 5,315,744 |
def hist(array : np.ndarray):
"""
given array of integer values,
returns the histogram of consecutive integer values without hole
"""
bins = np.append(np.arange(0,array.max()+1)-0.5,array.max()+0.5)
return np.histogram(array, bins = bins)[0] | 5,315,745 |
def delete_department_service(department_id):
"""
Deletes department from db.
:param department_id: department id
:return: None
"""
department = Department.query.get_or_404(department_id)
db.session.delete(department)
db.session.commit() | 5,315,746 |
def derive_shared_secret(private_key: bytes, public_key: bytes):
"""Generate a shared secret from keys in byte format."""
derive = ECDH(curve=NIST256p)
derive.load_private_key_bytes(unhexlify(private_key))
derive.load_received_public_key_bytes(unhexlify(public_key))
secret = derive.generate_shared... | 5,315,747 |
def generate_and_print_model_summary(config: ModelConfigBase, model: DeviceAwareModule) -> None:
"""
Writes a human readable summary of the present model to logging.info, and logs the number of trainable
parameters to AzureML.
:param config: The configuration for the model.
:param model: The instant... | 5,315,748 |
def compromised_top_relays_plot_times(start_time, end_time, compromise_stats,\
out_dir, out_name):
"""
Plots cdfs of times to compromise for statistics on compromised top relays.
Input:
start_time: timestamp of simulation start
end_time: timestamp of simulation end
compromise_st... | 5,315,749 |
def process_5p(chrom, positions, strand, vertex_IDs, gene_ID, gene_starts, edge_dict,
locations, run_info):
""" Conduct permissive match for 5' end and return assigned vertex,
edge, and distance """
# First get a permissively matched start vertex
start_vertex, diff_5p, known_start = ... | 5,315,750 |
def create_salt(length: int = 128) -> bytes:
"""
Create a new salt
:param int length: How many bytes should the salt be long?
:return: The salt
:rtype: bytes
"""
return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(length)) | 5,315,751 |
def convert_xclim_inputs_to_pywps(params: Dict, parent=None) -> List[PywpsInput]:
"""Convert xclim indicators properties to pywps inputs."""
# Ideally this would be based on the Parameters docstring section rather than name conventions.
inputs = []
# Mapping from xclim's InputKind to data_type
# On... | 5,315,752 |
def is_readable_key_pressed(code) -> bool:
"""
押されたキーがアルファベットキー、数字キー、「-」キーのいずれかかを判断する。
:param code: pygame.event.get()[n].keyから取得できる文字コード。
:return: 上記の条件に当てはまればTrue、なければFalse
"""
if chr(code) == "-":
return True
if not chr(code).isalnum():
return False
if not chr(code... | 5,315,753 |
def go(zip_filter):
"""
Weather update client
Connects SUB socket to tcp://localhost:5556
Collects weather updates and finds avg temp in zipcode
"""
# create SUB socket
sub = yield from aiozmq.create_zmq_stream(zmq.SUB, connect='tcp://localhost:5556')
sub.transport.subscribe(bytes(zip_f... | 5,315,754 |
def extend(sequence: Iterable[_T], minsize: int) -> List[_T]:
"""
Extend ``sequence`` by repetition until it is at least as long as ``minsize``.
.. versionadded:: 2.3.0
:param sequence:
:param minsize:
:rtype:
.. seealso:: :func:`~.extend_with` and :func:`~.extend_with_none`
"""
output = list(sequence)
c... | 5,315,755 |
def admin_view(view, cacheable=False):
"""
Overwrite the default admin view to return 404 for not logged in users.
"""
def inner(request, *args, **kwargs):
if not request.user.is_active and not request.user.is_staff:
raise Http404()
return view(request, *args, **kwargs)
... | 5,315,756 |
def rtn_dates(beg, end=None, using_weekend=False, rtn_string=True):
"""
:param beg: Date String, e.g. 20170901, 2017-09-01
:param end: Date String, e.g. 20170901, 2017-09-01, if not specified, using current date
:param using_weekend:
:param rtn_string: (indicate whether the returned value is a strin... | 5,315,757 |
def pr_auc_score(y_true: np.ndarray, y_score: np.ndarray):
"""
Area under Curve for Precision Recall Curve
Args:
y_true: Array of actual y values
y_score: Array of predicted probability for all y values
Returns:
Area under Curve for Precision Recall Curve
"""
assert y_tr... | 5,315,758 |
async def save_legal_person(request: LegalPersonInput):
"""
### Recurso que tem por objetivo salvar uma pessoa fisica.
"""
try:
manage_legal_person = ManageLegalPerson()
legal_person = LegalPerson(**request.dict())
legal_person = await manage_legal_person.save_legal_person(le... | 5,315,759 |
def describe_outputs(path):
"""Return a list of :class:`WorkflowOutput` objects for target workflow."""
workflow = _raw_dict(path)
outputs = []
for (order_index, step) in workflow["steps"].items():
step_outputs = step.get("workflow_outputs", [])
for step_output in step_outputs:
... | 5,315,760 |
def parse_content_length_value(stream: Union[str, int]) -> ContentLengthValue:
"""Parses the `Content-length` header value.
:param stream: String or integer value of the header.
:return: A `ContentLengthValue` instance.
:raises ParseError: When the value cannot be cast to an integer.
"""
try... | 5,315,761 |
def is_stale(target, source):
"""Test whether the target file/directory is stale based on the source
file/directory.
"""
if not os.path.exists(target):
return True
target_mtime = recursive_mtime(target) or 0
return compare_recursive_mtime(source, cutoff=target_mtime) | 5,315,762 |
def normalize_segments(path_segments):
"""Normalizes a list of path_segments
path_segments
A list of character strings representing path segments, for
example, as returned by :func:`split_path`.
Normalizing follows the rules for resolving relative URI paths, './'
and trailing '.' are r... | 5,315,763 |
def newsToEmail(item,eList):
"""
- item : One news item
- eList : A list of all person objects
- return : a list of validated email objects
"""
IDs = []
for e in eList:
print getPref(item)
if countCommon(getPref(item),e.pref) > 0:
IDs.append(e)
return I... | 5,315,764 |
def step(context, expected_type):
"""
Expects that the "when" step was run with the @testing.catch_all decorator.
"""
assert isinstance(context.exc, eval(expected_type)),\
"Invalid exception %s - expected %s"\
% (type(context.exc).__name__, expected_type) | 5,315,765 |
def test_audit_log(s3_stubber):
"""Test that reversion revisions are created."""
regions = list(UKRegion.objects.all())
project_without_change = InvestmentProjectFactory(
allow_blank_possible_uk_regions=True,
uk_region_locations=regions[0:1],
)
project_with_change = InvestmentProjec... | 5,315,766 |
def combine(background_img, figure_img):
"""
:param background_img: (SimpleImage) the original image that will replace the green screen
:param figure_img: (SimpleImage) the original image with green screen
:return: the updated image with green screen replaced as the background space ship
"""
bac... | 5,315,767 |
def slot_into_containers(container_objects, package_objects, overlap_threshold=0.5,
unique_assignment=True, forced_assignment=False):
"""
Slot a collection of objects into the container they occupy most (the container which holds the largest fraction of the object).
"""
best_mat... | 5,315,768 |
def return_function_info_data(data_kind, data_func_name):
"""
闭包,返回读取数据库函数
参数:
data_kind (str):数据种类,如'futures'
data_func_name (str) : 数据表名称,如'futures_date'
示例:
info_futures_basic = return_function_info_data(data_kind='futures', data_func_name='futures_date')
info_futures_basic为... | 5,315,769 |
def landscapes(request):
"""
"""
images = Landscapes.display_image()
return render(request, 'all-photos/landscapes.html', {"images": images}) | 5,315,770 |
def make_sparse_matrix(df):
"""
Make sparse matrix
:param df: train_df [userId, movieId, rating, ...]
:return: sparse_matrix (movie_n) * (user_n)
"""
sparse_matrix = (
df
.groupby('movieId')
.apply(lambda x: pd.Series(x['rating'].values, index=x['userId']))
.unsta... | 5,315,771 |
def genreport():
"""Generated report includes taskId, data time, task status and type
Args:
Examples:
>>> genreport()
"""
taks_list = []
status = ee.data.getTaskList()
for items in status:
ttype = items["task_type"]
tdesc = items["description"]
tstate = items... | 5,315,772 |
def main():
"""This is the hub for lambda."""
arguments = docopt(__doc__)
scope = LambdaHub(
inbound=parse_host_and_port(arguments["--inbound"]),
outbound=parse_host_and_port(arguments["--outbound"]),
server=int(arguments["--server"]),
mode_directory=arguments["--mode_direct... | 5,315,773 |
def input_file(ntemps, formula, delta_h, enthalpy_temp=0.0, break_temp=1000.0):
""" Writes a string for the input file for ThermP.
:param ntemps: number of temperatures
:type ntemps: int
:param formula: chemical formula for species
:type formula: str
:param delta_h: enthalpy... | 5,315,774 |
def create() -> None:
"""Create users."""
# group functions are registered as decorators, and this will
# decorate its subcommands, not `click` | 5,315,775 |
def plot_facet_meshfunction(f: dolfin.MeshFunction,
names: typing.Optional[IntEnum] = None,
invalid_values: typing.Optional[typing.List[int]] = None) -> None:
"""Plot a `size_t` meshfunction defined on facets of a 2D mesh.
Useful for checking whether boun... | 5,315,776 |
def get_etf_ticker_name(ticker: str) -> str:
"""종목 이름 조회
Args:
ticker (str): 티커
Returns:
str: 종목명
>> get_etf_ticker_name("069500")
KODEX 200
"""
return krx.get_etx_name(ticker) | 5,315,777 |
def getLogger(name='root') -> logging.Logger:
"""Method to get logger for tests.
Should be used to get correctly initialized logger. """
return logging.getLogger(name) | 5,315,778 |
def process_load_magic(path, cell):
"""Replace load magics with the solution."""
modified = False
# Find any load magics
load_magics = find_load_magics_in_cell(cell)
# Replace load magics with file contents
for magic_string in load_magics:
path = Path(path)
script_path = path.pa... | 5,315,779 |
def public_dict(obj):
"""Same as obj.__dict__, but without private fields."""
return {k: v for k, v in obj.__dict__.items() if not k.startswith('_')} | 5,315,780 |
def save_preds( t_params, m_params, li_preds, li_timestamps, li_truevalues, custom_test_loc=None, count=0 ):
"""Save predictions to file
Args:
t_params (dict): dictionary for train/test params
m_params (dict): dictionary for m params
li_preds (list): list of predictions
... | 5,315,781 |
def first_der_K_mulvar(x, kernel_type='Gaussian'):
""" First derivative of Multivariate seperable and isotropic, identity scale kernel( R^d--> R)
∇_c(K(x))=first_der_k_one_dim(x_c)*(Π_(l=1&& l!=c)^(dim) ((k_one_dim(x_l))))
"""
dim=x.size
loop_range=range(dim) #dimension of x
grad... | 5,315,782 |
def register_tasks() -> None:
"""Register all of our Task classes with celery."""
from fractalis import celery
from fractalis.analytics.task import AnalyticTask
from fractalis.data.etl import ETL
logger.info("Registering ETLs ...")
etl_classes = list_classes_with_base_class('fractalis.data.etls... | 5,315,783 |
def _to_serializable_prompt(
prompt, at_least_one_token=False
) -> Union[str, List[Dict[str, str]]]:
"""
Validates that a prompt and emits the format suitable for serialization as JSON
"""
if isinstance(prompt, str):
if at_least_one_token:
if len(prompt) == 0:
rai... | 5,315,784 |
def lrepeat(elem, n):
"""
>>> lrepeat(1, 2)
[1, 1]
"""
return list(repeat(elem, n)) | 5,315,785 |
def wer(ref_path, hyp_path):
""" Compute Word Error Rate between two files """
with open(ref_path) as ref_fp, open(hyp_path) as hyp_fp:
ref_line = ref_fp.readline()
hyp_line = hyp_fp.readline()
wer_score = 0.0
line_cpt = 0.0
while ref_line and hyp_line:
wer_sc... | 5,315,786 |
def main():
"""Wsgi start function."""
# Create a wsgi server
wsgi_server = cherrypy.wsgiserver.WSGIPathInfoDispatcher({'/': app})
cherrypy.tree.mount(None, '/static', config={
'/': {
'tools.caching.on': True,
'tools.staticdir.on': True,
'tools.staticdir.dir':... | 5,315,787 |
def get_supported_hmac_hash(hash_type_str: str) -> crypto.SupportedHashes:
"""Return a crypto SupportedHashes enum type from a string hash type
Args:
hash_type_str: String hashtype, i.e. SHA256
Returns:
appropriate crypto.SupportedHashes enum value
Raises:
ValueError when bad has... | 5,315,788 |
def export_cleaned_data(df):
""" Function to export merged df into specified folder
Args:
path (str): Path of the folder
filename(str): Name of the file
"""
path = os.getcwd()
filename = 'cleaned_merged_seasons.csv'
filepath = join(dirname(dirname("__file__")), path, 'data', fil... | 5,315,789 |
def make(version: str) -> None:
"""
Generate README.md.
:param version: Database version.
"""
with open('README.md', 'w') as f:
f.write('nuPlan DB schema. Version {} \n========== \n'.format(version))
f.write('`This file is automatically generated so do not edit this file. Stay DRY.`\... | 5,315,790 |
def get_tmpfile_name():
"""Get a new temporary file name"""
tmp_dir = tempfile._get_default_tempdir()
tmp_file = next(tempfile._get_candidate_names())
return os.path.join(tmp_dir, tmp_file) | 5,315,791 |
def adjustEdge(tu, isStart):
"""
Adjust tu time based on slot edge type
"""
# Adjust start and end so they don't pick the wrong slot when the end of one slot overlaps
# by one minute the start of the next
if isStart:
t = (tu + timedelta(minutes=1)).time()
else:
t = (... | 5,315,792 |
def parse_extensions(buf):
"""
Parse TLS extensions in passed buf. Returns an ordered list of extension tuples with
ordinal extension type as first value and extension data as second value.
Passed buf must start with the 2-byte extensions length TLV.
http://www.iana.org/assignments/tls-extensiontype... | 5,315,793 |
def COS(
number: func_xltypes.XlNumber
) -> func_xltypes.XlNumber:
"""Returns the cosine of the given angle.
https://support.office.com/en-us/article/
cos-function-0fb808a5-95d6-4553-8148-22aebdce5f05
"""
return np.cos(float(number)) | 5,315,794 |
def chart(coin: gecko.Coin, other_args: List[str]):
"""Plots chart for loaded cryptocurrency
Parameters
----------
coin : gecko_coin.Coin
Cryptocurrency
other_args : List[str]
argparse arguments
"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_... | 5,315,795 |
def validate_name(dataset):
"""Check wfs/cache and the bcdc api to see if dataset name is valid
"""
if dataset.upper() in list_tables():
return dataset.upper()
else:
return get_table_name(dataset.upper()) | 5,315,796 |
def subtaskComplexity() -> None:
"""Report on the complexity of project files."""
radonCCRaw = json.loads(_doSysExec(PY + " -X utf8 -m radon cc -j . ")[1])
ccAve = 0
for file in radonCCRaw:
fileStr = file.replace("\\", "/")
complexity = sum(ccRaw["complexity"] for ccRaw in radonCCRaw[file]) / len(radonCCRaw[fi... | 5,315,797 |
def setup_logging(verbose=False):
"""Setup the logging with a custom format to go to stdout."""
if not verbose:
level = logging.INFO
else:
level = logging.DEBUG
logging.basicConfig(format="%(asctime)s [%(levelname)s] %(message)s", level=level)
logging.StreamHandler()
logging.get... | 5,315,798 |
def farthest_point_sample(xyz, npoint):
"""
Input:
xyz: pointcloud data, [B, N, C], where C is probably 3
npoint: number of samples
Return:
centroids: sampled pointcloud index, [B, npoint]
"""
device = xyz.device
B, N, C = xyz.shape
centroids = torch.zeros(B, npoint, ... | 5,315,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.