content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def download_alpaca_etb(filepath_or_buffer=None, output="csv",
start_date=None, end_date=None,
universes=None, sids=None,
exclude_universes=None, exclude_sids=None):
"""
Query Alpaca easy-to-borrow data from the local database and download ... | 5,296,900 |
def addstr(str1, str2):
"""Concatenate strings str1 & str2"""
return str(str1) + str(str2) | 5,296,901 |
def ampfitfn1_1d(coeffs,x):
""" PN inspired ampitude fit a0 + a1*nu**a2"""
a0, a1, a2 = coeffs[:3]
nu = gwtools.q_to_nu(x)
return a0 + a1*nu**a2 | 5,296,902 |
def Ve_correct(Ve, Ig, Ic, Rprotect):
"""Because we use a resistor connected in a serries on the emitter circuit
in order to stabilize emission current, we need to correct voltage dropping
at the resistor, which is called as "Protection Resistor" or somthing like that.
Inputs -- Ve, Ig, Ic, Rprotect
... | 5,296,903 |
def test_sanity():
"""Sanity check."""
try:
assert not cmat2aset() # type: ignore
except Exception:
assert True | 5,296,904 |
def parse_estate(text, owner):
"""
@brief: Parse real estate string
@param text: Input property data
@param owner: Owner of property
"""
pos = text.find(':')
owner = text[:pos] if (pos > -1) else ''
pos = pos+1 if (pos > -1) else 0
match = re.search(r', ([0-9]+(?:|\.[0-9]+) кв\.)', ... | 5,296,905 |
def test_label_fraction_initialization(label_fraction_constraint):
"""Make sure the correct fields go to the correct places."""
assert label_fraction_constraint.formulation_descriptor == formulation_descriptor
assert label_fraction_constraint.label == 'bar'
assert label_fraction_constraint.min == 0.0
... | 5,296,906 |
def plot(
data: DataSetProtocol, save_pdf: bool = True, save_png: bool = True
) -> Tuple[
DataSetProtocol,
List[matplotlib.axes.Axes],
List[Optional[matplotlib.colorbar.Colorbar]],
]:
"""
The utility function to plot results and save the figures either in pdf or
png or both formats.
Arg... | 5,296,907 |
def getSph2CartTransfArr(r):
"""(Array version) Compute the transformation matrix from a spherical basis to a Cartesian
basis at the field point given by the input 'r'.
The output 'transf_sph2cart' is defined such that:
[[v_x], [v_y], [v_z]]=transf_sph2cart*matrix([[v_r], [v_phi], [v_theta]])."""
... | 5,296,908 |
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title):
"""
Visualize the Pauli Transfer Matrix of a process.
:param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix
:param ax: The matplotlib axes.
:param labels: The labels for the operator basis states.
:param title: The ti... | 5,296,909 |
def group_anagrams1(words : list[str]) -> list[str]:
"""
O(N logN ) solution.
Args:
words (list[str]): words
Returns:
list[str]: sorted by anagrams
"""
def get_word_value(word):
value = 0
for letter in word.lower():
if letter == ' ': c... | 5,296,910 |
def create_camera_ray_frame(K, T, size=0.1, color=[0, 0, 1]):
"""
K: 3x3
T: 4x4
"""
T, K, color = np.asarray(T), np.asarray(K), np.asarray(color)
sanity.assert_T(T)
sanity.assert_K(K)
sanity.assert_shape_3(color, "color")
# Pick 4 corner points
# Assumes that the camera offset i... | 5,296,911 |
def insert_delete_update(sql):
"""
执行数据库的增删改查操作
:param sql:
:return:
"""
print(sql)
conn = None
cur = None
try:
#1、获取连接
conn = pymysql.Connect(host=common_data.global_vars.get("database_ip"), user=common_data.global_vars.get("database_user"), password=common_data.glob... | 5,296,912 |
def get_name_similarities(name_pairs):
"""Get char LCS similarity for each signature pair."""
return [difflib.SequenceMatcher(None, sig1, sig2).ratio() for sig1, sig2 in name_pairs] | 5,296,913 |
def run_cmd(cmd_args, cwd=None, shell=False):
"""Runs a command and returns output as a string."""
process = subprocess.Popen(
cmd_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
cwd=cwd)
output = process.communicate()
if process.wai... | 5,296,914 |
def store_object(context, source):
"""Store a Sources instance to file."""
sources_path = Path(context["cwd"] + f"/{PICKLE_FILE}")
with open(sources_path, "wb") as f:
pickle.dump(source, f, pickle.DEFAULT_PROTOCOL) | 5,296,915 |
def _get_resource_image_registry_namespace(resource_type):
"""
Get image_registry_namespace by resource type.
:param resource_type: Type of resource (job, function, model, stream)
:return: str default name prefix by resource type when resource type is defined, else None
"""
if... | 5,296,916 |
def _get_sim203(node: ast.UnaryOp) -> List[Tuple[int, int, str]]:
"""
Get a list of all calls where an unary 'not' is used for an in-check.
"""
errors: List[Tuple[int, int, str]] = []
if (
not isinstance(node.op, ast.Not)
or not isinstance(node.operand, ast.Compare)
or len(no... | 5,296,917 |
def _get_key_and_value(field_string):
""" Extracts the key and value from a Java Thrift field string.
For example: "ids:[1,2,3]" --> "ids", [1,2,3]
:param field_string: the Java Thrift field string
:type field_string: str
:returns: a tuple of key and value of the represented field
:rtype: tupl... | 5,296,918 |
def output_intf_state(intf, intf_state):
"""Output interface state as HTML webpage.
Generate an HTML webpage displaying interface state
and providing a Refresh link.
Args:
intf (str) : Interface name.
intf_state (dict): Interface state dictionary.
"""
cgitb.enable()
... | 5,296,919 |
def extract_ut_args():
"""Extract unittest specific arguments from sys.argv"""
# -h -v -q -f -c -b
# --locals
# anything not starting with a -
newargs = []
for i in range(1, len(sys.argv)): # must ignore progname in argv[0]
arg = sys.argv[i]
if arg in ["-h", "-v", "-q", "-f", "-... | 5,296,920 |
def RemoveOutliers( array, max_deviations ):
"""
Function used to remove outliers from an array.
Args:
array (numpy.array): the interested array.
max_deviations (int): the maximum number of std.
Returns:
numpy.array: the array without outliers.
Testing:
>>>... | 5,296,921 |
def to_spark(spark_session):
"""Convert pandas df to spark."""
def _(df: pd.DataFrame, *args, **kwargs):
return spark_session.createDataFrame(df, *args, **kwargs)
return _ | 5,296,922 |
def nonconserved_bond_stereo_keys(ste_tsg, check=True):
""" Determine bond stereo centers which are not conserved by the reaction.
This includes bonds which are stereogenic for the products but not for the
reactants ("created" stereo centers) and bonds which are stereogenic for
the reactants but not fo... | 5,296,923 |
def build_bucket_table(
X: pd.DataFrame,
y: np.ndarray,
column: str,
bucketer=None,
bucket_mapping: Optional[BucketMapping] = None,
epsilon=0.00001,
display_missing=True,
verbose=False,
) -> pd.DataFrame:
"""
Calculates summary statistics for a bucket generated by a skorecard buc... | 5,296,924 |
def plot_and_save_credits(contributors, validators, project_data_dir):
"""
Plot and save an image (project_data_dir/contributors.png) listing the contributors and validators
:param contributors:
:param validators:
:param project_data_dir:
:return:
"""
max_y = 0.95
step_y = 0.025
... | 5,296,925 |
def available_classifier_paths(*restrictions):
"""Returns all classifier paths with given restrictions.
Args:
restrictions: Strings that should be included in the paths as :class:`str`.
Returns:
The path of the classifiers as :class:`list` of :class:`pathlib.Path`.
"""
paths = list... | 5,296,926 |
def summary(df: pd.DataFrame):
"""
Summarize the data
"""
print(f"Number of tweets: {df.shape[0]}")
print(f"Columns:\n{df.info()}") | 5,296,927 |
def createHTMLTable(matrix, batches, groups, caption=None, base_indent=8, indent=4, column_labels=None, skip_base_column=False):
"""
Givena a matrix, and a suitable column and row names, create an HTML table of the data
values in the matrix.
"""
if column_labels is None:
column_labels = {}
... | 5,296,928 |
def get_matched_headers(
headers: CaseInsensitiveDict, match_headers: Union[ParamList, bool]
) -> List[str]:
"""Get only the headers we should match against as a list of ``k=v`` strings, given an optional
include list.
"""
if not match_headers:
return []
if isinstance(match_headers, Ite... | 5,296,929 |
def parse_predictions_dict(predictions, num_growths):
"""Parses predictions dictionary to remove graph generated suffixes.
Args:
predictions: dict, predictions dictionary directly from SavedModel
inference call.
num_growths: int, number of model growths contained in export.
Ret... | 5,296,930 |
def unapprove(translations):
"""Set approved attribute for given translations to False."""
translations.update(approved=False, approved_user=None, approved_date=None) | 5,296,931 |
def normalized(a, axis=-1, order=2):
"""Utility function to normalize the rows of a numpy array."""
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] = 1
return a / np.expand_dims(l2, axis) | 5,296,932 |
def get_audio_sentiment_analysis(audio_filename:str):
"""
A function to get sentiment/emotion analysis from the audio
"""
audio = AudioSegment.from_file(audio_filename, "wav")
chunk_length_ms = 4000
chunks = make_chunks(audio, chunk_length_ms)
#Export all of the individual chunks as wav fil... | 5,296,933 |
def create_idx_to_path(lfw_dir):
"""
Create a dictionary where the key is the image index and the value is the
path to the image.
"""
labels = sorted(os.listdir(lfw_dir))
idx = 0
idx_to_path = {}
for label in labels:
for img in sorted(os.listdir(os.path.join(lfw_dir, label))):
... | 5,296,934 |
def test_set_initial_condition():
"""
Checks function SolveDiffusion2D.get_initial_function
"""
solver = SolveDiffusion2D()
solver.initialize_domain(100.0, 200.0, 0.4, 0.2)
solver.initialize_physical_parameters(20.0, 500.0, 550.0)
# I feel like this is bad practice because I should... | 5,296,935 |
def allowed_task_name(name: str) -> bool:
"""Determine whether a task, which is a 'non-core-OSCAL activity/directory is allowed.
args:
name: the task name which is assumed may take the form of a relative path for task/subtasks.
Returns:
Whether the task name is allowed or not allowed (inte... | 5,296,936 |
def create_movie(name, folder):
"""
Creates the movie with all the images present in the given directory
:param name:
:param folder:
:return: result of subprocess
"""
cmd = ["ffmpeg", "-framerate", "1", "-i", folder + "/pic%04d.png", "-c:v",
"libx264", "-r", "30", "-pix_fmt", "yuv... | 5,296,937 |
def exercise_label_seq_id_with_ac_2():
"""
Same as above, with fully split residues
"""
inp_pdb = """\
ATOM 832 N SER A 97 -2.470 -9.854 25.284 1.00 5.10 N
ATOM 833 CA SER A 97 -2.897 -11.122 25.819 1.00 5.95 C
ATOM 834 C SER A 97 -1.727 -11.884 26.... | 5,296,938 |
async def get_run_command(
commandId: str,
engine_store: EngineStore = Depends(get_engine_store),
run: Run = Depends(get_run_data_from_url),
) -> PydanticResponse[SimpleBody[pe_commands.Command]]:
"""Get a specific command from a run.
Arguments:
commandId: Command identifier, pulled from ro... | 5,296,939 |
def is_fully_paid(cart: Cart, taxes, discounts):
"""Check if checkout is fully paid."""
payments = [
payment for payment in cart.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
cart_total = cart.get_total(discounts=discounts, taxes=taxes).gross.amount
retur... | 5,296,940 |
def rescale_bbox(annot: namedtuple) -> namedtuple:
"""Return rescaled coordinates of bbox in the image size.
YOLO requires the bounding box coordinates should be
(relative_center_x, relative_center_y, relative_w, relative_h)
:param namedtuple annot: holds each vertex absoulte positions.
:ret... | 5,296,941 |
def uu_get_price():
"""
(可拿到当天数据)
获取股票历史交易数据,可以通过参数设置获取日k线、分钟k线数据。获取数据的基本属性如下
:param :security: 一支股票代码或者一个股票代码的list
start_date: 字符串或者[datetime.datetime]/[datetime.date]对象, 开始时间, 默认是’2015-01-01’. 注意:
当取分钟数据时, 时间可以精确到分钟, 比如: 传入 datetime.datetime(2015, 1, 1, 10, 0, 0) 或者 '2015-01-01... | 5,296,942 |
def profile_article(document):
"""
Temporary, profile the article by folder names in test data set
In real code we still want this to return the same values
"""
soup = parser.parse_document(document)
# elife id / doi id / manuscript id
fid = parser.doi(soup).split(".")[-1]
# volume
... | 5,296,943 |
def test_norm_epsilon():
"""Test computation of espilon norm on TF coefficients."""
tstep = np.array([2])
wsize = np.array([4])
n_times = 10
n_steps = np.ceil(n_times / tstep.astype(float)).astype(int)
n_freqs = wsize // 2 + 1
n_coefs = n_steps * n_freqs
phi = _Phi(wsize, tstep, n_coefs)... | 5,296,944 |
def test_calculate_load_stress_nothing():
"""calculate_load_stress() should return 0.0 when calculating load stress for unknown load type."""
ATTRIBUTES["application_id"] = 13
ATTRIBUTES["current_ratio"] = 0.2
_attributes = switch.calculate_load_stress_factor(ATTRIBUTES)
assert _attributes["piL"] =... | 5,296,945 |
def get_distribution(dataframe, target_column):
"""
method to find the distribution of a certain column in a given dataframe.
Shows the generated visualization to the user.
:param dataframe:
:param target_column: column upon which the distribution needs to be applied
:return: dictionary of uniqu... | 5,296,946 |
def high_pass_2_pole(candles: np.ndarray, period: int = 48, source_type: str = "close", sequential: bool = False) -> \
Union[
float, np.ndarray]:
"""
(2 pole) high-pass filter indicator by John F. Ehlers
:param candles: np.ndarray
:param period: int - default=48
:param source_ty... | 5,296,947 |
def rest_target_acquire(args):
"""
:param argparse.Namespace args: object containing the processed
command line arguments; need args.target
:returns: dictionary of tags
:raises: IndexError if target not found
"""
for target in args.target:
rtb, rt = _rest_target_find_by_id(target)
... | 5,296,948 |
def _add_schema_to_global_schema_dictionary(attr_name, schema, user_func):
"""
function to add a generated schema for 'attr_name', to the function schema dict
:param attr_name:
:type attr_name: str
:param schema:
:type schema: dict
:param user_func:
:type user_func: function | FunctionW... | 5,296,949 |
def twins(path):
"""data from Exercise 7.14, p225
The `twins` data frame has 24 rows and 3 columns.
This data frame contains the following columns:
id
Twin number
age
Age of twin's death from CHD, months
death
Death (male twin) from CHD indicator (1=dead from CHD, 0=alive or
oth... | 5,296,950 |
def cleanup():
"""
Performs dump cleanup
"""
# Remove old dump files, just in case
[os.remove(f) for f in glob.glob(settings.DUMPS_DIR_DUMP_REG)] | 5,296,951 |
def CommitPatch(options):
"""Makes a dummy commit for the changes in the index.
On trybots, bot_updated applies the patch to the index. We commit it to make
the fake git clone fetch it into node.js. We can leave the commit, as
bot_update will ensure a clean state on each run.
"""
print ">> Comitting patch"... | 5,296,952 |
def watchlist(request, listing_id):
"""Add on watch list, when watch list button is click"""
if request.method == "POST":
listing = get_object_or_404(Listing, pk=listing_id)
request.user.watch_listing.add(listing)
return HttpResponseRedirect(reverse("watchlist_view"))
return render(r... | 5,296,953 |
def stat(hdfs_url):
"""
stat the hdfs URL, return None if does not exist.
Returns a dictionary with keys
filename: base name of file
blocks: number of blocks
block_size: size of each block
mod_date: last modification
replication: number of copies in hdfs
"""
... | 5,296,954 |
def printprofile(profile, stream=sys.stderr):
"""Given a LineProfile() object from the line_profiler class,
prints it if it has something to print, to the given stream.
http://packages.python.org/line_profiler/
To use it, import it and create a new instance at the top of your module:
from line_... | 5,296,955 |
def deprecated(function, message):
"""
This is a function to be used inside other functions to mark them as
deprecated, and helps the user what to do.
"""
message = "[GMATE] - Call to a DEPRECATED FUNCTION: \"%s\".\n %s" % (function, message)
print message | 5,296,956 |
def lerp(a, b, x):
"""Linear interpolation."""
return a + x * (b - a) | 5,296,957 |
def create_feeds(length: int = 10) -> List[Feed]:
"""
Generate list of dummy feeds
:param length: length of list
:return: list of dummy feeds
"""
return rands(Feed, length) | 5,296,958 |
async def handle_hid_event(event: mdl.HidEvent = Depends(identify_sender)) -> mdl.GenericResponse:
"""Parse the event dict JSON"""
try:
if event.name == "rfid_reader":
logger.debug(f"Handling RFID event. String: {event.string}")
if WORKBENCH.employee is not None:
... | 5,296,959 |
def show3Dpose(channels, ax, lcolor="#3498db", rcolor="#e74c3c", add_labels=False): # blue, orange
"""
Visualize a 3d skeleton
Args
channels: 96x1 vector. The pose to plot.
ax: matplotlib 3d axis to draw on
lcolor: color for left part of the body
rcolor: color for right part of the body
add_l... | 5,296,960 |
def expect_raise(func, exception, *argc, **kwargs):
"""
assert the function will raise exception
:param func: execute function
:param exception: exception type
:param argc: source func list parameters
:param kwargs: source func dict parameters
"""
try:
func(*argc, **kwargs)
... | 5,296,961 |
def populate_description_columns(main_table: Table, cif: CifContainer) -> None:
"""
This Method adds the descriptions to the fist property table column.
"""
main_table.cell(0, 0).paragraphs[0].add_run('CCDC number')
main_table.cell(1, 0).paragraphs[0].add_run('Empirical formula')
main_table.cell... | 5,296,962 |
def test__optimized_cartesian_geometry():
""" test reader.optimized_cartesian_geometry
"""
# make sure we're including these programs
assert (set({'molpro2015', 'molpro2015-mppx'}) <=
set(reader.optimized_cartesian_geometry_programs()))
for prog in reader.optimized_cartesian_geometry_pr... | 5,296,963 |
def print_log():
"""打印日志信息到listbox"""
while 1:
lb.insert(tk.END, str(datetime.now()).split('.')[0]+' '+log_q.get())
lb.yview_moveto(1) | 5,296,964 |
def render_template(handler):
"""Render a set of templates against a dataframe and formhandler actions on it."""
orgdf = get_original_df(handler)
payload = json.loads(handler.request.body.decode('utf8'))
fh_args = payload['args']
templates = payload['template']
df = pd.DataFrame.from_records(pay... | 5,296,965 |
def logbeta(*args):
"""
Log multivariate beta function.
args
----
*args : arguments
returns
-------
float
"""
return loggamma(args).sum() - loggamma(sum(args)) | 5,296,966 |
def a3() -> rank.Arborescence:
"""Get the third SA of case in [camerini1980ranking]."""
g = nx.DiGraph()
g.add_edge("b1", "b4", label="e2", weight=1)
g.add_edge("b3", "b2", label="e4", weight=10)
g.add_edge("b4", "b3", label="e6", weight=8)
res = rank.Arborescence(g)
return res | 5,296,967 |
def hourly_quantities_to_csv(
output_filename: str = DATA_TIME_SERIES_FOLDER
+ "firestorms_raw_tweet_quantities.csv",
queries: dict = QUERIES,
) -> None:
"""Writes the hourly quantity of tweets for each of the firestorms to the output file -> time series of tweet quantities
:param output_filename: ... | 5,296,968 |
def connect_forwarder(forward_host=None,
forward_port=None,
max_retries=-1,
sleep_interval=1.0):
"""connect_forwarder
:param forward_host: host for receiving forwarded packets
:param forward_port: port for the forwarded packets
:param ma... | 5,296,969 |
def _softmax(x, implicit=False):
"""Safe softmax (with implicit class)"""
if implicit:
x = _pad_zero(x)
x = torch.softmax(x, dim=1)
return x | 5,296,970 |
def setup_logging():
"""
Setup default logging structures
:return:
"""
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
format_string = '[%(asctime)-17s] [%(levelname)-8s] [%(module)-15s] [%(funcName)-... | 5,296,971 |
def get_word_pattern(word: str) -> str:
""" Get word pattern.
This pattern is useful to break substitution cipher.
:param word: Word to get pattern for.
:return: Word pattern.
"""
# There is no ordered set type in Python, but we can get that behaviour using
# dict keys because since python... | 5,296,972 |
def check_matcher_data_is_loaded(response: requests.Response) -> bool:
""" Check that the matcher data is loaded """
try:
assert ('results' in response.json())
logger.debug('Matcher seems healthy')
return True
except Exception:
logger.debug('Matcher does not seem loaded, let\... | 5,296,973 |
def noll_to_zern(j):
"""
Convert from linear Noll index to a tuple of Zernike indicies.
:param int j: Linear Noll Index
"""
if (j < 0):
raise ValueError("Noll indices start at 0. j={:d}".format(j))
n = np.ceil((-3 + np.sqrt(9 + 8*j))/2)
m = 2*j - n*(n+2)
if not int... | 5,296,974 |
def connection_set_default(context, name, **options):
"""
Set a connection as the default connection.
Sets either the connection defined in the NAME argument as the default
current connection definition or, if there is no NAME argument on the
command it sets the current connection (if there is one)... | 5,296,975 |
def print_menu(main_list_of_contacts, p_id_number_itterate): # this takes as a parameter "main_list_of_contacts", which is an instance of the class ContactList.
"""The main interface where the user interacts with their contact list. Allowable actions are add, edit, delete, or list."""
user_selected_action = "... | 5,296,976 |
def LF_radiograph_view(c):
"""
Check if the term view occurs between the pain and anatomy mentions
in a candidate
:param c: pain-anatomy candidate
:return: -1 if True, 0 otherwise
"""
between_tokens = list(get_between_tokens(c))
between_phrase = ' '.join(between_tokens)
v = 'view'... | 5,296,977 |
def compute_centroids(x_mat: ndarray, idx_vec: ndarray):
"""
根据之前的聚类中心下标和样本,计算移动后的平均聚类中心值。
:param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数
:param idx_vec: 聚类中心下标
:return: 新的聚类中心
"""
x_mat = __t.r2m(x_mat)
idx_vec = __t.c2r(idx_vec)
m, n = x_mat.shape
k = np.max(idx_vec) + 1
cent... | 5,296,978 |
def R_hill2(rho_p, P,e=0):
"""
compute hill radius of a planet from its density rho_p in g/cm3 and period in days.
Returns
--------
R-hill: array-like;
radius of hill sphere in unit of planetary radius
"""
G = 498.23383
return (1-e)*(G*rho_p*P**2/(9*np.pi))**(1/3) | 5,296,979 |
def dir_checked():
"""The absolute path of the checked homeworks.
This path is valid on the storer machine."""
return abspath('checked') | 5,296,980 |
def color_diff(rgb1, rgb2):
"""
Calculate distance between two RGB colors. See discussion:
http://stackoverflow.com/questions/8863810/python-find-similar-colors-best-way
- for basic / fast calculations, you can use dE76 but beware of its problems
- for graphics arts use we recommend dE94 and perha... | 5,296,981 |
def clientid_to_accountid(clientid):
"""
Transform Clientid To Accountid
Parameters:
clientid : int
Returns:
None
"""
for i in _ba.get_game_roster():
if i['client_id'] == clientid:
return i['account_id']
return None | 5,296,982 |
def get_cube(ds, edge_um=1000, lev=0, center_yt=None):
"""
Extract a cube of raw data from 3D FLASH yt dataset.
Uses yt's "covering grid" method to ensure losslessness.
Replaces get_magnetic_field. This will take the center, edge length,
AMR Level, and data set, and it will return a co... | 5,296,983 |
def start_shortening(experiment, program):
""" Reads the raw output file of the specified program generated by the
specified experiment and tries to shorten the custom optimization
sequence.
Args:
experiment (string): the name of the experiment that generated the
raw file of the spe... | 5,296,984 |
def tf2ss(sys_):
"""
Convert transfer function model to state space model.
:param sys_: the system
:type sys_: TransferFunction
:return: corresponded transfer function model
:rtype: StateSpace
"""
try:
nump = np.poly1d(sys_.num)
denp = np.poly1d(sys_.den)
except Att... | 5,296,985 |
def StopStages1(active, BAUDRATE=38400):
""" Stops one stage
active: motor of the stage to stop
BAUDRATE: Baudrate of the controller
"""
device=GCSDevice(active["ctr"])
device.ConnectRS232(active["usb"], BAUDRATE)
device.STP(noraise=True) | 5,296,986 |
def test072():
"""
Check that find_by_name()'s name parameter check works
"""
assert isinstance(p, Pod)
try:
p.find_by_name(object())
assert False, "should have gotten a TypeError"
except TypeError:
pass | 5,296,987 |
def get_c_phi(rule,parses,psg,bigrams=None,start='S'):
"""wrapper
Arguments
rule : (lhs,rhs)
parses : list of (operation string, bigram string) pairs
psg : operations PSG
bigrams: bigram markhov chain
start : start category
"""
# get the charts and bigrams from the parses
... | 5,296,988 |
def softmax_2D(x, use_float64=False):
"""Compute softmax values for each row in x.
Parameters:
-----------
x: a 2D matrix
each row represents a set of entries over which a softmax
should be applied
Returns:
-------
normalized softmax entries, where each row is normalized usin... | 5,296,989 |
def test_seek_batch_prev_empty(at_instance, urls, resp, requests_mock):
"""
Test the seek_batch() method, ask to fetch the previous batch, it should contain no
tickets, therefore should return {}.
"""
# call get_current_batch() to set up self.url_prev
requests_mock.get(urls.page_1_init, json=res... | 5,296,990 |
def _run_op_1(task):
"""Test function using the function decorator."""
return task.run() | 5,296,991 |
def make_dtopo_from_subfaults(subfaults, dtopo_params):
"""
Create a dtopo file named *fname* based on applying the Okada
model to each of the subfaults specified in the list *subfaults*.
This should be a list of dictionaries that specify the necessary
Okada parameters and optionally 'rupture_... | 5,296,992 |
def upload_to_s3(bucket, channel, file):
"""
input: S3 bucket name, folder on the bucket, RecordIO file to upload
"""
s3 = boto3.resource('s3')
data = open(file, "rb") # read in binary mode
key = channel + '/' + file
#Key is location on S3 bucket, Body - binary data
s3.Bucket(bucket).put... | 5,296,993 |
def frozen_to_air(input_net, input_args):
"""
Frozen ckpt file to air file.
"""
ckpt_param_dict = load_checkpoint(input_args.get("ckpt_file"))
load_param_into_net(input_net, ckpt_param_dict)
input_arr = Tensor(np.zeros([input_args.get("batch_size"), 3, input_args.get("height"),
... | 5,296,994 |
def main(url):
"""create a tilemill project skeleton.
create zip archive including:
- project.mml
- style.mss
- icons/
"""
urlparts = urlparse(url)
if not url.endswith('.geojson'):
url += '.geojson'
c = urlopen(url).read()
if PY3: # pragma: no cover
c = c.decod... | 5,296,995 |
def _wrap(
native_estimator: Type[T_NativeEstimator] = None,
*,
name: Optional[str] = None,
base_wrapper: Optional[Type[EstimatorWrapperDF[T_NativeEstimator]]] = None,
native_estimator_bound: Optional[type] = None,
base_wrapper_bound: Type[EstimatorWrapperDF],
) -> Union[Type[EstimatorWrapperDF[... | 5,296,996 |
def create_local_gateway_routes_for_peers(
client: VNS3Client, local_network: str, peer_ips: typing.List[str]
):
"""Create route to local underlay gateway for IPs. This is commonly done for explicit routes
to VNS3 peers.
Arguments:
client {VNS3Client}
local_network {str} - local netw... | 5,296,997 |
def redgreenblue():
"""Change from red to green to blue."""
click.echo("Pretty colors.")
transitions = tr.rgb()
flow = yeelight.Flow(count=0, transitions=transitions)
for bulb in BULBS:
bulb.start_flow(flow) | 5,296,998 |
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info('making final data set from raw data')
print(input_filepath)
pr... | 5,296,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.