content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_ipython_extension(ipython):
"""
Any module file that define a function named `load_ipython_extension`
can be loaded via `%load_ext module.path` or be configured to be
autoloaded by IPython at startup time.
"""
# You can register the class itself without instantiating it. IPython will
... | 32,300 |
def hw_uint(value):
"""return HW of 16-bit unsigned integer in two's complement"""
bitcount = bin(value).count("1")
return bitcount | 32,301 |
def run_tunedmode():
"""Run the daemon with provided config."""
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
session_bus = dbus.SessionBus()
bus_name = dbus.service.BusName(TUNEDMODE_BUS_NAME, bus=session_bus)
with TunedMode(bus_name, TUNEDMODE_BUS_PATH):
loop = GLib.MainLoop()
... | 32,302 |
def step_impl(context, display_name):
"""
Args:
context (behave.runner.Context): The test context
display_name (str): The display name that identifies the monitor of interest.
"""
candidate_monitors = list(context.project.monitors().find_by_display_name(display_name))
assert_that(len... | 32,303 |
def clip(x,xmin,xmax) :
""" clip input array so that x<xmin becomes xmin, x>xmax becomes xmax, return clipped array
"""
new=copy.copy(x)
bd=np.where(x<xmin)[0]
new[bd]=xmin
bd=np.where(x>xmax)[0]
new[bd]=xmax
return new | 32,304 |
def emit(plugin):
"""Emit a simple string notification to topic "custom"
"""
plugin.notify("custom", "Hello world") | 32,305 |
def profile_from_creds(creds, keychain, cache):
"""Create a profile from an AWS credentials file."""
access_key, secret_key = get_keys_from_file(creds)
arn = security_store(access_key, secret_key, keychain, cache)
return profile_from_arn(arn) | 32,306 |
async def lb_d(_ctx: Context):
"""
Returns embedded text of daily leaderboard.
Top 10 members with highest study time in the day.
:param _ctx:
The command context, unused but needed.
"""
await send_leaderboard('daily', daily_leaderboard()) | 32,307 |
def get_files(pp: Paths, glob: str=DEFAULT_GLOB, sort: bool=True) -> Tuple[Path, ...]:
"""
Helper function to avoid boilerplate.
Tuple as return type is a bit friendlier for hashing/caching, so hopefully makes sense
"""
# TODO FIXME mm, some wrapper to assert iterator isn't empty?
sources: List... | 32,308 |
def test(model, test_loader, dynamics, fast_init):
"""
Evaluate prediction accuracy of an energy-based model on a given test set.
Args:
model: EnergyBasedModel
test_loader: Dataloader containing the test dataset
dynamics: Dictionary containing the keyword arguments
for t... | 32,309 |
def generate_data(input_path, label_path):
"""generate dataset for s11 parameter prediction"""
data_input = np.load(input_path)
if os.path.exists(DATA_CONFIG_PATH):
data_config = np.load(DATA_CONFIG_PATH)
mean = data_config["mean"]
std = data_config["std"]
data_input, me... | 32,310 |
def main(args):
"""Parse arguments and run test environment setup.
This installs and/or upgrades any skills needed for the tests and
collects the feature and step files for the skills.
"""
if args.config:
apply_config(args.config, args)
msm = create_skills_manager(args.platform, args.s... | 32,311 |
def get_cluster_activite(cluster_path_csv, test, train=None):
"""Get cluster activite csv from patch cluster_path_csv.
Merge cluster with station_id
Parameters
----------
cluster_path_csv : String :
Path to export df_labels DataFrame
test : pandas.DataFrame
train : pandas.DataFrame... | 32,312 |
def get_ssl_policy(name: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSSLPolicyResult:
"""
Gets an SSL Policy within GCE from its name, for use with Target HTTPS and Target SSL Proxies.
For more inf... | 32,313 |
def getitem(self, item):
"""Select elements at the specific index.
Parameters
----------
item : Union[slice, int, dragon.Tensor]
The index.
Returns
-------
dragon.Tensor
The output tensor.
"""
gather_args = []
if isinstance(item, Tensor):
if item.dtype ... | 32,314 |
def test_multi_range_potential_form():
"""Tests definition of multiple ranges for potential-form definitions"""
k = u"A"
v = u"potential 1.0 2.0 3.0"
parser = ConfigParser(io.StringIO())
actual = parser._parse_multi_range(k, v)
assert actual.species == k
assert actual.potential_form_instance.potential_f... | 32,315 |
def zdot_batch(x1, x2):
"""Finds the complex-valued dot product of two complex-valued multidimensional Tensors, preserving the batch dimension.
Args:
x1 (Tensor): The first multidimensional Tensor.
x2 (Tensor): The second multidimensional Tensor.
Returns:
The dot products along eac... | 32,316 |
def open_browser(url):
"""Open a browser using webbrowser."""
if 'browser_obj' in CONFIG and CONFIG['browser_obj']:
CONFIG['browser_obj'].open(utils.add_scheme(url))
else:
sys.stderr.write('Failed to open browser.\n') | 32,317 |
def show_progress(iteration, total, prefix = '', suffix = '', decimals = 0,
length = 50, fill = '=', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (... | 32,318 |
def test_post_document_annotation():
"""Create an Annotation via API."""
document_id = TEST_DOCUMENT
start_offset = 86
end_offset = 88
accuracy = 0.0001
label_id = 867 # Refers to Label Austellungsdatum
# create a revised annotation, so we can verify its existence via get_document_annotatio... | 32,319 |
def test_atomic_g_day_min_inclusive_2_nistxml_sv_iv_atomic_g_day_min_inclusive_3_5(mode, save_output, output_format):
"""
Type atomic/gDay is restricted by facet minInclusive with value ---24.
"""
assert_bindings(
schema="nistData/atomic/gDay/Schema+Instance/NISTSchema-SV-IV-atomic-gDay-minInclu... | 32,320 |
def add(request):
"""
Case of UPDATE REQUEST '/server/add/'
対象の更新
POST リクエストにのみレスポンス
"""
request_type = request.method
logger.debug(request_type)
if request_type == 'GET':
raise Http404
elif request_type == 'OPTION' or request_type == 'HEAD':
return HttpResponse("OK")... | 32,321 |
def gradient_check_numpy_expr(func, x, output_gradient, h=1e-5):
"""
This utility function calculates gradient of the function `func`
at `x`.
:param func:
:param x:
:param output_gradient:
:param h:
:return:
"""
grad = np.zeros_like(x).astype(np.float32)
iter = np.nditer(x, f... | 32,322 |
def serve_values(name, func, args, kwargs, serving_values, fallback_func, backend_name=None, implemented_funcs=None, supported_kwargs=None,): #249 (line num in coconut source)
"""Determines the parameter value to serve for the given parameter
name and kwargs. First checks for unsupported funcs or kwargs, then
... | 32,323 |
def find_peaks(sig):
"""
Find hard peaks and soft peaks in a signal, defined as follows:
- Hard peak: a peak that is either /\ or \/.
- Soft peak: a peak that is either /-*\ or \-*/.
In this case we define the middle as the peak.
Parameters
----------
sig : np array
The 1d si... | 32,324 |
def evenly_divides(x, y):
"""Returns if [x] evenly divides [y]."""
return int(y / x) == y / x | 32,325 |
def proxmap_sort(arr: list, key: Function = lambda x: x, reverse: bool = False) -> list:
"""Proxmap sort is a sorting algorithm that works by partitioning an array of data items, or keys, into a number of
"subarrays" (termed buckets, in similar sorts). The name is short for computing a "proximity map," which in... | 32,326 |
async def test_browse_media(
hass, hass_ws_client, mock_plex_server, requests_mock, library_movies_filtertypes
):
"""Test getting Plex clients from plex.tv."""
websocket_client = await hass_ws_client(hass)
media_players = hass.states.async_entity_ids("media_player")
msg_id = 1
# Browse base of... | 32,327 |
def load_footings_file(file: str):
"""Load footings generated file.
:param str file: The path to the file.
:return: A dict representing the respective file type.
:rtype: dict
.. seealso::
:obj:`footings.testing.load_footings_json_file`
:obj:`footings.testing.load_footings_xlsx_fi... | 32,328 |
def coupler(*, coupling: float = 0.5) -> SDict:
"""a simple coupler model"""
kappa = coupling ** 0.5
tau = (1 - coupling) ** 0.5
sdict = reciprocal(
{
("in0", "out0"): tau,
("in0", "out1"): 1j * kappa,
("in1", "out0"): 1j * kappa,
("in1", "out1"): ... | 32,329 |
def test_gen_weight_table_lis_no_intersect():
"""
Checks generating weight table for LIS grid with no intersect
"""
print("TEST 8: TEST GENERATE WEIGHT TABLE FOR LIS GRIDS WITH NO INTERSECT")
generated_weight_table_file = os.path.join(OUTPUT_DATA_PATH,
... | 32,330 |
def new_client(request):
"""
Function that allows a new client to register itself.
:param request: Who has made the request.
:return: Response 200 with user_type, state, message and token, if everything goes smoothly. Response 400 if there
is some kind of request error. Response 403 for forbidden. O... | 32,331 |
def display_stats(stats):
"""Prints the stats of a pokemon to the user.
If const.SHOW_IMAGES is set to True, displays the image of the pokemon to
the user.
Args:
stats: a tuple of:
-pokemon name (str)
-species_id (int)
-height (float)
-weight (fl... | 32,332 |
def test_build_Results():
"""Check that build results function returns properly labelled and processed dataframe."""
try:
search_term_df = ts().search_term("court")
except:
time.sleep(10)
search_term_df = ts().search_term("court")
assert not search_term_df.empty
preparedata =... | 32,333 |
def setup_info(nKPTs,nkpt_per_direction,KPTs,KPT_lengths,nkpoints,nbands,points,gaps,scissor):
"""
Print information about the system
"""
# BZ info
print("=== PATH ===")
print("directions: %d"%(nKPTs-1))
if np.array_equal(KPTs[-1],KPTs[0]): print("(Closed path)")
else: print("(Open path)... | 32,334 |
def parse_time_interval_seconds(time_str):
""" Convert a given time interval (e.g. '5m') into the number of seconds in that interval
:param time_str: the string to parse
:returns: the number of seconds in the interval
:raises ValueError: if the string could not be parsed
"""
cal = parsedatetime... | 32,335 |
def initialize_seed(seed=0):
"""
This makes experiments more comparable by
forcing the random number generator to produce
the same numbers in each run
"""
random.seed(a=seed)
numpy.random.seed(seed)
if hasattr(tf, 'set_random_seed'):
tf.set_random_seed(seed)
elif hasattr(tf.... | 32,336 |
def _map_class_names_to_probabilities(probabilities: List[float]) -> Dict[str, float]:
"""Creates a dictionary mapping readable class names to their corresponding probabilites.
Args:
probabilities (List[float]): A List of the probabilities for the best predicted classes.
Returns:
Dict[str,... | 32,337 |
def unobscured_all_rebars_on_view(view, visible=True, solid=None):
"""
Переопределить видимость всей арматуры на виде
:param view: Вид, на котором нужно переопределить видимость
:type view: DB.View
:param visible: Видимость
:type visible: bool
:param solid: Показать как тело
:type solid... | 32,338 |
def orca_printbas(fname, at):
"""
Prints the basis set parameters into the input file input.com
Parameters:
fname (char): Basis set name
at (char): Symbol of the element
"""
#bfile = pkg_resources.open_text(templates, 'GTBAS1')
#bfile_r = pkg_r... | 32,339 |
def order_items(records):
"""Orders records by ASC SHA256"""
return collections.OrderedDict(sorted(records.items(), key=lambda t: t[0])) | 32,340 |
def G2DListMutatorRealGaussianGradient(genome, **args):
""" A gaussian gradient mutator for G2DList of Real
Accepts the *rangemin* and *rangemax* genome parameters, both optional.
The difference is that this multiplies the gene by gauss(1.0, 0.0333), allowing
for a smooth gradient drift about the value.
... | 32,341 |
def convert_group_by(response, field):
"""
Convert to key, doc_count dictionary
"""
if not response.hits.hits:
return []
r = response.hits.hits[0]._source.to_dict()
stats = r.get(field)
result = [{"key": key, "doc_count": count} for key, count in stats.items()]
result_sorted = so... | 32,342 |
def get_different_columns(
meta_subset1: pd.DataFrame,
meta_subset2: pd.DataFrame,
common_cols: list) -> list:
"""Find which metadata columns have the
same name but their content differ.
Parameters
----------
meta_subset1 : pd.DataFrame
A metadata table
meta_subs... | 32,343 |
def _parse_single(argv, args_array, opt_def_dict, opt_val):
"""Function: _parse_single
Description: Processes a single-value argument in command line
arguments. Modifys the args_array by adding a dictionary key and a
value.
NOTE: Used by the arg_parse2() to reduce the complexity ratin... | 32,344 |
def sort_sentence(sentence)
words = break_words(sentence)
reutrn sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
"""print the first and last words of the sentence."""
"""PRINTS the first and last words of the senctence."""
words =... | 32,345 |
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}):
"""
task 0.5.9
comprehension whose value is the intersection of setA and setB
without using the '&' operator
"""
return {x for x in (setA | setB) if x in setA and x in setB} | 32,346 |
def d_beta():
"""
Real Name: b'D BETA'
Original Eqn: b'0.05'
Units: b''
Limits: (None, None)
Type: constant
b''
"""
return 0.05 | 32,347 |
def _get_data(filename):
"""
:param filename: name of a comma-separated data file with two columns: eccentricity and some other
quantity x
:return: eccentricities, x
"""
eccentricities = []
x = []
with open(filename) as file:
r = csv.reader(file)
for row in r:
... | 32,348 |
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) > 0:
common = strs[0]
for str in strs[1:]:
while not str.startswith(common):
common = common[:-1]
return common
else:
return '' | 32,349 |
def analytics_dashboard(request):
"""Main page for analytics related things"""
template = 'analytics/analyzer/dashboard.html'
return render(request, template) | 32,350 |
def insert(shape, axis=-1):
"""Shape -> shape with one axis inserted"""
return shape[:axis] + (1,) + shape[axis:] | 32,351 |
def simplify_text(text):
"""
:param text:
:return:
"""
no_html = re.sub('<[^<]+?>', '', str(text))
stripped = re.sub(r"[^a-zA-Z]+", "", str(no_html))
clean = stripped.lower()
return clean | 32,352 |
def sym2img_check(session, scan, data_manager):
""" Check sym2img conversion """
y0 = data_manager.get_labels(wall_color=0)
sym2img_check_sub(session, scan, y0, "sym2img0.png")
y1 = data_manager.get_labels(wall_color=0, floor_color=0)
sym2img_check_sub(session, scan, y1, "sym2img1.png")
y2 = data_manager.... | 32,353 |
def is_numpy_convertable(v):
"""
Return whether a value is meaningfully convertable to a numpy array
via 'numpy.array'
"""
return hasattr(v, "__array__") or hasattr(v, "__array_interface__") | 32,354 |
def grower(array):
"""grows masked regions by one pixel
"""
grower = np.array([[0,1,0],[1,1,1],[0,1,0]])
ag = convolve2d(array , grower , mode = "same")
ag = ag != 0
return ag | 32,355 |
def SMAPELossFlat(*args, axis=-1, floatify=True, **kwargs):
"""Same as `smape`, but flattens input and target.
DOES not work yet
"""
return BaseLoss(smape, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | 32,356 |
def get_fake_datetime(now: datetime):
"""Generate monkey patch class for `datetime.datetime`, whose now() and utcnow() always returns given value."""
class FakeDatetime:
"""Fake datetime.datetime class."""
@classmethod
def now(cls):
"""Return given value."""
ret... | 32,357 |
def generate_order_by(fields: List[str], sort_orders: List[str], table_pre: str = '') -> str:
"""Функция генерит ORDER BY запрос для SQL
Args:
fields: список полей для сортировки
sort_orders: список (asc\desc) значений
table_pre: префикс таблицы в запросе
Return:
sql ORBER BY... | 32,358 |
def toUnicode(glyph, isZapfDingbats=False):
"""Convert glyph names to Unicode, such as 'longs_t.oldstyle' --> u'ſt'
If isZapfDingbats is True, the implementation recognizes additional
glyph names (as required by the AGL specification).
"""
# https://github.com/adobe-type-tools/agl-specification#2-the-mapping
#
... | 32,359 |
def list_watchlist_items_command(client, args):
"""
Get specific watchlist item or list of watchlist items.
:param client: (AzureSentinelClient) The Azure Sentinel client to work with.
:param args: (dict) arguments for this command.
"""
# prepare the request
alias = args.get('watchlist_al... | 32,360 |
def blit_array(surface, array):
"""
Generates image pixels from a JNumeric array.
Arguments include destination Surface and array of integer colors.
JNumeric required as specified in numeric module.
"""
if not _initialized:
_init()
if len(array.shape) == 2:
data = numeric.tra... | 32,361 |
def soerp_numeric(slc, sqc, scp, var_moments, func0, title=None, debug=False,
silent=False):
"""
This performs the same moment calculations, but expects that all input
derivatives and moments have been put in standardized form. It can also
describe the variance contributions and print out any outpu... | 32,362 |
def generate_IO_examples(program, N, L, V):
""" Given a programs, randomly generates N IO examples.
using the specified length L for the input arrays. """
input_types = program.ins
input_nargs = len(input_types)
# Generate N input-output pairs
IO = []
for _ in range(N):
input_va... | 32,363 |
def populate_runtime_info(query, impala, converted_args, timeout_secs=maxint):
"""Runs the given query by itself repeatedly until the minimum memory is determined
with and without spilling. Potentially all fields in the Query class (except
'sql') will be populated by this method. 'required_mem_mb_without_spilling... | 32,364 |
def secrecy_capacity(dist, rvs=None, crvs=None, rv_mode=None, niter=None, bound_u=None):
"""
The rate at which X and Y can agree upon a key with Z eavesdropping,
and no public communication.
Parameters
----------
dist : Distribution
The distribution of interest.
rvs : iterable of it... | 32,365 |
def cli(app, environment, branch, open_deploy):
"""
Deploy an application to an environment.
"""
config = load_config()
try:
client = VMFarmsAPIClient.from_config(config)
application_list = client.get('applications')['results']
selected_application = next(application for appl... | 32,366 |
def encrypt_message(partner, message):
"""
Encrypt a message
:param parner: Name of partner
:param message: Message as string
:return: Message as numbers
"""
matrix = get_encryption_matrix(get_key(get_private_filename(partner)))
rank = np.linalg.matrix_rank(matrix)
num_blocks = ... | 32,367 |
def test_get_keys_default(client):
"""Tests if search and admin keys have been generated and can be retrieved."""
keys = client.get_keys()
assert isinstance(keys, dict)
assert len(keys['results']) == 2
assert 'actions' in keys['results'][0]
assert 'indexes' in keys['results'][0]
assert keys[... | 32,368 |
def create_event(title, start, end, capacity, location, coach, private):
"""Create event and submit to database"""
event = Class(title=title, start=start, end=end, capacity=capacity, location=location, coach=coach, free=capacity, private=private)
db.session.add(event)
db.session.commit()
return even... | 32,369 |
def PlotPregLengths(live, firsts, others):
"""Plots sampling distribution of difference in means.
live, firsts, others: DataFrames
"""
print('prglngth example')
delta = firsts.prglngth.mean() - others.prglngth.mean()
print(delta)
dist1 = SamplingDistMean(live.prglngth, len(firsts))
dis... | 32,370 |
def regret_obs(m_list, inputs, true_ymin=0):
"""Immediate regret using past observations.
Parameters
----------
m_list : list
A list of GPy models generated by `OptimalDesign`.
inputs : instance of `Inputs`
The input space.
true_ymin : float, optional
The minimum val... | 32,371 |
def pmat2cam_center(P):
"""
See Hartley & Zisserman (2003) p. 163
"""
assert P.shape == (3, 4)
determinant = numpy.linalg.det
# camera center
X = determinant([P[:, 1], P[:, 2], P[:, 3]])
Y = -determinant([P[:, 0], P[:, 2], P[:, 3]])
Z = determinant([P[:, 0], P[:, 1], P[:, 3]])
... | 32,372 |
def main():
"""Main entry point for script"""
start = time.time()
ten_thousand_first_prime()
timeutils.elapsed_time(time.time() - start) | 32,373 |
def _http_req(mocker):
"""Fixture providing HTTP Request mock."""
return mocker.Mock(spec=Request) | 32,374 |
def transform_data(df, steps_per_floor_):
"""Transform original dataset.
:param df: Input DataFrame.
:param steps_per_floor_: The number of steps per-floor at 43 Tanner
Street.
:return: Transformed DataFrame.
"""
df_transformed = (
df
.select(
col('id'),
... | 32,375 |
def get_client(bucket):
"""Get the Storage Client appropriate for the bucket.
Args:
bucket (str): Bucket including
Returns:
~Storage: Client for interacting with the cloud.
"""
try:
protocol, bucket_name = str(bucket).lower().split('://', 1)
except ValueError:
r... | 32,376 |
async def update_ltos(trade_list, data_dict, strategy_period_mapping, df_balance):
"""
Args:
lto_dict (dict): will be updated (status, result, exit sections)
data_dict (dict): used for getting the candle to see if trade status needs to change
current_ts (ts): used for info sections of lt... | 32,377 |
def extract_text(xml_string):
"""Get text from the body of the given NLM XML string.
Parameters
----------
xml_string : str
String containing valid NLM XML.
Returns
-------
str
Extracted plaintext.
"""
paragraphs = extract_paragraphs(xml_string)
if paragraphs:
... | 32,378 |
def get_processing_info(data_path, actual_names, labels):
"""
Iterates over the downloaded data and checks which one is in our database
Returns:
files_to_process: List of file paths to videos
labs_to_process: list of same length with corresponding labels
"""
files_to_process = []
... | 32,379 |
def search_organizations(search_term: str = None, limit: str = None):
"""
Looks up organizations by name & location.
:param search_term: e.g. "College of Nursing" or "Chicago, IL".
:param limit: The maximum number of matches you'd like returned - defaults to 10, maximum is 50.
:returns: String cont... | 32,380 |
def test_fetch_emd_history_fail(config=CONFIG):
"""happypath test for `fetch_market_history_emd`"""
with pytest.raises(requests.exceptions.HTTPError):
data = forecast_utils.fetch_market_history_emd(
region_id=config.get('TEST', 'region_id'),
type_id=config.get('TEST', 'type_id'),... | 32,381 |
def call_math_operator(value1, value2, op, default):
"""Return the result of the math operation on the given values."""
if not value1:
value1 = default
if not value2:
value2 = default
if not pyd.is_number(value1):
try:
value1 = float(value1)
except Exception... | 32,382 |
def AddGnuWinToPath():
"""Download some GNU win tools and add them to PATH."""
if sys.platform != 'win32':
return
gnuwin_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'gnuwin')
GNUWIN_VERSION = '9'
GNUWIN_STAMP = os.path.join(gnuwin_dir, 'stamp')
if ReadStampFile(GNUWIN_STAMP) == GNUWIN_VERSION:
print('G... | 32,383 |
async def _default_error_callback(ex: Exception) -> None:
"""
Provides a default way to handle async errors if the user
does not provide one.
"""
_logger.error('nats: encountered error', exc_info=ex) | 32,384 |
def addGems(ID, nbGems):
"""
Permet d'ajouter un nombre de gems à quelqu'un. Il nous faut son ID et le nombre de gems.
Si vous souhaitez en retirer mettez un nombre négatif.
Si il n'y a pas assez d'argent sur le compte la fonction retourne un nombre
strictement inférieur à 0.
"""
old_value =... | 32,385 |
def start(
release,
fqdn,
rabbit_pass,
rabbit_ips_list,
sql_ip,
sql_password,
https,
port,
secret,
):
""" Start the arcus api """
image = f"breqwatr/arcus-api:{release}"
rabbit_ips_csv = ",".join(rabbit_ips_list)
env_vars = {
"OPENSTACK_VIP": fqdn,
"PU... | 32,386 |
def BertzCT(mol, cutoff=100, dMat=None, forceDMat=1):
""" A topological index meant to quantify "complexity" of molecules.
Consists of a sum of two terms, one representing the complexity
of the bonding, the other representing the complexity of the
distribution of heteroatoms.
From S. H. Bertz, J... | 32,387 |
def conjugate(*args, **kwargs):
"""
the conjugate part of x
This function has been overriden from pymel.util.mathutils.conjugate to work element-wise on iterables
"""
pass | 32,388 |
def BOPTools_AlgoTools_CorrectRange(*args):
"""
* Correct shrunk range <aSR> taking into account 3D-curve resolution and corresp. tolerances' values of <aE1>, <aE2>
:param aE1:
:type aE1: TopoDS_Edge &
:param aE2:
:type aE2: TopoDS_Edge &
:param aSR:
:type aSR: IntTools_Range &
:param... | 32,389 |
def OldValue(lval, mem, exec_opts):
# type: (lvalue_t, Mem, optview.Exec) -> value_t
"""
Used by s+='x' and (( i += 1 ))
TODO: We need a stricter and less ambiguous version for Oil.
Problem:
- why does lvalue have Indexed and Keyed, while sh_lhs_expr only has
IndexedName?
- should I have lvalue.N... | 32,390 |
def approx_min_k(operand: Array,
k: int,
reduction_dimension: int = -1,
recall_target: float = 0.95,
reduction_input_size_override: int = -1,
aggregate_to_topk: bool = True) -> Tuple[Array, Array]:
"""Returns min ``k`` values and the... | 32,391 |
def set_run(environment: str, run_result_id: int, description: str):
""" creates all the necessary directories and sets up the Simpyl object for a run
"""
create_dir_if_needed(run_path(environment, run_result_id))
# write a text file with the description as as text file
filename = os.path.join(
... | 32,392 |
def sitemap_host_xml():
"""Supplementary Sitemap XML for Host Pages"""
database_connection.reconnect()
hosts = ww_host.info.retrieve_all(database_connection)
sitemap = render_template("sitemaps/hosts.xml",
hosts=hosts)
return Response(sitemap, mimetype="text/xml") | 32,393 |
def WTC(df,N):
"""Within Topic Coherence Measure.
[Note]
It ignores a word which does not have trained word vector.
Parameters
----------
df : Word-Topic distribution K by V
where K is number of topics and V is number of words
N : Number of top N words ... | 32,394 |
def launch_top_runs(top_paths, bp, command, auto_pupdate=False,
partition_name='debug', time_limit='04-00:00:00', memory_limit=2048):
"""
Launch the top runs.
@param top_paths: The full path to the base directory containing the top
results.
@param bp: The new base directory.
@param command: The b... | 32,395 |
def extract_static_override_features(
static_overrides):
"""Extract static feature override values.
Args:
static_overrides: A dataframe that contains the value for static overrides
to be passed to the GAM Encoders.
Returns:
A mapping from feature name to location and then to the override value... | 32,396 |
def job_list_View(request):
"""
"""
job_list = Job.objects.filter()
paginator = Paginator(job_list, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {
'page_obj': page_obj,
}
return render(request, 'jobapp/job-list.html', cont... | 32,397 |
def set_degree_as_weight(g):
"""Set degree of connected nodes as weight.
For metabolite graphs it is often desirable to see the routes with
less connected metabolites
"""
d = nx.degree_centrality(g)
for u, v in g.edges():
g[u][v]['weight'] = d[v] | 32,398 |
def find_tiledirs(channeldir: pathlib.Path,
tiles: Union[int, str, List[int], None] = None,
conditions: Union[str, List[str], None] = None) -> TileGenerator:
""" Find all the tiles under the channel dir
:param Path channeldir:
The channel directory to search
:par... | 32,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.