content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def poscar_parser_file_object():
"""Load POSCAR file using a file object.
"""
testdir = os.path.dirname(__file__)
poscarfile = testdir + '/POSCAR'
poscar = None
with open(poscarfile) as file_handler:
poscar = Poscar(file_handler=file_handler)
return poscar | 5,311,400 |
def test_no_el_multi_crossing():
"""Test el calculation with no el and severel parcel path-profile crossings."""
levels = np.array([918., 911., 880., 873.9, 850., 848., 843.5, 818., 813.8, 785.,
773., 763., 757.5, 730.5, 700., 679., 654.4, 645.,
643.9]) * units.mbar... | 5,311,401 |
def test_t_sample():
"""Test whether the parameters can be recovered from many samples."""
nu = np.array([0.5, 1., 1.5])
Psi = np.array([0.5, 1., 2.])
nParameters = Psi.shape[0]
nSamples = 1000000
shape = (nSamples, nParameters)
nIterations = 100
# sample from the distribution using the... | 5,311,402 |
def parse_json(file_handle):
"""Parse a repeats file in the .json format
Args:
file_handle(iterable(str))
Returns:
repeat_info(dict)
"""
repeat_info = {}
try:
raw_info = yaml.safe_load(file_handle)
except yaml.YAMLError as err:
raise SyntaxError("Repeats fil... | 5,311,403 |
def get_value(obj, expr):
"""
Extracts value from object or expression.
"""
if isinstance(expr, F):
expr = getattr(obj, expr.name)
elif hasattr(expr, 'value'):
expr = expr.value
return expr | 5,311,404 |
def write_dict_to_yaml(input_dict, outfile):
"""
dumps a dict to a file
"""
with open(outfile, "w") as f:
_safe_dump(input_dict, f, default_flow_style=False) | 5,311,405 |
def _get_common_evented_attributes(
layers: Iterable[Layer],
exclude: set[str] = {'thumbnail', 'status', 'name', 'data'},
with_private=False,
) -> set[str]:
"""Get the set of common, non-private evented attributes in ``layers``.
Not all layer events are attributes, and not all attributes have
c... | 5,311,406 |
def farthest_from_point(point, point_set):
"""
find the farthest point in point_set from point and return its coordinate and its distance squared to point_set
"""
record = []
for i in point_set:
distance = euclidean_distance_square(point, i)
record.append([i, distance])
# create ... | 5,311,407 |
def start_app():
"""
ASSUMES AN EMULATOR HAS ALREADY BEEN STARTED.
Starts the calculator program, finds the pid, and instantiates a
TestMutator object.
"""
subprocess.call(["adb", "shell", "am start " + PACKAGE])
time.sleep(10)
bits = subprocess.check_output('adb shell ps | ... | 5,311,408 |
def get_subtypes():
"""Get all available subtypes"""
subtypes = []
for subtype in Subtype:
subtypes.append(subtype.value)
return subtypes | 5,311,409 |
def clean_dict(dictionary: dict) -> dict:
"""Recursively removes `None` values from `dictionary`
Args:
dictionary (dict): subject dictionary
Returns:
dict: dictionary without None values
"""
for key, value in list(dictionary.items()):
if isinstance(value, dict):
... | 5,311,410 |
def create_emoticon_stream(table, n_hours=None):
"""Creates a twitter stream object that will insert queries into
object and will terminate in n_hours
Parameters:
-----------
table: connection to mongodb table
n_hours: number of hours to run before termination, default = None
Returns:
... | 5,311,411 |
def display_images(images, titles=None, cols=4, cmap=None, norm=None,
interpolation=None):
"""Display the given set of images, optionally with titles.
images: list or array of image tensors in HWC format.
titles: optional. A list of titles to display with each image.
cols: number of i... | 5,311,412 |
def quitar(update: Update, context: CallbackContext) -> None:
"""
Removes an item from a list
"""
if guard_editable_bot_message(update, context, LIST_HASHTAG):
return
content = update.message.reply_to_message.text
number = int(get_arg(update))
number_dash = str(number) + "-"
l... | 5,311,413 |
def tag_tranfsers(df):
"""Tag txns with description indicating tranfser payment."""
df = df.copy()
tfr_strings = [' ft', ' trf', 'xfer', 'transfer']
exclude = ['fee', 'interest']
mask = (df.transaction_description.str.contains('|'.join(tfr_strings))
& ~df.transaction_description.str.cont... | 5,311,414 |
def calc_box(
df: dd.DataFrame,
bins: int,
ngroups: int = 10,
largest: bool = True,
dtype: Optional[DTypeDef] = None,
) -> Tuple[pd.DataFrame, List[str], List[float], Optional[Dict[str, int]]]:
"""
Compute a box plot over either
1) the values in one column
2) the values corre... | 5,311,415 |
def remove_dead_exceptions(graph):
"""Exceptions can be removed if they are unreachable"""
def issubclassofmember(cls, seq):
for member in seq:
if member and issubclass(cls, member):
return True
return False
for block in list(graph.iterblocks()):
if not b... | 5,311,416 |
def borda_matrix(lTuple):
"""
Function to use the Borda count election
to integrate the rankings from different miRNA
coefficients.
Args:
lTuple list List of tuples with the correlation matrix, an the
name of the analysis (df,"value_name")
Returns:
... | 5,311,417 |
def drop_db():
"""Drops the db tables."""
db.drop_all() | 5,311,418 |
def main():
"""
Calculate the number of roots and the root(s).
"""
print("stanCode Quadratic Solver!")
a=int(input('Enter a:'))
b=int(input('Enter b:'))
c=int(input('Enter c:'))
discriminant=int(b*b-4*a*c)
if discriminant<0:
print('No real roots')
elif discriminant>0:
y = math.sqrt(discriminant)
x1 = ... | 5,311,419 |
def plotHeatmap(fcsDF, x, y, vI=sentinel, bins=300, scale='linear', xscale='linear', yscale='linear', thresh=1000, aspect='auto', **kwargs):
"""
Core plotting function of AliGater. Mainly intended to be called internally, but may be called directly.
Only plots. No gating functionalities.
**Paramete... | 5,311,420 |
def _ImportModuleHookBySuffix(name, package=None):
"""Callback when a module is imported through importlib.import_module."""
_IncrementNestLevel()
try:
# Really import modules.
module = _real_import_module(name, package)
finally:
if name.startswith('.'):
if package:
name = _ResolveRel... | 5,311,421 |
def from_fake(dbc_db,
signals_properties,
file_hash_blf=("00000000000000000000000000000000"
"00000000000000000000000000000000"),
file_hash_mat=("00000000000000000000000000000000"
"00000000000000000000000000000000"), **kw... | 5,311,422 |
def csr_row_set_nz_to_val(csr, row, value=0):
""" Set all nonzero elements (elements currently in the sparsity pattern)
to the given value. Useful to set to 0 mostly. """
if not isinstance(csr, spa.csr_matrix):
raise ValueError('Matrix given must be of CSR format.')
csr.data[csr.indptr[row]:csr.... | 5,311,423 |
def frozen(request: HttpRequest):
""" Заглушка для редиректа со страниц с замороженным функционалом """
context = {'title': _('Frozen feature')}
return render(request, template_name='core/frozen.html', context=context) | 5,311,424 |
def find_root_path(resource_name, extension):
""" Find root path, given name and extension
(example: "/home/pi/Media")
This will return the *first* instance of the file
Arguments:
resource_name -- name of file without the extension
extension -- ending of file (ex: ".json")
Output:... | 5,311,425 |
def zero_intensity_flag(row, name_group):
"""Check if the mean intensity of certain group of samples is zero. If zero, then
the metabolite is not existed in that material.
# Arguments:
row: certain row of peak table (pandas dataframe).
name_group: name of the group.
# Returns:
... | 5,311,426 |
def setTrackbarPos(trackbarname, winname, pos):
""" setTrackbarPos(trackbarname, winname, pos) -> None """
pass | 5,311,427 |
def assert_structure(operator, exp_trees=None, exp_iters=None):
"""
Utility function that helps to check loop structure of IETs. Retrieves trees from an
Operator and check that the blocking structure is as expected.
Examples
--------
To check that an Iteration tree has the following structure:
... | 5,311,428 |
def ComputeCountryTimeSeriesWaterChange(country_id, feature = None, zoom = 1):
"""Returns a series of water change over time for the country."""
collection = ee.ImageCollection('JRC/GSW1_0/YearlyHistory')
collection = collection.select('waterClass')
scale = REDUCTION_SCALE_METERS
if feature is None:
fea... | 5,311,429 |
def test_check_dsig():
""" Does the font have a DSIG table ? """
check = CheckTester(opentype_profile,
"com.google.fonts/check/dsig")
# Our reference Cabin Regular font is good (theres a DSIG table declared):
ttFont = TTFont(TEST_FILE("cabin/Cabin-Regular.ttf"))
# So it mus... | 5,311,430 |
def get_abspath(filepath):
"""helper function to facilitate absolute test file access"""
return os.path.join(TESTDATA_DIR, filepath) | 5,311,431 |
def get_wiki_img():
"""
Returns a path to local image.
"""
this = os.path.dirname(__file__)
img = os.path.join(this, "wiki.png")
if not os.path.exists(img):
raise FileNotFoundError("Unable to find '{}'.".format(img))
return img | 5,311,432 |
def _add_unit_to_tree(node, xpath_components, unit):
"""Walk down the tree rooted a node, and follow nodes which correspond to the
components of xpath_components. When reaching the end of xpath_components,
set the reference of the node to unit.
With reference to the tree diagram in build_unit_tree::
... | 5,311,433 |
def get_largest_component(G, strongly=False):
"""
Return the largest weakly or strongly connected component from a directed
graph.
Parameters
----------
G : networkx multidigraph
strongly : bool
if True, return the largest strongly instead of weakly connected
component
... | 5,311,434 |
def manifests():
"""Generate and deploy cluster manifests."""
pass | 5,311,435 |
def get_git_versions(repos, get_dirty_status=False, verbose=0):
""" Returns the repository head guid and dirty status and package version number if installed via pip.
The version is only returned if the repo is installed as pip package without edit mode.
NOTE: currently the dirty status is not worki... | 5,311,436 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the switch device according to its type."""
data = hass.data[DOMAIN][discovery_info[CONF_DEVICE_ID]]
device = data["device"]
switches = []
cfg = get_config(discovery_info[CONF_TYPE])
if cfg i... | 5,311,437 |
def _argmin(t: 'Tensor', axis=None, isnew: bool = True) -> 'Tensor':
"""
Also see:
--------
:param t:
:param axis:
:param isnew:
:return:
"""
data = t.data.argmin(axis = axis)
requires_grad = t.requires_grad
if isnew:
requires_grad = False
if requires_grad:
... | 5,311,438 |
def new_measure_get_activity_activity(data: dict) -> MeasureGetActivityActivity:
"""Create GetActivityActivity from json."""
timezone = timezone_or_raise(data.get("timezone"))
return MeasureGetActivityActivity(
date=arrow_or_raise(data.get("date")).replace(tzinfo=timezone),
timezone=timezon... | 5,311,439 |
def establecer_destino_archivo_imagen(instance, filename):
"""
Establece la ruta de destino para el archivo de imagen cargado a la instancia.
"""
# Almacena el archivo en:
# 'app_reservas/contingencia/<id_imagen>'
ruta_archivos_ubicacion = 'app_reservas/contingencia/'
filename = '{0!s}_{1!s}... | 5,311,440 |
def have_same_SNP_order(dict_A, dict_B):
"""
Checks if two dictionaries have the same SNP order.
"""
have_same_order = [k for k in dict_A.keys() if k != "ext"] == [k for k in dict_B.keys() if k != "ext"]
return have_same_order | 5,311,441 |
def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
"""random_forest(评估算法性能,返回模型得分)
Args:
train 训练数据集
test 测试数据集
max_depth 决策树深度不能太深,不然容易导致过拟合
min_size 叶子节点的大小
sample_size 训练数据集的样本比例
n_trees... | 5,311,442 |
def _listprint(lists):
"""for debug
"""
for x in lists:
print(x) | 5,311,443 |
def wavedash(s):
"""Conditions to wavedash"""
if (s.jcount > 0 and s.pL[2] + s.pV[2] / 20 < 32 and abs(s.r) < 0.1 and abs(s.a) < 0.04 and s.y > 400 and
0 < abs(s.pR[0] / U180) < 0.12 and not s.poG and s.pV[2] < -210):
# Forward wavedash
s.jump = not s.ljump
s.pitch = -1
... | 5,311,444 |
def define_plot_id(plot_name, plot_center):
"""Define plot id, keeping track of coordinates."""
plot_id = f"{plot_name}_X{int(plot_center[0])}_Y{int(plot_center[1])}"
return plot_id | 5,311,445 |
def build_mask_trace(ytrace, subarray='SUBSTRIP256', halfwidth=30,
extend_below=False, extend_above=False):
"""Mask out the trace in a given subarray based on the y-positions provided.
A band of pixels around the trace position of width = 2*halfwidth will be masked.
Optionally extend_ab... | 5,311,446 |
def test_register_secret_batch_with_pruned_block(
secret_registry_proxy, web3, private_keys, contract_manager
):
"""Test secret registration with a pruned given block."""
c1_client = JSONRPCClient(web3, private_keys[1])
c1_chain = BlockChainService(jsonrpc_client=c1_client, contract_manager=contract_man... | 5,311,447 |
def load_data():
"""記録データを返します"""
try:
# json モジュールでデータベースファイルを開きます
database = json.load(open(DATA_FILE, mode="r", encoding="utf-8"))
except FileNotFoundError:
database = []
return database | 5,311,448 |
def get_pattern(prefix: str) -> Optional[str]:
"""Get the pattern for the given prefix, if it's available.
:param prefix: The prefix to look up, which is normalized with :func:`normalize_prefix`
before lookup in the Bioregistry
:returns: The pattern for the prefix, if it is available, using the fol... | 5,311,449 |
def decompressStreamToBytes(inputStream: IOBase) -> int:
"""Compresses `inputStream` into `outputStream`. Processes the whole data."""
with BytesIO() as outputStream:
decompressStreamToStream(inputStream, outputStream)
return outputStream.getvalue() | 5,311,450 |
def request(url):
"""
Sends a request to a url
:param url:
"""
if not connected_to_internet():
raise ConnectionError(
"You need to have an internet connection to send requests."
)
response = requests.get(url)
if response.ok:
return response
else:
... | 5,311,451 |
def set_requires_grad(model, requires_grad=False, N=None):
"""
Set requies_grad=Fasle for all the networks to avoid unnecessary computations
:param model: model to who turn off gradient
:param requires_grad: True to request gradient
:return:
"""
if N is None:
for param in model.param... | 5,311,452 |
def test_opencadd_imported():
"""Sample test, will always pass so long as import statement worked"""
assert "opencadd" in sys.modules | 5,311,453 |
def pil_grid(images: List[Image.Image], max_horiz: int) -> Image.Image:
"""
Automatically creates a mosaic from a list of PIL images.
:param images: List of images in PIL form.
:param max_horiz: Maximum number of images in the column.
:return: Mosaic-like image.
"""
n_images = len(images)
... | 5,311,454 |
def test_mean_sem_ranking():
"""Test the mean ranking results of experiment."""
mean_ranking, sem_ranking = calculate_mean_sem_ranking(EXPERIMENT.results_)
assert set(mean_ranking.Classifier.unique()) == set(EXPERIMENT.classifiers_names_)
assert set(sem_ranking.Classifier.unique()) == set(EXPERIMENT.cla... | 5,311,455 |
def rd_current(phi, T):
"""
Thermionic emission current density based on Richardson-Dushman
Args:
phi: Work function (eV)
T: Temperature (K)
Returns:
Current density in J/cm**2
"""
A = 4 * np.pi * m_e * k ** 2 * e / h ** 3
return A * T ** 2 * np.exp(-phi / (k_ev * ... | 5,311,456 |
def _auto_levels_locator(
*args, N=None, norm=None, norm_kw=None, locator=None, locator_kw=None,
vmin=None, vmax=None, extend='both', symmetric=False,
positive=False, negative=False, nozero=False,
):
"""
Automatically generate level locations based on the input data, the
input locator, and the i... | 5,311,457 |
def get_default_session() -> requests.Session:
"""
get the default session used in online-judge-tools
:note: cookie is not saved to disk by default. check :py:func:`with_cookiejar`
"""
global _default_session
if _default_session is None:
_default_session = _new_session_with_our_user_ag... | 5,311,458 |
def find_nearest(array, value):
"""
Find the nearest element in array to value.
Parameters
----------
array : np.ndarray-like
The array to search in.
value : float
The value to search.
Returns
-------
value : float
The closest value in array.
idx : int
... | 5,311,459 |
def create_create_one_input(model: Type[IEntityModel]) -> type:
"""
Create input type for creating one entity.
:param model: class to be created
:return: input type
"""
fields = {f: model.get_attribute_type(f) for f in model.get_attributes(GraphQLOperation.CREATE_ONE)}
create_one = strawber... | 5,311,460 |
def cli_entrypoint():
"""
Used by setup.py to create a cli entrypoint script
"""
cli_args, sub_args = parse_cli()
try:
run(cli_args, sub_args)
except Exception:
raise
finally:
import {{cookiecutter.repo_name}}
global log
log.debug("Al... | 5,311,461 |
def imuCallback(imuData):
"""
formats and saves IMU data from the comp-filter to memory.
:param imuData: sensor_msgs/Imu
:return: None
"""
global data, saving
if not saving:
collected_data = {}
stamp = imuData.header.stamp
collected_data["time"] = format_time(stamp)
... | 5,311,462 |
def test_wrong_username(rok_ds_jwt, rok_connector_with_secret):
"""
check that an error is triggered when the connector
tries to authenticate with a wrong username
"""
responses.add(
responses.POST,
'https://rok.example.com/graphql',
json={
'Message': 'JwtLogon: T... | 5,311,463 |
def service_remove(service_id: str):
"""
Stops and removes a service. This can also be done with Service.remove().
@param service_id: the ID of the service you want to remove.
@return: boolean value of success status
"""
try:
client.service.get(service_id).remove()
return True
... | 5,311,464 |
def qedit_raw_save(topic_id, qt_id):
""" Accept the question editor form and save the results. """
valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
user_id = session['user_id']
course_id = Topics.get_course_id(topic_id)
if not (check_perm(user_id, course_id, "courseadmin")
... | 5,311,465 |
def wait_for_ctrl_c():
""" Waits for pressing Ctrl-C key by a user. If Ctrl-C key has been pressed - finishes execution """
continue_loop = True
def signal_handler(signal, frame):
nonlocal continue_loop
continue_loop = False
signal.signal(signal.SIGINT, signal_handler)
signal.signa... | 5,311,466 |
def test_bad_init():
""" Constructor argument names must match attribute names.
"""
@attrs
class BadInit(object):
def __init__(self, x):
self._x = x
with pytest.raises(AttributeError):
BadInit(1) | 5,311,467 |
def register_h5(h5, tables=None, prefix=None):
"""
Register tables in an h5 store with orca.
Parameters:
-----------
h5: str
Full path to the h5.
tables: list of str, optional, default None
If provided, subset of tables to register.
If not provided, registers all tables.... | 5,311,468 |
def _topDownConsistencySrcRec(tree1, tree2, matchList, bestMatchList):
"""
Recurrent version
"""
refML = []
ph2list = [ ph2 for (ph1,ph2) in matchList if ph1 is tree1 and \
( ph2 is tree2 or ph2.isDescendent(tree2))]
if PRINT_DEBUG:
print "Current pos: ", tree1.tag(), tr... | 5,311,469 |
def test_styles() -> None:
""" Test table styles """
styles = [
'plain', 'simple', 'grid', 'pipe', 'orgtbl', 'rst', 'mediawiki',
'latex', 'latex_raw', 'latex_booktabs'
]
for file in [TEST1[0], TEST2[0]]:
for style in styles:
expected_file = file + '.' + style + '.ou... | 5,311,470 |
def mock_badvector_problem():
"""Mocks noisy DataFrames for testing vectorization"""
feat_df, _, combined_df = mock_problem()
# Feature columns are numeric, but we want to assign bad non-numeric values to test our pre-processing.
# To be able to do this, we need to set the datatype to np.object.
fo... | 5,311,471 |
def name_parts(author):
"""
Given the name of an author, break it in to first, middle, last and assign a
case number to the type of name information we have
Case 0 last name only
Case 1 last name, first initial
Case 2 last name, first name
Case 3 last name, first initial, middle initial
... | 5,311,472 |
def _parse_header(header) -> dict:
"""
Parses the route duration, links (fare and map data), and misc. data
:param header: Element tree containing the header
"""
header, misc = header.find('td/table')
duration, links = header.findall('td')
return {
'duration': _parse_duration(dur... | 5,311,473 |
def get_version():
"""
Return package version as listed in `__version__` in `init.py`.
"""
return moni.VERSION | 5,311,474 |
def delete_credential(credential):
"""
function to delete a credential in the credential_list
"""
credential.delete_credential() | 5,311,475 |
def calculate_mean(i, peaklocationstart, peaklocationend):
"""
This function is for calculating the mean over the specified area and returns this mean.
"""
length = peaklocationend - peaklocationstart
mean = 0
if i:
for interval in i:
if interval[0] < peaklocationstar... | 5,311,476 |
def swag(print_swag=True):
"""Swag!"""
output = ("""
( ( (
)⧹ ))⧹ ) . ) ( )⧹ ) ( (
(()/(()/` ) /( )⧹ (()/(( )⧹))( .
/(_)/(_)( )(_)) (((_) /(_))⧹ ((_)()⧹ )
(_))(_))(_(_()) )⧹___(_))((_)_(())⧹_)()
| _ |_ _|_ _| (/ __| _ | __⧹ ⧹((_)/ /
| _/| ... | 5,311,477 |
def create_conn_matrix(name, width, n_neighbors=3, n_states=2, is_sparse=True):
"""
Creates a random square matrix with Gaussian distribution according to
parameters for evodynamic.connection.WeightedConnection.
Parameters
----------
name : str
Name of the Tensor.
width : int
Width of the adj... | 5,311,478 |
def noticeOnFinish(filepath=success_audio):
"""
decorator function, when the fun finishes, noticeOnfinish() will play an audio in wav format(default is success_audio)
:param filepath: wav audio path
:return:
"""
def decorator(fun):
def wrapper(*args, **kwargs):
check_file_ty... | 5,311,479 |
def pop_feedback_message_references(user_id, references_length):
"""Pop feedback message references which have been processed already.
Args:
- user_id: id of the receiving user.
- references_length: no. of feedback message references that have been
processed already."""
model = feedback_models.... | 5,311,480 |
def init_database(url: str=None):
"""
Initializes database connection.
See https://peewee.readthedocs.org/en/latest/peewee/database.html?highlight=url#connecting-using-a-database-url
for info on URL format.
Url defaults to 'sqlite:///hatbot.sqlite'.
Please note that psycopg2 package has to be ... | 5,311,481 |
def redirectOut(port=port, host=host):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port)) # caller operates... | 5,311,482 |
def buildBwaIndex(reference, dest, output=None, log=None):
"""Create BWA index for fasta file
:param reference: path to fasta reference file
:param dest: directory to place bwt file
:param output: file handle to write stdout and stderr. If None output is not captured
:param log: notation for loggin... | 5,311,483 |
def scriptTable(*args, **kwargs):
"""
Maya Bug Fix:
- fixed getCellCmd to work with python functions, previously only worked with mel callbacks
IMPORTANT: you cannot use the print statement within the getCellCmd callback function or your values will not be returned to the table
"""
import uitype... | 5,311,484 |
def trim_string(s, maxlen=1024, ellps='...'):
"""
Trim a string to a maximum length, adding an "ellipsis"
indicator if the string was trimmed
"""
# todo: allow cutting in the middle of the string,
# instead of just on the right end..?
if len(s) > maxlen:
return s[:maxlen - le... | 5,311,485 |
def train_SVM_model(trainX, trainY, testX, testY, class_names):
"""
1. Train and evaluate SVM model - use data augmentation to increase data sample.
2. Save classification report.
"""
# define model
base_model = SVC()
# define parameters
parameters = {'kernel':('linear', 'rbf'), 'C':[0... | 5,311,486 |
def setattr(p_object, name, value): # real signature unknown; restored from __doc__
"""
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
"""
pass | 5,311,487 |
async def enter_room(sid, data):
"""Enter a socketio room after checking permissions and running a room-specific function.
Parameters
----------
sid : str
The sid of the socket.
data : dict
The data sent with a "room" key containing the room name.
"""
if not isinstance(data.... | 5,311,488 |
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Caculate GC content',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'FASTA',
help='fasta file',
metavar='FASTA',
nargs='+')
par... | 5,311,489 |
def bookmarks(db_path, auth):
"""Save a folder of bookmarks"""
db = sqlite_utils.Database(db_path)
instapaper = utils.login(auth)
for folder in db["folders"].rows:
print(f"Fetching bookmarks of folder {folder['title']}...")
bookmarks = [
{key: getattr(entry, key) for key in ... | 5,311,490 |
def test_invalid_file_type(barred_list_importer):
"""Verify that Barred List data is not imported if the filename format is invalid."""
expect_failure(barred_list_importer, exc_message='Wrong suffix') | 5,311,491 |
def open_zip(filename, mode='r'):
"""
Open a file; if filename ends with .gz, opens as a gzip file
"""
if filename.endswith('.gz'):
openfn = gzip.open
else:
openfn = open
yield openfn(filename, mode) | 5,311,492 |
def lista_clientes(request):
""" Página com a lista de clientes """
# Pega informações da URL
codigo = request.GET.get('search_cod_client', '')
nome = request.GET.get('search_name_client', '')
deletado = request.GET.get('deleted', False)
page = int(request.GET.get('page', 1))
# Filtra list... | 5,311,493 |
def ping(dut, addresses, family='ipv4', **kwargs):
"""
To Perform ping to ipv4 or ipv6 address.
Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param :dut:
:param :addresses:
:param :family: ipv4|ipv6
:param :count: 3(default)
:param :timeout:
:param :interface:
:param :pa... | 5,311,494 |
def getRestrictedChemicalStates(labelArray, products, contexts, doubleAction):
"""
goes through a list of reaction center and their associated context and creates a dictionary of molecules
of possible chemical states
"""
# sortedChemicalStates = defaultdict(lambda: defaultdict(lambda: defaultdict(s... | 5,311,495 |
def CompileBERTCustomPass():
"""Compiles custom graph pass for BERT into a library. It offers performance improvements"""
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger()
input_pass_file = 'bertpass_gpu.cc'
out_lib_file = 'bertpass_lib.so'
log.info(' ... compi... | 5,311,496 |
def CreateVariableFromDictionary(ds,variable):
"""
Purpose:
Create a variable in the data structure.
If the variable already exists in the data structure, data values, QC flags and
attributes will be overwritten.
This utility is the prefered method for creating or updating a data series beca... | 5,311,497 |
def collection_getter (getter, *args, **kwargs):
"""Adds variables to relevant collections."""
var = getter(*args, **kwargs)
name = kwargs['name']
trainable = kwargs['trainable']
if trainable:
if 'kernel' in name:
tf.add_to_collection(tf.GraphKeys.WEIGHTS, var)
if 'bia... | 5,311,498 |
def E_edgePair(mesh, edgePair, width, height, edge_len):
"""
Compute the energy coefficient matrix over a single edge pair.
Inputs:
mesh - the model in OBJ format
edgePair - the edgePair of the model in (fi, (fv0, fv1)) format
width, height - texture's dimensions
edge_len - ... | 5,311,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.