content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def set_admin(userid):
""" Set a given user as admin """
user = User.query.filter_by(username=userid).first()
if not user:
print "Utente %s non trovato nel db" % (userid)
return
user.is_admin = True
db.session.add(user)
db.session.commit()
print "%s impostato come admin" % us... | 42,900 |
def GetHighlightColour():
"""
Gets the default highlight color.
:rtype: :class:`wx.Colour`
"""
if wx.Platform == '__WXMAC__':
if CARBON:
if wx.VERSION < (2, 9, 0, 0, ''):
# kThemeBrushButtonPressedLightHighlight
brush = wx.Brush(wx.BLACK)
... | 42,901 |
def video_to_frames(width, height, video_path, frames_dir, overwrite=False, every=1):
"""
Extracts the frames from a video
:param width: width of input video
:param height: height of input video
:param video_path: path to the video
:param frames_dir: directory to save the frames
:param overw... | 42,902 |
def ignores(path):
"""Pull the flake8 ignores out of the tox file"""
toxini = path + "/tox.ini"
LOG.debug("Tox %s\n" % toxini)
config = configparser.ConfigParser()
config.read(toxini)
options = {}
for option in ('ignore', 'import-order-style',
'application-import-names', '... | 42,903 |
def goa_fitter_1(ecm_para_config_dict, repeat_time=1):
"""
Function
:param
ecm_para_config_dict:{
'exp_fn': the name of file Containing EIS experiment data, it does not have appendix '.txt', like '1-1', '5-35'
'ecm_num': int
'limit': [[para_0_low_limit, para_0_upp... | 42,904 |
def add_to_data(d: dict, data: dict, next_id: int = None) -> None:
"""
updates dictionary d to include/update the data. Also removes None values.
Args:
d: a Dictionary of ID: data to which we want to update the data according to ID
data: the data to update. data must have an "ID" field.
... | 42,905 |
def get_classes(mod):
"""Return a list of all classes in module 'mod'"""
return [
key
for key, _ in inspect.getmembers(mod, inspect.isclass)
if key[0].isupper()
] | 42,906 |
def _mate(
i_one: genetic_algorithm_results.VCOptimizationIndividual,
i_two: genetic_algorithm_results.VCOptimizationIndividual) -> None:
"""Mates two individuals, modifies them in-place."""
i_one = i_one[0]
i_two = i_two[0]
if len(i_one.protocol.steps) != len(i_two.protocol.steps):
... | 42,907 |
def test_language_enumeration004_1431_language_enumeration004_1431_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=enumeration and value=en fr de
and document value=en
"""
assert_bindings(
schema="msData/datatypes/Facets/language/language_enumeration004.xsd",
... | 42,908 |
def ustring_to_string(ptr, length=None):
"""Convert a pointer to UTF-16 data into a Python string encoded with utf-8.
ptr and length are both gdb.Value objects.
If length is unspecified, will guess at the length."""
error_message = ''
if length is None:
length, error_message = guess_string_... | 42,909 |
def handle_outgoing(msg):
"""
Should return a requeue flag, so if it returns True, the message will be
requeued and processed again immediately, and if it returns False, it will
not be queued again.
"""
def onerror():
logging.exception("Exception while processing SMS %s" % msg._id)
... | 42,910 |
def add_entry(ynew: float, s: float, s2: float, n: int, calc_var: bool):
"""Adds an entry to the metrics, s, s2, and n.
s: previous value of sum of y[]
s2: previous value of sum of y[]*y[]
n: previous number of entries in the metric
"""
n = n + 1
s = s + ynew
s2 = s2 + ynew * ynew
... | 42,911 |
def get_conversion_dict(conversion_name):
"""Retrieves a hard-coded label conversion dictionary.
When coarsening the label set of a task based on a predefined
conversion scheme like Penn Treebank tags to Universal PoS tags,
this function provides the map, out of a fixed list of known
maps addressed by a keyw... | 42,912 |
def test_is_natural():
"""Test objects on being natural numbers."""
assert not is_natural(-1)
assert not is_natural(0)
assert not is_natural(1.0)
assert is_natural(1) | 42,913 |
def discount_cumsum(x, discount):
"""
magic from rllab for computing discounted cumulative sums of vectors.
input:
vector x,
[x0,
x1,
x2]
output:
[x0 + discount * x1 + discount^2 * x2,
x1 + discount * x2,
x2]
"""
return scipy.signal.l... | 42,914 |
def compute_rgb_scales(alpha_thres=0.9):
"""Computes RGB scales that match predicted albedo to ground truth,
using just the first validation view.
"""
config_ini = configutil.get_config_ini(FLAGS.ckpt)
config = ioutil.read_config(config_ini)
# First validation view
vali_dir = join(config_in... | 42,915 |
def pick_pareto_front(points, keep_equal=False):
"""Returns the Pareto-optimal points from a set of points,
assuming all objectives are minimisation objectives.
The n points in d-dimensional objective space are given in an ndarray
of shape (n,d), and the return value is of shape (m,d) where m is the
... | 42,916 |
def get_market_conditions(filename):
"""
Creates the market condition table from the scenario file and risk factors
"""
market_conditions = []
print("Generate conditions")
#open the csv file to be read
with open(filename) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
... | 42,917 |
def PaperSize(s):
"""Return a tuple (width, height) for a given paper format string. 'A4-L' will
return (842, 595), the values for A4 landscape. Suffix '-P' and no suffix
returns portrait."""
size = s.lower()
f = "p"
if size.endswith("-l"):
f = "l"
size = size[:-2]
if size.en... | 42,918 |
def make_command_recipe(chat_id, cook_request):
"""Отправляем рецепт блюда"""
if cook_request.dish:
portion = recipes[cook_request.dish][0]
recipe = recipes[cook_request.dish][1]
bot.send_message(chat_id=chat_id, text=f'Одна порция - {portion}\nРецепт - {recipe}\n'
... | 42,919 |
def clean_detections(npts, on_off):
"""Removes spurious seismic detections that occur within a window following
a detection.
Parameters
----------
npts : int
Length of window in data samples.
on_off : array
On/off indexes for detections.
Returns
-------
array
... | 42,920 |
def filter_game_data(input_dict):
"""Filter out information about the game."""
game_dict = input_dict['data']['attributes']
time = datetime.strptime(game_dict['createdAt'], "%Y-%m-%dT%H:%M:%SZ")
game.date = time.strftime('%a, %b %d')
game.duration = seconds_to_minutes(game_dict['duration'])
game... | 42,921 |
def register(linter):
"""Required method to auto register this checker.
:param linter: Main interface object for Pylint plugins
:type linter: Pylint object
"""
linter.register_checker(WhileChecker(linter)) | 42,922 |
def register_validator(fn):
"""
collect validator functions into ckanext.scheming.all_helpers dict
"""
all_validators[fn.__name__] = fn
return fn | 42,923 |
def save_config():
"""
:return: Completed save.
"""
global host_id_start
# Save start and end to file.
cfgfile = open("config.ini",'w')
try:
Config.add_section('Host ID')
except ConfigParser.DuplicateSectionError, e:
# File already exists.
pass
Config.set('Hos... | 42,924 |
def split_args(args):
"""Run the comp study splitting sub-command."""
conf = parse_config_file(args.config_file)
if args.sig_p:
conf['comp_sig_pval'] = float(args.sig_p)
if args.non_sig_p:
conf['comp_nonsig_pval'] = float(args.non_sig_p)
# Run the splitting algorithm
split_study... | 42,925 |
def encode_data_image_to_16bit(data_image: np.ndarray, max_data_value: int = 120) -> np.ndarray:
"""
this method sets all data values above max_data_value to zero, scales it by the max_data_value
and rescales the depth image to the uint16 range.
:param data_image:
:param max_data_value:
:return... | 42,926 |
def unlink(path):
"""Remove |path| and ignore errors if it doesn't exist."""
try:
os.unlink(path)
except FileNotFoundError:
pass | 42,927 |
def get_database(name: Optional[str] = None,
resource_group_name: Optional[str] = None,
server_name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabaseResult:
"""
... | 42,928 |
def read_status_yaml(path: str, year: int = None):
"""Reads a yaml file containing categories and date ranges for each categories."""
with open(path, "rt") as f:
data = yaml.load(f, Loader=yaml.Loader)
categories = []
for category, datestrlist in data.items():
status = Status(category.l... | 42,929 |
def S_inv_eulerZYX_body_deriv(euler_coordinates, omega):
""" Compute dE(euler_coordinates)*omega/deuler_coordinates
cfo, 2015/08/13
"""
y = euler_coordinates[1]
z = euler_coordinates[2]
"""
w1 = omega[0]; w2 = omega[1]; w3 = omega[2]
J = numpy.zeros((3,3))
... | 42,930 |
def _mini_batch_step(X, sample_weight, x_squared_norms, centers, weight_sums,
old_center_buffer, compute_squared_diff,
distances, random_reassign=False,
random_state=None, reassignment_ratio=.01,
verbose=False):
"""Incremental updat... | 42,931 |
def ensure_dir(path):
"""Make sure the specified directory exists
and is writable
"""
try:
os.mkdir(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
if os.stat(path).st_mode & stat.S_IRWXU != stat.S_IRWXU:
raise IOError(errno.EPERM,
... | 42,932 |
def get_user_ida_projects():
"""
List IDA projects for current user without the prefix.
Returns:
list(str) -- List of projects.
"""
user_ida_groups = get_user_ida_groups()
if user_ida_groups is None:
log.error('Could not get user IDA projects.\n')
return None
try:
... | 42,933 |
def user_ask_configs_all():
"""Show user all current configs and ask if all of them are correct.
If they are not correct, show a menu to let user change the wrong ones.
"""
global s
while True:
user_show_configs_all(s)
change = user_ask_yn('Do you want to change any configuration?')... | 42,934 |
def bf_get_issue_config(major, minor):
# type: (str, str) -> IssueConfig
"""Returns the issue config for the active network."""
return IssueConfig.from_dict(
restv2helper.get_issue_config(bf_session, major, minor)
) | 42,935 |
def normalize_rotmat(mat: torch.Tensor) -> torch.Tensor:
"""Normalizes rotation matrix to a valid one"""
u, _, v = torch.svd(mat)
s = torch.zeros_like(mat)
s[..., 0, 0] = 1.0
s[..., 1, 1] = 1.0
s[..., 2, 2] = torch.det(u) * torch.det(v)
return u @ s @ v.transpose(-1, -2) | 42,936 |
def responder():
"""Responder fixture."""
return MockResponder() | 42,937 |
def ortho(U, V, A, X=1, G=None, Z=0):
"""
U is NxL array of cell factors
V is JxL array of loadings onto genes
X is NxKo array of cell specific covariates
A is JxKo array of coefficients of X
Z is JxKf array of gene specific covariates
G is NxKf array of coefficients of Z
assume the data Y is of dimen... | 42,938 |
def test_write_odt():
"""Test the basics.
"""
sio = StringIO()
ds = gio.read_odt('data/OdT/3d_horizon/Segment_ILXL_Single-line-header.dat')
_ = gio.to_odt(sio, ds, header='none')
assert sio.getvalue()[:7].split() == ['376', '914']
sio = StringIO()
_ = gio.to_odt(sio, ds)
assert sio.... | 42,939 |
def testFiles(s,k):
"""
s(int): la quantitée de la confiture
k(int): la longeur du systéme de capacité
Cette fonction crée trois fichiers de données qu'on peut lire avec la fonction readFile, les fichiers contiennet le volume s, la longeur k du systéme de capacité, et la liste des volumes de... | 42,940 |
def get_all_users_projects(is_authenticated):
"""Pull every assigned project for all users from Users_Projects table"""
if is_authenticated and auth0.is_admin():
app.logger.info(
f"Received request at {const.INTERMEDIATE_API_ALL_USERS_PROJECTS_ENDPOINT}"
)
auth0_users, _ = au... | 42,941 |
def get_status_code(ep):
"""Function that gets an endpoint and returns its HTTP status code"""
req = requests.get(ep)
return req.status_code | 42,942 |
def process_repository(repo_dict):
""" Takes a dictionary containing keys: path, branches and revisions and
returns a Repository object. This method should only be called by
read_yaml. """
path = repo_dict[REPOSITORY_PATH]
revisions = {}
if REPOSITORY_REVISIONS in repo_dict:
for revisi... | 42,943 |
def hash_algorithm(alg, allow_raw=False):
"""Parse an hash algorithm"""
# canonical name: only alphanumeric uppercase characters
alg = re.sub(r'[^0-9A-Z]', '', alg.upper())
if alg in DIGEST_ASN1_PREFIXES:
return alg
elif allow_raw and alg == 'RAW':
return alg
raise ValueError("Un... | 42,944 |
def fista(gradient_op, linear_op, prox_op, cost_op, kspace_generator=None, estimate_call_period=None,
lambda_init=1.0, max_nb_of_iter=300, x_init=None,
metric_call_period=5, metrics={},
verbose=0, **lambda_update_params):
"""FISTA sparse reconstruction.
Parameters
----------
... | 42,945 |
def print_total_switches_and_switchports_searched(switch_objects):
"""Iterates through a list of switch objects and prints the
total number of switches and total number of interfaces searched
Args:
switch_objects (list): list of switch objects
Returns:
None
"""
number_of_switc... | 42,946 |
def get_entry_from_args():
"""
Handle finding the file entry using the user supplied arguments
return the entry or quits script entirely.
:rtype: object containing the entry of the found file and the entry_id or error & exit
"""
# Get the pcap file from arguments
entry_id = None
if 'pca... | 42,947 |
def GetGerritFetchUrl(host):
"""Given a gerrit host name returns URL of a gerrit instance to fetch from."""
return 'https://%s/' % host | 42,948 |
def _source() -> Source:
"""
checks HTTP header source is present and points to an available resource
:return: parsed HTTP headers, transformed into a Source object
"""
source_header = request.headers.get("source")
if not source_header:
abort(Response("HTTP header 'source' not found", 4... | 42,949 |
def seed():
"""
Seeds the database with some initial values for the weight categories.
The initially seeded values stem from the cargo profile the brochure
"Container securing systems - product catalogue" of MacGregor (Edition 101601, February 2016)
URL: https://www.macgregor.com/globalassets/pictu... | 42,950 |
def deep_copy(pcollection):
"""Create a deep copy of a PCollection up to materialization boundaries."""
if not isinstance(pcollection, pvalue.PCollection):
raise ValueError('Input to deep_copy must be a PCollection.')
# AppliedPTransform.update_input_refcounts() is a vestigial method that
# uses an incorre... | 42,951 |
def compute_lm_accuracy(eval_preds):
"""Compute the accuracy given the predictions and labels, contained in `eval_preds`.
It assumes the logits have been reduced with argmax(-1) by `preprocess_logits_for_accuracy`.
"""
preds, labels = eval_preds
# preds have the same shape as the labels, after ... | 42,952 |
def _handle_whois(dispatch, action, manifest):
"""Reply with iama"""
handle = "hdmimatrix@dummy"
if action["payload"] == handle or action["payload"] == "*":
dispatch(iama(manifest)) | 42,953 |
def is_folder(dir_path):
"""Determines if a given local directory should map to a SmugMug Folder or
Gallery by presence of a .smfolder file"""
if os.path.isfile(dir_path + "/.smfolder"):
return True
else:
return False | 42,954 |
def fix_path(path):
"""Fix a path and convert to an absolute location.
Parameters
----------
path : str
Path to fix.
Returns
-------
str
Absolute path.
"""
if THIS_PLATFORM == 'Windows':
path = PureWindowsPath(path)
return str(Path(path).absolute()) | 42,955 |
def get_shfe_daily(date = None):
"""
获取上期所日交易数据
Parameters
------
date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
Return
-------
DataFrame
上期所日交易数据(DataFrame):
symbol 合约代码
date 日期
open ... | 42,956 |
def partition_skymodel_by_flux(sc, model, flux_threshold=-numpy.inf):
"""
:param sc:
:param model:
:param flux_threshold:
:return:
"""
brightsc = filter_skycomponents_by_flux(sc, flux_min=flux_threshold)
weaksc = filter_skycomponents_by_flux(sc, flux_max=flux_threshold)
log.info... | 42,957 |
def getNumberOfDaysBetween(d1, d2, tz_str='UTC'):
""" d1 and d2 are datetime objects in UTC """
d1_date = utcInTz(d1, tz_str)
d2_date = utcInTz(d2, tz_str)
d1_date = deepcopy(d1_date).replace(hour = 0, minute = 0, second = 0, microsecond = 0)
d2_date = deepcopy(d2_date).replace(hour = 0, minute = 0, second = 0, m... | 42,958 |
def get_language_specifics() -> BaseLanguage:
"""Gets the language specific actions."""
return PluginLoader().languageSpecifics | 42,959 |
def get_darknet53(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join('~', '.mxnet', 'models'),
**kwargs):
"""
Create DarkNet model with specific parameters.
Parameters:
----------
model_name : str or None, default ... | 42,960 |
def add_item():
"""Create a new item. This will list all login uuser created """
if 'username' not in log_session:
flash("Please login in to continue.")
return redirect(url_for('login'))
elif request.method == 'POST':
item = session.query(Item).filter_by(name=request.form['name']).... | 42,961 |
def SGLD(nburnin, nsample, gradU, p, batch, eta=0.0001, L=100, V=3):
"""
Function to get posterior samples given parameters with SGLD
"""
n = nburnin + nsample
if type(p) != "np.array":
d = 1
else:
d = len(p)
samples = np.zeros((n,d))
for i in range(n):
... | 42,962 |
def create_commands(device_ids: List[str], file_path: str) -> List[CommandRunner.Command]:
"""
Create a list of `Command` of the remove file command to `Cortex XDR` and `CrowdstrikeFalcon`
:param device_ids: The device id's to run on
:param file_path: The file_path to delete
:return: A list of `Com... | 42,963 |
def test_base_all_commands():
"""Test that all commands in ``cmd_root`` are reachable and can print the help message.
This doesn't guarantee that the command works but at least that it can be successfully called and there are no
import errors or other basic problems.
"""
def recursively_print_help... | 42,964 |
def pytest_addoption(parser: typing.Any) -> None:
"""Add force option to pytest."""
parser.addoption(
"--zpool",
action="store",
help="Select a ZFS pool for the unit tests"
) | 42,965 |
def compiler(stats_set):
"""
Processes the API data into a clean dataframe for analysis and predictions.
Parameters
----------
stats_set: list
Incoming data on all previous games from the balldontlie API request.
Returns
----------
final: pandas dataframe
The train... | 42,966 |
def generate_cpda_eligible_lists(request):
"""
Function retrieves the eligible user information and related unreviewed,approved and archived CPDA applications.
"""
active_apps = (Cpda_application.objects
.select_related('applicant')
.filter(applicant=request.u... | 42,967 |
def get_points_on_sphere(n_points, r=1):
"""
Find n evenly spaced points on a sphere using the "How to generate
equidistributed points on the surface of a sphere" by Markus Deserno, 2004.
Arguments:
n_points (int): number of points to generate
r (float): radius of the sphere
Return... | 42,968 |
def bottleneck_block(x, filters, kernel_size=(3, 3), padding="same", strides=1):
"""
bottleneck_block(x, filters, kernel_size=(3, 3), padding="same", strides=1)
This function creates a bottleneck block layer, which is the addition of a convolution block and a batch normalized/activated block
INPUTS:
... | 42,969 |
def ClusterAndFindSplit(values, rand=None):
"""Finds a list of indices where we can detect significant changes.
This algorithm looks for the point at which clusterings of the "left" and
"right" datapoints show a significant difference. We understand that this
algorithm is working on potentially already-aggrega... | 42,970 |
def list_nodelets():
"""
List all nodelets in all packages.
"""
nodelets = []
for p in rospkg.RosPack().get_depends_on('nodelet', implicit=False):
nodelets += Package(p).list_nodelets()
return nodelets | 42,971 |
def deploy():
"""Run deployment tasks."""
from flask.ext.migrate import upgrade
from app.models import Role, User
# migrate database to latest revision
upgrade()
# create user roles
Role.insert_roles()
# create self-follows for all users
User.add_self_follows() | 42,972 |
def general_distance_matrix(X, dist_function):
"""General distance matrix with custom distance function.
Parameters
----------
X : array, shape (n, k)
The first set of column vectors. This is a set of k vectors with
dimension of n.
dist_function: array, shape (n, n)
The cust... | 42,973 |
def install_openwhisk_action_in_path(packaging_params, action_params_to_env, path):
"""
This performs the equivalent of the command line:
wsk action create fetch_aws_keys --docker tleyden5iwx/openwhisk-dockerskeleton --param AwsAccessKeyId "$AWS_ACCESS_KEY_ID" --param AwsSecretAccessKey "$AWS_SECRET_ACCES... | 42,974 |
def checkMysql(checkOptions, options, required=False):
""" Used in functions that may use the DB interface either that this is required
or that functionality may be degraded.
<condition> = mysql is not used or pymysql is available
arguments:
options: dictionnary, derived fr... | 42,975 |
def predict():
"""Predict route"""
audio_id = request.args.get('id')
db.download(audio_id)
y = detector.predict("data//audio.wav")
state = {"status": str(y)}
return jsonify(state) | 42,976 |
def test_partial_config_override() -> None:
"""Test config can be partially oerriden."""
bot = Phial("test-token", config={"prefix": "/"})
assert bot.config["prefix"] == "/"
assert bot.config["baseHelpText"] == "All available commands:" | 42,977 |
def colorize(text, color, bold=False):
"""Colorize some text using ANSI color codes.
Note that while ANSI color codes look good in a terminal they look
like noise in log files unless viewed in an ANSI color capable
viewer (such as 'less -R').
Args:
text: The text to colorize.
color: One of the color... | 42,978 |
def _create_log_entry(class_, message, author, created_at=None, **kwargs):
"""
This method will create a new LogEntry of the given type with the given
arguments.
:param type type: A subclass of LogEntry which should be created.
:param unicode message: the log message text
:param User author: us... | 42,979 |
def avg_stimpos(band, eclipse):
"""
Define the mean detector stim positions.
:param band: The band to return the average stim positions for,
either 'FUV' or 'NUV'.
:type band: str
:param eclipse: The eclipse number to return the average stim positions for.
:type eclipse: int
:re... | 42,980 |
def multiclass_positive_predictive_value(confusion_matrix: np.ndarray,
label_index: int) -> Number:
"""
Gets the "positive predictive value" for a multi-class confusion matrix.
The positive predictive value is also known as *precision*.
See the documentation of... | 42,981 |
def install_editable(
candidate: Candidate, scheme_dict: dict[str, str] | None = None
) -> None:
"""Install package in editable mode using the legacy `python setup.py develop`"""
# TODO: PEP 660
from pdm.builders import EditableBuilder
candidate.prepare()
env = candidate.environment
assert ... | 42,982 |
def test_no_update_development(qtbot):
"""Test we don't offer updates for development versions."""
worker = WorkerUpdates(None, False, version="3.3.2.dev0",
releases=['3.3.1'])
worker.start()
assert not worker.update_available | 42,983 |
def get_matching_cost_swap_bf(election_1: OrdinalElection, election_2: OrdinalElection,
mapping):
""" Return: Cost table """
cost_table = np.zeros([election_1.num_voters, election_1.num_voters])
for v1 in range(election_1.num_voters):
for v2 in range(election_2.num_vot... | 42,984 |
def auditable(event_type, msg_on_success):
"""
Makes the result of an endpoint audit loggable - passes an
AuditLogger object to the handler so that it can set extra data to be
logged.
"""
def decorator(f):
@wraps(f)
def _(self, request, *args, **kwargs):
audit_logger ... | 42,985 |
def rec_pow(a, b):
"""Compute a**b recursively"""
if b == 0:
return 1
if b == 1:
return a
return (rec_pow(a,b//2)**2) * (a if b % 2 else 1) | 42,986 |
def omega_d(m, bvectors, bweights, idx=None): # Eq. 36
"""
Compute the diagonal contribution to the spread functional
Parameters
----------
m: ndarray, shape (nkpts, nntot, nbnds, nbnds)
the overlap matrix
bvectors: ndarray, shape (nkpts, nntot, 3)
bweights: ndarray, shape (nntot,... | 42,987 |
def get_github_info(packages=packages):
"""
Get information about subpackage releases that have been tagged on github
"""
no_release = []
release = {}
for package in packages:
url = f"https://api.github.com/repos/pysal/{package}/releases/latest"
print(url)
d = json.loads... | 42,988 |
def matrix_str_to_dict(matrix_str: str) -> Dict[str, Dict[str, int]]:
"""Transform dictionary string to 2-d array of ints."""
scoring_matrix = {}
table = [line.split() for line in matrix_str.split("\n") if line[0] != "#"]
aa_tos = table[0]
for row in table[1:]:
aa_from = row[0]
... | 42,989 |
def restriction(model, sfield, residual, sc_dir):
"""Downsampling of grid, model, and fields to a coarser grid.
The restriction of the residual is used as source term for the coarse grid.
Corresponds to Equations 8 and 9 and surrounding text in [Muld06]_. In the
case of the restriction of the residual... | 42,990 |
def check_good_not_bad(decider, good, bad):
"""Check if bad prof becomes GOOD by adding funcs it lacks from good prof"""
bad_copy = bad.copy()
for func in good:
if func not in bad:
bad_copy[func] = good[func]
return decider.run(bad_copy) == StatusEnum.GOOD_STATUS | 42,991 |
def plot_particles_and_highlight_collision(particles, particles1, particles2):
"""
Plot the stars and on top of these plot the particles involved
in the collision.
"""
figure = pyplot.figure()
subplot = figure.add_subplot(1, 1, 1)
subplot.scatter(
particles.x.value_in(nbody_system.l... | 42,992 |
def predict_culmulative_swing_loyal(start, end, prob=0.68):
"""
从历史开始每天累积
"""
rsts = []
intention = {}
_period = pendulum.Period(start, end)
for dt in _period:
print(dt)
# save
print("load ~", f"disk/cul_from_March_1/{dt.to_date_string()}-{prob}.txt")
cu... | 42,993 |
def mpl_setup_cjk_font():
""" update matplotlib sans-serif font list for CJK """
import locale
country_or_region, _ = locale.getdefaultlocale()
if sys.platform == 'win32':
if country_or_region == 'zh_CN':
plt.rcParams['font.sans-serif'].insert(0, 'Microsoft YaHei')
elif count... | 42,994 |
def filter_by_length(data: List[list], lower_bound: int, upper_bound: int) -> List[list]:
"""
:param data: [[word1, word2, word3], ..., [word1, word2]]
:param lower_bound: 3
:param upper_bound: 5
:return: [[word1, word2, word3, ... ], ..., None]
"""
for index in range(len(data)):
if... | 42,995 |
def run_games_and_record_payoffs(game_queries, evaluate_game, ckpt_to_policy):
"""Simulate games according to game queries and return results.
Args:
game_queries: set of tuples containing indices specifying each players strat
evaluate_game: callable function that takes a list of policies as argument
ck... | 42,996 |
def gnocchiclient(request):
""" Initialization of Gnocchi client.
"""
auth_endpoint = getattr(settings, 'OPENSTACK_KEYSTONE_URL', None)
loader = loading.get_plugin_loader('token')
auth = loader.load_from_options(auth_url=auth_endpoint,
token=request.user.token.id... | 42,997 |
def backup(input_string):
"""
Performs the operations for the backup command, i.e, moves the files to the backup location if not specified.
Args:
input_string (str array): array of options for backup command.
"""
if(input_string == "syntax"):
print("backup [-d] [directory] ")
el... | 42,998 |
def create_namespace_handler(
file_type: Type[NamespaceFile],
namespace_scope: Tuple[str, ...],
namespace_extension: str,
) -> Type[NamespaceFile]:
"""Create handler that turns yaml namespace files into json."""
class AutoYamlNamespaceHandler(YamlFile, NamespaceFile):
scope = namespace_scop... | 42,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.