content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from goopylib.objects.GraphicsObject import GraphicsObject from goopylib.styles import *
[ 6738, 467, 404, 2645, 571, 13, 48205, 13, 18172, 10267, 1330, 19840, 10267, 198, 198, 6738, 467, 404, 2645, 571, 13, 47720, 1330, 1635, 628 ]
3.64
25
# https://www.acmicpc.net/problem/1260 n, m, v = map(int, input().split()) graph = [[0] * (n+1) for _ in range(n+1)] visit = [False] * (n+1) for _ in range(m): R, C = map(int, input().split()) graph[R][C] = 1 graph[C][R] = 1 dfs(v) print() bfs(v)
[ 2, 3740, 1378, 2503, 13, 330, 9383, 14751, 13, 3262, 14, 45573, 14, 1065, 1899, 198, 198, 77, 11, 285, 11, 410, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 34960, 796, 16410, 15, 60, 1635, 357, 77, 10, 16, 8, 329, 480...
2.007692
130
""" Testing helper functions ======================= Collection of helper functions for the testing suite. """ from datetime import datetime import numpy as np import pytest import pysteps as stp from pysteps import io, rcparams def get_precipitation_fields(num_prev_files=0): """Get a precipitation field from the archive to be used as reference.""" # Selected case date = datetime.strptime("201505151630", "%Y%m%d%H%M") data_source = rcparams.data_sources["mch"] root_path = data_source["root_path"] path_fmt = data_source["path_fmt"] fn_pattern = data_source["fn_pattern"] fn_ext = data_source["fn_ext"] importer_name = data_source["importer"] importer_kwargs = data_source["importer_kwargs"] # Find the input files from the archive fns = io.archive.find_by_date(date, root_path, path_fmt, fn_pattern, fn_ext, timestep=5, num_prev_files=num_prev_files) # Read the radar composites importer = io.get_method(importer_name, "importer") reference_field, quality, metadata = io.read_timeseries(fns, importer, **importer_kwargs) del quality # Not used if num_prev_files == 0: reference_field = np.squeeze(reference_field) # Remove time dimension # Convert to mm/h reference_field, metadata = stp.utils.to_rainrate(reference_field, metadata) # Mask invalid values reference_field = np.ma.masked_invalid(reference_field) # Log-transform the data [dBR] reference_field, metadata = stp.utils.dB_transform(reference_field, metadata, threshold=0.1, zerovalue=-15.0) return reference_field def smart_assert(actual_value, expected, tolerance=None): """ Assert by equality for non-numeric values, or by approximation otherwise. If the precision keyword is None, assert by equality. When the precision is not None, assert that two numeric values (or two sets of numbers) are equal to each other within the tolerance. """ if tolerance is None: assert actual_value == expected else: # Compare numbers up to a certain precision assert actual_value == pytest.approx(expected, 1e-6)
[ 37811, 198, 44154, 31904, 5499, 198, 4770, 1421, 18604, 198, 198, 36307, 286, 31904, 5499, 329, 262, 4856, 18389, 13, 198, 37811, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, ...
2.425832
991
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Courses module.""" __author__ = 'Pavel Simakov (psimakov@google.com)' from common import resource from controllers import assessments from controllers import lessons from controllers import utils from models import content from models import resources_display from models import custom_modules from models import roles from tools import verify All_LOCALES_PERMISSION = 'can_pick_all_locales' All_LOCALES_DESCRIPTION = 'Can pick all locales, including unavailable ones.' SEE_DRAFTS_PERMISSION = 'can_see_draft_content' SEE_DRAFTS_DESCRIPTION = 'Can see lessons and assessments with draft status.' custom_module = None def register_module(): """Registers this module in the registry.""" # provide parser to verify verify.parse_content = content.parse_string_in_scope # setup routes courses_routes = [ ('/', lessons.CourseHandler), ('/activity', lessons.UnitHandler), ('/answer', assessments.AnswerHandler), ('/assessment', lessons.AssessmentHandler), ('/course', lessons.CourseHandler), ('/forum', utils.ForumHandler), ('/preview', utils.PreviewHandler), ('/register', utils.RegisterHandler), ('/resources', utils.ResourcesHandler), ('/rest/locale', utils.StudentLocaleRESTHandler), ('/review', lessons.ReviewHandler), ('/reviewdashboard', lessons.ReviewDashboardHandler), ('/student/editstudent', utils.StudentEditStudentHandler), ('/student/settracks', utils.StudentSetTracksHandler), ('/student/home', utils.StudentProfileHandler), ('/student/unenroll', utils.StudentUnenrollHandler), ('/unit', lessons.UnitHandler)] global custom_module # pylint: disable=global-statement custom_module = custom_modules.Module( 'Course', 'A set of pages for delivering an online course.', [], courses_routes, notify_module_enabled=on_module_enabled) return custom_module
[ 2, 15069, 2321, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.072879
837
# -*- coding: utf-8 -*- # # michael a.g. avzis <michael.aivazis@para-sim.com> # (c) 1998-2021 all rights reserved # support import merlin # the manager of intermediate and final build products # end of file
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 285, 40302, 257, 13, 70, 13, 1196, 89, 271, 1279, 76, 40302, 13, 64, 452, 1031, 271, 31, 1845, 64, 12, 14323, 13, 785, 29, 198, 2, 357, 66, 8, 7795, ...
2.6625
80
########################################################################## # # Copyright (c) 2011, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import maya.cmds import IECore import IECoreImage import IECoreMaya if __name__ == "__main__": IECoreMaya.TestProgram()
[ 29113, 29113, 7804, 2235, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 2813, 11, 7412, 7117, 8495, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 198, ...
3.46098
551
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import torch from omegaconf import OmegaConf from pytorch_lightning import Trainer from pytorch_lightning.utilities.distributed import rank_zero_only from nemo.core import ModelPT from nemo.utils import logging from nemo.utils.exp_manager import ExpManagerConfig, exp_manager def instantiate_multinode_ddp_if_possible(): num_gpus = torch.cuda.device_count() trainer = Trainer(gpus=num_gpus, accelerator='ddp', logger=None, checkpoint_callback=None) exp_manager_cfg = ExpManagerConfig(exp_dir='./ddp_check/', use_datetime_version=False, version="") exp_manager(trainer, cfg=OmegaConf.structured(exp_manager_cfg)) return trainer def setup_model(trainer: Trainer): model = ExampleModel(trainer=trainer) logging.info(f"M.Global Rank:{model.global_rank}") logging.info(f"M.Local Rank:{model.local_rank}") logging.info(f"M.World Size:{model.trainer.world_size}") trainer.predict(model) return model def get_rank_info(texts: list, rank_key: str) -> int: for line in texts: if rank_key in line: rank_value = line.split(":")[-1] rank_value = int(rank_value) return rank_value print("Could not find the correct rank key !") exit(1) def run_checks(): cleanup() trainer = instantiate_multinode_ddp_if_possible() model = setup_model(trainer) check_model_ranks(model) print("DDP checks passed !") cleanup() if __name__ == '__main__': run_checks()
[ 2, 15069, 357, 66, 8, 33448, 11, 15127, 23929, 44680, 6234, 13, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393...
2.890859
733
"""" Copyright Krypton 2022 - https://github.com/kkrypt0nn (https://krypton.ninja) Description: This is a template to create your own discord bot in python. Version: 4.1 """ import json def add_user_to_blacklist(user_id: int) -> None: """ This function will add a user based on its ID in the blacklist.json file. :param user_id: The ID of the user that should be added into the blacklist.json file. """ with open("blacklist.json", "r+") as file: file_data = json.load(file) file_data["ids"].append(user_id) with open("blacklist.json", "w") as file: file.seek(0) json.dump(file_data, file, indent=4) def remove_user_from_blacklist(user_id: int) -> None: """ This function will remove a user based on its ID from the blacklist.json file. :param user_id: The ID of the user that should be removed from the blacklist.json file. """ with open("blacklist.json", "r") as file: file_data = json.load(file) file_data["ids"].remove(user_id) with open("blacklist.json", "w") as file: file.seek(0) json.dump(file_data, file, indent=4)
[ 15931, 15931, 198, 15269, 220, 44679, 261, 33160, 532, 3740, 1378, 12567, 13, 785, 14, 28747, 6012, 15, 20471, 357, 5450, 1378, 74, 6012, 261, 13, 35073, 6592, 8, 198, 11828, 25, 198, 1212, 318, 257, 11055, 284, 2251, 534, 898, 36446,...
2.601367
439
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Make sure that generic functions work exactly as we expect.''' # IMPORT STANDARD LIBRARIES import unittest # IMPORT WAYS LIBRARIES from ways import common
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 7061, 6, 12050, 1654, 326, 14276, 5499, 670, 3446, 355, 356, 1607, 2637, 7061, 198, 198, 2, 30023, 9863, 49053, ...
2.929577
71
from setuptools import setup, find_packages setup( name='natasha', version='0.2.0', description='Named-entity recognition for russian language', url='https://github.com/bureaucratic-labs/natasha', author='Dmitry Veselov', author_email='d.a.veselov@yandex.ru', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='natural language processing, russian morphology, named entity recognition, tomita', packages=find_packages(), install_requires=[ 'yargy==0.3.0' ], extras_require={ 'web': [ 'ujson', 'aiohttp', ], }, )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 32353, 14715, 3256, 198, 220, 220, 220, 2196, 11639, 15, 13, 17, 13, 15, 3256, 198, 220, 220, 220, 6764, 11639, 45, 2434,...
2.427835
388
import os, sys import random import string try: # Make Python2 work like Python3 input = raw_input except NameError: # On Python3; already using input pass letters = string.ascii_letters numbers = string.digits punctuation = string.punctuation def generate(password_length, at_least_one_letter, at_least_one_number, at_least_one_punctuation): """Generate a password by include enough random characters to meet the password length restriction. In addition, the user can specify that at least one of the each of the classes of character be used. """ # # Any combination of characters is valid # valid_characters = "" if at_least_one_letter: valid_characters += letters if at_least_one_number: valid_characters += numbers if at_least_one_punctuation: valid_characters += punctuation # # Start with a blank password and then go round enough # times to make a password of the required length. # password = "" for i in range(password_length): # # Each time around, ensure that one of each of the selected # groups is chosen, and then just choose randomly from all # groups. # if at_least_one_letter: character = random.choice(letters) at_least_one_letter = False elif at_least_one_number: character = random.choice(numbers) at_least_one_number = False elif at_least_one_punctuation: character = random.choice(punctuation) at_least_one_punctuation = False else: character = random.choice(valid_characters) password += character # # Finally, shuffle the password so we don't always get a # letter at the beginning, with a number after and some # punctuation. # characters = list(password) # # random.shuffle shuffles a list *in place* # random.shuffle(characters) # # X.join(...) means: return all the strings in (...) joined by X # ", ".join(['Eggs', 'Bacon', 'Beans']) => "Eggs, Bacon, Beans" # But if you want to generate *real* .csv files, use the csv module # because there are lots of corner-cases. # password = "".join(characters) return password if __name__ == '__main__': password_length = int(input("How many letters? ")) at_least_one_letter = "Y" == (input("At least one letter [Y/n]? ").upper() or "Y") at_least_one_number = "Y" == (input("At least one number [Y/n]? ").upper() or "Y") at_least_one_punctuation = "Y" == (input("At least one punctuation [Y/n]? ").upper() or "Y") password = generate(password_length, at_least_one_letter, at_least_one_number, at_least_one_punctuation) print("Your password is: {}".format(password))
[ 11748, 28686, 11, 25064, 198, 11748, 4738, 198, 11748, 4731, 198, 198, 28311, 25, 198, 220, 220, 220, 1303, 6889, 11361, 17, 670, 588, 11361, 18, 198, 220, 220, 220, 5128, 796, 8246, 62, 15414, 198, 16341, 6530, 12331, 25, 198, 220, ...
2.579285
1,091
from constants.messages import get_node_health_warning_message, get_node_healthy_again_message from handlers.chat_helpers import try_message_with_home_menu, try_message_to_all_users from packaging import version from service.utils import * def check_thorchain_catch_up_status(context, node_address): """ Check if node is some blocks behind with catch up status """ chat_id = context.job.context['chat_id'] node_data = context.job.context['chat_data']['nodes'][node_address] if 'is_catching_up' not in node_data: node_data['is_catching_up'] = False try: is_currently_catching_up = is_thorchain_catching_up( node_data['ip_address']) except (Timeout, ConnectionError): logger.warning(f"Timeout or Connection error with {node_data['ip_address']}") return if node_data['is_catching_up'] != is_currently_catching_up: try: block_height = get_latest_block_height(node_data['ip_address']) except (Timeout, ConnectionError): logger.warning(f"Timeout or Connection error with {node_data['ip_address']}") block_height = "currently unavailable" if is_currently_catching_up: node_data['is_catching_up'] = True text = 'The Node is behind the latest block height and catching up! ' + '\n' + \ 'IP: ' + node_data['ip_address'] + '\n' + \ 'THORNode: ' + node_data['alias'] + '\n' + \ 'Node address: ' + node_address + '\n' + \ 'Current block height: ' + block_height + '\n\n' + \ 'Please check your Thornode immediately!' else: node_data['is_catching_up'] = False text = 'The node caught up to the latest block height again! ' + '\n' + \ 'IP: ' + node_data['ip_address'] + '\n' + \ 'THORNode: ' + node_data['alias'] + '\n' + \ 'Node address: ' + node_address + '\n' + \ 'Current block height: ' + block_height try_message_with_home_menu(context=context, chat_id=chat_id, text=text) def check_thorchain_midgard_api(context, node_address): """ Check that Midgard API is ok """ chat_id = context.job.context['chat_id'] node_data = context.job.context['chat_data']['nodes'][node_address] was_healthy = node_data.setdefault('is_midgard_healthy', True) is_midgard_healthy = is_midgard_api_healthy(node_data['ip_address']) if was_healthy != is_midgard_healthy: if is_midgard_healthy: text = 'Midgard API is healthy again! ' + '\n' + \ 'IP: ' + node_data['ip_address'] + '\n' + \ 'THORNode: ' + node_data['alias'] + '\n' + \ 'Node address: ' + node_address try_message_with_home_menu(context, chat_id=chat_id, text=text) else: text = 'Midgard API is not healthy anymore! ' + '\n' + \ 'IP: ' + node_data['ip_address'] + '\n' + \ 'THORNode: ' + node_data['alias'] + '\n' + \ 'Node address: ' + node_address + '\n\n' + \ 'Please check your Thornode immediately!' try_message_with_home_menu(context, chat_id=chat_id, text=text) node_data['is_midgard_healthy'] = is_midgard_healthy
[ 6738, 38491, 13, 37348, 1095, 1330, 651, 62, 17440, 62, 13948, 62, 43917, 62, 20500, 11, 651, 62, 17440, 62, 22796, 62, 17776, 62, 20500, 198, 6738, 32847, 13, 17006, 62, 16794, 364, 1330, 1949, 62, 20500, 62, 4480, 62, 11195, 62, 2...
2.215827
1,529
from pylab import * from numpy import * from numpy.linalg import solve from scipy.integrate import odeint from scipy.stats import norm, uniform, beta from scipy.special import jacobi a = 0.0 b = 3.0 theta=1.0 sigma=sqrt(theta/(2*(a+b+2))) tscale = 0.05 invariant_distribution = poly1d( [-1 for x in range(int(a))], True)*poly1d( [1 for x in range(int(b))], True) gaussian_var = norm() def poly_to_jacobi(x): """x is a poly1d object""" xc = x.coeffs N = x.order+1 matrix = zeros(shape=(N,N), dtype=float) for i in range(N): matrix[N-i-1:N, i] = jacobi(i,a,b).coeffs return solve(matrix, xc) def propagate_jacobi(pc, t): """Takes jacobi coefficients and propagates them""" n = arange(pc.shape[0], dtype=float) l = theta*n*(n+a+b+1.0)/(a+b+2.0)*tscale return exp(-l*t)*pc tmax = 4 prior = beta_prior(40, 20) prior_in_jacobi = poly_to_jacobi(prior) dt = 0.1 times = arange(0,tmax,dt) x = arange(-1,1,0.01) rw_dt = 0.01 t, y = random_walk(0.35*2-1, tmax, rw_dt) solution_as_x = zeros(shape=(times.size, x.size), dtype=float) solution_as_jacobi = None empirical_ctr = zeros(shape=(4,), dtype=float) for i in range(0,4): nt = int(1.0/dt) prior = prior_in_jacobi rnd = uniform(0,1) if (i > 0): nsamples = 40 r = rnd.rvs(nsamples) ctr = (y[i/rw_dt]+1)/2.0 print "CTR: " + str(ctr) success = (r < ctr).sum() print "Empirical: " + str(success / float(nsamples)) evidence = beta_prior( nsamples - success, success) prior = None j = truncate_unnecessary_jacobi(solution_as_jacobi[int(1/dt)-1]) prior = poly_to_jacobi(evidence * jacobi_to_poly_no_invariant(j)) empirical_ctr[i] = success / float(nsamples) solution_as_jacobi = pde_solve(prior, times[i*nt:(i+1)*nt]) solution_as_x[i*nt:(i+1)*nt] = transform_to_x(solution_as_jacobi, x) plot(arange(0,4), empirical_ctr, 'go') plot(t, (y+1)/2.0, 'k') imshow(solution_as_x.transpose(), origin='lower', extent=[0,tmax,0,1]) xlabel("time") ylabel("CTR") title("Bayesian Estimate of CTR") colorbar() show()
[ 6738, 279, 2645, 397, 1330, 1635, 198, 6738, 299, 32152, 1330, 1635, 198, 6738, 299, 32152, 13, 75, 1292, 70, 1330, 8494, 198, 6738, 629, 541, 88, 13, 18908, 4873, 1330, 267, 2934, 600, 198, 6738, 629, 541, 88, 13, 34242, 1330, 2593...
2.088845
1,013
# forms are not just about display, instead they are more of validation # wtf forms protect our site against csrf attacks from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, TextAreaField from wtforms.validators import (DataRequired, Regexp, ValidationError, Email, Length, EqualTo) from models import User
[ 2, 5107, 389, 407, 655, 546, 3359, 11, 2427, 484, 389, 517, 286, 21201, 198, 2, 266, 27110, 5107, 1805, 674, 2524, 1028, 269, 27891, 69, 3434, 198, 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 266, 83, 23914, 1330, 1090...
3.597938
97
from sys import stderr, stdout from enum import Enum from colored import fg, attr PANTAM: str = fg("yellow") + attr("bold") + "PANTAM" + attr("reset") colour_msg = lambda msg, colour: fg(colour) + attr("bold") + msg + attr("reset") info_msg = lambda msg: colour_msg(msg, "blue") success_msg = lambda msg: colour_msg(msg, "green") error_msg = lambda msg: colour_msg(msg, "red") def write_msg(msg: str, spacing: NewLine = None) -> None: """Write message to stdout""" prefix: str = "\n" if spacing in (NewLine.before, NewLine.both) else "" suffix: str = "\n" if spacing in (NewLine.after, NewLine.both) else "" stdout.write("%s%s%s" % (prefix, msg, suffix)) def write_error(msg: str) -> None: """Write message to stderr""" stderr.write("\n%s\n" % msg) welcome_msg = ( lambda: PANTAM + """ The microframework for microservices. Let's build your app... """ ) name_index_file_msg = lambda: "What is the name of your main script?" name_actions_folder_msg = lambda: "What is the name of your actions folder?" def create_actions_file_msg(second_run: bool): """Actions File Message""" article = "another" if second_run else "an" return "Do you want to create %s action file?" % article name_actions_file_msg = lambda: "What is the name of your actions file?" confirm_structure_msg = ( lambda structure: """Your application will look like this: %s Happy to proceed?""" % structure )
[ 6738, 25064, 1330, 336, 1082, 81, 11, 14367, 448, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 16396, 1330, 277, 70, 11, 708, 81, 198, 198, 47, 8643, 2390, 25, 965, 796, 277, 70, 7203, 36022, 4943, 1343, 708, 81, 7203, 36575, 4943,...
2.825832
511
""" A Testcase to remove mon from when I/O's are happening. Polarion-ID- OCS-355 """ import logging import pytest from ocs_ci.ocs import ocp, constants from ocs_ci.framework.testlib import tier4, ManageTest from ocs_ci.framework import config from ocs_ci.ocs.resources import pod from tests.helpers import run_io_with_rados_bench, delete_cephblockpool from ocs_ci.ocs.cluster import CephCluster from ocs_ci.utility.retry import retry from ocs_ci.ocs.exceptions import CephHealthException log = logging.getLogger(__name__) def run_io_on_pool(): """ Runs the I/O on the pool and delete the pool Returns: A thread of I/O """ tools_pod = pod.get_ceph_tools_pod() tools_pod.add_role(role='client') return run_io_with_rados_bench( ceph_pods=[tools_pod], config={'time': 45, 'cleanup': False, 'pool': 'test-pool' } )
[ 37811, 198, 32, 6208, 7442, 284, 4781, 937, 422, 198, 12518, 314, 14, 46, 338, 389, 5836, 13, 198, 198, 47, 6192, 295, 12, 2389, 12, 440, 7902, 12, 28567, 198, 198, 37811, 198, 198, 11748, 18931, 198, 11748, 12972, 9288, 198, 6738, ...
2.435135
370
from smartystreets_python_sdk import Request from smartystreets_python_sdk.exceptions import SmartyException from smartystreets_python_sdk.us_autocomplete_pro import Suggestion, geolocation_type
[ 6738, 4451, 88, 22853, 1039, 62, 29412, 62, 21282, 74, 1330, 19390, 198, 6738, 4451, 88, 22853, 1039, 62, 29412, 62, 21282, 74, 13, 1069, 11755, 1330, 10880, 88, 16922, 198, 6738, 4451, 88, 22853, 1039, 62, 29412, 62, 21282, 74, 13, ...
3.322034
59
# -*- coding: utf-8 -*- """ mssqlvc ~~~~~~~ Database version control utility for Microsoft SQL Server. See README.md for more information. Licensed under the BSD license. See LICENSE file in the project root for full license information. """ import argparse import datetime import io import logging import os import re import sys import urlparse try: import clr except ImportError: print('Cannot import crl module, make sure you run this script using IronPython') exit(2) import System clr.AddReference('Microsoft.SqlServer.Smo') clr.AddReference('Microsoft.SqlServer.SqlEnum') clr.AddReference('Microsoft.SqlServer.ConnectionInfo') import Microsoft.SqlServer.Management.Smo as Smo import Microsoft.SqlServer.Management.Common as Common __author__ = 'Ivan Kozhin' __copyright__ = 'Copyright (c) 2015-2016, Saritasa' __license__ = 'BSD' __version__ = '1.4.5' __all__ = ['MsSqlVersion'] def get_cmd_line_parser(): """Get initialized argparse.ArgumentParser object""" parser = argparse.ArgumentParser( description='MSSQL database patch history tool', formatter_class=argparse.RawDescriptionHelpFormatter, epilog='''Example: %(prog)s -c "mssql://sa:123@host\instance/database" -d "D:/1/project/patch"''') parser.add_argument('--connection', '-c', required=True, dest='connection', action='store', help='connection string in rfc1738 url format, required') parser.add_argument('--directory', '-d', dest='directory', action='store', default='.', help='directory with patch files') parser.add_argument('--log', '-l', dest='log', action='store', help='log file') parser.add_argument('--noexecute', '-n', action='store_true', dest='noexecute', default=False, help='displays pending script files with no execution') parser.add_argument('--noexecute-fill', '-nf', action='store_true', dest='noexecute_fill', default=False, help='displays pending script files with no execution and fills patch table') parser.add_argument('--stop-on-error', '-soe', action='store_true', dest='stop_on_error', default=False, help='stops execution if any script fails') parser.add_argument('--exclude-pattern', '-ep', dest='exclude_pattern', help='skips files match to regular expression') parser.add_argument('--record-files-only', '-rfo', action='store_true', dest='record_files_only', default=False, help='only file names will be stored to patch table without folder paths') parser.add_argument('--case-insensitive', '-ci', action='store_true', dest='case_insensitive', default=False, help='use case insensitive to compare patch files so "PatchName.sql" and "patchname.sql" is the same') parser.add_argument('--debug', action='store_true', dest='debug', default=False, help='enables debug output') parser.add_argument('--version', '-v', action='version', version='%(prog)s ' + __version__) return parser if __name__ == '__main__': # parser parser = get_cmd_line_parser() parser_args = parser.parse_args() if parser_args.connection is None or parser_args.directory is None: parser.print_help() exit(1) # logging logger = logging.getLogger('mssql') if parser_args.log: fh = logging.FileHandler(parser_args.log) fh.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')) logger.addHandler(fh) ch = logging.StreamHandler() ch.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')) logger.setLevel(logging.DEBUG if parser_args.debug else logging.INFO) logger.addHandler(ch) # database handle sqlvc = MsSqlVersion(parser_args.connection, parser_args.directory, exclude_pattern=parser_args.exclude_pattern, stop_on_error=parser_args.stop_on_error, case_insensitive=parser_args.case_insensitive, record_files_only=parser_args.record_files_only, logger=logger) if parser_args.noexecute: for patch in sqlvc.get_pending_patches(): logger.info(' ' + patch) elif parser_args.noexecute_fill: sqlvc.fill() else: sqlvc.update()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 285, 824, 80, 6780, 66, 198, 220, 220, 220, 220, 8728, 4907, 93, 628, 220, 220, 220, 24047, 2196, 1630, 10361, 329, 5413, 16363, 9652, 13, ...
2.539436
1,737
''' Unit tests table.py. :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 ''' from __future__ import absolute_import from statsmodels.compat.python import zip import numpy as np from numpy.testing import assert_equal __docformat__ = "restructuredtext en" from statsmodels.iolib.table import Cell, SimpleTable from statsmodels.iolib.table import default_latex_fmt from statsmodels.iolib.table import default_html_fmt ltx_fmt1 = default_latex_fmt.copy() html_fmt1 = default_html_fmt.copy() txt_fmt1 = dict( data_fmts = ['%0.2f', '%d'], empty_cell = ' ', colwidths = 1, colsep=' * ', row_pre = '* ', row_post = ' *', table_dec_above='*', table_dec_below='*', header_dec_below='*', header_fmt = '%s', stub_fmt = '%s', title_align='r', header_align = 'r', data_aligns = "r", stubs_align = "l", fmt = 'txt' ) cell0data = 0.0000 cell1data = 1 row0data = [cell0data, cell1data] row1data = [2, 3.333] table1data = [ row0data, row1data ] test1stubs = ('stub1', 'stub2') test1header = ('header1', 'header2') #test1header = ('header1\nheader1a', 'header2\nheader2a') tbl = SimpleTable(table1data, test1header, test1stubs, txt_fmt=txt_fmt1, ltx_fmt=ltx_fmt1, html_fmt=html_fmt1)
[ 7061, 6, 198, 26453, 5254, 3084, 13, 9078, 13, 198, 198, 25, 3826, 25, 2638, 1378, 31628, 13, 29412, 13, 2398, 14, 8019, 14, 1084, 4402, 12, 20688, 13, 6494, 329, 281, 18951, 284, 555, 715, 395, 198, 25, 3826, 25, 2638, 1378, 363,...
2.371476
603
"""Types for the Todoist component.""" from __future__ import annotations from typing import TypedDict
[ 37811, 31431, 329, 262, 309, 24313, 396, 7515, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 17134, 276, 35, 713, 628 ]
3.888889
27
from collections import namedtuple from enum import IntEnum from ._zstd import * from . import _zstd __all__ = (# From this file 'compressionLevel_values', 'get_frame_info', 'CParameter', 'DParameter', 'Strategy', # From _zstd 'ZstdCompressor', 'RichMemZstdCompressor', 'ZstdDecompressor', 'EndlessZstdDecompressor', 'ZstdDict', 'ZstdError', 'decompress', 'get_frame_size', 'compress_stream', 'decompress_stream', 'zstd_version', 'zstd_version_info', 'zstd_support_multithread') # Used in __init__.py _ZSTD_DStreamInSize = _zstd._ZSTD_DStreamInSize _train_dict = _zstd._train_dict _finalize_dict = _zstd._finalize_dict # compressionLevel_values _nt_values = namedtuple('values', ['default', 'min', 'max']) compressionLevel_values = _nt_values(_zstd._ZSTD_defaultCLevel, _zstd._ZSTD_minCLevel, _zstd._ZSTD_maxCLevel) _nt_frame_info = namedtuple('frame_info', ['decompressed_size', 'dictionary_id']) def get_frame_info(frame_buffer): """Get zstd frame infomation from a frame header. Argument frame_buffer: A bytes-like object. It should starts from the beginning of a frame, and needs to include at least the frame header (6 to 18 bytes). Return a two-items namedtuple: (decompressed_size, dictionary_id) If decompressed_size is None, decompressed size is unknown. dictionary_id is a 32-bit unsigned integer value. 0 means dictionary ID was not recorded in the frame header, the frame may or may not need a dictionary to be decoded, and the ID of such a dictionary is not specified. It's possible to append more items to the namedtuple in the future.""" ret_tuple = _zstd._get_frame_info(frame_buffer) return _nt_frame_info(*ret_tuple) # Set CParameter/DParameter types for validity check _zstd._set_parameter_types(CParameter, DParameter)
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 33829, 1330, 2558, 4834, 388, 198, 198, 6738, 47540, 89, 19282, 1330, 1635, 198, 6738, 764, 1330, 4808, 89, 19282, 198, 198, 834, 439, 834, 796, 17426, 3574, 428, 2393, 198, 220, 220, 220...
2.464156
823
from abc import ABC, abstractmethod from contextlib import contextmanager from uuid import uuid4 import pytest from sqlalchemy import ( delete, select, UniqueConstraint, ) def persist(session, obj, return_id=True): """ Use the session to store obj in database, then remove obj from session, so that on a subsequent load from the database we get a clean instance. """ session.add(obj) session.flush() obj_id = obj.id if return_id else None # save this before obj is expunged session.expunge(obj) return obj_id def delete_from_database(session, objects): """ Delete each object in objects from database. May be called at the end of a test if use of a context manager is impractical. (Assume all objects have the id field as their primary key.) """ # Ensure we have a list of objects (check for list explicitly: a model can be iterable) if not isinstance(objects, list): objects = [objects] for obj in objects: table = obj.__table__ stmt = delete(table).where(table.c.id == obj.id) session.execute(stmt) def collection_consists_of_objects(collection, *objects): """ Returns True iff list(collection) == list(objects), where object equality is determined by primary key equality: object1.id == object2.id. """ if len(collection) != len(objects): # False if lengths are different return False if not collection: # True if both are empty return True # Sort, then compare each member by its 'id' attribute, which must be its primary key. collection.sort(key=lambda item: item.id) objects_l = list(objects) objects_l.sort(key=lambda item: item.id) for item1, item2 in zip(collection, objects_l): if item1.id is None or item2.id is None or item1.id != item2.id: return False return True def get_unique_value(): """Generate unique values to accommodate unique constraints.""" return uuid4().hex
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 334, 27112, 1330, 334, 27112, 19, 198, 198, 11748, 12972, 9288, 198, 6738, 44161, 282, 26599, 1330, 357, 198, 220, 220, 220, 12233, 11, ...
2.928675
687
from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model
[ 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 201, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 201, 198, 201, 198 ]
3.21875
32
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ An `image.layer` is a set of `feature` with some additional parameters. Its purpose to materialize those `feature`s as a btrfs subvolume in the per-repo `buck-image/out/volume/targets`. We call the subvolume a "layer" because it can be built on top of a snapshot of its `parent_layer`, and thus can be represented as a btrfs send-stream for more efficient storage & distribution. The Buck output of an `image.layer` target is a JSON file with information on how to find the resulting layer in the per-repo `buck-image/out/volume/targets`. See `SubvolumeOnDisk.to_json_file`. ## Implementation notes The implementation of this converter deliberately minimizes the amount of business logic in its command. The converter must include **only** our interactions with the buck target graph. Everything else should be delegated to subcommands. ### Command In composing the `bash` command, our core maxim is: make it a hermetic function of the converter's inputs -- do not read data from disk, do not insert disk paths into the command, do not do anything that might cause the bytes of the command to vary between machines or between runs. To achieve this, we use Buck macros to resolve all paths, including those to helper scripts. We rely on environment variables or pipes to pass data between the helper scripts. Another reason to keep this converter minimal is that `buck test` cannot make assertions about targets that fail to build. Since we only have the ability to test the "good" targets, it behooves us to put most logic in external scripts, so that we can unit-test its successes **and** failures thoroughly. ### Output We mark `image.layer` uncacheable, because there's no easy way to teach Buck to serialize a btrfs subvolume (for that, we have `package.new`). That said, we should still follow best practices to avoid problems if e.g. the user renames their repo, or similar. These practices include: - The output JSON must store no absolute paths. - Store Buck target paths instead of paths into the output directory. ### Dependency resolution An `image.layer` consumes a set of `feature` outputs to decide what to put into the btrfs subvolume. These outputs are actually just JSON files that reference other targets, and do not contain the data to be written into the image. Therefore, `image.layer` has to explicitly tell buck that it needs all direct dependencies of its `feature`s to be present on disk -- see our `attrfilter` queries below. Without this, Buck would merrily fetch the just the `feature` JSONs from its cache, and not provide us with any of the buid artifacts that comprise the image. We do NOT need the direct dependencies of the parent layer's features, because we treat the parent layer as a black box -- whatever it has laid down in the image, that's what it provides (and we don't care about how). The consequences of this information hiding are: - Better Buck cache efficiency -- we don't have to download the dependencies of the ancestor layers' features. Doing that would be wasteful, since those bits are redundant with what's in the parent. - Ability to use genrule image layers / apply non-pure post-processing to a layer. In terms of engineering, both of these non-pure approaches are a terrible idea and a maintainability headache, but they do provide a useful bridge for transitioning to Buck image builds from legacy imperative systems. - The image compiler needs a litte extra code to walk the parent layer and determine what it provides. - We cannot have "unobservable" dependencies between features. Since feature dependencies are expected to routinely cross layer boundaries, feature implementations are forced only to depend on data that can be inferred from the filesystem -- since this is all that the parent layer implementation can do. NB: This is easy to relax in the future by writing a manifest with additional metadata into each layer, and using that metadata during compilation. """ load(":compile_image_features.bzl", "compile_image_features") load(":image_layer_utils.bzl", "image_layer_utils") load(":image_utils.bzl", "image_utils") def image_layer( name, parent_layer = None, features = None, flavor = None, flavor_config_override = None, antlir_rule = "user-internal", **image_layer_kwargs): """ Arguments - `parent_layer`: The name of another `image_layer` target, on top of which the current layer will install its features. - `features`: List of `feature` target paths and/or nameless structs from `feature.new`. - `flavor`: Picks default build options for the layer, including `build_appliance`, RPM installer, and others. See `flavor_helpers.bzl` for details. - `flavor_config_override`: A struct that can override the default values fetched from `REPO_CFG[flavor].flavor_to_config`. - `mount_config`: Specifies how this layer is mounted in the `mounts` field of a `feature` of a parent layer. See the field in `_image_layer_impl` in `image_layer_utils.bzl` - `runtime`: A list of desired helper buck targets to be emitted. `container` is always included in the list by default. See the field in `_image_layer_impl` in `image_layer_utils.bzl` and the [docs](/docs/tutorials/helper-buck-targets#imagelayer) for the list of possible helpers, their respective behaviours, and how to invoke them. """ image_layer_utils.image_layer_impl( _rule_type = "image_layer", _layer_name = name, # Build a new layer. It may be empty. _make_subvol_cmd = compile_image_features( name = name, current_target = image_utils.current_target(name), parent_layer = parent_layer, features = features, flavor = flavor, flavor_config_override = flavor_config_override, ), antlir_rule = antlir_rule, **image_layer_kwargs )
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, ...
3.390616
1,833
from calendar import setfirstweekday stopped_in_user_file = True setfirstweekday(15)
[ 6738, 11845, 1330, 900, 11085, 10464, 820, 198, 301, 38333, 62, 259, 62, 7220, 62, 7753, 796, 6407, 198, 2617, 11085, 10464, 820, 7, 1314, 8 ]
3.230769
26
''' __main__, to run: python -m promt_tr ''' import sys from random import randint from promt_tr import promt_tr, LANG_CODES # pragma: no cover def main(): '''main''' from_lang = 'auto' to_lang = 'zh' text = 'test ' + str(randint(0, 10000)) if not sys.argv[1:]: print('Provide some English text, with an optional to_lang') print('E.g., python -m promt_tr test this and that de') print('Testing with some random text\n') else: argv = sys.argv[1:] len_ = len(argv) if len_ == 1: if argv[0] in LANG_CODES: to_lang = argv[0] else: text = argv[0] elif argv[-1] in LANG_CODES: to_lang = argv[-1] text = ' '.join(argv[:-1]) else: text = ' '.join(argv) for to_lang in ['zh', 'de', 'fr', 'it', 'es']: resu = promt_tr(text, from_lang, to_lang) print(f'[{text}] translated to [{to_lang}]: [{resu}]') if __name__ == '__main__': main()
[ 7061, 6, 11593, 12417, 834, 11, 284, 1057, 25, 198, 29412, 532, 76, 1552, 83, 62, 2213, 198, 7061, 6, 198, 11748, 25064, 198, 6738, 4738, 1330, 43720, 600, 198, 198, 6738, 1552, 83, 62, 2213, 1330, 1552, 83, 62, 2213, 11, 406, 155...
1.925651
538
import os import sys import pandas as pd from datetime import datetime from settings import RAW_DATA_DIR, DataV3, DATA_V3_SUBVERSION from src.features.helpers.processing import add_missing_timestamp_values from src.features.helpers.processing_v3 import get_closest_players, get_players_and_ball_indices, calculate_distance, \ normalize_according_to_play_direction, check_group_event from src.features.helpers.processing_v4 import home_has_possession, calculate_team_sitation week_num = int(sys.argv[1]) data_v3 = DataV3(DATA_V3_SUBVERSION) save_file_path = data_v3.get_step1_checkpoint_path(week_num) try: clean_df = pd.read_csv(save_file_path) save_file_exists = True except FileNotFoundError: save_file_exists = False if not save_file_exists: print("Started loading data") play_df = pd.read_csv(os.path.join(RAW_DATA_DIR, 'plays.csv')) games_df = pd.read_csv(os.path.join(RAW_DATA_DIR, 'games.csv')) week_and_games = games_df[games_df.week == week_num] tracking_df = pd.read_csv(os.path.join(RAW_DATA_DIR, f'week{week_num}.csv')) print("Data loaded. Start processing timestamps") tracking_df = add_missing_timestamp_values(tracking_df) games_n_plays_df = play_df.merge(week_and_games, how='inner', on='gameId') m_grouped = games_n_plays_df.groupby(['gameId', 'playId']) df_t = tracking_df.merge(games_n_plays_df, how='left', on=['gameId', 'playId']) # Remove all events without 'pass_forward' df_t_grouped = df_t.groupby(['gameId', 'playId']) df_t_v3 = df_t.copy().sort_index() for name, group in df_t_grouped: game_id, play_id = name # if group does not contain pass forward, drop it if all(group.event != 'pass_forward'): df_t_v3 = df_t_v3[(df_t_v3.gameId != game_id) | (df_t_v3.playId != play_id)] df_t_v3_s = df_t_v3.sort_values(by=['gameId', 'playId', 'time', 'event']) df_t_v3_s = df_t_v3_s.reset_index(drop=True) df_t_grouped = df_t_v3_s.groupby(['gameId', 'playId']) # remove all values before 'pass_forward' print("Removing all values before pass forward event...") for name, group in df_t_grouped: game_id, play_id = name pass_forward_frame_id = group[group.event == 'pass_forward'].index.min() - 1 remove_start = group.index.min() df_t_v3_s = df_t_v3_s.drop(df_t_v3_s.loc[remove_start:pass_forward_frame_id].index) pd.options.mode.chained_assignment = None gb = df_t_v3_s.groupby(['gameId', 'playId']) print('Getting closest players...') keep_indices = [] for name, group in gb: game_id, play_id = name try: event_3rd = group.event.unique()[2] except IndexError: print('Number of events is < 3, skipping...') continue situation_df = group[group.event == event_3rd] # convert dataframe into series ball_row = situation_df[situation_df.team == 'football'].head(1) # remove ball player_situation_df = situation_df[situation_df.team != 'football'] try: p1, p2 = get_closest_players(player_situation_df, ball_row.x.item(), ball_row.y.item()) except ValueError: print('Value Error raised. This group will be skipped.') continue p_n_b_indices = get_players_and_ball_indices(group, p1, p2) if p_n_b_indices: keep_indices.extend(p_n_b_indices) clean_df = df_t_v3_s[df_t_v3_s.index.isin(keep_indices)] clean_df.to_csv( save_file_path, index=False ) print('Normalize...') clean_df = normalize_according_to_play_direction(clean_df) clean_df['homeHasPossession'] = clean_df.apply( lambda row: home_has_possession(row), axis=1 ) clean_df['teamSituation'] = clean_df.apply( lambda row: calculate_team_sitation(row), axis=1 ) print('Creating features...') min_df = clean_df[[ 'time', 'x', 'y', 's', 'o', 'dir', 'event', 'team', 'gameId', 'playId', 'frameId', 'isDefensivePI' ]] gb_2 = clean_df.groupby(['gameId', 'playId', 'frameId']) # ball direction and orientation are NaN calc_df = pd.DataFrame( columns=[ 'time', 'att_def_d', 'att_ball_d', 'def_ball_d', 'att_s', 'def_s', 'ball_s', 'att_o', 'def_o', 'att_dir', 'def_dir', 'event', 'gameId', 'playId', 'frameId', 'isDefensivePI' ] ) GROUP_SIZE_MINIMUM = 3 for name, group in gb_2: game_id, play_id, frameId = name if len(group) < GROUP_SIZE_MINIMUM: continue ball = group[group.teamSituation == 'football'].head(1).squeeze() p_att = group[group.teamSituation == 'attacking'].head(1).squeeze() p_def = group[group.teamSituation == 'defending'].head(1).squeeze() group_row = group.head(1).squeeze() group_events = group.event.unique().tolist() dict_to_append = { 'time': group_row.time, 'att_def_d': calculate_distance(p_att.x, p_att.y, p_def.x, p_def.y), 'att_ball_d': calculate_distance(p_att.x, p_att.y, ball.x, ball.y), 'def_ball_d': calculate_distance(p_def.x, p_def.y, ball.x, ball.y), 'att_s': p_att.s, 'def_s': p_def.s, 'ball_s': ball.s, 'att_a': p_att.a, 'def_a': p_def.a, 'ball_a': ball.a, 'att_o': p_att.o, 'def_o': p_def.o, 'att_dir': p_att.dir, 'def_dir': p_def.dir, 'event': group_row.event, 'pass_arrived': check_group_event(group_events, 'pass_arrived'), 'pass_outcome_caught': check_group_event(group_events, 'pass_outcome_caught'), 'tackle': check_group_event(group_events, 'tackle'), 'first_contact': check_group_event(group_events, 'first_contact'), 'pass_outcome_incomplete': check_group_event(group_events, 'pass_outcome_incomplete'), 'out_of_bounds': check_group_event(group_events, 'out_of_bounds'), 'week': week_num, 'gameId': group_row.gameId, 'playId': group_row.playId, 'frameId': group_row.frameId, 'isDefensivePI': group_row.isDefensivePI } calc_df = calc_df.append( dict_to_append, ignore_index=True ) print("Saving data...") calc_df.to_csv( data_v3.get_step1_end_path(week_num), index=False ) print(f'End time: {datetime.now().strftime("%H:%M:%S")}')
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 6460, 1330, 33782, 62, 26947, 62, 34720, 11, 6060, 53, 18, 11, 42865, 62, 53, 18, 62, 50, 10526, 43717, 198, ...
2.212218
2,832
#!/usr/bin/python """Annotates -E preprocessed source input with line numbers. Read std input, then annotate each line with line number based on previous expanded line directives from -E output. Useful in the context of compiler debugging. """ import getopt import os import re import sys import script_utils as u flag_reverse = True def usage(msgarg): """Print usage and exit.""" if msgarg: sys.stderr.write("error: %s\n" % msgarg) print """\ usage: %s [options] < input > output options: -d increase debug msg verbosity level """ % os.path.basename(sys.argv[0]) sys.exit(1) def parse_args(): """Command line argument parsing.""" global flag_reverse try: optlist, _ = getopt.getopt(sys.argv[1:], "dr") except getopt.GetoptError as err: # unrecognized option usage(str(err)) for opt, _ in optlist: if opt == "-d": u.increment_verbosity() elif opt == "-r": flag_reverse = False # Setup u.setdeflanglocale() parse_args() # Read lines = sys.stdin.readlines() lnum = -1 matcher = re.compile(r"^\#\s+(\d+)\s+\"(\S+)\".*$") for line in lines: m = matcher.match(line) if m: lnum = int(m.group(1)) afile = m.group(2) print "<%s:%d>" % (afile, lnum) continue print "%d:%s" % (lnum, line.strip()) lnum += 1
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 37811, 2025, 1662, 689, 532, 36, 662, 14681, 276, 2723, 5128, 351, 1627, 3146, 13, 198, 198, 5569, 14367, 5128, 11, 788, 24708, 378, 1123, 1627, 351, 1627, 1271, 1912, 319, 2180, 198, 11201, ...
2.537718
517
import streamlit as st import tensorflow as tf import numpy from utils.get_owm_data import get_open_weather_map_data from utils.get_date import get_date_list_for_gmt import plotly.graph_objects as go from plotly import tools import plotly.offline as py import plotly.express as px
[ 11748, 4269, 18250, 355, 336, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 198, 6738, 3384, 4487, 13, 1136, 62, 322, 76, 62, 7890, 1330, 651, 62, 9654, 62, 23563, 62, 8899, 62, 7890, 198, 6738, 3384, 4487, 13, ...
3.076087
92
# -*- coding: utf-8 -*- import os ROOT = os.path.abspath(os.path.dirname(__file__)) path = lambda *args: os.path.join(ROOT, *args) """ Template for local settings of the FST webservice (fst_web) Please edit this file and replace all generic values with values suitable to your particular installation. """ # NOTE! Always set this to False before deploying DEBUG = True # NOTE! Before deploying on a public, uncomment ALLOWED_HOSTS # and add IP address and/or domain of your site ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'fst.magokoro.nu'] # Look for instance-specific settings try: from .instance_settings import * except ImportError: from .default_instance_settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': path('database/fst_demo.db') } } LOG_LEVEL = "DEBUG" # Enable this to override global DB Debug setting # DB_DEBUG_LEVEL = "DEBUG" # Setup mail server for sending email notifications. # You can use any mail server you want. # But a very simple way to get started is to use a gmail account. EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 # EMAIL_HOST_USER = 'your email' # EMAIL_HOST_PASSWORD = 'your password' # Admins specified here receive email notifications on critical errors. ADMINS = () MANAGERS = ADMINS # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = os.path.join("/dokument/") # Site and port for hosting FST service (do not add ending '/'). FST_SITE_URL = "http://127.0.0.1:8000" # TODO - Check if FST_INSTANCE_PREFIX can be removed # Site and port of specific FST instance (do not add ending '/'). FST_INSTANCE_URL = os.path.join( "http://127.0.0.1:8000", FST_INSTANCE_PREFIX)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 198, 13252, 2394, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 6978, 796, 37456, 1635,...
2.819847
655
#! /usr/bin/env python3.6 import argparse import argcomplete from argcomplete.completers import ChoicesCompleter from argcomplete.completers import EnvironCompleter import requests from bthread import BookingThread from bs4 import BeautifulSoup from file_writer import FileWriter hotels = [] def prep_data(rooms=1, country='Macedonia', dest_id='-1', DayIni='01/01/2019', DayFim='02/01/2019', out_format=None): ''' Prepare data for saving :return: hotels: set() ''' offset = 1 session = requests.Session() parsed_html = get_booking_page(session, offset, rooms, country, dest_id, DayIni,DayFim) all_offset = parsed_html.find_all('li', {'class': 'sr_pagination_item'})[-1].get_text().splitlines()[-1] threads = [] for i in range(int(all_offset)): offset += 1 t = BookingThread(session, offset, rooms, country,dest_id,DayIni, DayFim, process_hotels) threads.append(t) for t in threads: t.start() for t in threads: t.join() hotels2 = hotels return hotels2 def get_data(rooms=1, country='Macedonia', dest_id='-1',DayIni='01/01/2019',DayFim='02/01/2019', out_format=None): ''' Get all accomodations in Macedonia and save them in file :return: hotels-in-macedonia.{txt/csv/xlsx} file ''' print('Procurando por',country) hotels_list = prep_data(rooms, country,dest_id, DayIni, DayFim, out_format) save_data(hotels_list , out_format=out_format, country=country) def save_data(data, out_format, country): ''' Saves hotels list in file :param data: hotels list :param out_format: json, csv or excel :return: ''' writer = FileWriter(data, out_format, country) file = writer.output_file() print('All accommodations are saved.') print('You can find them in', file, 'file') if __name__ == "__main__": parser = argparse.ArgumentParser() countries = get_countries() parser.add_argument("--rooms", help='Add the number of rooms to the booking request.', default=1, type=int, nargs='?') parser.add_argument("--country", help='Add the country to the booking request.', default='Macedonia', nargs='?').completer = ChoicesCompleter(countries) parser.add_argument("--dest_id", help='Add the country to the booking request.', default='0', nargs='?') parser.add_argument("--DayIni", help='Data inicial', default='01/01/2019', nargs='?') parser.add_argument("--DayFim", help='Data inicial', default='02/01/2019', nargs='?') parser.add_argument("--out_format", help='Add the format for the output file. Add excel, json or csv.', default='json', choices=['json', 'excel', 'csv'], nargs='?').completer = EnvironCompleter argcomplete.autocomplete(parser) args = parser.parse_args() localidades = [{ 'Pais': 'London', 'dest_id': '-2601889' }, { 'Pais': 'Utrecht', 'dest_id': '-2154382' }, { 'Pais': 'Buzios', 'dest_id': '-626254' }, { 'Pais': '', 'dest_id': '' }] countryAux = [d['Pais'] for d in localidades if args.dest_id in d['dest_id']] if len(countryAux)>0: country = countryAux[0] print('Parametros') print(args.rooms, country,args.dest_id,args.DayIni,args.DayFim, args.out_format) get_data(args.rooms, country,args.dest_id,args.DayIni,args.DayFim, args.out_format) else: country = 'Nao Identificado' locais = [d['Pais'] + ':' + d['dest_id'] for d in localidades if d['Pais'] != ''] print('----------') print('Utilize uma das seguintes localizaes') for i in locais: print(i) print('----------')
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 13, 21, 198, 11748, 1822, 29572, 198, 11748, 1822, 20751, 198, 6738, 1822, 20751, 13, 785, 1154, 1010, 1330, 10031, 1063, 5377, 1154, 353, 198, 6738, 1822, 20751, 13, 785, 1154, 1010,...
2.083168
2,020
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from google.appengine.api import users import webapp2 # For datastore import cgi import urllib from google.appengine.ext import ndb # ************** MainHandler ************* # # ************** GetUser ************* # # ************** HasData ************* # app = webapp2.WSGIApplication([ ('/', MainHandler), ('/GetUser/', GetUser), ('/HasData/', HasData), ('/chrome-sync/command/', PostData), ('/GetSyncData/', GetSyncData) ], debug=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 4343, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, ...
3.268293
328
# Comet VOEvent Broker. from twisted.application.internet import ClientService from comet.protocol.subscriber import VOEventSubscriberFactory __all__ = ["makeSubscriberService"] def makeSubscriberService(endpoint, local_ivo, validators, handlers, filters): """Create a reconnecting VOEvent subscriber service. Parameters ---------- endpoint : implements `twisted.internet.interfaces.IStreamClientEndpoint` The endpoint to which the service will connect. local_ivo : `str` or `None` IVOA identifier for the subscriber. validators : `list` of implementers of `~comet.icomet.IValidator`. Validators which will be applied to incoming events. Events which fail validation will be rejected. handlers : `list` of implementers of `~comet.icomet.IHandler`. Handlers to which events which pass validation will be passed. filters : `list` of `str` XPath filters. Will be passed to upstream as a request to filter the alerts being sent. Notes ----- Upstream brokes may not provide support for XPath filtering; in this case, the filters suppplied will be ignored. Reconnection is handled according to the default policies of `twisted.application.internet.ClientService`. """ factory = VOEventSubscriberFactory(local_ivo, validators, handlers, filters) service = ClientService(endpoint, factory) return service
[ 2, 36238, 30578, 9237, 2806, 6122, 13, 198, 198, 6738, 19074, 13, 31438, 13, 37675, 1330, 20985, 16177, 198, 198, 6738, 31733, 13, 11235, 4668, 13, 7266, 1416, 24735, 1330, 30578, 9237, 7004, 1416, 24735, 22810, 198, 198, 834, 439, 834,...
3.244344
442
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import json import os import re import shutil import zlib from StringIO import StringIO try: # Create a block to work around evil sys.modules manipulation in # email/__init__.py that triggers pylint false positives. # pylint: disable=E0611,F0401 from email.Message import Message from email.Utils import formatdate except ImportError: raise from buildbot.process.properties import Properties from buildbot.schedulers.trysched import TryBase from twisted.internet import defer, reactor, utils from twisted.mail.smtp import SMTPSenderFactory from twisted.python import log from common.twisted_util.response import StringResponse from master import gitiles_poller from master.try_job_base import BadJobfile def translate_v1_to_v2(parsed_job): """Translate tryjob desc from V1 to V2.""" parsed_job.setdefault('extra_args', []).append('--remote-trybot') parsed_job['version'] = 2 def translate_v2_to_v3(parsed_job): """Translate tryjob desc from V2 to V3.""" # V3 --remote-patches format is not backwards compatible. if any(a.startswith('--remote-patches') for a in parsed_job.get('extra_args', ())): raise BadJobfile('Cannot translate --remote-patches from tryjob v.2 to ' 'v.3. Please run repo sync.') parsed_job['version'] = 3
[ 2, 15069, 357, 66, 8, 2321, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 1...
3.094142
478
# ------------------------------ # 515. Find Largest Value in Each Tree Row # # Description: # You need to find the largest value in each row of a binary tree. # Example: # Input: # 1 # / \ # 3 2 # / \ \ # 5 3 9 # Output: [1, 3, 9] # # Version: 1.0 # 12/22/18 by Jianfa # ------------------------------ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # BFS solution.
[ 2, 34400, 26171, 198, 2, 642, 1314, 13, 9938, 406, 853, 395, 11052, 287, 5501, 12200, 11314, 198, 2, 220, 198, 2, 12489, 25, 198, 2, 921, 761, 284, 1064, 262, 4387, 1988, 287, 1123, 5752, 286, 257, 13934, 5509, 13, 198, 2, 17934, ...
2.377289
273
# Copyright 2018 Michael DeHaan LLC, <michael@michaeldehaan.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os
[ 2, 15069, 2864, 3899, 1024, 23303, 272, 11419, 11, 1279, 76, 40302, 31, 76, 488, 3609, 35209, 3099, 272, 13, 3262, 29, 198, 2, 220, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, ...
3.664706
170
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 198 ]
3.666667
6
import cocos from MultiLanguage import MultiLanguage from package.helper import ProjectHelper
[ 198, 11748, 8954, 418, 198, 6738, 15237, 32065, 1330, 15237, 32065, 198, 198, 6738, 5301, 13, 2978, 525, 1330, 4935, 47429, 628 ]
4.409091
22
from matplotlib import colors import numpy as np
[ 6738, 2603, 29487, 8019, 1330, 7577, 198, 11748, 299, 32152, 355, 45941, 198 ]
3.769231
13
""" Manage the connection to the MongoDB server. """ import tornado.gen import tornado.ioloop import motor
[ 37811, 198, 5124, 496, 262, 4637, 284, 262, 42591, 11012, 4382, 13, 198, 37811, 198, 198, 11748, 33718, 13, 5235, 198, 11748, 33718, 13, 1669, 11224, 198, 198, 11748, 5584, 628, 198 ]
3.46875
32
################################################# ####### Author: Hugo Pibernat ####### ####### Contact: hugopibernat@gmail.com ####### ####### Date: April 2014 ####### ################################################# from bayesianABTest import sampleSuccessRateForBinomial, sampleMeanForLogNormal, probabilityOfABetterThanB from numpy.random import lognormal from numpy import mean, concatenate, zeros # Generate Log-Normal data A_actuals = lognormal(mean=4.10, sigma=1.0, size=100) B_actuals = lognormal(mean=4.00, sigma=1.0, size=100) # Plus some zeros A_data = concatenate([A_actuals,zeros(10000)]) B_data = concatenate([B_actuals,zeros(10000)]) # Modeling conversions with a binomial variable A_purchases = sum(A_data > 0) A_sessions = len(A_data) B_purchases = sum(B_data > 0) B_sessions = len(B_data) A_CR = sampleSuccessRateForBinomial(A_sessions,A_purchases) B_CR = sampleSuccessRateForBinomial(B_sessions,B_purchases) # Modeling the spend with a log-normal A_non_zero_data = A_data[A_data > 0] B_non_zero_data = B_data[B_data > 0] A_spend = sampleMeanForLogNormal(A_non_zero_data) B_spend = sampleMeanForLogNormal(B_non_zero_data) # Combining the two A_rps = A_CR*A_spend B_rps = B_CR*B_spend # Result: print probabilityOfABetterThanB(A_rps,B_rps)
[ 29113, 14468, 2, 198, 4242, 21017, 6434, 25, 25930, 350, 1856, 32353, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 46424, 2235, 198, 4242, 21017, 14039, 25, 16225, 404, 1856, 32353, 31, 14816, 13, 785, 220, 220, 46424, ...
2.585657
502
# This file is part of the airslate. # # Copyright (c) 2021 airSlate, Inc. # # For the full copyright and license information, please view # the LICENSE file that was distributed with this source code. from airslate.models.documents import UpdateFields from airslate.entities.fields import Field
[ 2, 770, 2393, 318, 636, 286, 262, 1633, 6649, 378, 13, 198, 2, 198, 2, 15069, 357, 66, 8, 33448, 1633, 11122, 378, 11, 3457, 13, 198, 2, 198, 2, 1114, 262, 1336, 6634, 290, 5964, 1321, 11, 3387, 1570, 198, 2, 262, 38559, 24290, ...
3.60241
83
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app import api from app.core.config import config app = FastAPI(title="Sheypoor") # Set all CORS enabled origins app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(api.router, prefix=config.API_URI)
[ 6738, 3049, 15042, 1330, 12549, 17614, 198, 6738, 3049, 15042, 13, 27171, 1574, 13, 66, 669, 1330, 23929, 12310, 2509, 1574, 198, 198, 6738, 598, 1330, 40391, 198, 6738, 598, 13, 7295, 13, 11250, 1330, 4566, 198, 198, 1324, 796, 12549, ...
2.721088
147
from typing import List, NamedTuple CCDS_FILE = 'CCDS.current.txt' CHROMOSOMES = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', 'X', 'Y') def load_ccds() -> List[CdsPos]: """Load file with CDS locations within GRCh38 genome as a list of :class:`CdsPos`.""" cds = [] with open(CCDS_FILE, encoding='utf-8', newline='\n') as fp: for line in fp: if not line: # Skip empty lines continue if line.startswith('#'): # Skip comments continue parts = line.split('\t') ccds_id = parts[4] status = parts[5] if 'Public' not in status: # CDS is not yet public continue if parts[6] == '-': # CDS strand negative order = reverse-complement continue locations_str = parts[9] if locations_str == '-': # CDS location unknown continue chromosome = parts[0] assert chromosome in CHROMOSOMES, chromosome locations = [] assert locations_str.startswith('[') assert locations_str.endswith(']') for location_str in locations_str[1:-1].split(','): start_str, stop_str = location_str.split('-') start, stop = int(start_str), int(stop_str) + 1 locations.append((start, stop)) if sum(b - a for a, b in locations) % 3 != 0: # Skip CDS which are not multiple of three in length. continue cds.append(CdsPos( ccds_id=ccds_id, molecule='chr' + chromosome, indexes=locations )) return cds
[ 6738, 19720, 1330, 7343, 11, 34441, 51, 29291, 198, 198, 4093, 5258, 62, 25664, 796, 705, 4093, 5258, 13, 14421, 13, 14116, 6, 198, 3398, 33676, 2640, 2662, 1546, 796, 19203, 16, 3256, 705, 17, 3256, 705, 18, 3256, 705, 19, 3256, 70...
1.879684
1,014
import pytest from copy import deepcopy from gefest.core.structure.point import Point from gefest.core.structure.polygon import Polygon from gefest.core.structure.structure import Structure from gefest.core.algs.postproc.resolve_errors import * from gefest.core.algs.geom.validation import * # marking length and width for testing polygon poly_width = 10 poly_length = 20 # creating a testing polygons via corner points rectangle_points = [(-1, 40), (-1, poly_length+40), (-poly_width-10, poly_length+40), (-poly_width-10, 40)] out_bounds_rectangle_poly = Polygon('rectangle', points=[Point(*coords) for coords in rectangle_points]) triangle_points = [(1, 1), (poly_width, poly_length), (1, poly_length)] unclosed_triangle_poly = Polygon('triangle', points=[Point(*coords) for coords in triangle_points]) incorrect_points = [(5, 5), (5, poly_length), (8, poly_length), (5, 5), (5, 30)] incorrect_poly = Polygon('incorrect_poly', points=[Point(*coords) for coords in incorrect_points]) domain = Domain()
[ 11748, 12972, 9288, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 308, 891, 395, 13, 7295, 13, 301, 5620, 13, 4122, 1330, 6252, 198, 6738, 308, 891, 395, 13, 7295, 13, 301, 5620, 13, 35428, 14520, 1330, 12280, 14520, 198, 6738, 308, ...
3.045045
333
from unittest.mock import MagicMock, Mock from i3ipc.aio import Con import i3_live_tree.tree_serializer # noqa: F401
[ 6738, 555, 715, 395, 13, 76, 735, 1330, 6139, 44, 735, 11, 44123, 198, 198, 6738, 1312, 18, 541, 66, 13, 64, 952, 1330, 1482, 198, 198, 11748, 1312, 18, 62, 12583, 62, 21048, 13, 21048, 62, 46911, 7509, 220, 1303, 645, 20402, 25, ...
2.5625
48
#!/usr/bin/env python # -*- coding: utf-8 -*- """Gcp methods module.""" from hvac import exceptions from hvac.api.vault_api_base import VaultApiBase from hvac.constants.gcp import DEFAULT_MOUNT_POINT, ALLOWED_CREDS_ENDPOINTS
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 38, 13155, 5050, 8265, 526, 15931, 198, 6738, 289, 85, 330, 1330, 13269, 198, 6738, 289, 85, 330, 13, 15042, 1...
2.483516
91
import token from tokenize import tokenize from brownie import Contract, chain from brownie.exceptions import ContractNotFound from cachetools.func import ttl_cache from .utils.cache import memory from .utils.multicall2 import fetch_multicall from .interfaces.ERC20 import ERC20ABI import ypricemagic.magic import ypricemagic.utils.utils from .constants import STABLECOINS, dai, usdc, usdt, wbtc, weth, sushi # NOTE: If this is failing to pull a price for a token you need, it's likely because that token requires a special swap path. # Please add a viable swap path below to fetch price data successfully. #project.load() if chain.id == 1: FACTORIES = { "uniswap": "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f", "sushiswap": "0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac", } ROUTERS = { "uniswap": Contract("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"), "sushiswap": Contract("0xD9E1CE17F2641F24AE83637AB66A2CCA9C378B9F"), } SPECIAL_PATHS = { "sushiswap": { "0xEF69B5697f2Fb0345cC680210fD39b593a2f9684": ["0xEF69B5697f2Fb0345cC680210fD39b593a2f9684","0x6B3595068778DD592e39A122f4f5a5cF09C90fE2",weth,usdc] ,"0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e": ["0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e","0xC28E27870558cF22ADD83540d2126da2e4b464c2",weth,usdc] ,"0x3166C570935a7D8554c8f4eA792ff965D2EFe1f2": ["0x3166C570935a7D8554c8f4eA792ff965D2EFe1f2","0x4954Db6391F4feB5468b6B943D4935353596aEC9",usdc] ,"0xE6279E1c65DD41b30bA3760DCaC3CD8bbb4420D6": ["0xE6279E1c65DD41b30bA3760DCaC3CD8bbb4420D6","0x87F5F9eBE40786D49D35E1B5997b07cCAA8ADbFF",weth,usdc] ,"0x4954Db6391F4feB5468b6B943D4935353596aEC9": ["0x4954Db6391F4feB5468b6B943D4935353596aEC9",usdc] ,"0x1E18821E69B9FAA8e6e75DFFe54E7E25754beDa0": ["0x1E18821E69B9FAA8e6e75DFFe54E7E25754beDa0","0xEF69B5697f2Fb0345cC680210fD39b593a2f9684","0x6B3595068778DD592e39A122f4f5a5cF09C90fE2",weth,usdc] ,"0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d": ["0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d","0xba100000625a3754423978a60c9317c58a424e3D",weth,usdc] ,"0xBA50933C268F567BDC86E1aC131BE072C6B0b71a": ["0xBA50933C268F567BDC86E1aC131BE072C6B0b71a",weth,usdc] ,"0x6102407f07029892eB5Ff02164ADFaFb85f4d222": ["0x6102407f07029892eB5Ff02164ADFaFb85f4d222",usdt] ,"0x85034b3b2e292493D029443455Cc62ab669573B3": ["0x85034b3b2e292493D029443455Cc62ab669573B3","0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",weth,usdc] ,"0xb220D53F7D0f52897Bcf25E47c4c3DC0bac344F8": ["0xb220D53F7D0f52897Bcf25E47c4c3DC0bac344F8", usdc] ,"0x383518188C0C6d7730D91b2c03a03C837814a899": ["0x383518188C0C6d7730D91b2c03a03C837814a899",dai] ,"0xafcE9B78D409bF74980CACF610AFB851BF02F257": ["0xafcE9B78D409bF74980CACF610AFB851BF02F257",wbtc,weth,usdc] }, "uniswap": { } } elif chain.id == 56: ROUTERS = { "pancakeswapv2": Contract("0x10ED43C718714eb63d5aA57B78B54704E256024E"), "pancakeswapv1": Contract("0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F") } FACTORIES = { "pancakeswapv2": "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73", "pancakeswapv1": "0xBCfCcbde45cE874adCB698cC183deBcF17952812" } SPECIAL_PATHS = { "pancakeswapv2": { }, "pancakeswapv1": { } } elif chain.id == 137: ROUTERS = { "quickswap": Contract("0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff") } FACTORIES = { "quickswap": "0x5757371414417b8C6CAad45bAeF941aBc7d3Ab32", } SPECIAL_PATHS = { "quickswap": { } } FACTORY_TO_ROUTER = {FACTORIES[name]: ROUTERS[name] for name in FACTORIES} FACTORY_TO_PROTOCOL = {FACTORIES[name]: name for name in FACTORIES}
[ 11748, 11241, 198, 6738, 11241, 1096, 1330, 11241, 1096, 198, 6738, 7586, 494, 1330, 17453, 11, 6333, 198, 6738, 7586, 494, 13, 1069, 11755, 1330, 17453, 3673, 21077, 198, 6738, 40428, 3202, 10141, 13, 20786, 1330, 256, 28781, 62, 23870, ...
1.716083
2,226
""" TextRNN model configuration """
[ 37811, 8255, 49, 6144, 2746, 8398, 37227, 198 ]
4.5
8
DEBUG_MEMBER_LIST = [ 503131177, ]
[ 30531, 62, 44, 28952, 62, 45849, 796, 685, 198, 220, 220, 220, 2026, 25838, 1157, 3324, 11, 198, 60 ]
2
19
from typing import Tuple import torch from torch.autograd import Function import torch.nn as nn from metrics.pointops import pointops_cuda import numpy as np furthestsampling = FurthestSampling.apply gathering = Gathering.apply nearestneighbor = NearestNeighbor.apply interpolation = Interpolation.apply grouping = Grouping.apply grouping_int = GroupingInt.apply ballquery = BallQuery.apply featuredistribute = FeatureDistribute.apply featuregather = FeatureGather.apply labelstat_ballrange = LabelStatBallRange.apply labelstat_idx = LabelStatIdx.apply labelstat_and_ballquery = LabelStatAndBallQuery.apply def pairwise_distances(x, y=None): ''' Input: x is a Nxd matrix y is an optional Mxd matirx Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:] if y is not given then use 'y=x'. i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2 ''' x_norm = (x ** 2).sum(1).view(-1, 1) if y is not None: y_t = torch.transpose(y, 0, 1) y_norm = (y ** 2).sum(1).view(1, -1) else: y_t = torch.transpose(x, 0, 1) y_norm = x_norm.view(1, -1) dist = x_norm + y_norm - 2.0 * torch.mm(x, y_t) import numpy as np return torch.clamp(dist, 0.0, np.inf) knnquery_naive = KNNQueryNaive.apply knnquery = KNNQuery.apply knnquery_exclude = KNNQueryExclude.apply
[ 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 28034, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 15553, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 198, 6738, 20731, 13, 4122, 2840, 1330, 966, 2840, 62, 66, 15339, 198, 198, 11...
2.414508
579
from collections import defaultdict from logging import getLogger from operator import itemgetter from os import environ from time import time from zope.cachedescriptors.property import Lazy as cachedproperty from zeit.cms.content.sources import FEATURE_TOGGLES from zope.component import getUtility from zeit.connector.interfaces import IConnector from zeit.connector.filesystem import Connector log = getLogger(__name__) __cache = ContentCache() get = __cache.get info = __cache.info
[ 6738, 17268, 1330, 4277, 11600, 198, 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, 6738, 28686, 1330, 551, 2268, 198, 6738, 640, 1330, 640, 198, 6738, 1976, 3008, 13, 66, 2317, 3798, 1968, 669, 13, ...
3.532374
139
"""Project""" from __future__ import absolute_import, division, print_function, unicode_literals
[ 37811, 16775, 37811, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 628 ]
3.92
25
# Create your views here. from django.db.models import QuerySet from django.utils.decorators import method_decorator from drf_yasg.utils import swagger_auto_schema from rest_framework import viewsets, status from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from rest_framework.viewsets import mixins from account.documents import DjangoFilterDescriptionInspector from account.models import Customer from account.serializers import CustomerInfoSerializer, SignUpFormSerializer
[ 2, 13610, 534, 5009, 994, 13, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 43301, 7248, 198, 6738, 42625, 14208, 13, 26791, 13, 12501, 273, 2024, 1330, 2446, 62, 12501, 273, 1352, 198, 6738, 1553, 69, 62, 88, 292, 70, 13, 267...
3.992593
135
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import argparse # pylint: disable=protected-access
[ 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 1783, 10541, 198,...
6.359375
64
"""Provides all the data related to the development.""" LICENSES = [ "Apache License, 2.0 (Apache-2.0)", "The BSD 3-Clause License", "The BSD 2-Clause License", "GNU General Public License (GPL)", "General Public License (LGPL)", "MIT License (MIT)", "Mozilla Public License 2.0 (MPL-2.0)", "Common Development and Distribution License (CDDL-1.0)", "Eclipse Public License (EPL-1.0)", ] PROGRAMMING_LANGS = [ "ASP", "Assembly", "AutoIt", "Awk", "Bash", "C", "C Shell", "C#", "C++", "Caml", "Ceylon", "Clojure", "CoffeeScript", "Common Lisp", "D", "Dart", "Delphi", "Dylan", "ECMAScript", "Elixir", "Emacs Lisp", "Erlang", "F#", "Falcon", "Fortran", "GNU Octave", "Go", "Groovy", "Haskell", "haXe", "Io", "J#", "Java", "JavaScript", "Julia", "Kotlin", "Lisp", "Lua", "Mathematica", "Objective-C", "OCaml", "Perl", "PHP", "PL-I", "PL-SQL", "PowerShell", "Prolog", "Python", "R", "Racket", "Ruby", "Rust", "Scala", "Scheme", "Smalltalk", "Tcl", "Tex", "Transact-SQL", "TypeScript", "Z shell", ] OS = [ "Arch", "CentOS", "Debian", "Fedora", "FreeBSD", "Gentoo", "Kali", "Lubuntu", "Manjaro", "Mint", "OS X", "macOS", "OpenBSD", "PCLinuxOS", "Slackware", "Ubuntu", "Windows 10", "Windows 7", "Windows 8", "Windows 8.1", "Zorin", "elementaryOS", "macOS", "openSUSE", ] FOLDERS = [ "Development", "Downloads", "Documents", "Music", "Video", "Work", "Pictures", "Desktop", "Study", ] PROJECT_NAMES = [ "aardonyx", "abelisaurus", "achelousaurus", "achillobator", "acrocanthosaurus", "aegyptosaurus", "afrovenator", "agilisaurus", "alamosaurus", "albertaceratops", "albertosaurus", "alectrosaurus", "alioramus", "allosaurus", "alvarezsaurus", "amargasaurus", "ammosaurus", "ampelosaurus", "amygdalodon", "anatotitan", "anchiceratops", "anchisaurus", "ankylosaurus", "anserimimus", "antarctopelta", "antarctosaurus", "apatosaurus", "aragosaurus", "aralosaurus", "archaeoceratops", "archaeopteryx", "archaeornithomimus", "argentinosaurus", "arrhinoceratops", "atlascopcosaurus", "aucasaurus", "austrosaurus", "avaceratops", "avalonia", "avimimus", "azendohsaurus", "bactrosaurus", "bagaceratops", "bambiraptor", "barapasaurus", "barosaurus", "baryonyx", "becklespinax", "beipiaosaurus", "bellusaurus", "borogovia", "brachiosaurus", "brachyceratops", "bugenasaura", "buitreraptor", "camarasaurus", "camptosaurus", "carnotaurus", "caudipteryx", "cedarpelta", "centrosaurus", "ceratosaurus", "cetiosauriscus", "cetiosaurus", "chaoyangsaurus", "chasmosaurus", "chialingosaurus", "chindesaurus", "chinshakiangosaurus", "chirostenotes", "chubutisaurus", "chungkingosaurus", "citipati", "coelophysis", "coelurus", "coloradisaurus", "compsognathus", "conchoraptor", "confuciusornis", "corythosaurus", "cryolophosaurus", "dacentrurus", "daspletosaurus", "datousaurus", "deinocheirus", "deinonychus", "deltadromeus", "diceratops", "dicraeosaurus", "dilophosaurus", "diplodocus", "dracorex", "dravidosaurus", "dromaeosaurus", "dromiceiomimus", "dryosaurus", "dryptosaurus", "dubreuillosaurus", "edmontonia", "edmontosaurus", "einiosaurus", "elaphrosaurus", "emausaurus", "eolambia", "eoraptor", "eotyrannus", "equijubus", "erketu", "erlikosaurus", "euhelopus", "euoplocephalus", "europasaurus", "euskelosaurus", "eustreptospondylus", "fukuiraptor", "fukuisaurus", "gallimimus", "gargoyleosaurus", "garudimimus", "gasosaurus", "gasparinisaura", "gastonia", "giganotosaurus", "gilmoreosaurus", "giraffatitan", "gobisaurus", "gorgosaurus", "goyocephale", "graciliceratops", "gryposaurus", "guaibasaurus", "guanlong", "hadrosaurus", "hagryphus", "haplocanthosaurus", "harpymimus", "herrerasaurus", "hesperosaurus", "heterodontosaurus", "homalocephale", "huayangosaurus", "hylaeosaurus", "hypacrosaurus", "hypselosaurus", "hypsilophodon", "iguanodon", "indosuchus", "ingenia", "irritator", "isisaurus", "janenschia", "jaxartosaurus", "jingshanosaurus", "jinzhousaurus", "jobaria", "juravenator", "kentrosaurus", "khaan", "kotasaurus", "kritosaurus", "lamaceratops", "lambeosaurus", "lapparentosaurus", "leaellynasaura", "leptoceratops", "lesothosaurus", "lexovisaurus", "liaoceratops", "liaoxiornis", "ligabuesaurus", "liliensternus", "lophorhothon", "lophostropheus", "lufengosaurus", "lurdusaurus", "lycorhinus", "magyarosaurus", "maiasaura", "majungatholus", "malawisaurus", "mamenchisaurus", "mapusaurus", "marshosaurus", "masiakasaurus", "massospondylus", "maxakalisaurus", "megalosaurus", "melanorosaurus", "metriacanthosaurus", "microceratops", "micropachycephalosaurus", "microraptor", "minmi", "monolophosaurus", "mononykus", "mussaurus", "muttaburrasaurus", "nanotyrannus", "nanshiungosaurus", "nemegtosaurus", "neovenator", "neuquenosaurus", "nigersaurus", "nipponosaurus", "noasaurus", "nodosaurus", "nomingia", "nothronychus", "nqwebasaurus", "omeisaurus", "ornitholestes", "ornithomimus", "orodromeus", "oryctodromeus", "othnielia", "ouranosaurus", "oviraptor", "rebbachisaurus", "rhabdodon", "rhoetosaurus", "rinchenia", "riojasaurus", "rugops", "saichania", "saltasaurus", "saltopus", "sarcosaurus", "saurolophus", "sauropelta", "saurophaganax", "saurornithoides", "scelidosaurus", "scutellosaurus", "secernosaurus", "segisaurus", "segnosaurus", "seismosaurus", "shamosaurus", "shanag", "shantungosaurus", "shunosaurus", "shuvuuia", "silvisaurus", "sinocalliopteryx", "sinornithosaurus", "sinosauropteryx", "sinraptor", "sinvenator", "zalmoxes", "zephyrosaurus", "zuniceratops", "byzantine", "svengali", "accolade", "acrimony", "angst", "anomaly", "antidote", "baroque", "bona_fide", "bourgeois", "bravado", "brogue", "brusque", "cacophony", "caustic", "charisma", "cloying", "deja-vu", "dichotomy", "elan", "ennui", "epitome", "esoteric", "euphemism", "faux pas", "fiasco", "finagle", "glib", "harbinger", "hedonist", "heresy", "idyllic", "insidious", "junket", "kitsch", "litany", "lurid", "malaise", "malinger", "mantra", "maudlin", "mercenary", "misnomer", "nirvana", "oblivion", "ogle", "ostracize", "panacea", "paradox", "peevish", "propriety", "revel", "rhetoric", "spartan", "stigma", "stoic", "suave", "sycophant", "tirade", "tryst", "untenable", "vicarious", "vile", "waft", "zealous", ]
[ 37811, 15946, 1460, 477, 262, 1366, 3519, 284, 262, 2478, 526, 15931, 198, 198, 43, 2149, 16938, 1546, 796, 685, 198, 220, 220, 220, 366, 25189, 4891, 13789, 11, 362, 13, 15, 357, 25189, 4891, 12, 17, 13, 15, 42501, 198, 220, 220, ...
1.931095
4,020
""" A preliminary attempt at parsing an RST file's math syntax in order to make math render as inline rather than display mode. This doesn't work as of yet but might be useful. It could, however, be not useful if there's a pandoc option for converting .md to .rst that makes math inline and not display. Keeping it around, though. """ import re s = """Define .. math:: v_{des} as the desired velocity, .. math:: 1^k a vector of ones of length""" with open('/Users/nishant/Downloads/tutorialtest.rst', 'r') as myfile: s = myfile.read() print([elem[11:-2] for elem in re.findall('\n.. math:: *\S*\n\n', s)])
[ 37811, 198, 32, 15223, 2230, 379, 32096, 281, 371, 2257, 2393, 338, 10688, 15582, 198, 259, 1502, 284, 787, 10688, 8543, 355, 26098, 2138, 621, 3359, 198, 14171, 13, 770, 1595, 470, 670, 355, 286, 1865, 475, 1244, 307, 4465, 13, 198, ...
3.02439
205
from layout import Shape, Widget from flash.text.engine import TextBlock, TextElement
[ 6738, 12461, 1330, 25959, 11, 370, 17484, 198, 6738, 7644, 13, 5239, 13, 18392, 1330, 8255, 12235, 11, 8255, 20180, 198 ]
4.095238
21
import traceback import uuid import socket import logging import os import base64 import zlib import gzip import time import datetime from http import cookies from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from threading import Thread import WebRequest if __name__ == '__main__': wg = WebRequest.WebGetRobust() srv = start_server( assertion_class = None, from_wg = wg, skip_header_checks = True) print("running server on port: ", srv) while 1: time.sleep(1)
[ 198, 11748, 12854, 1891, 198, 11748, 334, 27112, 198, 11748, 17802, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 2779, 2414, 198, 11748, 1976, 8019, 198, 11748, 308, 13344, 198, 11748, 640, 198, 11748, 4818, 8079, 198, 6738, 2638, 13...
2.933333
180
import csv import math import numpy as np import pandas import scipy.optimize import sys import argparse if __name__ == '__main__': main()
[ 11748, 269, 21370, 198, 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 198, 11748, 629, 541, 88, 13, 40085, 1096, 198, 11748, 25064, 198, 11748, 1822, 29572, 628, 628, 628, 628, 198, 361, 11593, 3672, 834, 662...
2.849057
53
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['TestMatrixArgs', 'TestMatrix'] def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, client_info: Optional[pulumi.Input[pulumi.InputType['ClientInfoArgs']]] = None, environment_matrix: Optional[pulumi.Input[pulumi.InputType['EnvironmentMatrixArgs']]] = None, fail_fast: Optional[pulumi.Input[bool]] = None, flaky_test_attempts: Optional[pulumi.Input[int]] = None, project: Optional[pulumi.Input[str]] = None, request_id: Optional[pulumi.Input[str]] = None, result_storage: Optional[pulumi.Input[pulumi.InputType['ResultStorageArgs']]] = None, test_specification: Optional[pulumi.Input[pulumi.InputType['TestSpecificationArgs']]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = TestMatrixArgs.__new__(TestMatrixArgs) __props__.__dict__["client_info"] = client_info if environment_matrix is None and not opts.urn: raise TypeError("Missing required property 'environment_matrix'") __props__.__dict__["environment_matrix"] = environment_matrix __props__.__dict__["fail_fast"] = fail_fast __props__.__dict__["flaky_test_attempts"] = flaky_test_attempts __props__.__dict__["project"] = project __props__.__dict__["request_id"] = request_id if result_storage is None and not opts.urn: raise TypeError("Missing required property 'result_storage'") __props__.__dict__["result_storage"] = result_storage if test_specification is None and not opts.urn: raise TypeError("Missing required property 'test_specification'") __props__.__dict__["test_specification"] = test_specification __props__.__dict__["invalid_matrix_details"] = None __props__.__dict__["outcome_summary"] = None __props__.__dict__["state"] = None __props__.__dict__["test_executions"] = None __props__.__dict__["test_matrix_id"] = None __props__.__dict__["timestamp"] = None super(TestMatrix, __self__).__init__( 'google-native:testing/v1:TestMatrix', resource_name, __props__, opts)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.286908
1,436
import tkinter as tk import tkinter.messagebox from Control import Control
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 11748, 256, 74, 3849, 13, 20500, 3524, 198, 6738, 6779, 1330, 6779, 198 ]
3.571429
21
#coding:utf-8 # # id: bugs.core_3355 # title: Wrong comparsion of DATE and TIMESTAMP if index is used # decription: # tracker_id: CORE-3355 # min_versions: ['2.1.5'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [] init_script_1 = """create table tdate (id integer not null primary key, val date); create index tdateix1 on tdate (val); commit; insert into tdate values (0, '1997-12-31'); insert into tdate values (1, '1998-01-01'); insert into tdate values (2, '1998-01-02'); insert into tdate values (3, '1998-01-03'); insert into tdate values (4, '1998-01-04'); insert into tdate values (5, '1998-01-05'); commit; """ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1) test_script_1 = """select count(*) from tdate where val >= timestamp'1998-01-04 12:00:00.0000'; select count(*) from tdate where val < timestamp'1998-01-04 12:00:00.0000'; """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ COUNT ===================== 1 COUNT ===================== 5 """
[ 2, 66, 7656, 25, 40477, 12, 23, 198, 2, 198, 2, 4686, 25, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 11316, 13, 7295, 62, 2091, 2816, 198, 2, 3670, 25, 220, 220, 220, 220, 220, 220, 220, 28843, 552, 945, 295, 286, 360, ...
2.354167
528
""" @author: anilkdegala """ import os from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator, BranchPythonOperator from datetime import date, timedelta, datetime from collections import OrderedDict from scripts.dag_pebbles import DagPebbles from airflow.configuration import conf from scripts.configurations import * from airflow.operators.dummy_operator import DummyOperator default_args = { "owner": "anilkdegala", "depends_on_past": True, "max_active_runs": 1, "start_date": datetime(2015, 6, 1), "is_active": True, "is_paused_upon_creation": False, } with DAG( "DOWNLOAD_DECRYPT_TRANSFER", description="Download, Decrypt, Transfer files (Source: S3, Staging: EC2: Target: RDS Oracle)", default_args=default_args, schedule_interval=None, catchup=False, orientation="TB", tags=['Utils'], dagrun_timeout=timedelta(hours=240) ) as dag: t_pipeline_begin = PythonOperator( task_id="begin_pipeline", python_callable=begin_pipeline, provide_context=True, dag=dag, ) t_check_pipeline = BranchPythonOperator( task_id="check_pipeline", python_callable=pipeline_enable_check, provide_context=True, dag=dag, ) t_pipeline_check_passed = PythonOperator( task_id="pipeline_check_passed", python_callable=pipeline_check_passed, provide_context=True, dag=dag, ) t_pipeline_check_skipped = PythonOperator( task_id="pipeline_check_skipped", python_callable=pipeline_check_skipped, provide_context=True, dag=dag, ) download_files_cmd = "/opt/bitnami/airflow/airflow-data/scripts/download_files.sh "+"{{ ti.xcom_pull(key='download_decrypt_arguments')}}" t_download_files = BashOperator( task_id='download_files', bash_command=download_files_cmd, dag=dag) decrypt_files_cmd = "/opt/bitnami/airflow/airflow-data/scripts/decrypt_files.sh "+"{{ ti.xcom_pull(key='download_decrypt_arguments')}} " t_decrypt_files = BashOperator( task_id='decrypt_files', bash_command=decrypt_files_cmd, dag=dag) transfer_files_cmd = "/opt/bitnami/airflow/airflow-data/scripts/transfer_files_rds.pl "+"{{ ti.xcom_pull(key='transfer_arguments')}} " t_transfer_files = BashOperator( task_id='transfer_files', bash_command=transfer_files_cmd, dag=dag) t_end_pipeline = PythonOperator( task_id="end_pipeline", python_callable=end_pipeline, provide_context=True, trigger_rule="none_failed", dag=dag, ) t_notify = PythonOperator( task_id="send_notifications", python_callable=notify, provide_context=True, trigger_rule="none_failed", dag=dag, ) t_cleanup = PythonOperator( task_id="cleanup", python_callable=cleanup, provide_context=True, trigger_rule="none_failed", dag=dag, ) t_end = PythonOperator( task_id="end", python_callable=end, provide_context=True, trigger_rule="none_failed", dag=dag, ) t_pipeline_begin >> t_check_pipeline t_check_pipeline >> t_pipeline_check_skipped >> t_end_pipeline t_check_pipeline >> t_pipeline_check_passed >> t_download_files >> t_decrypt_files >> t_transfer_files >> t_end_pipeline t_end_pipeline >> t_cleanup >> t_notify >> t_end
[ 37811, 198, 31, 9800, 25, 281, 43545, 13500, 6081, 198, 37811, 198, 11748, 28686, 198, 6738, 45771, 1330, 360, 4760, 198, 6738, 45771, 13, 3575, 2024, 13, 41757, 62, 46616, 1330, 15743, 18843, 1352, 198, 6738, 45771, 13, 3575, 2024, 13,...
2.157925
1,716
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystone.common import controller from keystone.common import dependency from keystone import notifications
[ 2, 15069, 1946, 19764, 11421, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 1...
3.982659
173
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains the command line app. Why does this file exist, and why not put this in __main__? You might be tempted to import things from __main__ later, but that will cause problems: the code will get executed twice: - When you run `python -m nibetaseries` python will execute ``__main__.py`` as a script. That means there won't be any ``nibetaseries.__main__`` in ``sys.modules``. - When you import __main__ it will get executed again (as a module) because there's no ``nibetaseries.__main__`` in ``sys.modules``. Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration """ from __future__ import absolute_import import os import argparse from argparse import RawTextHelpFormatter from glob import glob from multiprocessing import cpu_count from nipype import config as ncfg def get_parser(): """Build parser object""" from ..__init__ import __version__ import sys verstr = 'nibs v{}'.format(__version__) parser = argparse.ArgumentParser(description='NiBetaSeries BIDS arguments', formatter_class=RawTextHelpFormatter) parser.add_argument('bids_dir', help='The directory with the input dataset ' 'formatted according to the BIDS standard.') parser.add_argument('derivatives_pipeline', help='The pipeline that contains ' 'minimally preprocessed img, brainmask, and confounds.tsv') parser.add_argument('output_dir', help='The directory where the output directory ' 'and files should be stored. If you are running group level analysis ' 'this folder should be prepopulated with the results of the' 'participant level analysis.') parser.add_argument('analysis_level', choices=['participant', 'group'], help='Level of the analysis that will be performed ' 'Multiple participant level analyses can be run independently ' '(in parallel) using the same output_dir') parser.add_argument('-v', '--version', action='version', version=verstr) # Atlas Arguments (Required Options) atlas_args = parser.add_argument_group('Required Atlas Arguments') atlas_args.add_argument('-a', '--atlas-img', action='store', required=('-l' in sys.argv or '--atlas-lut' in sys.argv), help='input atlas nifti where each voxel within a "region" ' 'is labeled with the same integer and there is a unique ' 'integer associated with each region of interest.') atlas_args.add_argument('-l', '--atlas-lut', action='store', required=('-a' in sys.argv or '--atlas-img' in sys.argv), help='atlas look up table (tsv) formatted with the columns: ' 'index, regions which correspond to the regions in the ' 'nifti file specified by --atlas-img.') # preprocessing options proc_opts = parser.add_argument_group('Options for processing') proc_opts.add_argument('--estimator', default='lss', choices=['lss', 'lsa'], help='beta series modeling method') proc_opts.add_argument('-sm', '--smoothing-kernel', action='store', type=float, default=6.0, help='select a smoothing kernel (mm)') proc_opts.add_argument('-hp', '--high-pass', action='store', type=float, default=0.0078125, help='high pass filter (Hz)') proc_opts.add_argument('-c', '--confounds', help='The confound column names ' 'that are to be included in nuisance regression. ' 'write the confounds you wish to include separated by a space', nargs="+") proc_opts.add_argument('--hrf-model', default='glover', choices=['glover', 'spm', 'fir', 'glover + derivative', 'glover + derivative + dispersion', 'spm + derivative', 'spm + derivative + dispersion'], help='convolve your regressors ' 'with one of the following hemodynamic response functions') proc_opts.add_argument('--fir-delays', default=None, nargs='+', type=int, help='FIR delays in volumes', metavar='VOL') proc_opts.add_argument('-w', '--work-dir', help='directory where temporary files ' 'are stored (i.e. non-essential files). ' 'This directory can be deleted once you are reasonably ' 'certain nibs finished as expected.') # Image Selection options image_opts = parser.add_argument_group('Options for selecting images') parser.add_argument('--participant-label', nargs="+", help='The label(s) of the participant(s) ' 'that should be analyzed. The label ' 'corresponds to sub-<participant_label> from the BIDS spec ' '(so it does not include "sub-"). If this parameter is not ' 'provided all subjects should be analyzed. Multiple ' 'participants can be specified with a space separated list.') image_opts.add_argument('--session-label', action='store', default=None, help='select a session to analyze') image_opts.add_argument('-t', '--task-label', action='store', default=None, help='select a specific task to be processed') image_opts.add_argument('--run-label', action='store', default=None, help='select a run to analyze') image_opts.add_argument('-sp', '--space-label', action='store', default='MNI152NLin2009cAsym', choices=['MNI152NLin2009cAsym'], help='select a bold derivative in a specific space to be used') image_opts.add_argument('--description-label', action='store', default=None, help='select a bold file with particular ' '`desc` label to process') image_opts.add_argument('--exclude-description-label', action='store_true', default=False, help='exclude this `desc` label from nibetaseries') # performance options g_perfm = parser.add_argument_group('Options to handle performance') g_perfm.add_argument('--nthreads', '-n-cpus', action='store', type=int, help='maximum number of threads across all processes') g_perfm.add_argument('--use-plugin', action='store', default=None, help='nipype plugin configuration file') # misc options misc = parser.add_argument_group('misc options') misc.add_argument('--graph', action='store_true', default=False, help='generates a graph png of the workflow') return parser init()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 26796, 326, 4909, 262, 3141, 1627, 598, 13, 198, 198, 5195, 857, 428, 2393, 2152, 11, 290, 1521, 407, 123...
2.224153
3,337
"""Config flow for SENZ WiFi.""" from __future__ import annotations import logging from typing import Any import voluptuous as vol from homeassistant.components import persistent_notification from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers import config_entry_oauth2_flow from .const import DOMAIN from .pysenz import PreAPI
[ 37811, 16934, 5202, 329, 44738, 57, 24904, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 18931, 198, 6738, 19720, 1330, 4377, 198, 198, 11748, 2322, 37623, 5623, 355, 2322, 198, 6738, 1363, 562, 10167, 13, ...
3.731959
97
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for retrieving revision information from a project's git repository. """ # Do not remove the following comment; it is used by # astropy_helpers.version_helpers to determine the beginning of the code in # this module # BEGIN import locale import os import subprocess import warnings def update_git_devstr(version, path=None): """ Updates the git revision string if and only if the path is being imported directly from a git working copy. This ensures that the revision number in the version string is accurate. """ try: # Quick way to determine if we're in git or not - returns '' if not devstr = get_git_devstr(sha=True, show_warning=False, path=path) except OSError: return version if not devstr: # Probably not in git so just pass silently return version if 'dev' in version: # update to the current git revision version_base = version.split('.dev', 1)[0] devstr = get_git_devstr(sha=False, show_warning=False, path=path) return version_base + '.dev' + devstr else: # otherwise it's already the true/release version return version def get_git_devstr(sha=False, show_warning=True, path=None): """ Determines the number of revisions in this repository. Parameters ---------- sha : bool If True, the full SHA1 hash will be returned. Otherwise, the total count of commits in the repository will be used as a "revision number". show_warning : bool If True, issue a warning if git returns an error code, otherwise errors pass silently. path : str or None If a string, specifies the directory to look in to find the git repository. If `None`, the current working directory is used, and must be the root of the git repository. If given a filename it uses the directory containing that file. Returns ------- devversion : str Either a string with the revision number (if `sha` is False), the SHA1 hash of the current commit (if `sha` is True), or an empty string if git version info could not be identified. """ if path is None: path = os.getcwd() if not os.path.isdir(path): path = os.path.abspath(os.path.dirname(path)) if sha: # Faster for getting just the hash of HEAD cmd = ['rev-parse', 'HEAD'] else: cmd = ['rev-list', '--count', 'HEAD'] returncode, stdout, stderr = run_git(cmd) if not sha and returncode == 128: # git returns 128 if the command is not run from within a git # repository tree. In this case, a warning is produced above but we # return the default dev version of '0'. return '0' elif not sha and returncode == 129: # git returns 129 if a command option failed to parse; in # particular this could happen in git versions older than 1.7.2 # where the --count option is not supported # Also use --abbrev-commit and --abbrev=0 to display the minimum # number of characters needed per-commit (rather than the full hash) cmd = ['rev-list', '--abbrev-commit', '--abbrev=0', 'HEAD'] returncode, stdout, stderr = run_git(cmd) # Fall back on the old method of getting all revisions and counting # the lines if returncode == 0: return str(stdout.count(b'\n')) else: return '' elif sha: return _decode_stdio(stdout)[:40] else: return _decode_stdio(stdout).strip() # This function is tested but it is only ever executed within a subprocess when # creating a fake package, so it doesn't get picked up by coverage metrics. def _get_repo_path(pathname, levels=None): # pragma: no cover """ Given a file or directory name, determine the root of the git repository this path is under. If given, this won't look any higher than ``levels`` (that is, if ``levels=0`` then the given path must be the root of the git repository and is returned if so. Returns `None` if the given path could not be determined to belong to a git repo. """ if os.path.isfile(pathname): current_dir = os.path.abspath(os.path.dirname(pathname)) elif os.path.isdir(pathname): current_dir = os.path.abspath(pathname) else: return None current_level = 0 while levels is None or current_level <= levels: if os.path.exists(os.path.join(current_dir, '.git')): return current_dir current_level += 1 if current_dir == os.path.dirname(current_dir): break current_dir = os.path.dirname(current_dir) return None
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 198, 37811, 198, 18274, 2410, 329, 50122, 18440, 1321, 422, 257, 1628, 338, 17606, 16099, 13, 198, 37811, 198, 198, 2, 2141, 40...
2.724138
1,769
'''Test feet admittance control''' from sot_talos_balance.utils.run_test_utils import run_ft_calibration, run_test, runCommandClient try: # Python 2 input = raw_input # noqa except NameError: pass run_test('appli_feet_admittance.py') run_ft_calibration('robot.ftc') input("Wait before running the test") print('Set saturation value') runCommandClient('robot.admBF_dqSaturation.sin.value = [0.0, 0.0, 0.01, 0.0, 0.0, 0.0]') input("Wait before dumping the data") runCommandClient('dump_tracer(robot.tracer)')
[ 7061, 6, 14402, 3625, 6178, 47912, 1630, 7061, 6, 198, 6738, 264, 313, 62, 39240, 418, 62, 20427, 13, 26791, 13, 5143, 62, 9288, 62, 26791, 1330, 1057, 62, 701, 62, 9948, 571, 1358, 11, 1057, 62, 9288, 11, 1057, 21575, 11792, 198, ...
2.616915
201
import os from tendermint.db import VanillaDB from tendermint.utils import home_dir
[ 11748, 28686, 198, 198, 6738, 15403, 34289, 13, 9945, 1330, 33897, 11012, 198, 6738, 15403, 34289, 13, 26791, 1330, 1363, 62, 15908, 198 ]
3.695652
23
from django.test import TestCase from django.test import Client
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 9288, 1330, 20985, 628 ]
3.823529
17
# # Modified by Peize Sun # Contact: sunpeize@foxmail.com # # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ OneNet Transformer class. Copy-paste from torch.nn.Transformer with modifications: * positional encodings are passed in MHattention * extra LN at the end of encoder is removed * decoder returns a stack of activations from all decoding layers """ import copy import math from typing import Optional, List import torch from torch import nn, Tensor import torch.nn.functional as F from detectron2.modeling.poolers import ROIPooler, cat from detectron2.structures import Boxes from .deconv import CenternetDeconv def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
[ 2, 198, 2, 40499, 416, 2631, 1096, 3825, 198, 2, 14039, 25, 4252, 431, 1096, 31, 12792, 4529, 13, 785, 198, 2, 198, 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 6923, 33876, 198, 37811, 198, 3198, 7934, 3...
3.13099
313
"""Various utility functions. .. todo:: Reorganize this package in a more meaningful way. """ from __future__ import print_function from __future__ import absolute_import # from builtins import str # from builtins import range import torch from torch.nn.parameter import Parameter from torch.autograd import Variable from .libraries.modules.stn_nd import STN_ND_BCXYZ from .data_wrapper import AdaptVal from .data_wrapper import MyTensor from . import smoother_factory as sf from .data_wrapper import USE_CUDA import numpy as np from . import finite_differences as fd import torch.nn as nn import torch.nn.init as init from . import module_parameters as pars from .spline_interpolation import SplineInterpolation_ND_BCXYZ import os try: from .libraries.functions.nn_interpolation import get_nn_interpolation except ImportError: print('WARNING: nn_interpolation could not be imported (only supported in CUDA at the moment). ' 'Some functionality may not be available.') def my_hasnan(x): """Check if any input elements are NaNs. :param x: numpy array :return: True if NaNs are present, False else """ return (x != x).any() def combine_dict(d1,d2): """Creates a dictionary which has entries from both of them. :param d1: dictionary 1 :param d2: dictionary 2 :return: resulting dictionary """ d = d1.copy() d.update(d2) return d def get_parameter_list_from_parameter_dict(pd): """Takes a dictionary which contains key value pairs for model parameters and converts it into a list of parameters that can be used as an input to an optimizer. :param pd: parameter dictionary :return: list of parameters """ pl = [] for key in pd: pl.append(pd[key]) return pl def get_parameter_list_and_par_to_name_dict_from_parameter_dict(pd): """Same as get_parameter_list_from_parameter_dict; but also returns a dictionary which keeps track of the keys based on memory id. :param pd: parameter dictionary :return: tuple of (parameter_list, name_dictionary) """ par_to_name_dict = dict() pl = [] for key in pd: pl.append(pd[key]) par_to_name_dict[pd[key]] = key return pl, par_to_name_dict def lift_to_dimension(A, dim): """Creates a view of A of dimension dim (by adding dummy dimensions if necessary). :param A: numpy array :param dim: desired dimension of view :return: returns view of A of appropriate dimension """ current_dim = len(A.shape) if current_dim > dim: raise ValueError('Can only add dimensions, but not remove them') if current_dim == dim: return A else: return A.reshape([1]*(dim-current_dim)+list(A.shape)) def get_dim_of_affine_transform(Ab): """Returns the number of dimensions corresponding to an affine transformation of the form y=Ax+b stored in a column vector. For A =[a1,a2,a3], the parameter vector is simply [a1;a2;a3;b], i.e., all columns stacked on top of each other. :param Ab: parameter vector :return: dimensionality of transform (1,2,or 3) """ nr = len(Ab) if nr==2: return 1 elif nr==6: return 2 elif nr==12: return 3 else: raise ValueError('Only supports dimensions 1, 2, and 3.') def set_affine_transform_to_identity(Ab): """Sets the affine transformation as given by the column vector Ab to the identity transform. :param Ab: Affine parameter vector (will be overwritten with the identity transform) :return: """ dim = get_dim_of_affine_transform(Ab) if dim==1: Ab.zero_() Ab[0]=1. elif dim==2: Ab.zero_() Ab[0]=1. Ab[3]=1. elif dim==3: Ab.zero_() Ab[0]=1. Ab[4]=1. Ab[8]=1. else: raise ValueError('Only supports dimensions 1, 2, and 3.') def set_affine_transform_to_identity_multiN(Ab): """Set the affine transforms to the identity (in the case of arbitrary batch size). :param Ab: Parameter vectors B x pars (batch size x param. vector); will be overwritten with identity trans. :return: """ sz = Ab.size() nr_of_images = sz[0] for nrI in range(nr_of_images): set_affine_transform_to_identity(Ab[nrI, :]) def get_inverse_affine_param(Ab): """Computes inverse of affine transformation. Formally: C(Ax+b)+d = CAx+Cb+d = x; C = inv(A), d = -Cb :param Ab: B x pars (batch size x param. vector) :return: Inverse of affine parameters """ dim =0 if Ab.shape[1] == 2: dim = 1 elif Ab.shape[1] == 6: dim = 2 elif Ab.shape[1] == 12: dim = 3 if dim not in [1, 2, 3]: raise ValueError('Only supports dimensions 1, 2, and 3.') Ab = Ab.view(Ab.shape[0], dim+1, dim).transpose(1,2) Ab_inv = torch.zeros_like(Ab) for n in range(Ab.shape[0]): tm_inv = torch.inverse(Ab[n, :, :dim]) Ab_inv[n, :, :dim] = tm_inv Ab_inv[n, :, dim] = - torch.matmul(tm_inv, Ab[n,:,dim]) inv_affine_param = Ab_inv.transpose(1, 2).contiguous().view(Ab.shape[0], -1) return inv_affine_param def update_affine_param(Ab, Cd): """Update affine parameters. Formally: C(Ax+b)+d = CAx+Cb+d :param Ab: B x pars (batch size x param. vector) :return: Updated affine parameters """ dim = 0 if Ab.shape[1]==2: dim = 1 elif Ab.shape[1]==6: dim = 2 elif Ab.shape[1]==12: dim = 3 if dim not in [1, 2, 3]: raise ValueError('Only supports dimensions 1, 2, and 3.') Ab = Ab.view(Ab.shape[0], dim+1, dim).transpose(1, 2) Cd = Cd.view(Cd.shape[0], dim+1, dim).transpose(1, 2) updated_param = torch.zeros_like(Ab) for n in range(Ab.shape[0]): tm_param = torch.matmul(Cd[n,:,:dim],Ab[n,:,:dim]) updated_param[n,:,:dim] = tm_param updated_param[n,:,dim] = torch.matmul(Cd[n,:,:dim], Ab[n,:,dim]) +Cd[n,:,dim] updated_param = updated_param.transpose(1,2).contiguous().view(Ab.shape[0],-1) return updated_param def apply_affine_transform_to_map(Ab,phi): """Applies an affine transform to a map. :param Ab: affine transform parameter column vector :param phi: map; format nrCxXxYxZ (nrC corresponds to dimension) :return: returns transformed map """ sz = phi.size() dim = len(sz) - 1 if dim not in [1,2,3]: raise ValueError('Only supports dimensions 1, 2, and 3.') phiR = MyTensor(sz).zero_().type_as(phi) if dim == 1: phiR = phi * Ab[0] + Ab[1] elif dim == 2: phiR[0, ...] = Ab[0] * phi[0, ...] + Ab[2] * phi[1, ...] + Ab[4] # a_11x+a_21y+b1 phiR[1, ...] = Ab[1] * phi[0, ...] + Ab[3] * phi[1, ...] + Ab[5] # a_12x+a_22y+b2 elif dim == 3: phiR[0, ...] = Ab[0] * phi[0, ...] + Ab[3] * phi[1, ...] + Ab[6] * phi[2, ...] + Ab[9] phiR[1, ...] = Ab[1] * phi[0, ...] + Ab[4] * phi[1, ...] + Ab[7] * phi[2, ...] + Ab[10] phiR[2, ...] = Ab[2] * phi[0, ...] + Ab[5] * phi[1, ...] + Ab[8] * phi[2, ...] + Ab[11] else: raise ValueError('Only supports dimensions 1, 2, and 3.') return phiR def apply_affine_transform_to_map_multiNC(Ab,phi): """Applies an affine transform to maps (for arbitrary batch size). :param Ab: affine transform parameter column vectors (batch size x param. vector) :param phi: maps; format batchxnrCxXxYxZ (nrC corresponds to dimension) :return: returns transformed maps """ sz = phi.size() dim = get_dim_of_affine_transform(Ab[0,:]) nr_of_images = Ab.size()[0] if nr_of_images != sz[0]: raise ValueError('Incompatible number of affine transforms') if dim != len(sz)-2: raise ValueError('Incompatible number of affine transforms') phiR = MyTensor(sz).zero_().type_as(phi) for nrI in range(nr_of_images): phiR[nrI, ...] = apply_affine_transform_to_map(Ab[nrI, :], phi[nrI, ...]) return phiR def compute_normalized_gaussian(X, mu, sig): """Computes a normalized Gaussian. :param X: map with coordinates at which to evaluate :param mu: array indicating the mean :param sig: array indicating the standard deviations for the different dimensions :return: Normalized Gaussian evaluated at coordinates in X Example:: >>> mu, sig = [1,1], [1,1] >>> X = [0,0] >>> print(compute_normalized_gaussian(X, mu, sig) """ dim = len(mu) if dim == 1: g = np.exp(-np.power(X[0, :] - mu[0], 2.)/(2*np.power(sig[0], 2.))) g = g/g.sum() return g elif dim == 2: g = np.exp(-np.power(X[0,:,:]-mu[0],2.)/(2*np.power(sig[0],2.)) - np.power(X[1,:, :] - mu[1], 2.) / (2 * np.power(sig[1], 2.))) g = g/g.sum() return g elif dim == 3: g = np.exp(-np.power(X[0,:, :, :] - mu[0], 2.) / (2 * np.power(sig[0], 2.)) -np.power(X[1,:, :, :] - mu[1], 2.) / (2 * np.power(sig[1], 2.)) -np.power(X[2,:, :, :] - mu[2], 2.) / (2 * np.power(sig[2], 2.))) g = g / g.sum() return g else: raise ValueError('Can only compute Gaussians in dimensions 1-3') def compute_warped_image(I0, phi, spacing, spline_order, zero_boundary=False, use_01_input=True): """Warps image. :param I0: image to warp, image size XxYxZ :param phi: map for the warping, size dimxXxYxZ :param spacing: image spacing [dx,dy,dz] :return: returns the warped image of size XxYxZ """ # implements this by creating a different view (effectively adding dimensions) Iw = compute_warped_image_multiNC(I0.view(torch.Size([1, 1] + list(I0.size()))), phi.view(torch.Size([1] + list(phi.size()))), spacing, spline_order, zero_boundary, use_01_input) return Iw.view(I0.size()) def compute_warped_image_multiNC(I0, phi, spacing, spline_order, zero_boundary=False, use_01_input=True): """Warps image. :param I0: image to warp, image size BxCxXxYxZ :param phi: map for the warping, size BxdimxXxYxZ :param spacing: image spacing [dx,dy,dz] :return: returns the warped image of size BxCxXxYxZ """ dim = I0.dim()-2 if dim == 1: return _compute_warped_image_multiNC_1d(I0, phi, spacing, spline_order,zero_boundary,use_01_input=use_01_input) elif dim == 2: return _compute_warped_image_multiNC_2d(I0, phi, spacing, spline_order,zero_boundary,use_01_input=use_01_input) elif dim == 3: return _compute_warped_image_multiNC_3d(I0, phi, spacing, spline_order,zero_boundary,use_01_input=use_01_input) else: raise ValueError('Images can only be warped in dimensions 1 to 3') def _get_low_res_spacing_from_spacing(spacing, sz, lowResSize): """Computes spacing for the low-res parametrization from image spacing. :param spacing: image spacing :param sz: size of image :param lowResSize: size of low re parameterization :return: returns spacing of low res parameterization """ #todo: check that this is the correct way of doing it return spacing * (np.array(sz[2::])-1) / (np.array(lowResSize[2::])-1) def _get_low_res_size_from_size(sz, factor): """Returns the corresponding low-res size from a (high-res) sz. :param sz: size (high-res) :param factor: low-res factor (needs to be <1) :return: low res size """ if (factor is None) or (factor >= 1): print('WARNING: Could not compute low_res_size as factor was ' + str(factor)) return np.array(sz) else: low_res_sz = np.array(sz) low_res_sz[2::] = (np.ceil((np.array(sz[2::]) * factor))).astype('int16') return low_res_sz def compute_vector_momentum_from_scalar_momentum_multiNC(lam, I, sz, spacing): """Computes the vector momentum from the scalar momentum: :math:`m=\\lambda\\nabla I`. :param lam: scalar momentum, BxCxXxYxZ :param I: image, BxCxXxYxZ :param sz: size of image :param spacing: spacing of image :return: returns the vector momentum """ nrOfI = sz[0] # number of images m = create_ND_vector_field_variable_multiN(sz[2::], nrOfI) # attention that the second dimension here is image dim, not nrOfC nrOfC = sz[1] for c in range(nrOfC): # loop over all the channels and add the results m = m + compute_vector_momentum_from_scalar_momentum_multiN(lam[:, c, ...], I[:, c, ...], nrOfI, sz[2::], spacing) return m def compute_vector_momentum_from_scalar_momentum_multiN(lam, I, nrOfI, sz, spacing): """Computes the vector momentum from the scalar momentum: :math:`m=\\lambda\\nabla I`. :param lam: scalar momentum, batchxXxYxZ :param I: image, batchXxYxZ :param sz: size of image :param spacing: spacing of image :return: returns the vector momentum """ fdt = fd.FD_torch(spacing) dim = len(sz) m = create_ND_vector_field_variable_multiN(sz, nrOfI) if dim == 1: m[:, 0, :] = fdt.dXc(I)*lam elif dim == 2: m[:, 0, :, :] = fdt.dXc(I)*lam m[:, 1, :, :] = fdt.dYc(I)*lam elif dim == 3: m[:, 0, :, :, :] = fdt.dXc(I)*lam m[:, 1, :, :, :] = fdt.dYc(I)*lam m[:, 2, :, :, :] = fdt.dZc(I)*lam else: raise ValueError('Can only convert scalar to vector momentum in dimensions 1-3') return m def create_ND_vector_field_variable_multiN(sz, nr_of_images=1): """ Create vector field torch Variable of given size :param sz: just the spatial sizes (e.g., [5] in 1D, [5,10] in 2D, [5,10,10] in 3D) :param nrOfI: number of images :return: returns vector field of size nrOfIxdimxXxYxZ """ dim = len(sz) csz = np.array(sz) # just to make sure it is a numpy array csz = np.array([nr_of_images, dim]+list(csz)) return MyTensor(*(csz.tolist())).normal_(0., 1e-7) def create_ND_vector_field_variable(sz): """Create vector field torch Variable of given size. :param sz: just the spatial sizes (e.g., [5] in 1D, [5,10] in 2D, [5,10,10] in 3D) :return: returns vector field of size dimxXxYxZ """ dim = len(sz) csz = np.array(sz) # just to make sure it is a numpy array csz = np.array([dim]+list(csz)) return MyTensor(*(csz.tolist())).normal_(0.,1e-7) def create_vector_parameter(nr_of_elements): """Creates a vector parameters with a specified number of elements. :param nr_of_elements: number of vector elements :return: returns the parameter vector """ return Parameter(MyTensor(nr_of_elements).normal_(0., 1e-7)) def create_ND_vector_field_parameter_multiN(sz, nrOfI=1,get_field_from_external_network=False): """Create vector field torch Parameter of given size. :param sz: just the spatial sizes (e.g., [5] in 1D, [5,10] in 2D, [5,10,10] in 3D) :param nrOfI: number of images :return: returns vector field of size nrOfIxdimxXxYxZ """ dim = len(sz) csz = np.array(sz) # just to make sure it is a numpy array csz = np.array([nrOfI, dim]+list(csz)) if get_field_from_external_network: tmp = MyTensor(*(csz.tolist())).normal_(0.,1e-7) tmp.requires_grad = True else: tmp = Parameter(MyTensor(*(csz.tolist())).normal_(0.,1e-7)) return tmp def create_local_filter_weights_parameter_multiN(sz,gaussian_std_weights, nrOfI=1,sched='w_K_w',get_preweight_from_network=False): """ Create vector field torch Parameter of given size :param sz: just the spatial sizes (e.g., [5] in 1D, [5,10] in 2D, [5,10,10] in 3D) :param nrOfI: number of images :return: returns vector field of size nrOfIxdimxXxYxZ """ nr_of_mg_weights = len(gaussian_std_weights) csz = np.array(sz) # just to make sure it is a numpy array csz = np.array([nrOfI,nr_of_mg_weights]+list(csz)) weights = torch.empty(*csz) # set the default if sched =='w_K_w': gaussian_std_weights = [torch.sqrt(std_w) for std_w in gaussian_std_weights] for g in range(nr_of_mg_weights): weights[:, g, ...] = gaussian_std_weights[g] tmp = AdaptVal(weights) if get_preweight_from_network: tmp.requires_grad = True else: tmp = Parameter(tmp) return tmp def create_ND_scalar_field_parameter_multiNC(sz, nrOfI=1, nrOfC=1): """ Create vector field torch Parameter of given size :param sz: just the spatial sizes (e.g., [5] in 1D, [5,10] in 2D, [5,10,10] in 3D) :param nrOfI: number of images :param nrOfC: number of channels :return: returns vector field of size nrOfIxnrOfCxXxYxZ """ csz = np.array(sz) # just to make sure it is a numpy array csz = np.array([nrOfI,nrOfC]+list(csz)) return Parameter(MyTensor(*(csz.tolist())).normal_(0.,1e-7)) def centered_identity_map_multiN(sz, spacing, dtype='float32'): """ Create a centered identity map (shifted so it is centered around 0) :param sz: size of an image in BxCxXxYxZ format :param spacing: list with spacing information [sx,sy,sz] :param dtype: numpy data-type ('float32', 'float64', ...) :return: returns the identity map """ dim = len(sz) - 2 nrOfI = sz[0] if dim == 1: id = np.zeros([nrOfI, 1, sz[2]], dtype=dtype) elif dim == 2: id = np.zeros([nrOfI, 2, sz[2], sz[3]], dtype=dtype) elif dim == 3: id = np.zeros([nrOfI, 3, sz[2], sz[3], sz[4]], dtype=dtype) else: raise ValueError('Only dimensions 1-3 are currently supported for the identity map') for n in range(nrOfI): id[n, ...] = centered_identity_map(sz[2::], spacing,dtype=dtype) return id def identity_map_multiN(sz,spacing,dtype='float32'): """ Create an identity map :param sz: size of an image in BxCxXxYxZ format :param spacing: list with spacing information [sx,sy,sz] :param dtype: numpy data-type ('float32', 'float64', ...) :return: returns the identity map """ dim = len(sz)-2 nrOfI = int(sz[0]) if dim == 1: id = np.zeros([nrOfI,1,sz[2]],dtype=dtype) elif dim == 2: id = np.zeros([nrOfI,2,sz[2],sz[3]],dtype=dtype) elif dim == 3: id = np.zeros([nrOfI,3,sz[2],sz[3],sz[4]],dtype=dtype) else: raise ValueError('Only dimensions 1-3 are currently supported for the identity map') for n in range(nrOfI): id[n,...] = identity_map(sz[2::],spacing,dtype=dtype) return id def centered_identity_map(sz, spacing, dtype='float32'): """ Returns a centered identity map (with 0 in the middle) if the sz is odd Otherwise shifts everything by 0.5*spacing :param sz: just the spatial dimensions, i.e., XxYxZ :param spacing: list with spacing information [sx,sy,sz] :param dtype: numpy data-type ('float32', 'float64', ...) :return: returns the identity map of dimension dimxXxYxZ """ dim = len(sz) if dim == 1: id = np.mgrid[0:sz[0]] elif dim == 2: id = np.mgrid[0:sz[0], 0:sz[1]] elif dim == 3: id = np.mgrid[0:sz[0], 0:sz[1], 0:sz[2]] else: raise ValueError('Only dimensions 1-3 are currently supported for the identity map') # now get it into range [0,(sz-1)*spacing]^d id = np.array(id.astype(dtype)) if dim == 1: id = id.reshape(1, sz[0]) # add a dummy first index for d in range(dim): id[d] *= spacing[d] if sz[d]%2==0: #even id[d] -= spacing[d]*(sz[d]//2) else: #odd id[d] -= spacing[d]*((sz[d]+1)//2) # and now store it in a dim+1 array if dim == 1: idnp = np.zeros([1, sz[0]], dtype=dtype) idnp[0, :] = id[0] elif dim == 2: idnp = np.zeros([2, sz[0], sz[1]], dtype=dtype) idnp[0, :, :] = id[0] idnp[1, :, :] = id[1] elif dim == 3: idnp = np.zeros([3, sz[0], sz[1], sz[2]], dtype=dtype) idnp[0, :, :, :] = id[0] idnp[1, :, :, :] = id[1] idnp[2, :, :, :] = id[2] else: raise ValueError('Only dimensions 1-3 are currently supported for the centered identity map') return idnp # # def centered_min_normalized_identity_map(sz, spacing, dtype='float32'): # """ # Returns a centered identity map (with 0 in the middle) if the sz is odd # Otherwise shifts everything by 0.5*spacing # # :param sz: just the spatial dimensions, i.e., XxYxZ # :param spacing: list with spacing information [sx,sy,sz] # :param dtype: numpy data-type ('float32', 'float64', ...) # :return: returns the identity map of dimension dimxXxYxZ # """ # dim = len(sz) # if dim == 1: # id = np.mgrid[0:sz[0]] # elif dim == 2: # id = np.mgrid[0:sz[0], 0:sz[1]] # elif dim == 3: # id = np.mgrid[0:sz[0], 0:sz[1], 0:sz[2]] # else: # raise ValueError('Only dimensions 1-3 are currently supported for the identity map') # # min_spacing = np.min(spacing) # spacing_ratio = spacing/min_spacing # # # # now get it into range [0,(sz-1)*spacing]^d # id = np.array(id.astype(dtype)) # if dim == 1: # id = id.reshape(1, sz[0]) # add a dummy first index # # for d in range(dim): # id[d] *= spacing[d] # if sz[d]%2==0: # #even # id[d] -= spacing[d]*(sz[d]//2) # else: # #odd # id[d] -= spacing[d]*((sz[d]+1)//2) # # # and now store it in a dim+1 array and rescale by the ratio # if dim == 1: # idnp = np.zeros([1, sz[0]], dtype=dtype) # idnp[0, :] = id[0] * spacing_ratio[0] # elif dim == 2: # idnp = np.zeros([2, sz[0], sz[1]], dtype=dtype) # idnp[0, :, :] = id[0] * spacing_ratio[0] # idnp[1, :, :] = id[1] * spacing_ratio[1] # elif dim == 3: # idnp = np.zeros([3, sz[0], sz[1], sz[2]], dtype=dtype) # idnp[0, :, :, :] = id[0] * spacing_ratio[0] # idnp[1, :, :, :] = id[1] * spacing_ratio[1] # idnp[2, :, :, :] = id[2] * spacing_ratio[2] # else: # raise ValueError('Only dimensions 1-3 are currently supported for the centered identity map') # # return idnp # # def tranfrom_var_list_into_min_normalized_space(var_list,spacing,do_transform=True): # if do_transform: # min_spacing = np.min(spacing) # spacing_ratio =min_spacing/spacing # dim = spacing.size # spacing_ratio_t = AdaptVal(torch.Tensor(spacing_ratio)) # sp_sz = [1]+[dim] +[1]*dim # spacing_ratio_t = spacing_ratio_t.view(*sp_sz) # new_var_list = [var*spacing_ratio_t if var is not None else None for var in var_list] # else: # new_var_list = var_list # return new_var_list # def recover_var_list_from_min_normalized_space(var_list,spacing,do_transform=True): # if do_transform: # min_spacing = np.min(spacing) # spacing_ratio =spacing/min_spacing # dim = spacing.size # spacing_ratio_t = AdaptVal(torch.Tensor(spacing_ratio)) # sp_sz = [1]+[dim] +[1]*dim # spacing_ratio_t = spacing_ratio_t.view(*sp_sz) # new_var_list = [var*spacing_ratio_t if var is not None else None for var in var_list] # else: # new_var_list = var_list # return new_var_list # def identity_map(sz,spacing,dtype='float32'): """ Returns an identity map. :param sz: just the spatial dimensions, i.e., XxYxZ :param spacing: list with spacing information [sx,sy,sz] :param dtype: numpy data-type ('float32', 'float64', ...) :return: returns the identity map of dimension dimxXxYxZ """ dim = len(sz) if dim==1: id = np.mgrid[0:sz[0]] elif dim==2: id = np.mgrid[0:sz[0],0:sz[1]] elif dim==3: id = np.mgrid[0:sz[0],0:sz[1],0:sz[2]] else: raise ValueError('Only dimensions 1-3 are currently supported for the identity map') # now get it into range [0,(sz-1)*spacing]^d id = np.array( id.astype(dtype) ) if dim==1: id = id.reshape(1,sz[0]) # add a dummy first index for d in range(dim): id[d]*=spacing[d] #id[d]*=2./(sz[d]-1) #id[d]-=1. # and now store it in a dim+1 array if dim==1: idnp = np.zeros([1, sz[0]], dtype=dtype) idnp[0,:] = id[0] elif dim==2: idnp = np.zeros([2, sz[0], sz[1]], dtype=dtype) idnp[0,:, :] = id[0] idnp[1,:, :] = id[1] elif dim==3: idnp = np.zeros([3,sz[0], sz[1], sz[2]], dtype=dtype) idnp[0,:, :, :] = id[0] idnp[1,:, :, :] = id[1] idnp[2,:, :, :] = id[2] else: raise ValueError('Only dimensions 1-3 are currently supported for the identity map') return idnp def omt_boundary_weight_mask(img_sz,spacing,mask_range=5,mask_value=5,smoother_std =0.05): """generate a smooth weight mask for the omt """ dim = len(img_sz) mask_sz = [1,1]+ list(img_sz) mask = AdaptVal(torch.ones(*mask_sz))*mask_value if dim ==2: mask[:,:,mask_range:-mask_range,mask_range:-mask_range]=1 elif dim==3: mask[:,:,mask_range:-mask_range,mask_range:-mask_range,mask_range:-mask_range ]=1 sm = get_single_gaussian_smoother(smoother_std,img_sz,spacing) mask = sm.smooth(mask) return mask.detach() def momentum_boundary_weight_mask(img_sz,spacing,mask_range=5,smoother_std =0.05,pow=2): """generate a smooth weight mask for the omt """ dim = len(img_sz) mask_sz = [1,1]+ list(img_sz) mask = AdaptVal(torch.zeros(*mask_sz)) if dim ==2: mask[:,:,mask_range:-mask_range,mask_range:-mask_range]=1 elif dim==3: mask[:,:,mask_range:-mask_range,mask_range:-mask_range,mask_range:-mask_range ]=1 sm = get_single_gaussian_smoother(smoother_std,img_sz,spacing) mask = sm.smooth(mask) if pow ==2: mask = mask**2 if pow ==3: mask = mask*mask*mask return mask # def compute_omt_const(stds,param,dim): # omt_power = param['forward_model']['smoother']['omt_power'] # omt_weight_penalty = param['forward_model']['smoother']['omt_weight_penalty'] # min_std = torch.min(stds) # max_std = torch.max(stds) # omt_const = torch.abs(torch.log(max_std/stds))**omt_power # omt_const = omt_const/(torch.abs(torch.log(max_std / min_std)) ** omt_power) # omt_const = omt_const*omt_weight_penalty/(EV.reg_factor_in_mermaid*2) # sz = [1]+ [len(stds)] +[1]*(dim+1) # return omt_const.view(*sz) def t2np(v): """ Takes a torch array and returns it as a numpy array on the cpu :param v: torch array :return: numpy array """ return (v.detach()).cpu().numpy() def cxyz_to_xyzc( v ): """ Takes a torch array and returns it as a numpy array on the cpu :param v: torch array :return: numpy array """ dim = len(v.shape)-2 if dim ==2: v = v.permute(0,2,3,1) if dim ==3: v = v.permute(0,2,3,4,1) return v def checkNan(x): """" input should be list of Variable """ return [len(np.argwhere(np.isnan(elem.detach().cpu().numpy()))) for elem in x] def get_resampled_image(I, spacing, desiredSize, spline_order=1, zero_boundary=False, identity_map=None): """ :param I: B C X Y Z :param spacing: spx spy spz :param desiredSize: B C X Y Z :param spline_order: :param zero_boundary: :param identity_map: :return: """ if spacing is None: img_sz = I.shape[2:] spacing = 1. / (np.array(img_sz) - 1) if identity_map is not None: # todo will remove, currently fix for symmetric training if I.shape[0] != identity_map.shape[0]: n_batch = I.shape[0] desiredSize = desiredSize.copy() desiredSize[0] = n_batch identity_map = identity_map[:n_batch] resampled, new_spacing = resample_image(I, spacing, desiredSize, spline_order=spline_order, zero_boundary=zero_boundary, identity_map=identity_map) return resampled def resample_image(I, spacing, desiredSize, spline_order=1, zero_boundary=False, identity_map=None): """ Resample an image to a given desired size :param I: Input image (expected to be of BxCxXxYxZ format) :param spacing: array describing the spatial spacing :param desiredSize: array for the desired size (excluding B and C, i.e, 1 entry for 1D, 2 for 2D, and 3 for 3D) :return: returns a tuple: the downsampled image, the new spacing after downsampling """ desiredSize = desiredSize[2:] is_numpy = False if not isinstance(I, torch.Tensor): I = torch.Tensor(I) is_numpy = True sz = np.array(list(I.size())) # check that the batch size and the number of channels is the same nrOfI = sz[0] nrOfC = sz[1] desiredSizeNC = np.array([nrOfI, nrOfC] + list(desiredSize)) newspacing = spacing * ((sz[2::].astype('float') - 1.) / ( desiredSizeNC[2::].astype('float') - 1.)) ########################################### if identity_map is not None: idDes = identity_map else: idDes = AdaptVal(torch.from_numpy(identity_map_multiN(desiredSizeNC, newspacing))) # now use this map for resampling ID = compute_warped_image_multiNC(I, idDes, newspacing, spline_order, zero_boundary) return ID if not is_numpy else ID.numpy(), newspacing def get_res_size_from_size(sz, factor): """ Returns the corresponding low-res size from a (high-res) sz :param sz: size (high-res) :param factor: low-res factor (needs to be <1) :return: low res size """ if (factor is None): print('WARNING: Could not compute low_res_size as factor was ' + str(factor)) return sz else: lowResSize = np.array(sz) if not isinstance(factor, list): lowResSize[2::] = (np.ceil((np.array(sz[2:]) * factor))).astype('int16') else: lowResSize[2::] = (np.ceil((np.array(sz[2:]) * np.array(factor)))).astype('int16') if lowResSize[-1] % 2 != 0: lowResSize[-1] -= 1 print( '\n\nWARNING: forcing last dimension to be even: fix properly in the Fourier transform later!\n\n') return lowResSize def get_res_spacing_from_spacing(spacing, sz, lowResSize): """ Computes spacing for the low-res parameterization from image spacing :param spacing: image spacing :param sz: size of image :param lowResSize: size of low re parameterization :return: returns spacing of low res parameterization """ # todo: check that this is the correct way of doing it return spacing * (np.array(sz[2::]) - 1) / (np.array(lowResSize[2::]) - 1) ########################################## Adaptive Net ###################################################3 def space_normal(tensors, std=0.1): """ space normalize for the net kernel :param tensor: :param mean: :param std: :return: """ if isinstance(tensors, Variable): space_normal(tensors.data, std=std) return tensors for n in range(tensors.size()[0]): for c in range(tensors.size()[1]): dim = tensors[n][c].dim() sz = tensors[n][c].size() mus = np.zeros(dim) stds = std * np.ones(dim) print('WARNING: What should the spacing be here? Needed for new identity map code') raise ValueError('Double check the spacing here before running this code') spacing = np.ones(dim) centered_id = centered_identity_map(sz,spacing) g = compute_normalized_gaussian(centered_id, mus, stds) tensors[n,c] = torch.from_numpy(g)
[ 37811, 40009, 10361, 5499, 13, 198, 198, 492, 284, 4598, 3712, 198, 220, 220, 220, 797, 9971, 1096, 428, 5301, 287, 257, 517, 11570, 835, 13, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834...
2.17805
14,788
""" ================================== Reading and writing an evoked file ================================== This script shows how to read and write evoked datasets. """ # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) from mne import read_evokeds from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname = data_path + '/MEG/sample/sample_audvis-ave.fif' # Reading condition = 'Left Auditory' evoked = read_evokeds(fname, condition=condition, baseline=(None, 0), proj=True) ############################################################################### # Show result as a butterfly plot: # By using exclude=[] bad channels are not excluded and are shown in red evoked.plot(exclude=[], time_unit='s') # Show result as a 2D image (x: time, y: channels, color: amplitude) evoked.plot_image(exclude=[], time_unit='s') ############################################################################### # Use :func:`mne.Evoked.save` or :func:`mne.write_evokeds` to write the evoked # responses to a file.
[ 37811, 198, 10052, 855, 198, 36120, 290, 3597, 281, 819, 6545, 2393, 198, 10052, 855, 198, 198, 1212, 4226, 2523, 703, 284, 1100, 290, 3551, 819, 6545, 40522, 13, 198, 37811, 198, 2, 6434, 25, 21000, 260, 20159, 3319, 1279, 1000, 87, ...
3.292169
332
# A part of NonVisual Desktop Access (NVDA) # Copyright (C) 2021 NV Access Limited # This file is covered by the GNU General Public License. # See the file COPYING for more details. from . import wxMonkeyPatches applyWxMonkeyPatches = wxMonkeyPatches.apply
[ 2, 317, 636, 286, 8504, 36259, 27850, 8798, 357, 27159, 5631, 8, 201, 198, 2, 15069, 357, 34, 8, 33448, 23973, 8798, 15302, 201, 198, 2, 770, 2393, 318, 5017, 416, 262, 22961, 3611, 5094, 13789, 13, 201, 198, 2, 4091, 262, 2393, 2...
3.079545
88
from .common import InfoExtractor from ..compat import compat_str from ..utils import ( ExtractorError, int_or_none, float_or_none, smuggle_url, str_or_none, try_get, unified_strdate, unified_timestamp, )
[ 6738, 764, 11321, 1330, 14151, 11627, 40450, 198, 6738, 11485, 5589, 265, 1330, 8330, 62, 2536, 198, 6738, 11485, 26791, 1330, 357, 198, 220, 220, 220, 29677, 273, 12331, 11, 198, 220, 220, 220, 493, 62, 273, 62, 23108, 11, 198, 220, ...
2.428571
98
import torch from torch.autograd import Variable from torch.autograd.function import Function, once_differentiable import apex_C
[ 11748, 28034, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 6738, 28034, 13, 2306, 519, 6335, 13, 8818, 1330, 15553, 11, 1752, 62, 39799, 3379, 198, 11748, 40167, 62, 34, 198 ]
3.909091
33
""" Module holds all stuff regarding Grinder tool usage Copyright 2015 BlazeMeter Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import re import time from bzt import TaurusConfigError, ToolError from bzt.engine import ScenarioExecutor, FileLister, HavingInstallableTools, SelfDiagnosable from bzt.modules.aggregator import ConsolidatingAggregator, ResultsReader from bzt.modules.console import WidgetProvider, ExecutorWidget from bzt.modules.java import TaurusJavaHelper from bzt.requests_model import HTTPRequest from bzt.six import iteritems from bzt.utils import MirrorsManager, dehumanize_time, get_full_path, PythonGenerator, CALL_PROBLEMS from bzt.utils import unzip, RequiredTool, JavaVM, shutdown_process, TclLibrary, FileReader, RESOURCES_DIR
[ 37811, 198, 26796, 6622, 477, 3404, 5115, 1902, 5540, 2891, 8748, 198, 198, 15269, 1853, 33965, 44, 2357, 3457, 13, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, ...
3.609195
348
import getopt import sys comment = ('#' + sys.argv[1]).encode() opts, args = getopt.getopt(sys.argv[2:], 'cf:o:xy') optstring = '' length = len(comment) for opt, arg in opts: if opt == '-o': out = arg elif opt not in ('-f', '-K'): optstring = optstring + ' ' + opt infile = open(args[0], 'rb') outfile = open(out, 'wb') outfile.write((optstring + "\n").encode()) for l in infile.readlines(): if l[:length] != comment: outfile.write(l) sys.exit(0)
[ 11748, 651, 8738, 198, 11748, 25064, 198, 23893, 796, 19203, 2, 6, 1343, 25064, 13, 853, 85, 58, 16, 35944, 268, 8189, 3419, 198, 404, 912, 11, 26498, 796, 651, 8738, 13, 1136, 8738, 7, 17597, 13, 853, 85, 58, 17, 25, 4357, 705, ...
2.358586
198
import io import os import base64 from pathlib import Path from nbconvert import filters from pygments.formatters.latex import LatexFormatter from zen_knit import formattor from zen_knit.data_types import ChunkOption, ExecutedData, OrganizedChunk, OrganizedData from zen_knit.formattor.html_formatter import HTMLFormatter mime_extensions = {"image/png" : "png", "image/jpg" : "jpg"}
[ 11748, 33245, 198, 11748, 28686, 198, 11748, 2779, 2414, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 299, 65, 1102, 1851, 1330, 16628, 198, 6738, 12972, 11726, 13, 18982, 1010, 13, 17660, 87, 1330, 18319, 87, 8479, 1436, 198, 67...
2.677215
158
#!/usr/bin/env python # coding: utf-8 import sys import pybullet from qibullet.camera import * from qibullet.link import Link from qibullet.joint import Joint IS_VERSION_PYTHON_3 = sys.version_info[0] >= 3
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 25064, 198, 11748, 12972, 15065, 1616, 198, 6738, 10662, 571, 377, 1616, 13, 25695, 1330, 1635, 198, 6738, 10662, 571, 377, 1616, 13, ...
2.6125
80
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import pytest import json from kafkacli.formatter import Formatter sampleJson = json.loads('{"a":"s", "b":1}')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 12972, 9288, 198, 11748, 33918, 198, 6738, 479, 1878, 74, 330, 4528, 13, 687, 1436, 1330...
2.492754
69
from django import forms from .models import Application
[ 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 764, 27530, 1330, 15678 ]
4.75
12
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: protocolo.py # # Tests: vistprotocol unit test # # Mark C. Miller, Tue Jan 11 10:19:23 PST 2011 # ---------------------------------------------------------------------------- tapp = visit_bin_path("visitprotocol") res = sexe(tapp,ret_output=True) if res["return_code"] == 0: excode = 111 else: excode = 113 Exit(excode)
[ 2, 16529, 10541, 198, 2, 220, 42715, 1546, 25, 37862, 198, 2, 198, 2, 220, 6208, 8913, 25, 220, 8435, 78, 13, 9078, 198, 2, 198, 2, 220, 30307, 25, 220, 220, 220, 220, 220, 410, 396, 11235, 4668, 4326, 1332, 198, 2, 198, 2, 22...
3.416667
132
import libtcodpy as libtcod from random import randint nSquares = 30 nTiles = nSquares * 2 + 1 SCREEN_WIDTH = nTiles SCREEN_HEIGHT = nTiles libtcod.console_set_custom_font("cp437_12x12.png", libtcod.FONT_LAYOUT_ASCII_INROW) libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'pyMazeBacktrack', False, libtcod.RENDERER_OPENGL) black = libtcod.black white = libtcod.white Table = [[0 for i in range(nTiles)]for i in range(nTiles)] for x in range(nTiles): for y in range(nTiles): Table[x][y] = black libtcod.console_put_char_ex(None,x,y,219,Table[x][y],libtcod.white) libtcod.console_flush() Memory = [] CurrX = 1 CurrY = 1 Table[CurrX][CurrY] = white end = 0 while end == 0: while Possible(CurrX,CurrY,Table,nTiles): Dir = randint(1,4) while CheckDir(CurrX,CurrY,nTiles,Dir,Table) == 0: Dir = randint(1,4) if Dir == 1: Table[CurrX][CurrY - 1] = white CurrY -= 2 Table[CurrX][CurrY] = white elif Dir == 2: Table[CurrX + 1][CurrY] = white CurrX += 2 Table[CurrX][CurrY] = white elif Dir == 3: Table[CurrX][CurrY + 1] = white CurrY += 2 Table[CurrX][CurrY] = white elif Dir == 4: Table[CurrX - 1][CurrY] = white CurrX -= 2 Table[CurrX][CurrY] = white Memory.append(Dir) #print for x in range(nTiles): for y in range(nTiles): libtcod.console_put_char_ex(None,x,y,219,Table[x][y],libtcod.white) libtcod.console_flush() while Possible(CurrX,CurrY,Table,nTiles) == 0: MemorySize = len(Memory) Dir = Memory[MemorySize-1] if Dir == 1: CurrY += 2 elif Dir == 2: CurrX -= 2 elif Dir == 3: CurrY -= 2 elif Dir == 4: CurrX += 2 del Memory[MemorySize-1] if CurrX == 1 and CurrY == 1: end = 1 break #print for x in range(nTiles): for y in range(nTiles): libtcod.console_put_char_ex(None,x,y,219,Table[x][y],libtcod.white) libtcod.console_flush() libtcod.console_wait_for_keypress(True)
[ 11748, 9195, 83, 19815, 9078, 355, 9195, 83, 19815, 201, 198, 6738, 4738, 1330, 43720, 600, 201, 198, 201, 198, 77, 22266, 3565, 796, 1542, 201, 198, 77, 51, 2915, 796, 299, 22266, 3565, 1635, 362, 1343, 352, 201, 198, 201, 198, 617...
1.752562
1,366
# ###################################################################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance # # with the License. You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed # # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for # # the specific language governing permissions and limitations under the License. # # ###################################################################################################################### import pytest from shared.resource import ( DatasetGroup, Schema, Dataset, DatasetImportJob, Solution, SolutionVersion, Campaign, EventTracker, BatchSegmentJob, BatchInferenceJob, )
[ 2, 1303, 29113, 29113, 29113, 14468, 4242, 2, 198, 2, 220, 15069, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.956826
857
"""Auto-generated file, do not edit by hand. AG metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_AG = PhoneMetadata(id='AG', country_code=1, international_prefix='011', general_desc=PhoneNumberDesc(national_number_pattern='(?:268|[58]\\d\\d|900)\\d{7}', possible_length=(10,), possible_length_local_only=(7,)), fixed_line=PhoneNumberDesc(national_number_pattern='268(?:4(?:6[0-38]|84)|56[0-2])\\d{4}', example_number='2684601234', possible_length=(10,), possible_length_local_only=(7,)), mobile=PhoneNumberDesc(national_number_pattern='268(?:464|7(?:1[3-9]|[28]\\d|3[0246]|64|7[0-689]))\\d{4}', example_number='2684641234', possible_length=(10,), possible_length_local_only=(7,)), toll_free=PhoneNumberDesc(national_number_pattern='8(?:00|33|44|55|66|77|88)[2-9]\\d{6}', example_number='8002123456', possible_length=(10,)), premium_rate=PhoneNumberDesc(national_number_pattern='900[2-9]\\d{6}', example_number='9002123456', possible_length=(10,)), personal_number=PhoneNumberDesc(national_number_pattern='52(?:355[0-46-9]|4(?:5(?:2[024-9]|5[0-46-9])|60[1-9]|9(?:2[0-5]|49)))\\d{4}|52(?:3(?:[2-46-9][02-9]|5[02-46-9])|4(?:[2-478][02-9]|5[034]|6[2-9]|9[05-9])|7[2-4]\\d)\\d{5}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[1256]|33|44|66|77|88)[2-9]\\d{6}', example_number='5002345678', possible_length=(10,)), voip=PhoneNumberDesc(national_number_pattern='26848[01]\\d{4}', example_number='2684801234', possible_length=(10,), possible_length_local_only=(7,)), pager=PhoneNumberDesc(national_number_pattern='26840[69]\\d{4}', example_number='2684061234', possible_length=(10,), possible_length_local_only=(7,)), national_prefix='1', national_prefix_for_parsing='1|([457]\\d{6})$', national_prefix_transform_rule='268\\1', leading_digits='268', mobile_number_portable_region=True)
[ 37811, 27722, 12, 27568, 2393, 11, 466, 407, 4370, 416, 1021, 13, 13077, 20150, 37811, 198, 6738, 11485, 746, 261, 19261, 14706, 1330, 7913, 26227, 11, 14484, 15057, 24564, 11, 14484, 9171, 14706, 198, 198, 11909, 11651, 62, 47123, 2885, ...
2.361111
792
##################################################################### ## ## gradefiles-send.py ## ## Script to send grade files by email to enrolled students; the ## input grade file names should correspond to the user names of ## the students. ## ## from email.mime.text import MIMEText # For creating a message string. from subprocess import Popen, PIPE # For sending email on linux. import sys # For command line arguments. import os # For commands and file manipulation (walk, path, system). ##################################################################### ## Sending a simple email message. ## ##################################################################### ## Process the command line parameters. ## if len(sys.argv) == 6\ and (int(sys.argv[1][0:3]) in range(100,1000))\ and sys.argv[2] in ['Fall', 'Spring']\ and int(sys.argv[3]) in range(2000,2100): courseNumber = sys.argv[1] # Accepts course names like "591 X1." season = sys.argv[2] year = sys.argv[3] task = sys.argv[4] sender = sys.argv[5] else: print('\n Usage:\n\n % python gradefiles-send.py <###> <Fall|Spring> <YYYY> <task> <sender-username>\n') exit() ##################################################################### ## Check for list of files. ## if not os.path.exists('./data'): print('No folder "data" containing grade files found. Exiting.') exit() ##################################################################### ## Send the grade files. ## for curdir, dirs, files in os.walk('./data/'): for file in files: txt = open('./data/'+file, 'r').read() targets = file.split('.')[0].split("_") send(txt, courseNumber, task, sender, targets) print('Sent grade file to ' + str(targets) + '.') #eof
[ 29113, 29113, 4242, 2, 198, 2235, 220, 198, 2235, 9559, 16624, 12, 21280, 13, 9078, 198, 2235, 198, 2235, 220, 220, 12327, 284, 3758, 9559, 3696, 416, 3053, 284, 18724, 2444, 26, 262, 198, 2235, 220, 220, 5128, 9559, 2393, 3891, 815, ...
3.087931
580
import os import pickle import tensorflow as tf import wolframclient.serializers as wxf name = 'karras2018iclr-celebahq-1024x1024' file = open(name + '.pkl', 'rb') sess = tf.InteractiveSession() G, D, Gs = pickle.load(file) saver = tf.train.Saver() save_path = "./target/" + name + "/" model_name = 'model' if not os.path.exists(save_path): os.makedirs(save_path) save_path_full = os.path.join(save_path, model_name) saver.save(sess, save_path_full) ckpt = tf.train.get_checkpoint_state(save_path) reader = tf.train.NewCheckpointReader(ckpt.model_checkpoint_path) all_variables = list(reader.get_variable_to_shape_map().keys()) npy = dict(zip(all_variables, map(reader.get_tensor, all_variables))) wxf.export(npy, name + '.wxf', target_format='wxf') # Save as protobuf with tf.Session() as sess: tf.initialize_all_variables().run() output_graph_def = tf.graph_util.convert_variables_to_constants( sess=sess, input_graph_def=sess.graph_def, # output_node_names=['G_paper_1/images_out'] output_node_names=['G_paper_1/ToRGB_lod0/add'] ) with tf.gfile.GFile("./target/" + name + ".pb", "wb") as file: # file.write(output_graph_def.SerializeToString()) #
[ 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 17481, 859, 16366, 13, 46911, 11341, 355, 266, 26152, 198, 198, 3672, 796, 705, 74, 3258, 292, 7908, 291, 14050, 12, 49840, 47041, 80, 12, 35500...
2.392927
509
#!/usr/bin/env python import os import os.path import yaml import time import random import multiprocessing import RPi.GPIO as GPIO from talk import say GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) from adafruit_servokit import ServoKit Motor1 = {'EN': 27, 'input1': 19, 'input2': 16} Motor2 = {'EN': 22, 'input1': 26, 'input2': 20} for x in Motor1: GPIO.setup(Motor1[x], GPIO.OUT) GPIO.setup(Motor2[x], GPIO.OUT) EN1 = GPIO.PWM(Motor1['EN'], 100) EN2 = GPIO.PWM(Motor2['EN'], 100) EN1.start(0) EN2.start(0) hand = ServoKit(channels=16) ROOT_PATH = os.path.realpath(os.path.join(__file__, '..', '..')) servo = readYaml() if servo == None: with open('{}/src/configurationBackUp.yaml'.format(ROOT_PATH),'r+', encoding='utf8') as conf: servoBackUp = yaml.load(conf, Loader=yaml.FullLoader) writeYaml(servoBackUp) servo = readYaml() if servo == None: print('close') exit() Initial = servo['Initial_Position']['I2C'] Current = servo['Current_Position']['I2C'] InitialGpio = servo['Initial_Position']['Gpio'] CurrentGpio = servo['Current_Position']['Gpio'] GpioPin = servo['Pin']['Gpio'] for i in range(0,6): GPIO.setup(GpioPin[i], GPIO.OUT) Servo = [] for i in range(0,6): Servo.append(GPIO.PWM(GpioPin[i],50)) Servo[i].start(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 331, 43695, 198, 11748, 640, 198, 11748, 4738, 198, 11748, 18540, 305, 919, 278, 198, 11748, 25812, 72, 13, 16960, 9399, 355, ...
2.16242
628
from uuid import uuid4 from sqlalchemy import Index, Column, Text, Table, ForeignKey from sqlalchemy.orm import object_session from onegov.core.orm import Base from onegov.core.orm.types import UUID spoken_association_table = Table( 'spoken_lang_association', Base.metadata, Column( 'translator_id', UUID, ForeignKey('translators.id'), nullable=False), Column('lang_id', UUID, ForeignKey('languages.id'), nullable=False) ) written_association_table = Table( 'written_lang_association', Base.metadata, Column( 'translator_id', UUID, ForeignKey('translators.id'), nullable=False), Column('lang_id', UUID, ForeignKey('languages.id'), nullable=False) ) mother_tongue_association_table = Table( 'mother_tongue_association', Base.metadata, Column( 'translator_id', UUID, ForeignKey('translators.id'), nullable=False), Column('lang_id', UUID, ForeignKey('languages.id'), nullable=False) )
[ 6738, 334, 27112, 1330, 334, 27112, 19, 198, 198, 6738, 44161, 282, 26599, 1330, 12901, 11, 29201, 11, 8255, 11, 8655, 11, 8708, 9218, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 2134, 62, 29891, 198, 198, 6738, 530, 9567, 13, 7295, ...
2.424883
426
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import re from tensorflow.core.framework import graph_pb2 from tensorflow.core.framework import node_def_pb2 from tensorflow.python.framework import tensor_util # Custom op name for fused depthwise conv2d FUSED_DEPTHWISE_CONV2D = 'FusedDepthwiseConv2dNative' # The grappler op name for fused MatMul which starts with '_' FUSED_MATMUL = '_FusedMatMul' def node_from_map(node_map, name): """Pulls a node def from a dictionary for a given name. Args: node_map: Dictionary containing an entry indexed by name for every node. name: Identifies the node we want to find. Returns: NodeDef of the node with the given name. Raises: ValueError: If the node isn't present in the dictionary. """ stripped_name = node_name_from_input(name) if stripped_name not in node_map: raise ValueError("No node named '%s' found in map." % name) return node_map[stripped_name] def values_from_const(node_def): """Extracts the values from a const NodeDef as a numpy ndarray. Args: node_def: Const NodeDef that has the values we want to access. Returns: Numpy ndarray containing the values. Raises: ValueError: If the node isn't a Const. """ if node_def.op != "Const": raise ValueError( "Node named '%s' should be a Const op for values_from_const." % node_def.name) input_tensor = node_def.attr["value"].tensor tensor_value = tensor_util.MakeNdarray(input_tensor) return tensor_value # Whether to scale by gamma after normalization. def node_name_from_input(node_name): """Strips off ports and other decorations to get the underlying node name.""" if node_name.startswith("^"): node_name = node_name[1:] m = re.search(r"(.*):\d+$", node_name) if m: node_name = m.group(1) return node_name def cleanup_graph_def(input_graph_def, nodes_to_skip, inputs_to_remove): """Clean up the graph def by removing the skipped nodes and clean up the nodes with inputs that have been removed. Args: input_graph_def: GraphDef object to be cleaned. node_to_skip: Dict with node names to be skipped. inputs_to_remove: List of nodes to be removed from inputs of all nodes. Returns: GraphDef that has been cleaned. """ result_graph_def = graph_pb2.GraphDef() for node in input_graph_def.node: if node.name in nodes_to_skip: continue new_node = node_def_pb2.NodeDef() new_node.CopyFrom(node) for value in inputs_to_remove: for i, input_node in enumerate(new_node.input): if input_node == value.name: new_node.input[i] = value.input[0] result_graph_def.node.extend([new_node]) result_graph_def.library.CopyFrom(input_graph_def.library) result_graph_def.versions.CopyFrom(input_graph_def.versions) return result_graph_def
[ 2, 15069, 13130, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.0035
1,143
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch.nn import functional as F from torch import Tensor import argparse from . import register_classification_loss_fn from .. import BaseCriteria
[ 2, 198, 2, 1114, 15665, 766, 19249, 38559, 24290, 2393, 13, 198, 2, 15069, 357, 34, 8, 33160, 4196, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 198, 6738, 28034, 13, 20471, 1330, 10345, 355, 376, 198, 6738, 28034, 1330, 309, 22854...
3.808824
68
""" Insertion Sort Algorithm:""" """Implementation""" # Using the special variable # __name__ if __name__ == "__main__": main()
[ 37811, 35835, 295, 33947, 978, 42289, 11097, 15931, 628, 198, 37811, 3546, 32851, 37811, 628, 628, 198, 2, 8554, 262, 2041, 7885, 198, 2, 11593, 3672, 834, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 2...
3.066667
45
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Top-level namespace for spm.""" from .base import (Info, SPMCommand, logger, no_spm, scans_for_fname, scans_for_fnames) from .preprocess import (FieldMap, SliceTiming, Realign, RealignUnwarp, Coregister, Normalize, Normalize12, Segment, Smooth, NewSegment, DARTEL, DARTELNorm2MNI, CreateWarped, VBMSegment) from .model import (Level1Design, EstimateModel, EstimateContrast, Threshold, OneSampleTTestDesign, TwoSampleTTestDesign, PairedTTestDesign, MultipleRegressionDesign) from .utils import (Analyze2nii, CalcCoregAffine, ApplyTransform, Reslice, ApplyInverseDeformation, ResliceToReference, DicomImport)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 795, 16436, 25, 532, 9, 12, 4235, 25, 21015, 26, 12972, 12, 521, 298, 12, 28968, 25, 604, 26, 33793, 12, 8658, 82, 12, 14171, 25, 18038, 532, 9, 12, 198, 2, 2...
2.155131
419
import numpy as np from mathUtils import *
[ 11748, 299, 32152, 355, 45941, 198, 6738, 10688, 18274, 4487, 1330, 1635 ]
3.5
12
from datetime import datetime from marquez_airflow import DAG from airflow.operators.postgres_operator import PostgresOperator from airflow.utils.dates import days_ago default_args = { 'owner': 'datascience', 'depends_on_past': False, 'start_date': days_ago(1), 'email_on_failure': False, 'email_on_retry': False, 'email': ['datascience@example.com'] } dag = DAG( 'etl_orders_7_days', schedule_interval='@hourly', catchup=False, default_args=default_args, description='Loads newly placed orders weekly.' ) t1 = PostgresOperator( task_id='if_not_exists', postgres_conn_id='food_delivery_db', sql=''' CREATE TABLE IF NOT EXISTS orders_7_days ( order_id INTEGER REFERENCES orders(id), placed_on TIMESTAMP NOT NULL, discount_id INTEGER REFERENCES discounts(id), menu_id INTEGER REFERENCES menus(id), restaurant_id INTEGER REFERENCES restaurants(id), menu_item_id INTEGER REFERENCES menu_items(id), category_id INTEGER REFERENCES categories(id) );''', dag=dag ) t2 = PostgresOperator( task_id='tuncate', postgres_conn_id='food_delivery_db', sql='TRUNCATE TABLE orders_7_days;', dag=dag ) t3 = PostgresOperator( task_id='insert', postgres_conn_id='food_delivery_db', sql=''' INSERT INTO orders_7_days (order_id, placed_on, discount_id, menu_id, restaurant_id, menu_item_id, category_id) SELECT o.id AS order_id, o.placed_on, o.discount_id, m.id AS menu_id, m.restaurant_id, mi.id AS menu_item_id, c.id AS category_id FROM orders AS o INNER JOIN menu_items AS mi ON mi.id = o.menu_item_id INNER JOIN categories AS c ON c.id = mi.category_id INNER JOIN menus AS m ON m.id = c.menu_id WHERE o.placed_on >= NOW() - interval '7 days' ''', dag=dag ) t1 >> t2 >> t3
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 1667, 22281, 62, 958, 11125, 1330, 360, 4760, 198, 6738, 45771, 13, 3575, 2024, 13, 7353, 34239, 62, 46616, 1330, 2947, 34239, 18843, 1352, 198, 6738, 45771, 13, 26791, 13, 19581, 1330, 152...
2.268496
838
# store information about a pizza being ordered pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra vegan cheese'] } # summarize the order print("You ordered a " + pizza['crust'] + "-crust pizza" + "with the following toppings:") for topping in pizza['toppings']: print("\t" + topping)
[ 2, 3650, 1321, 546, 257, 14256, 852, 6149, 198, 79, 9990, 796, 1391, 198, 220, 220, 220, 705, 6098, 436, 10354, 705, 400, 624, 3256, 198, 220, 220, 220, 705, 1462, 37840, 10354, 37250, 76, 1530, 9649, 3256, 705, 26086, 15169, 9891, ...
2.925234
107
a = float(input('Qual o preo do produto? R$')) d = a - (a * 23 / 100) print('O produto que custava R${:.2f}, na promoo de 23% de desconto vai custar: R${:.2f}' .format(a, d))
[ 64, 796, 220, 12178, 7, 15414, 10786, 46181, 220, 267, 662, 78, 466, 40426, 9390, 30, 371, 3, 6, 4008, 198, 67, 796, 257, 532, 357, 64, 1635, 2242, 1220, 1802, 8, 198, 4798, 10786, 46, 40426, 9390, 8358, 9378, 4170, 371, 38892, 25...
2.269231
78
# Submit a function to be run either locally or in a computing cluster. # Compared to original StyleGAN implementation, we extend the support for automatic training resumption, # and network recompilation. import copy import inspect import os import pathlib import pickle import platform import pprint import re import shutil import sys import time import traceback from enum import Enum from .. import util from ..util import EasyDict from . import internal _user_name_override = None
[ 2, 39900, 257, 2163, 284, 307, 1057, 2035, 15726, 393, 287, 257, 14492, 13946, 13, 198, 2, 27492, 284, 2656, 17738, 45028, 7822, 11, 356, 9117, 262, 1104, 329, 11353, 3047, 581, 24098, 11, 198, 2, 290, 3127, 48765, 10520, 13, 198, 1...
4.049587
121