content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gps_link_init(session_id):
""" 将所有无线网 断开,初始化仿真节点经纬高 """
sql = f'SELECT * FROM session_{session_id}_iface'
temp_data = nest_data.mysql_cmd1(sql,True)
for i in temp_data:
if i['node2_eth']=='':
core.node_command(session_id,i['node1_id'],f"ip link set {i['node1_eth']} down",False)
... | 33,200 |
def starting():
"""
Start a deployment, make sure server(s) ready.
""" | 33,201 |
def cache_fun(fname_cache, fun):
"""Check whether cached data exists, otherwise call fun and return
Parameters
----------
fname_cache: string
name of cache to look for
fun: function
function to call in case cache doesn't exist
probably a lambda function
"""
try:
... | 33,202 |
def find_server_storage_UUIDs(serveruuid):
"""
@rtype : list
@return:
"""
storageuuids = []
db = dbconnect()
cursor = db.cursor()
cursor.execute("SELECT UUID, ServerUUID FROM Storage WHERE ServerUUID = '%s'" % serveruuid)
results = cursor.fetchall()
for row in results:
... | 33,203 |
def unpack_bidirectional_lstm_state(state, num_directions=2):
"""
Unpack the packed hidden state of a BiLSTM s.t. the first dimension equals to the number of layers multiplied by
the number of directions.
"""
batch_size = state.size(1)
new_hidden_dim = int(state.size(2) / num_directions)
ret... | 33,204 |
def isna(obj: Literal["0"]):
"""
usage.dask: 1
"""
... | 33,205 |
def macd_diff(close, window_slow=26, window_fast=12, window_sign=9, fillna=False):
"""Moving Average Convergence Divergence (MACD Diff)
Shows the relationship between MACD and MACD Signal.
https://en.wikipedia.org/wiki/MACD
Args:
close(pandas.Series): dataset 'Close' column.
window_fa... | 33,206 |
def spike_histogram(series, merge_spikes=True, window_duration=60, n_bins=8):
"""
Args:
* series (pd.Series): watts
* merge_spikes (bool): Default = True
* window_duration (float): Width of each window in seconds
* n_bins (int): number of bins per window.
Returns:
sp... | 33,207 |
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_information_rate_post(uuid, local_id, tapi_common_capacity_value=None): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_infor... | 33,208 |
def any(*args, span=None):
"""Create a new experssion of the union of all conditions in the arguments
Parameters
----------
args : list
List of symbolic boolean expressions
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
expr: Ex... | 33,209 |
def firstOrNone(list: List[Any]) -> Any:
"""
Return the first element of a list or None if it is not set
"""
return nthOrNone(list, 0) | 33,210 |
def ellipse_points( xy=[0,-5.], ex=254., ez=190., n=1000 ):
"""
:param ec: center of ellipse
:param ex: xy radius of ellipse
:param ez: z radius of ellipse
:param n: number of points
:return e: array of shape (n,2) of points on the ellipse
"""
t = np.linspace( 0, 2*np.pi, n )
e = np... | 33,211 |
def sum_dose_maps(dose_maps):
""" sum a collection of dose maps to obtain the total dose """
ps.logger.debug('Summing %s dose_maps', len(dose_maps))
dose_maps = np.stack(dose_maps)
return np.nansum(dose_maps, axis=0) | 33,212 |
def ion_list():
"""List of ions with pre-computed CLOUDY ionization fraction"""
ions = np.array(['al2','c2','c3','c4','fe2','h1','mg2',
'n1','n2','n3','n4','n5','ne8','o1','o6',
'o7','o8','si2','si3','si4'])
return ions | 33,213 |
def test():
"""
For bug testing. Changes often.
"""
g = Game()
Chessboard.new_board('default')
r1 = Rook(color='w')
n1 = Knight('a5', color='b')
p1 = Pawn('e1', color='w')
p2 = Pawn('e8', color='b')
p3 = Pawn('f7', color='w')
r1.teleport('b3')
# p1.teleport('f4')
# ... | 33,214 |
def is_valid_filename(filename):
"""Determines if a filename is valid (with extension)."""
valid_extensions = ['mp4', 'webm', 'ogg']
extension = get_extension(filename)
return bool(extension and extension in valid_extensions) | 33,215 |
def read(line_str, line_pos, pattern='[0-9a-zA-Z_:?!><=&]'):
"""
Read all tokens from a code line matching specific characters,
starting at a specified position.
Args:
line_str (str): The code line.
line_pos (int): The code line position to start reading.
pattern (str): Regular... | 33,216 |
def demographic(population: int, highest_lvl_ratio: int = ONE_MILLION, num_levels: int = NUM_LEVELS) -> Dict[int, int]:
"""
Calculate the number of levelled NPCs in a given population.
Args:
population:
The population to consider these levelled NPCs in.
highest_lvl_ratio:
... | 33,217 |
def gencpppxd(env, exceptions=True, ts=None):
"""Generates all cpp_*.pxd Cython header files for an environment of modules.
Parameters
----------
env : dict
Environment dictonary mapping target module names to module description
dictionaries.
exceptions : bool or str, optional
... | 33,218 |
def configure_mongo_connection(
key: str, host: str, port: int, dbname: str, username: str, password: str
):
"""
Configure the connection with the given `key` in fidesops with your PostgreSQL database credentials.
Returns the response JSON if successful, or throws an error otherwise.
See http://loca... | 33,219 |
def fully_random(entries, count):
"""Choose completely at random from all entries"""
return random.sample(entries, count) | 33,220 |
def _get_sets_grp(grpName="controllers_grp"):
"""Get set group
Args:
grpName (str, optional): group name
Returns:
PyNode: Set
"""
rig = _get_simple_rig_root()
sets = rig.listConnections(type="objectSet")
controllersGrp = None
for oSet in sets:
if grpName in oSe... | 33,221 |
def clean_text(text, cvt_to_lowercase=True, norm_whitespaces=True):
"""
Cleans a text for language detection by transforming it to lowercase, removing unwanted
characters and replacing whitespace characters for a simple space.
:rtype : string
:param text: Text to clean
:param cvt_to_lowerc... | 33,222 |
def test_v1_5_3_migration(
tmp_path: Path, cloned_template: Path, supported_odoo_version: float
):
"""Test migration to v1.5.3."""
auto_addons = tmp_path / "odoo" / "auto" / "addons"
# This part makes sense only when v1.5.3 is not yet released
with local.cwd(cloned_template):
if "v1.5.3" not... | 33,223 |
def print(*args, **kwargs) -> None:
"""Proxy for Console print."""
console = get_console()
return console.print(*args, **kwargs) | 33,224 |
def student_dashboard(lti=lti, user_id=None):
# def student_dashboard(user_id=None):
"""
Dashboard froms a student view. Used for students, parents and advisors
:param lti: pylti
:param user_id: users Canvas ID
:return: template or error message
"""
# TODO REMOVE ME - not using records anymo... | 33,225 |
def _yaml_to_dict(yaml_string):
"""
Converts a yaml string to dictionary
Args:
yaml_string: String containing YAML
Returns:
Dictionary containing the same object
"""
return yaml.safe_load(yaml_string) | 33,226 |
def room_urls_for_search_url(url):
"""
the urls of all rooms that are yieled in a search url
"""
with urllib.request.urlopen(url) as response:
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
room_urls = {erg_list_entry.find('a').find('strong').get_text():
... | 33,227 |
def bittrex_get_balance(api_key, api_secret):
"""Get your total balances for your bittrex account
args:
required:
api_key (str)
api_secret (str)
return:
results (DataFrame) of balance information for each crypto
"""
nonce = int(time.time()*1000)
url =... | 33,228 |
def check_vm_snapshot_sanity(vm_id):
"""
Checks if the snapshot information of VM is in sync with actual snapshots of the VM.
"""
vm_data = db.vm_data[vm_id]
snapshot_check = []
try:
conn = libvirt.openReadOnly('qemu+ssh://root@'+vm_data.host_id.host_ip.private_ip+'/system')
doma... | 33,229 |
def get_device(device_path: str) -> Device:
"""Safely get an evdev device handle."""
fd = open(device_path, 'rb')
evdev = Device(fd)
try:
yield evdev
finally:
fd.close() | 33,230 |
def evaluate_functions(payload, context, get_node_instances_method, get_node_instance_method, get_node_method):
"""
Evaluate functions in payload.
:param payload: The payload to evaluate.
:param context: Context used during evaluation.
:param get_node_instances_method: A method for getting node ins... | 33,231 |
def rollout(render=False):
""" Execute a rollout and returns minus cumulative reward.
Load :params: into the controller and execute a single rollout. This
is the main API of this class.
:args params: parameters as a single 1D np array
:returns: minus cumulative reward
# Why is this the minus ... | 33,232 |
def _update_bcbiovm():
"""Update or install a local bcbiovm install with tools and dependencies"""
print("## CWL support with bcbio-vm")
python_env = "python=3.6"
conda_bin, env_name = _add_environment("bcbiovm", python_env)
base_cmd = [conda_bin, "install", "--yes", "--name", env_name]
subproce... | 33,233 |
def get_request(url, access_token, origin_address: str = None):
"""
Create a HTTP get request.
"""
api_headers = {
'Authorization': 'Bearer {0}'.format(access_token),
'X-Forwarded-For': origin_address
}
response = requests.get(
url,
headers=api_headers
)
... | 33,234 |
async def test_emissions_nursery_wraps(is_async):
"""Emissions nursery wraps callbacks as requested."""
class SignalHost(QtCore.QObject):
signal = QtCore.Signal()
class LocalUniqueException(Exception):
pass
result: outcome.Outcome
event = trio.Event()
signal_host = SignalHost... | 33,235 |
def join_metadata(df: pd.DataFrame) -> pd.DataFrame:
"""Joins data including 'agent_id' to work out agent settings."""
assert 'agent_id' in df.columns
sweep = make_agent_sweep()
data = []
for agent_id, agent_ctor_config in enumerate(sweep):
agent_params = {'agent_id': agent_id}
agent_params.update(ag... | 33,236 |
def mocked_get_release_by_id(id_, includes=[], release_status=[],
release_type=[]):
"""Mimic musicbrainzngs.get_release_by_id, accepting only a restricted list
of MB ids (ID_RELEASE_0, ID_RELEASE_1). The returned dict differs only in
the release title and artist name, so that ID... | 33,237 |
def test_taxii20_collection(mocker, taxii2_server_v20):
"""
Given
TAXII Server v2.0, collection_id
When
Calling collection by id api request
Then
Validate that right collection returned
"""
collections = util_load_json('test_files/collections20.jso... | 33,238 |
def mp_rf_optimizer_func(fn_tuple):
"""Executes in parallel creation of random forrest creation."""
fn, flags, file_suffix = fn_tuple
n_trees = flags["n_trees"]
is_regressor = flags["is_regressor"]
sample_size = flags["sample_size"]
n_features = flags["n_features"]
max_depth = flags["max_depth"]
if n... | 33,239 |
def GetTracePaths(bucket):
"""Returns a list of trace files in a bucket.
Finds and loads the trace databases, and returns their content as a list of
paths.
This function assumes a specific structure for the files in the bucket. These
assumptions must match the behavior of the backend:
- The trace database... | 33,240 |
def FindRunfilesDirectory() -> typing.Optional[pathlib.Path]:
"""Find the '.runfiles' directory, if there is one.
Returns:
The absolute path of the runfiles directory, else None if not found.
"""
# Follow symlinks, looking for my module space
stub_filename = os.path.abspath(__file__)
module_space = stu... | 33,241 |
def get_name_with_template_specialization(node):
"""
node is a class
returns the name, possibly added with the <..> of the specialisation
"""
if not node.kind in (
CursorKind.CLASS_DECL, CursorKind.STRUCT_DECL, CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION): return None
tokens = get_token... | 33,242 |
def linear_timeseries(
start_value: float = 0,
end_value: float = 1,
start: Optional[Union[pd.Timestamp, int]] = pd.Timestamp("2000-01-01"),
end: Optional[Union[pd.Timestamp, int]] = None,
length: Optional[int] = None,
freq: str = "D",
column_name: Optional[str] = "linear",
dtype: np.dty... | 33,243 |
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, iface=None):
"""Send packets at layer 2 using tcpreplay for performance
pps: packets per second
mpbs: MBits per second
realtime: use packet's timestamp, bending time with realtime value
loop: number of times to process the packet list
... | 33,244 |
def outlierBySd(X: Matrix,
max_iterations: int,
**kwargs: Dict[str, VALID_INPUT_TYPES]):
"""
Builtin function for detecting and repairing outliers using standard deviation
:param X: Matrix X
:param k: threshold values 1, 2, 3 for 68%, 95%, 99.7% respective... | 33,245 |
def stop():
"""Stop S3 sync service."""
from . import s3_sync_impl
s3_sync_impl.stop() | 33,246 |
def _DownloadStatusHook(a, b, c):
"""Shows progress of download."""
print '% 3.1f%% of %d bytes\r' % (min(100, float(a * b) / c * 100), c) | 33,247 |
def encode_address(address: Dict) -> bytes:
"""
Creates bytes representation of address data.
args:
address: Dictionary containing the address data.
returns:
Bytes to be saved as address value in DB.
"""
address_str = ''
address_str += address['balance'] + '\0'
address_... | 33,248 |
def analyze_image(image_url, tag_limit=10):
"""
Given an image_url and a tag_limit, make requests to both the Clarifai API
and the Microsoft Congnitive Services API to return two things:
(1) A list of tags, limited by tag_limit,
(2) A description of the image
"""
clarifai_tags = clarifai_analysis(im... | 33,249 |
def _decision_function(scope, operator, container, model, proto_type):
"""Predict for linear model.
score = X * coefficient + intercept
"""
coef_name = scope.get_unique_variable_name('coef')
intercept_name = scope.get_unique_variable_name('intercept')
matmul_result_name = scope.get_unique_variab... | 33,250 |
def create_mapping(dico):
"""
Create a mapping (item to ID / ID to item) from a dictionary.
Items are ordered by decreasing frequency.
"""
sorted_items = sorted(list(dico.items()), key=lambda x: (-x[1], x[0]))
id_to_item = {i: v[0] for i, v in enumerate(sorted_items)}
item_to_id = {v: k for ... | 33,251 |
def _splitall(path):
"""
This function splits a path /a/b/c into a list [/,a,b,c]
"""
allparts = []
while True:
parts = os.path.split(path)
if parts[0] == path:
allparts.insert(0, parts[0])
break
if parts[1] == path:
allparts.insert(0, p... | 33,252 |
def read_library(args):
"""Read in a haplotype library. Returns a HaplotypeLibrary() and allele coding array"""
assert args.library or args.libphase
filename = args.library if args.library else args.libphase
print(f'Reading haplotype library from: {filename}')
library = Pedigree.Pedigree()
if ar... | 33,253 |
def to_async(func: Callable, scheduler=None) -> Callable:
"""Converts the function into an asynchronous function. Each
invocation of the resulting asynchronous function causes an
invocation of the original synchronous function on the specified
scheduler.
Example:
res = Observable.to_async(lambd... | 33,254 |
def error(message): #pragma: no cover
""" Utility error function to ease logging. """
_leverage_logger.error(message) | 33,255 |
def get_symbolic_quaternion_from_axis_angle(axis, angle, convention='xyzw'):
"""Get the symbolic quaternion associated from the axis/angle representation.
Args:
axis (np.array[float[3]], np.array[sympy.Symbol[3]]): 3d axis vector.
angle (float, sympy.Symbol): angle.
convention (str): co... | 33,256 |
def get_session(role_arn, session_name, duration_seconds=900):
"""
Returns a boto3 session for the specified role.
"""
response = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName=session_name,
DurationSeconds=duration_seconds,
)
creds = response["Credentials"]
... | 33,257 |
def _format_status(filename, current, total):
"""Wrapper to print progress while uploading.
"""
progress = 0
if total > 0:
progress = float(current)/float(total)*100
sys.stdout.write("\r%(filename)s %(percent)d %% "
"(%(current)s B of %(total)s B)" % {
... | 33,258 |
def base_kinesis_role(construct, resource_name: str, principal_resource: str, **kwargs):
"""
Function that generates an IAM Role with a Policy for SQS Send Message.
:param construct: Custom construct that will use this function. From the external construct is usually 'self'.
:param resource_name: Name o... | 33,259 |
def set_age_distribution_default(dic, value=None, drop=False):
"""
Set the ages_distribution key of dictionary to the given value or to the
World's age distribution.
"""
ages = dic.pop("age_distribution", None)
if ages is None:
ages = world_age_distribution() if value is None else valu... | 33,260 |
async def on_message(message : discord.Message):
"""
All messages are directly handled by cmdHandler
:param message:
:return:
"""
try:
await cmdHandler(message)
except discord.errors.HTTPException:
pass | 33,261 |
def home():
"""Home page"""
return render_template('home.html') | 33,262 |
def csv2dict(file_csv, delimiter=','):
"""
This function is used to load the csv file and return a dict which contains
the information of the csv file. The first row of the csv file contains the
column names.
Parameters
----------
file_csv : str
The input filename including path of ... | 33,263 |
def make_bb_coord_l(contour_l, img, IMG_HEIGHT):
"""
Take in a list of contour arrays and return a list of four coordinates
of a bounding box for each contour array.
"""
assert isinstance(contour_l, list)
coord_l = []
for i in range(len(contour_l)):
c = contou... | 33,264 |
def calc_pair_scale(seqs, obs1, obs2, weights1, weights2):
"""Return entropies and weights for comparable alignment.
A comparable alignment is one in which, for each paired state ij, all
alternate observable paired symbols are created. For instance, let the
symbols {A,C} be observed at position i and {A... | 33,265 |
def distance_to_line(pt, line_pt_pair):
"""
Returns perpendicular distance of point 'pt' to a line given by
the pair of points in second argument
"""
x = pt[0]
y = pt[1]
p, q = line_pt_pair
q0_m_p0 = q[0]-p[0]
q1_m_p1 = q[1]-p[1]
denom = sqrt(q0_m_p0*q0_m_p0 + q1_m_p1*q1_m_p1)
... | 33,266 |
def extension_suffixes(*args, **kwargs): # real signature unknown
""" Returns the list of file suffixes used to identify extension modules. """
pass | 33,267 |
def test_noderoledimension_construction_item():
"""Check that we construct node role dimension when sub-props are not a list."""
role = NodeRole("a", "b")
dimension1 = NodeRoleDimension("g1", roles=[role])
assert NodeRoleDimension("g1", roles=role) == dimension1
rdMap = RoleDimensionMapping("a", []... | 33,268 |
def _paste(bg: Image, p_conf: PasteConf) -> None:
"""
according to paste configuration paste image over another
:param bg: background image
:param p_conf: paste configuration
:return: None
"""
with Image.open(p_conf.im_path) as im:
im = im.convert('RGBA')
im_w, im_h = im.size... | 33,269 |
def define_wfr(ekev):
"""
defines the wavefront in the plane prior to the mirror ie., after d1
:param ekev: energy of the source
"""
spb = Instrument()
spb.build_elements(focus = 'nano')
spb.build_beamline(focus = 'nano')
spb.crop_beamline(element1 = "d1")
bl = spb.get_beamline(... | 33,270 |
def ratlab(top="K+", bottom="H+", molality=False):
"""
Python wrapper for the ratlab() function in CHNOSZ.
Produces a expression for the activity ratio between the ions in the top and
bottom arguments. The default is a ratio with H+, i.e.
(activity of the ion) / [(activity of H+) ^ (charge of t... | 33,271 |
def demean_dataframe_two_cat(df_copy, consist_var, category_col, is_unbalance):
"""
reference: Baltagi http://library.wbi.ac.id/repository/27.pdf page 176, equation (9.30)
:param df_copy: Dataframe
:param consist_var: List of columns need centering on fixed effects
:param category_col: List of fixed... | 33,272 |
def get_time_string(time_obj=None):
"""The canonical time string format (in UTC).
:param time_obj: an optional datetime.datetime or timestruct (defaults to
gm_time)
Note: Changing this function will change all times that this project uses
in the returned data.
"""
if isins... | 33,273 |
def apply_activation_checkpointing_wrapper(
model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=lambda _: True
):
"""
Applies :func:`checkpoint_wrapper` to modules within `model` based on a user-defined
configuration. For each module within `model`, the `check_fn` is used to decide
whether `mo... | 33,274 |
def train_validation_split(x, y):
"""
Prepare validation data with proper size
Args:
x: (pandas.DataFrame) Feature set / Affecting features
y: (pandas.Dataframe) Target set / dependent feature
Returns:
x_train: (pandas.DataFrame) Feature set / Affecting features for training
... | 33,275 |
def gen_data_set(file_name, num_of_var, num_of_clause, atom_count_set):
""" Generate a data set with clauses size drawn uniformly from atom_count_set """
out_file = open(file_name, "w")
out_file.write("p cnf " + str(num_of_var) + " " + str(num_of_clause) + "\n")
for i in range(0, num_of_clause):
... | 33,276 |
def test_record_default_with_long() -> None:
"""Confirm that record defaults are respected."""
tool_path = get_data("tests/wf/paramref_arguments_roundtrip.cwl")
err_code, stdout, stderr = get_main_output([tool_path])
assert err_code == 0
result = json.loads(stdout)["same_record"]
assert result["... | 33,277 |
def topk_accuracy(
rankings: np.ndarray, labels: np.ndarray, ks: Union[Tuple[int, ...], int] = (1, 5)
) -> List[float]:
"""Computes Top-K accuracies for different values of k
Args:
rankings: 2D rankings array: shape = (instance_count, label_count)
labels: 1D correct labels array: shape = (i... | 33,278 |
def has_substr(line, chars):
""" checks to see if the line has one of the substrings given """
for char in chars:
if char in line:
return True
return False | 33,279 |
def multifiltertestmethod(testmethod, strfilters):
"""returns a version of the testmethod that operates on filtered strings using strfilter"""
def filteredmethod(str1, str2):
return testmethod(multifilter(str1, strfilters), multifilter(str2, strfilters))
filteredmethod.__doc__ = testmethod.__doc__
... | 33,280 |
def add_node_set(structure, guids, name):
"""
Adds node set information from Rhino point guids.
Parameters
----------
structure : obj
Structure object to update.
guids : list
Rhino point guids.
name : str
Name of the new node set.
Returns
-------
None
... | 33,281 |
def getbasins(basin,Nx,Ny,Nz,S1,S2,S3):
"""
Args:
basin (numpy array): including the
Returns:
N/A
Only Extend CHGCAR while mode is 'all'
"""
temp = np.zeros(Nx*Ny*Nz*S1*S2*S3)
basins = np.resize(temp,(Nz*S3,Ny*S2,Nx*S1))
block = np.resize(temp,(Nz*S3,Ny*S2,Nx*S1))
flag = 0
b = 1
teemp = []
for kss in... | 33,282 |
def test_ExogenousParameters_init():
"""Test initialization of ExogenousParameters object"""
# Set a PRNG key to use
key = jax.random.PRNGKey(0)
# Test with a range of sizes
sizes = range(1, 10)
for size in sizes:
ep = ExogenousParameters(size)
# Initialization should be succes... | 33,283 |
def makeframefromhumanstring(s):
"""Create a frame from a human readable string
Strings have the form:
<request-id> <stream-id> <stream-flags> <type> <flags> <payload>
This can be used by user-facing applications and tests for creating
frames easily without having to type out a bunch of const... | 33,284 |
def display_full_name_with_correct_capitalization(full_name):
"""
See documentation here: https://github.com/derek73/python-nameparser
:param full_name:
:return:
"""
full_name.strip()
full_name_parsed = HumanName(full_name)
full_name_parsed.capitalize()
full_name_capitalized = str(fu... | 33,285 |
def staging():
"""
Use the staging server
"""
# the flavor of the django environment
env.flavor = 'staging'
# the process name, also the base name
env.procname = GLUE_SETTINGS['staging']['process_name']
# mix_env
env.mix_env = 'prod'
# the dockerfile
env.dockerfile = 'Docker... | 33,286 |
def load_experiment_artifacts(
src_dir: str, file_name: str, selected_idxs: Optional[Iterable[int]] = None
) -> Dict[int, Any]:
"""
Load all the files in dirs under `src_dir` that match `file_name`.
This function assumes subdirectories withing `dst_dir` have the following
structure:
```
{ds... | 33,287 |
def upgrade_oozie_database_and_sharelib():
"""
Performs the creation and upload of the sharelib and the upgrade of the
database. This method will also perform a kinit if necessary.
It is run before the upgrade of oozie begins exactly once as part of the
upgrade orchestration.
Since this runs before the upg... | 33,288 |
def get_market_metrics(market_portfolio: pd.DataFrame, t_costs: float, index_id: str, index_name: str,
test_data_start_date: datetime.date, test_data_end_date: datetime.date, market_logs=False) -> \
Tuple[pd.Series, pd.Series, pd.Series]:
"""
Get performance metrics for full equal... | 33,289 |
def get_puf_columns(seed=True, categorical=True, calculated=True):
"""Get a list of columns.
Args:
seed: Whether to include standard seed columns: ['MARS', 'XTOT', 'S006']
categorical: Whether to include categorical columns: ['F6251', 'MIDR', 'FDED', 'DSI']
calculated: Whether to includ... | 33,290 |
def list_all_vms(osvars):
"""Returns a listing of all VM objects as reported by Nova"""
novac = novaclient.Client('2',
osvars['OS_USERNAME'],
osvars['OS_PASSWORD'],
osvars['OS_TENANT_NAME'],
... | 33,291 |
def test_highest4():
"""First new test."""
x = 'making up sentences is very hard'
assert high(x) == 'sentences' | 33,292 |
def exec_cmd(cmd, path):
""" Execute the specified command and return the result. """
out = ''
err = ''
sys.stdout.write("-------- Running \"%s\" in \"%s\"...\n" % (cmd, path))
parts = cmd.split()
try:
process = subprocess.Popen(parts, cwd=path,
stdout=subprocess.PIPE,
... | 33,293 |
def test_upload_retry(tmpdir, default_repo, capsys):
"""Print retry messages when the upload response indicates a server error."""
default_repo.disable_progress_bar = True
default_repo.session = pretend.stub(
post=lambda url, data, allow_redirects, headers: response_with(
status_code=50... | 33,294 |
def test_orientation_error5():
""" """
yaw1 = np.deg2rad(3)
yaw2 = np.deg2rad(-3)
error_deg = get_orientation_error_deg(yaw1, yaw2)
assert np.allclose(error_deg, 6.0, atol=1e-2) | 33,295 |
def contains_numbers(iterable):
""" Check if first iterable item is a number. """
return isinstance(iterable[0], Number) | 33,296 |
def get_image(img: PathStr) -> PILImage:
"""Get picture from either a path or URL"""
if str(img).startswith("http"):
with tempfile.TemporaryDirectory() as tmpdirname:
dest = Path(tmpdirname) / str(img).split("?")[0].rpartition("/")[-1]
# NOTE: to be replaced by download(url, des... | 33,297 |
def FAIMSNETNN_model(train_df, train_y, val_df, val_y, model_args, cv=3):
"""FIT neuralnetwork model."""
input_dim = train_df.shape[1]
if model_args["grid"] == "tiny":
param_grid = {"n1": [100], "d1": [0.3, 0.1], "lr": [0.001, 0.01], "epochs": [50],
"batch_size": [32, 128], "in... | 33,298 |
def assign_exam_blocks(data, departments, splitted_departments, number_exam_days):
"""
Assign departments to exam blocks and optimize this schedule to reduce conflicts.
data (pandas.DataFrame): Course enrollments data
departments (dict): Departments (str key) and courses in departments (list value)
... | 33,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.