content
stringlengths
5
1.05M
import pyOcean_cpu as ocean a = ocean.asTensor([1,2,3]) s = a.storage b = ocean.int8(9) x = ocean.ensure(a, a.dtype) print(x.obj == a.obj) print(x.storage.obj == a.storage.obj) x = ocean.ensure(a, ocean.float) print(x) ocean.ensure(a, ocean.int8, ocean.cpu, True) print(a) x = ocean.ensure(s, s.dtype) print(x is s)...
import os import shutil import build_utils import build_config def get_supported_targets(platform): if platform == 'win32': return ['win32'] else: return [] def get_dependencies_for_target(target): return [] def build_for_target(target, working_directory_path, root_project_path): i...
"""Tests for full relationship schema checking.""" import pytest from open_alchemy.schemas.validation.property_.relationship import full TESTS = [ pytest.param( { "type": "object", "properties": {"id": {"type": "integer", "x-primary-key": True}}, }, "ref_schemas", ...
# -*- coding: utf-8 -*- """Module with init command.""" from argparse import Namespace import six from termius.account.commands import LoginCommand from termius.cloud.commands import PullCommand, PushCommand from termius.core.commands import AbstractCommand from termius.porting.commands import SSHImportCommand cla...
#!/usr/bin/env python3 import pytest import yaml from romanlengths.roman_conversion import convert_to_numeral numerals = yaml.load(open("tests/roman-numerals.yml", 'r')) @pytest.mark.parametrize('value', range(1, 5000)) def test_conversion(value): assert convert_to_numeral(value) == numerals[value]
import torch import torch.nn as nn import copy import time import numpy as np import torch.optim as optim from .meta_pruner import MetaPruner class Pruner(MetaPruner): def __init__(self, model, args): super(Pruner, self).__init__(model, args) def prune(self): self._get_kept_wg_L1() sel...
# Generated by Django 4.0.2 on 2022-03-07 05:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0011_orderitem_complete_orderitem_customer'), ] operations = [ migrations.AddField( model_name='shippingaddress', ...
# -*- coding: utf-8 -*- from typing import Callable, Awaitable, List from mypy_extensions import Arg from aiohttp.web import Request from mtpylon.income_message import IncomeMessage from mtpylon.middlewares import MiddleWareFunc from mtpylon.message_sender import MessageSender HandleStrategy = Callable[ [ ...
from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy as _l from qatrack.faults import models from qatrack.qatrack_core.dates import format_datetime from qa...
# -*- coding: utf-8 -*- """ Created on Tue Oct 10 17:40:37 2017 @author: karja """ from math import sqrt # The best formula for GCD that can be found in wikipedia def gcd(a,b): while b != 0: a, b = b, a % b return a # Class that set the dict that represent the # range of pythagores that have intege...
from social_core.backends.mendeley import MendeleyMixin, MendeleyOAuth, \ MendeleyOAuth2
import brownie from brownie import Wei, accounts, Contract, config import math def test_cloning( gov, token, vault, strategist, whale, strategy, keeper, rewards, chain, StrategyFraxUniswapUSDC, guardian, amount, tests_using_tenderly, ): # tenderly doesn't work f...
############################################################################### # Copyright (c) 2007-2018, National Research Foundation (Square Kilometre Array) # # Licensed under the BSD 3-Clause License (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy # of the ...
'''Views and logic for github OAuth.''' from flask import url_for, request, session, redirect from flask_oauthlib.client import OAuth import github def install_github_oauth(app): oauth = OAuth(app) github_auth = oauth.remote_app( 'github', consumer_key=app.config['GITHUB_CLIENT_ID'], ...
# # WIEN2k.py derived from OpenMX.py # # Interface to WIEN2k (http://susi.theochem.tuwien.ac.at/) # # Copyright (c) 2001 P. Blaha and K. Schwarz # import numpy as np class Wien2kParser(object): def __init__(self): self._prefix = None self._lattice_vector = None self._inverse_lattice_vect...
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from ..core.parameterization import Parameterized, Param from paramz.transformations import Logexp import sys class WarpingFunction(Parameterized): """ abstract function for war...
import numpy as np import scipy.stats as st # ------------------------------ # functions # ------------------------------ # make 2D Gaussian array # this script is introduced in stack overflow # https://stackoverflow.com/questions/29731726/how-to-calculate-a-gaussian-kernel-matrix-efficiently-in-numpy def gkern(ke...
# Import classifiers from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifi...
# -*- encoding: utf-8 -*- """ Copyright (c) 2019 - present AppSeed.us """ from apps.home import blueprint from flask import render_template, request from flask_login import login_required from jinja2 import TemplateNotFound @blueprint.route('/index') @login_required def index(): return render_template('home/ind...
import numpy as np import matplotlib.pyplot as plt import seekr2.modules.common_base as base import matplotlib.animation as animation import plotting title = "Entropy Barrier System" model_file = "/home/lvotapka/toy_seekr_systems/entropy_barrier/model.xml" model = base.load_model(model_file) boundaries = np.array([[-...
import os,sys class ScenarioConfig(object): # ADD_TO_CONF_SYSTEM 加入参数搜索路径 do not remove this comment !!! map_ = '3m' step_mul = 8 difficulty = '7' game_version = 'latest' replay_dir = '' episode_limit = 60 N_TEAM = 1 N_AGENT_EACH_TEAM = [3,] # because map_ = '3m' AGENT_ID_EACH...
import time,random,re,requests,json # 因为时间有点久, 忘记这个文件是否可以删除了 class Qiass: def __init__(self) -> None: self.__createSession() def __createSession(self): self.__session = requests.session() self.__refreshSessionHeaders() def __refreshSessionHeaders(self): ...
from sklearn.cluster import DBSCAN, KMeans import numpy as np import cv2 from numba import jit def get_clustering_points(img): ''' Retrieve points that need to be clustered from a grayscale image Parameters: img - grayscale img Returns: coordinates of each non-zero pixel in the mask (ro...
import requests def LookupActress(): url = 'https://jav-rest-api-htpvmrzjet.now.sh/api/actress?name=' actressName = input("Search for an actress: ") actressURL = url + actressName # print(actressURL) actressRequest = requests.get(actressURL).json() counts = len(actressRequest['result']) pr...
# -*- coding:utf-8 -*- from .symbol import Symbol from .exception import CoilSyntaxError, CoilRuntimeError class Scheme(object): """ """ symbol_tables = {keyword: Symbol(keyword) for keyword in ['quote', 'if', 'set!', 'define', 'lambda', 'begin']} @classmethod def pause(cls, tokenizer): ""...
import bisect # Usig binary search class Solution(object): def suggestedProducts(self, products, searchWord): """ :type products: List[str] :type searchWord: str :rtype: List[List[str]] """ products.sort() result, prefix, startIdx = [], "", 0 for char...
# Copyright (c) 1999-2008 Mark D. Hill and David A. Wood # Copyright (c) 2009 The Hewlett-Packard Development Company # 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 co...
import re import types from unittest import TestCase from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.core.files.uploadedfile import SimpleUploadedFile class TestFieldWithValidators(TestCase): def test_all_errors_get_reported(self): ...
from typing import Union from .validator import Validator, ValidationError, StopValidation class CurrentPassword(Validator): def __init__(self, model, message: Union[str, None] = None, parse: bool = True) -> None: self.parse = parse self.message = message or 'The password is incorrect.' se...
# coding: utf-8 class Solution: """ @param A : A string includes Upper Case letters @param B : A string includes Upper Case letters @return : if string A contains all of the characters in B return True else return False """ def compareStrings(self, A, B): # write your code here ...
'''You are given two lists, rat_1 and rat_2, that contain the daily weights of two rats over a period of ten days. Assume the rats never have exactly the same weight. Write statements to do the following:''' rat_1 = [2,4] rat_2 = [1,3] """ We are assuming the rats never have the same weight""" #1 If the weight of ...
"""This module sets up a base list of configuration entries.""" __revision__ = '$Revision$' import copy import lxml.etree import sys # py3k compatibility if sys.hexversion >= 0x03000000: from functools import reduce import Bcfg2.Server.Plugin class Base(Bcfg2.Server.Plugin.Plugin, Bcfg2.Server.Plugin...
icons = "♠ ♥ ♦" result = "" r1 = " _____\n|♠ |\n| |\n| A|\n ¯¯¯¯¯ " r2 = " _____\n|♠ |\n| |\n| K|\n ¯¯¯¯¯ " r3 = " _____\n|♠ |\n| |\n| Q|\n ¯¯¯¯¯ " r4 = " _____\n|♠ |\n| |\n| J|\n ¯¯¯¯¯ " r5 = " _____\n|♠ |\n| |\n| 2|\n ¯¯¯¯¯ " r6 = " _____\n|♠ |\n| ...
# VerTeX | Copyright (c) 2010-2021 Steve Kieffer | MIT license # SPDX-License-Identifier: MIT """ Translating math mode snippets from VerTeX to TeX. """ import re from vertex2tex.config import * ############### # Node classes class Node: """ The basic Node class, which contains the basic translation metho...
# Importing the base class from co_simulation_solvers.gauss_seidel_strong_coupling_solver import GaussSeidelStrongCouplingSolver def CreateSolver(cosim_solver_settings, level): return SimpleSteadyCouplingSolver(cosim_solver_settings, level) class SimpleSteadyCouplingSolver(GaussSeidelStrongCouplingSolver): d...
import pathlib class _BaseSaver: """ Base class to save figures or data """ def __init__(self, *args, **kwargs): allowed_kwargs = { 'out_dir', 'modes', 'clip', 'alpha', ...
import torch from torch.nn import functional as F from torch.nn import Dropout, Sequential, Linear, Softmax class GradientReversalFunction(torch.autograd.Function): """Revert gradient without any further input modification.""" @staticmethod def forward(ctx, x, l, c): ctx.l = l ctx.c = c ...
from django.db import models from django.utils.text import slugify from django.shortcuts import reverse class Actor(models.Model): name = models.CharField(max_length=30) photo = models.ImageField(upload_to="actor_photo/", blank=True) def __str__(self): return self.name class Movie(models.Model)...
# Generated by Django 2.2.1 on 2019-07-27 12:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0010_auto_20190724_1051'), ] operations = [ migrations.CreateModel( name='OpenTime', fields=[ ...
#!/usr/bin/env python # # Copyright The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify,...
"""Basic timing tools.""" from functools import wraps import time import numpy as np def timed(f): """Wraps a function so it returns results and run time.""" @wraps(f) def wrapper(*args, **kwargs): start = time.monotonic() result = f(*args, **kwargs) end = time.monotonic() ...
#!/usr/bin/env python3 # # usage: # python3 -m venv ve3 # ve3/bin/pip install markdown2 # ve3/bin/python misc/release.py import argparse import base64 import io import logging import os import re import shlex import subprocess import tarfile import time try: import grp def groupname(gid): return grp.g...
import math import numpy as np class Utils(): @staticmethod def normal_distr(x, avg, std): return 1/(std*((2*math.pi)**0.5))*math.exp(-0.5*((x - avg)/std)**2) @staticmethod def get_freq_hist(data): freq = np.zeros(data.shape[0]) unique = np.unique(data) for val in u...
import argparse import sys from termy.constants import TERMY_INTRO_MESSAGE, VERSION from termy.service.flow_handler.handle_flows import configure_termy, search_and_execute, update_termy, \ resolve_command_from_GPT3, display_current_configs, periodic_update_prompt DESCRIPTION = TERMY_INTRO_MESSAGE def init_cli_a...
#!/usr/bin/env python '''CPS Helpers for the DHCP IO Library''' # Copyright (c) 2018 Inocybe Technologies. # # 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/LIC...
def main(): a = float(input()) b = float(input()) c = float(input()) pi = 3.14159 d = ((a*c)/2) e = (pi*c*c) f = (((a+b)*c)/2) g = (b*b) h = (a*b) print("TRIANGULO: %.3f" %d) print("CIRCULO: %.3f" %e) print("TRAPEZIO: %.3f" %f) print("QUADRADO...
import tensorflow as tf from stepcovnet.config.TrainingConfig import TrainingConfig from stepcovnet.inputs.AbstractInput import AbstractInput from stepcovnet.training.TrainingFeatureGenerator import TrainingFeatureGenerator class TrainingInput(AbstractInput): def __init__(self, training_config: TrainingConfig): ...
"""demo_register URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class...
from city_scrapers_core.constants import COMMISSION from city_scrapers_core.spiders import CityScrapersSpider from city_scrapers.mixins import DetCityMixin class DetEntertainmentCommissionSpider(DetCityMixin, CityScrapersSpider): name = "det_entertainment_commission" agency = "Detroit Entertainment Commissio...
"""Find translation keys that are in Lokalise but no longer defined in source.""" import argparse import json from .const import CORE_PROJECT_ID, FRONTEND_DIR, FRONTEND_PROJECT_ID, INTEGRATIONS_DIR from .error import ExitApp from .lokalise import get_api from .util import get_base_arg_parser def get_arguments() -> a...
import csv import json import time from datetime import datetime from django.contrib import messages from django.core.urlresolvers import reverse from django.db import transaction from django.http import JsonResponse, HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404...
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
"""Step placement functions.""" from genologics.entities import Process, StepActions def finish_protocol_complete(lims, process_id): """Finish next step after current step is finished (Dx Mark protocol complete).""" process = Process(lims, id=process_id) inputs = '' actions = [] # Check all ana...
# -*- coding: utf-8 -*- """ Test 'pymonzo.monzo_api' file """ from __future__ import unicode_literals import codecs import json import os import tempfile import pytest from six.moves.urllib.parse import urljoin from pymonzo import MonzoAPI from pymonzo import config from pymonzo.api_objects import MonzoAccount, Monz...
import vtk def getSliderObjects(sliderRep, sliderWidget, titleText, iren, initVal, minVal, maxVal, posXLeft, posY, callBackFunc): sliderRep.SetMinimumValue(minVal) sliderRep.SetMaximumValue(maxVal) sliderRep.SetValue(initVal) sliderRep.SetTitleText(titleText) sliderRep.GetPoint1Coordinate().SetCoo...
from typing import IO import javaproperties from .._FileWriter import FileWriter from ._Report import Report from . import constants class ReportFileWriter(FileWriter[str, Report, "ReportFileWriter"]): """ Writer for report files. """ def _dump(self, obj: Report, file: IO[str]): # Create a J...
import os import tensorflow as tf import numpy as np from tensorflow import keras import time from matplotlib import pyplot as plt from gd import Discriminator, Generator tf.random.set_seed(22) np.random.seed(22) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' assert tf.__version__.startswith('2.') batch_size...
from models.Playerlist import * import time def main(): with open("players.txt", 'r') as f: players = f.readlines() PlayerList = Playerlist() #users that were not found in riot database errorUsers = list() j = 0 for player in players: #make sure we dont exceed request limit from temp api if(j<5): j +...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from neodroid.utilities.unity_specifications import Motion, Reaction, ReactionParameters __author__ = "Christian Heider Nielsen" import neodroid.wrappers.formal_wrapper as neo def construct_reactions(env): parameters = ReactionParameters( terminable=True, ...
import time import numpy as np from extra_foam.algorithms import ( nanmean, nansum ) def benchmark_nan_without_axis(f_cpp, f_py, shape, dtype): data = np.random.randn(*shape).astype(dtype) + 1. # shift to avoid very small mean data[:, :3, ::3] = np.nan t0 = time.perf_counter() ret_cpp = f_cpp(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ***************************************************************************** # Copyright (c) 2016-2020, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the followi...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Any from omegaconf import DictConfig import hydra def add(app_cfg: DictConfig, key1: str, key2: str) -> Any: num1 = app_cfg[key1] num2 = app_cfg[key2] ret = num1 + num2 print(f"Hello {app_cfg.user}, {num1} + {n...
# -*- coding: utf-8 -*- import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) from webtest import http from doctest import SKIP from tests.apps import input_app PY3 = sys.version_info >= (3,) def setup_test(test): for example in test.examples: # urlopen as moved in py3 ...
import json class nsfc: @staticmethod def load_discipline(): dic = {} with open('data/nsfc.jl', 'r', encoding='utf-8') as f: for line in f: th = json.loads(line) dic[th['_id']] = th return dic discipline = load_discipline.__func__()
import utility from .UnivariateLocalEstimator import UnivariateLocalEstimator from .VineKernelDensity import VineKernelDensity
import sys import datetime from pyspark import SparkContext from csv import reader from operator import add def week(datetimestr): #get weeknumber of the yaer date, time = datetimestr.split(' ') yearstr, monthstr, daystr = date.split('-') year = int(yearstr) month = int(monthstr) day = int(daystr) isoyear, isow...
# Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Software License Agreement (BSD License 2.0) # # 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 a...
#!/usr/bin/env python ################################################################## # Copyright (c) 2012, Sergej Srepfler <[email protected]> # February 2012 - # Version 0.3.1, Last change on Nov 15, 2012 # This software is distributed under the terms of BSD license. ##################################...
from typing import Tuple, Union, Iterable, List, Callable, Dict, Optional from nnuncert.models._network import MakeNet from nnuncert.models.dnnc import DNNCModel, DNNCRidge, DNNCHorseshoe, DNNCPred from nnuncert.models.mc_dropout import DropoutTF, MCDropout, MCDropoutPred from nnuncert.models.ensemble import Ensemble,...
class UndergroundSystem(object): def __init__(self): # record the customer's starting trip # card ID: [station, t] self.customer_trip = {} # record the average travel time from start station to end station # (start, end): [t, times] self.trips = {} def checkIn(...
from .interface import Capreole
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains decorators for Qt """ from __future__ import print_function, division, absolute_import from functools import wraps from Qt.QtCore import Qt from Qt.QtWidgets import QApplication from Qt.QtGui import QCursor def show_wait_cursor(fn): """ ...
# -*- coding: utf-8 -*- """ Created on Mon Jul 26 13:44:11 2021 @author: user24 """ import tkinter as tk import tkinter.filedialog as fd root = tk.Tk() root.withdraw() file = fd.askopenfilename( title="ファイルを選んでください。", filetypes=[("TEXT", ".txt"), ("TEXT", ".py"), ("HTML", ".html")] ) if file: with open...
import pandas as pd import numpy as np import scipy.stats import matplotlib.pyplot as plt plt.style.use('../acmart.mplrc') ### latency vs stages print("loading csv") d = pd.read_csv('perf-data/results.csv') print("filtering data") d = d[d['max_copy'] == 512] d = d[d['pipes'] == 6] d = d[d['samples'] == 20000000] d =...
"""Treadmill trace CLI. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import logging import sys import click from six.moves import urllib_parse from treadmill import cli from treadmill import context from tre...
import sys from typing import Any, Dict, Iterable, Optional import mlflow import pandas as pd import pytest import yaml from kedro.config import ConfigLoader from kedro.extras.datasets.pickle import PickleDataSet from kedro.framework.hooks import hook_impl from kedro.framework.project import Validator, _ProjectPipelin...
import logging import numpy as np from scipy.stats import ks_2samp, describe from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from sklearn.preprocessing import StandardScaler from sklearn.model_selection import StratifiedKFold from test_harness.experiments.baseline_experiment import...
import sys import unittest import six from conans.errors import ConanException from conans.model.options import Options, OptionsValues, PackageOptionValues, PackageOptions, \ option_undefined_msg from conans.model.ref import ConanFileReference class OptionsTest(unittest.TestCase): def setUp(self): ...
import hashlib import hmac import logging import os import tornado.escape import tornado.httpserver import tornado.gen import tornado.ioloop import tornado.log import tornado.web from . import update_pr class MainHandler(tornado.web.RequestHandler): def get(self): self.set_status(404) self.write...
import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout, QPushButton from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot def window(): app = QApplication(sys.argv) win = QWidget() grid = QGridLayout() for i in range(0,5): for j in range(0,5): ...
nodeList = [] class CLS_node(object): def __init__(self,v,i,l,r): self.left = l self.right = r self.ind = i self.value = v def __str__(self): return str(nodeList[self.left])+str(self.value)+str(nodeList[self.right])
from itertools import combinations,product comb = list(combinations([0,1,2,3,4,5,6,7,8,9],6)) comb = [[6 if y==9 else y for y in x ] for x in comb] valid = [tuple(map(int, list(str(s*s).zfill(2)))) for s in range(1,10)] valid.remove((0,9)) valid.remove((4,9)) valid.append((0,6)) valid.append((4,6)) def isvalid(comb1,c...
from .main import greet if __name__ == '__main__': greet()
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from copy import deepcopy from math import isfinite, isnan import numpy as np fr...
""" Overall these views are awful. - Add back option between steps - Make use of GeneriViews - ViewClass - between each step, post to self, validate data and use next to go to next step """ from django.shortcuts import render, redirect from collections import defaultdict, namedtuple from .forms import SetupForm, scor...
# Generated by Django 2.2 on 2021-07-01 02:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20210701_0707'), ] operations = [ migrations.AlterField( model_name='category', name='category_name'...
from argparse import Namespace from typing import Tuple, Callable import torch.nn as nn import torch from torch import Tensor from .learnable import Scale, Balance from .registry import register @register("linear_residual") class LinearResidual(nn.Module): def __init__(self, weight: float, lea...
import os from flask import Flask, render_template, redirect, request from flask_dropzone import Dropzone from convert import convert_to_line app = Flask(__name__) dropzone = Dropzone(app) filename = None dir_path = os.path.dirname(os.path.realpath(__file__)) input_path = os.path.join(dir_path, 'static/input') app.con...
import os import sys from helperFunctions import * foldersToCreate = ['SummedSystematics', 'SingleSystematicResults', 'UEsubtractedJetResults', 'Efficiencycorrected', 'Efficiencycorrected/PDF'] folderEffCorrection = 'Efficiencycorrected' if len(sys.argv) < 2: print('Provide name of analysis folder') exit() analy...
""" MIT License Copyright (c) 2021 Matthias Konrath Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publi...
import numpy as np from scipy.signal import savgol_filter class SavitzkyGolov(object): def __init__(self, window_length:int, poly:int): self.size=window_length self.poly=poly def set_window_size(self, size): self.size=size if self.size%2==0: self.size = self.size+1 def process(self, traj:np.ndarray...
from pathlib import Path from typing import Union __all__ = ("ScreenshotPath",) class ScreenshotPath: def __init__(self, dir_: Path) -> None: self.dir = dir_ self.rerun: Union[int, None] = None self.timestamp: Union[int, None] = None self.scenario_path: Union[Path, None] = None ...
from django.shortcuts import render from django.http import HttpResponse import telebot from .models import * from django.views.decorators.csrf import csrf_exempt import json import re from block_io import BlockIo from datetime import datetime import requests from time import sleep from django.utils.translation import...
from pycsp3 import * n, m, points1, points2 = data nPairs = len(points1) # x[i][j] is the value at row i and column j (a boundary is put around the board). x = VarArray(size=[n + 2, m + 2], dom=lambda i, j: {0} if i in {0, n + 1} or j in {0, m + 1} else range(nPairs + 1)) table = ({(0, ANY, ANY, ANY, ANY)} ...
AVATAR_AUTO_GENERATE_SIZES = 150 # Control the forms that django-allauth uses ACCOUNT_FORMS = { "login": "allauth.account.forms.LoginForm", "add_email": "allauth.account.forms.AddEmailForm", "change_password": "allauth.account.forms.ChangePasswordForm", "set_password": "allauth.account.forms.SetPasswor...
from typing import List """ Rotate array equals to flip array 3 times. First time, flip the whole array. Second time, flip the left part all the way to length k. Third time, flip the remaining right part. Time complexity: O(N) Space complexity: O(1) """ class Solution: def rotate(self, nums: List[int], k: int) -> N...
# Copyright (c) 2021 PaddlePaddle Authors. 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 ap...
from django.apps import AppConfig class CoderDojoChiConfig(AppConfig): name = "coderdojochi" verbose_name = "CoderDojoChi" def ready(self): import coderdojochi.signals_handlers
print("How many primes do you want?") N = input() a = 2 while a < N: a =a+1 j=2 x=a while x > j: if x%j==0 and j!=x: #print x, " is not prime, divisible by ", j break j=j+1 else: print j,# " is prime, divisible by 1 and itself", x
# # demo_kmeans.py # import kmeans import numpy as np import matplotlib.pyplot as plt data = [] number_of_clusters = 5 points_per_cluster = 25 np.random.seed(4) ''' Generate random clusters. ''' for _ in range(number_of_clusters): ages_centroid = np.random.uniform(20.0, 70.0) income_centroid = np.random....