content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_observed_stats_file(observed_df, param_num, path_run_ABC):
"""
Create file of 'observed' stats from dataframe from one simulation.
:param observed_df: dataframe of parameter and summary stats from one simulation.
:param param_num: number of parameters
:param path_run_ABC: full or relativ... | 5,325,500 |
def setup_source_space(subject, fname=True, spacing='oct6', surface='white',
overwrite=False, subjects_dir=None, add_dist=None,
verbose=None):
"""Setup a source space with subsampling
Parameters
----------
subject : str
Subject to process.
fname... | 5,325,501 |
def install_volta() -> None:
"""Install volta if missing, and set up node and npm."""
shaper.download.install_with_remote_script(
"volta", "https://get.volta.sh", ["--skip-setup"]
)
HOME = pathlib.Path.home()
os.environ.update(
{
"VOLTA_HOME": f"{HOME}/.volta",
... | 5,325,502 |
def validate_model(model_data, model_schema, enum_info):
"""Ensure the value is valid for the field type. Scales values as needed."""
for k in model_schema:
label = model_schema[k][0]
field_type = model_schema[k][1]
if k in model_data:
value = model_data[k]
elif len(m... | 5,325,503 |
def get_my_ip() -> None:
"""
Funtion to get current ip in Network
"""
url = "http://checkip.dyndns.com/"
return re.compile(r"Address: (\d+.\d+.\d+.\d+)").search(get(url).text).group(1) | 5,325,504 |
def param_squared_mean(ns_run, logw=None, simulate=False, param_ind=0):
"""Mean of the square of single parameter (second moment of its
posterior distribution).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
... | 5,325,505 |
def get_historical_data(Code=None):
"""
A function to get a historical data corresponding to a specified stock code.
Args:
Code (str): A stock code corresponding to the historical data.
Returns:
A historical data corresponding to the stock code in DataFrame format of Pandas.
"""
... | 5,325,506 |
def match_login_url_with(username, default="https://foo.bar/login"):
"""
Match a given username with the corresponding
login URL
:param username: username of user. type str
:returns URL: login URL for user. type str
"""
return matches(
{
"yelluw": "https://yelluw.com/log... | 5,325,507 |
def odict_1to1(from_sp, to_sp):
"""
Filtered flat odict with only 1to1 orthologs.
"""
od = odict(from_sp, to_sp)
od_rev = odict(to_sp, from_sp)
return dict([(k,list(v)[0]) for k,v in od.items() if len(v)==1 and
len(od_rev[list(v)[0]])==1]) | 5,325,508 |
def find_devices(vendor=None, product=None, serial_number=None, custom_match=None, **kwargs):
"""Find connected USB devices matching certain keywords.
Wildcards can be used for vendor, product and serial_number.
:param vendor: name or id of the vendor (manufacturer)
:param product: name or id of the p... | 5,325,509 |
def get_static_graph(app_name=None, app_dict=None, *args, **kwargs):
""" Explicityl avoid request and user. """
return get_graph(app_name=app_name, app_dict=app_dict, request=None) | 5,325,510 |
def primitive_triplets(limit):
"""See Euclid's formula
(https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple)
for more information
"""
for m, n in euclidian_coprimes(limit):
m2, n2 = m * m, n * n
a, b, c = m2 - n2, 2 * m * n, m2 + n2
if a > b:
a, b... | 5,325,511 |
def tune(data_path, labels, tempdir, batch_size, weights_out):
""" [NOT IMPLEMENTED] Update network with new data.
Finetune the network for a different task by keeping the
trained weights, replacing the top layer with one that outputs
the new classes, and re-training for a few epochs to hav... | 5,325,512 |
def run_post_install(post_install: List[Text], source: Location):
"""
Running the post-install scripts
"""
for script in post_install:
source.run_script(script) | 5,325,513 |
def test_initial_position_zero():
"""Tests that the inverted path initial position is the right one."""
batch_size = 10
input_stream = 10
input_channels = 3
path = torch.rand((batch_size, input_stream, input_channels))
for depth in (2, 4, 6):
signature = signatory.signature(path, depth)
... | 5,325,514 |
def downsample_spectrum(ar_wavelength, ar_flux, ar_ivar, scale):
"""
:type ar_wavelength: np.ndarray
:type ar_flux: np.ndarray
:type ar_ivar: np.ndarray
:type scale: int
:return: (np.ndarray, np.ndarray, np.ndarray)
"""
new_length = ar_wavelength.size // scale
old_length_clipped = ne... | 5,325,515 |
def format_date(date):
"""
Format date for creation of Twitter URL and Facebook API.
Format a datetime object to a string in the form of '%Y-%m-%d', e.g. '2018-01-21'
Parameters
----------
date : datetime
date to be formated
Returns
-------
str
date in string repre... | 5,325,516 |
def basic_token(username, password):
"""Generate the Authorization token for Resource Orchestrator (SO-ub container).
Args:
username (str): the SO-ub username
password (str): the SO-ub password
Returns:
str: the Basic token
"""
if not isinstance(username, str):
rais... | 5,325,517 |
def read_alias(alias_csv_path):
"""Reads alias.csv at the specified path.
Then returns a dict mapping from alias to monster id.
"""
with open(alias_csv_path) as alias_csv:
return {
alias: int(monster_id)
for alias, monster_id in csv.reader(alias_csv)} | 5,325,518 |
def makedirpath(fpath: str):
"""Make path."""
dpath = os.path.dirname(fpath)
if dpath:
os.makedirs(dpath, exist_ok=True) | 5,325,519 |
async def get_pipeline_run_node_steps(request: web.Request, organization, pipeline, run, node) -> web.Response:
"""get_pipeline_run_node_steps
Retrieve run node steps details for an organization pipeline
:param organization: Name of the organization
:type organization: str
:param pipeline: Name of... | 5,325,520 |
def query_available_collections(opts: Options) -> pd.DataFrame:
"""Search for the available collections."""
# Graphql query to get the collections
query = create_collections_query()
# Call the server
reply = query_server(opts.web, query)
collections = json_properties_to_dataframe(reply["collecti... | 5,325,521 |
def _create_agent_object_list(
trial_list: List[List[Dict[str, Any]]],
agent_object_config_list: List[ObjectConfigWithMaterial],
unit_size: Tuple[float, float]
) -> List[Dict[str, Any]]:
"""Create and return the MCS scene's agent object list using the given
trial list from the JSON file data."""
... | 5,325,522 |
async def send_data_controller_details_message_handler(request: web.BaseRequest):
"""Send data controller details message to remote agent hosted by Data Controller."""
context = request.app["request_context"]
connection_id = request.match_info["connection_id"]
# Initialise MyData DID Manager.
myda... | 5,325,523 |
def test_llhelper(monkeypatch):
"""Show how to get function pointers used in type slots"""
FT = lltype.FuncType([], lltype.Signed)
FTPTR = lltype.Ptr(FT)
def make_wrapper(self, space):
def wrapper():
return self.callable(space)
return wrapper
monkeypatch.setattr... | 5,325,524 |
def get_chronicle_http_client(account_info):
"""
Return an http client that is authorized with the given credentials
using oauth2client or google-auth.
"""
try:
credentials = service_account.Credentials.from_service_account_info(
account_info, scopes=current_app.config['AUTH_SCO... | 5,325,525 |
def add_singlesample_parser(subparsers):
"""Add function 'singlesample' argument parsers."""
argparser_gsea = subparsers.add_parser("ssgsea", help="Run Single Sample GSEA.")
# group for input files
group_input = argparser_gsea.add_argument_group("Input files arguments")
group_input.add_argument("-... | 5,325,526 |
def svn_auth_save_credentials(*args):
"""svn_auth_save_credentials(svn_auth_iterstate_t state, apr_pool_t pool) -> svn_error_t"""
return apply(_core.svn_auth_save_credentials, args) | 5,325,527 |
def setProgressParent(parent):
"""
Enable the FTP progress GUI, and set the parent frame.
Usage: setProgressParent(parent)
"""
global _progressParent
_progressParent = parent
# Notify cache module that window dialogs should be used.
cache.useWindow() | 5,325,528 |
def write_directory_status(directory_status):
"""
Writes a status to the status file:
Overwrites anything that is in the file
Writes a timestamp to the time of last written
:param directory_status: DirectoryStatus object containing status to write to directory
:return: None
"""
if conf... | 5,325,529 |
def toggleDisplayOrigShape(inMesh, inColor =(.8, 0.2, 0.2), both = False, progressBar=None):
"""
toggle the display of the mesh beteen the output and the input shape of the skincluster. the input shape will receive default lamber + vertex colors to make sure there is a big distinction between the 2
:todo... | 5,325,530 |
def get_nodes_str (name, nodes):
"""
helper function to dump nodes as a list of names
"""
nodes_str = " %s nodes = %d\n" % (name, len(nodes))
nodes_str += " " + ", ".join(map(lambda x: x._name, nodes)) + "\n"
return nodes_str | 5,325,531 |
def test_corr():
"""
Test top-level functions in pyccl.correlation module.
"""
for cosmo in reference_models():
yield check_corr, cosmo
for cosmo_nu in reference_models_nu():
yield check_corr, cosmo_nu
for cosmo in reference_models():
yield check_corr_3d, cosmo
for... | 5,325,532 |
def compute_X_axis(dataset, frame, dss, ref_freq=None, vspline=None,
time=None):
"""
Computes the appropriate X-axis for the averaged difference spectrum
'vobj' is velocity of the object in the rest velocity of frame specified.
Acceptable frames are defined in the SAOhdf5.rel... | 5,325,533 |
def _reduce_child(node: Node, child: Node, root: RootNode):
"""
Sets node's results to the child's result, keeping node's tag_name.
"""
node._set_result(child._result)
update_attr(node, (child,), root)
# update_attr(child, (node,), root)
# if child.has_attr():
# node._xml_attr = chil... | 5,325,534 |
def clean_df(df, selected_columns=default_columns):
"""Take a dataframe with GDELT2.0 data and only retain the useful columns for us and also add the country where the news was written
Keyword arguments:
df -- The dataframe complying to GDELT2.0 columns format
selected_columns (optionn... | 5,325,535 |
def mse(y_true, y_pred, reduce_mode="mean"):
"""mean squared error。"""
return reduce(tf.math.square(y_pred - y_true), reduce_mode) | 5,325,536 |
def calculate_assignment_probabilites(assignments, num_clusters):
"""
Just counts the occurence of each assignment to get an empirical pdf estimate
"""
temp = np.arange(num_clusters)
hist_b_edges = np.hstack([-np.inf, (temp[:-1] + temp[1:]) / 2, np.inf])
assignment_counts, _ = np.histogram(assignments, hist... | 5,325,537 |
def unix_getpass(prompt='Password: ', stream=None):
"""Prompt for a password, with echo turned off.
Args:
prompt: Written on stream to ask for the input. Default: 'Password: '
stream: A writable file object to display the prompt. Defaults to
the tty. If no tty is available defaults ... | 5,325,538 |
def getStudiesOptions(request, id):
""" Get a list of studies for an investigation id.
Input:
id, investigation id.
"""
seekdb = SeekDB(None, None, None)
user_seek = seekdb.getSeekLogin(request, False)
investigation_id = id
studies = seekdb.getStudiesFromID(investigation_id)... | 5,325,539 |
def fibonacci_thrid(n):
"""计算斐波那契数列3"""
return n if n < 2 else fibonacci_thrid(n - 2) + fibonacci_thrid(n - 1) | 5,325,540 |
def make_frame_image(xs, ys, Cs):
""" Create a figure displaying the frame data. """
## The minimum x value.
x_min = 0
## The maximum x value.
x_max = 256
## The minimum y value.
y_min = 0
## The maximum y value.
y_max = 256
## The width of the frame.
w = 256
## The... | 5,325,541 |
def background_thread():
"""Example of how to send server generated events to clients."""
global viewerParams, updateViewerParams, MLParams, updateMLParams
while True:
socketio.sleep(seconds)
if (updateViewerParams):
print("========= viewerParams:",viewerParams.keys())
socketio.emit('update_viewerParams', ... | 5,325,542 |
def main(pargs):
""" Run
"""
import warnings
from frb.builds import build_specdb
from frb.builds import build_frbs
from frb.builds import build_hosts
from frb.builds import build_fg
# Parse
item = pargs.item.lower()
if item == 'frbs':
build_frbs.main(inflg=pargs.flag)
... | 5,325,543 |
def site_url(url):
"""
Determine the server URL.
"""
base_url = 'http://%s' % socket.gethostname()
if server.port is not 80:
base_url += ':%d' % server.port
return urlparse.urljoin(base_url, url) | 5,325,544 |
def get_coordinates(
mask: np.ndarray, ths: int = 5, kernel_len: int = 10
) -> Tuple[List, np.ndarray, np.ndarray]:
"""This function extract the coordinate of table, horizontal and vertical lines.
Args:
mask (np.darray): A binary table image
ths (int, optional): Threshold value to ignore th... | 5,325,545 |
def save_users(user):
"""
Function that saves the new user
"""
user.save_user() | 5,325,546 |
def get_pixels(extrinsic, intrinsic, X):
"""
Returns the x, y pixels for the given X vector
:param extrinsic: extrinsic (4*4) matrix obtained from the headset
:param intrinsic: intrinsic (3*3) matrix obtained from the headset
:param X: the position vector
:return: image pixels for the vector
... | 5,325,547 |
def boggle_helper(word, used_position, current_word, x, y, found_list):
"""
:param word: the nested list of the alphabets of the boggle
:param used_position: the (x, y) coordinates which have been used
:param current_word: the current word that the program is processing
:param x: the x coordinate of... | 5,325,548 |
def delete_question(media_package, level=0):
"""
Ask user the question whether they want to delete the distribution artefacts for the next media package or for all
remaining media packages.
:param media_package: The media package to ask the question for
:type: str
:param level: The level to ind... | 5,325,549 |
def import_submodules(package, recursive=True):
""" Import all submodules of a package, recursively, including subpackages
Arguments:
1. package = (string) name of the package
(module) loader of the package
2. recrusive = (bool) True = load packages and modules from all sub-pack... | 5,325,550 |
def is_collision_ray_cell(map_obj, cell):
"""
cell : cell r, c index from left bottom.
"""
idx = cell[0] + map_obj.mapdim[0] * cell[1]
if (cell[0] < 0) or (cell[1] < 0) or (cell[0] >= map_obj.mapdim[0]) or (cell[1] >= map_obj.mapdim[1]):
return True
#elif (map_obj.map is not None) and map_obj.map[cell[0... | 5,325,551 |
def test_override_tab_value():
"""Test the override_tab_value() function."""
data = [[1, '\tJohn'], [2, 'Jill']]
headers = ['id', 'name']
expected = ([[1, ' John'], [2, 'Jill']], ['id', 'name'])
results = override_tab_value(data, headers)
assert expected == (list(results[0]), results[1]) | 5,325,552 |
def time_of_trip(datum, city):
"""
Takes as input a dictionary containing info about a single trip (datum) and
its origin city (city) and returns the month, hour, and day of the week in
which the trip was made.
Remember that NYC includes seconds, while Washington and Chicago do not.
HINT: You ... | 5,325,553 |
def transform_resource_name(ctx, param, value):
"""Callback to transform resource_name into title case."""
if value is not None:
return value.title()
return value | 5,325,554 |
def extrema (im):
"""
Return the minimum and maximum of an image.
Arguments:
im image whose extrema are to be found
"""
return [im.min(), im.max()] | 5,325,555 |
def _create_statement(name, colnames):
"""Create table if not exists foo (...).
Note:
Every type is numeric.
Table name and column names are all lowercased
"""
# every col is numeric, this may not be so elegant but simple to handle.
# If you want to change this, Think again
... | 5,325,556 |
def createBundle():
"""create bundled type of OSC messages"""
b = OSC.OSCMessage()
b.address = ""
b.append("#bundle")
b.append(0)
b.append(0)
return b | 5,325,557 |
def binary_or(a: int, b: int):
"""
Take in 2 integers, convert them to binary, and return a binary number that is the
result of a binary or operation on the integers provided.
>>> binary_or(25, 32)
'0b111001'
>>> binary_or(37, 50)
'0b110111'
>>> binary_or(21, 30)
'0b11111'... | 5,325,558 |
def tukey(N, alpha):
"""
generate a tukey window
The Tukey window, also known as the tapered cosine window, can be regarded as a cosine lobe of width \alpha * N / 2
that is convolved with a rectangle window of width (1 - \alpha / 2). At \alpha = 1 it becomes rectangular, and
... | 5,325,559 |
def get_response(log, url, **kwargs):
"""
Get data from server at given url.
Parameters:
- log: Standard python log instance
- url: The url to make a post/get request to.
- kwargs: Keyword arguments.
- data: dict of post data. If data != None, get_response makes a
http... | 5,325,560 |
def check_dir(path):
""" (path:str) -> bool
Check if path is absolute and is a directory.
"""
if not isabs(path):
raise ValueError("Path %r is not absolute" % path)
if not isdir(path):
raise ValueError("Path %r is not a directory" % path) | 5,325,561 |
def psi(X, Y, c_i, A, config, pkg='numpy'):
"""Computes the value of magnetic flux at point (X, Y)
according to coefficients ci.
Args:
X (float or numpy.array): x coordinate
Y (float or numpy.array): y coordinate
c_i (list): list of floats, the ci coefficients
A (float): pla... | 5,325,562 |
def get(baseurl, params=None, headers=None, private_keys_to_ignore=["key", "secret"], permanent_cache_file=PERMANENT_CACHE_FNAME, temp_cache_file=TEMP_CACHE_FNAME):
"""
Return a Response object (defined in this file) for the given URL.
Look in temp_cache first, then permanent_cache.
If not found, fetc... | 5,325,563 |
def tempConvert(temp, unit):
""" Convert Fahrenheit to Celsius """
if unit == 'F':
celsius = (temp-32) * 5/9
return celsius
else:
return temp | 5,325,564 |
def blueprintCreation(inputs: dict, con: bytes) -> None:
"""Creates blueprints if correct config present
Args:
inputDict (dict): User YAML input
con (bytes): JCL class instance object
"""
for item in inputs:
response = con.blueprintCreate(blueprintName=item['name'], template... | 5,325,565 |
def register_snapshot_listeners():
"""Attaches listeners to various models."""
rules = get_rules()
# Initialize listening on parent objects
for model_cls in rules.rules.iterkeys():
model = getattr(models.all_models, model_cls)
signals.Restful.model_posted_after_commit.connect(
create_all, mode... | 5,325,566 |
def scriptJob(allChildren: bool = False,attributeAdded: Tuple[str, str] = tuple("", ""),attributeChange: Tuple[str, str] = tuple("", ""),attributeDeleted: Tuple[str, str] = tuple("", ""),compressUndo: bool = False,conditionChange: Tuple[str, str] = tuple("", ""),conditionFalse: Tuple[str, str] = tuple("", ""),condition... | 5,325,567 |
def _find_best_twitter_key(type, reset, remaining, limit, proxies, auth):
"""
This function switches to another pair of Twitter API keys, if they are available, to avoid pausing.
* WANT TO SWAP KEYS HERE B/C PAUSE IS MORE THAN 3 MINUTES
:param type: Type of API call: "timeline", "friends", "followers"... | 5,325,568 |
def allowed_file(filename, allowed_exts):
"""
The validator for blueimp that limits which file extensions are allowed.
Args:
filename (str): a filepath
allowed_exts (str): set of allowed file extensions
Returns:
bool: True if extension is an allowed file type, False otherwise
... | 5,325,569 |
def tokenize(document):
"""
Given a document (represented as a string), return a list of all of the
words in that document, in order.
Process document by coverting all words to lowercase, and removing any
punctuation or English stopwords.
"""
words = document.lower()
words = nltk.w... | 5,325,570 |
def _test_divide_uniform():
"""
Currently fails because division poorly defined for identical Normal Messages
"""
prior = af.UniformPrior(
lower_limit=0.2,
upper_limit=0.8
)
result = prior / af.UniformPrior()
assert not np.isnan(result.lower_limit) | 5,325,571 |
def return_file_size(file_path):
"""This is taking the final size of the pre-processed file, and this number will be used in the rendering process.
"""
size = os.path.getsize(file_path)
return size | 5,325,572 |
def test_get_intervals_valid_duration():
""" Tests that InterestInterval entries returned by 'get_interest_intervals' function last no longer than LendingInterval entries they originated from """
lending_intervals = generate_sample_lending_intervals(30, 10, 1450000000, 1510000000)
for lending_interval in lending_int... | 5,325,573 |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
database = db_connect()
cursor = database.cursor()
cursor.execute("SELECT password, active FROM users WHERE api_user=%s;", (username,))
results = cursor.fetchone()
c... | 5,325,574 |
def train(
data="StephenColbert/medium_no_vtx1",
labels="labels.json",
sentence_dataset=False,
occlussion_threshold=0.8,
train_split=0.8,
num_workers=1,
refresh=False,
patience=10,
batch_size=4,
learning_rate=1e-4,
annealings=2,
enable_ctc=False,
grad_norm=50,
t... | 5,325,575 |
def _handle_axis(axis: Union[str, int]) -> int:
"""Handles axis arguments including "columns" and "index" strings."""
if axis not in {0, 1, 'columns', 'index'}:
raise ValueError(
"axis value error: not in {0, 1, 'columns', 'index'}"
)
# Map to int if str
if isinstance(axis, ... | 5,325,576 |
def test_odds_type_raise_value_error():
"""Test the raise of value error for check of odds type."""
dataloader = DummySoccerDataLoader()
with pytest.raises(
ValueError,
match="Parameter `odds_type` should be a prefix of available odds columns. "
"Got `pinnacle` instead.",
):
... | 5,325,577 |
async def create_app() -> web.Application:
"""Create an web application."""
app = web.Application(
middlewares=[
cors_middleware(allow_all=True),
error_middleware(), # default error handler for whole application
]
)
# Set up logging
logging.basicConfig(level=... | 5,325,578 |
def section_setup(section, zip_directory, corpus_directory):
"""Make folders for individual SE site (section)'s unzipped files and
processed data, and generate expected path to 7z file on disk"""
# makes folder for unzipped files for a site
section_directory = os.path.join(zip_directory, section)
m... | 5,325,579 |
def get_file_size(file):
"""Get file size.
Args:
file (str): Input file.
Returns:
int: Return size of the file in bytes.
"""
return os.stat(file).st_size | 5,325,580 |
def is_icmp_dest_unreach(icmp_data):
"""is ICMP_DEST_UNREACH?"""
return icmp_data["TYPE"] == ICMP_DEST_UNREACH | 5,325,581 |
def printFeature(f, default=0.0, t=60):
"""Prints feature f."""
traverse(f, lambda i, x: print(str((i, x))), default, t) | 5,325,582 |
def save_tweets(tweets: List[Status], overwrite=False, sentiment_analyzer=None):
""" Saves a list of tweets to postgres """
save_users([t.user for t in tweets])
unique_tweets = [*toolz.unique(tweets, key=lambda t: t.id)]
conn = db_conn()
crs = conn.cursor()
records = [*map(tweet_to_record, uniq... | 5,325,583 |
def exists_user_notifications(session, user_id):
"""Helper method to check if notifications for user exists."""
res = session.execute(text("""SELECT EXISTS(
SELECT 1 FROM public.notification WHERE user_id='{0}') AS user"""
.format(user_id))).fet... | 5,325,584 |
def export_onnx(model, config, device, onnx_model_path, verbose):
""" Export GPT-2 model with past state to ONNX model
"""
num_layer = config.n_layer
dummy_inputs = get_dummy_inputs(batch_size=1,
past_sequence_length=1,
sequence_len... | 5,325,585 |
def merge_ref(mask, found_id, position):
"""
Merges the ids that are congruent to each other in the mask
Note: side effect of merge_ref leaves pixels of the mask skipping IDs if
merged
TODO: optimize by splitting into a equivalency list and passing merge_ref
at end
Parameters
---------... | 5,325,586 |
def set_peak_elo(df: DataFrame, playersElo) -> DataFrame:
"""Add 2 columns PeakElo and PeakEloSince to a dataframe containing Date, P1Id and P2Id fields
Args:
df (DataFrame): the dataframe from where we read row by row (match by match)
playersElo ([type]): dict <id>:[eloratings_history]
Re... | 5,325,587 |
def _async_validate_auto_generated_cost_entity(
hass: HomeAssistant, energy_entity_id: str, result: list[ValidationIssue]
) -> None:
"""Validate that the auto generated cost entity is correct."""
if energy_entity_id not in hass.data[DOMAIN]["cost_sensors"]:
# The cost entity has not been setup
... | 5,325,588 |
def calc_plane_vector(atom_pos):
"""
Method to calculate best-fitted (unit) plane vector given a set of points using SVD
ARGS:
atom_pos (ndarray) :: ndarray storing atomic positions
returns:
ndarray
"""
# Zero-centering centroid of atoms before SVD
atom_pos_0 = atom_pos.T - np... | 5,325,589 |
def search_reddit(search, subreddit='', t='week', limit='100',
sort='new', restrict_sr='1'):
"""
search - string object, representing your search query
subreddit - string object, representing the subreddit
t - string object, one of (hour, day, week, month, year, all)
limit - strin... | 5,325,590 |
def _expected_type_expression(typedef: Typedef) -> str:
"""
Determine the type expression supplied to ``from_obj`` function corresponding to the type definition.
:param typedef: type definition in Python representation
:return: Python code representing the type definition
"""
# pylint: disable=... | 5,325,591 |
def adjoint(m):
"""Compute the Hermitian adjoint."""
return np.transpose(np.conj(m)) | 5,325,592 |
def get_graphic_template_variables(path, graphic_number):
"""
Generates the template variables for each graphic
"""
slug, abspath = utils.parse_path(path)
graphic_path = '%s/%s' % (abspath, slug)
## Get Spreadsheet Path
try:
graphic_config = load_graphic_config(graphic_path)
exc... | 5,325,593 |
def svc(self, model):
""" Obtain the model and the search space of the SVC
classifier. """
svc_sp = {}
if model == "linear":
svc = LinearSVC(dual=False, class_weight='balanced')
else:
svc = SVC(cache_size=1000, class_weight='balanced')
svc_sp['kernel'] = ['linear', 'poly', '... | 5,325,594 |
def plot_difference( field, coord, iteration, F_cpu, F_gpu, info ):
"""
Plots the simulation results on CPU and GPU
"""
import matplotlib.pyplot as plt
plt.figure()
plt.suptitle( field + coord )
plt.subplot(311)
plt.imshow( F_gpu, aspect='auto',
origin='lower', extent=1.e... | 5,325,595 |
def _FormatDataTransferIdentifiers(client, transfer_identifier):
"""Formats a transfer config or run identifier.
Transfer configuration/run commands should be able to support different
formats of how the user could input the project information. This function
will take the user input and create a uniform trans... | 5,325,596 |
def getReactionUrl(reaction, family=None, estimator=None, resonance=True):
"""
Get the URL (for kinetics data) of a reaction.
Returns '' if the reaction contains functional Groups or LogicNodes instead
of real Species or Molecules.
"""
kwargs = dict()
for index, reactant in enumerate(reacti... | 5,325,597 |
def test_mcs_nonmatch(graph, subgraph, attrs):
"""
Test against networkx reference implementation using graphs that are
probably not subgraphs without considering symmetry.
"""
if attrs is None:
node_match = lambda n1, n2: True
attrs = []
else:
node_match = nx.isomorphism... | 5,325,598 |
def hexLat2W(nrows=5, ncols=5):
"""
Create a W object for a hexagonal lattice.
Parameters
----------
nrows : int
number of rows
ncols : int
number of columns
Returns
-------
w : W
instance of spatial weights class W
Notes
-----
... | 5,325,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.