text
stringlengths
3.07k
22.1k
from functools import lru_cache from math import factorial as factorial_int from math import floor, sqrt def factorial(x: float) -> int: return factorial_int(int(x)) def ishalfint(x: float) -> bool: """check if value is half integer Arguments: x: is this a half integer? Returns: Tr...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import random import time import copy from sys import maxsize from itertools import permutations class Population(): def __init__(self, bag, adjacency_mat): self.bag = bag self.parents = [] self.score ...
import pandas as pd import numpy as np import matplotlib import matplotlib.pylab as plt import seaborn as sns import sys from scipy import stats from scipy.cluster.hierarchy import fcluster matplotlib.use('agg') STANDARD_SIZES=[ str(i) for i in list(range(101)) ] STANDARD_COLORS=["blue","green","red","cyan","magenta",...
# -*- coding: utf-8 -*- """Django settings for OLDP (using django-configurations)""" import os from configurations import Configuration, importer, values from configurations import importer from django.contrib.messages import constants as message_constants from django.utils.translation import ugettext_lazy as _ impo...
from requests.api import request from itertools import chain def extend(base, name=None, **kwargs): return type(name, (base,), kwargs) class Entity(dict): __getattr__ = dict.get def __repr__(self): printable = self.name or self.id if not printable: return super(Entity, self...
# Copyright 2014-2016 The Meson development team # 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 agree...
import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd import os import torch import torch.nn as nn import torch.nn.functional as F from torch import optim import time from torch.utils.data import Dataset, DataLoader import torchaudio import torchvision.transforms as transforms import...
import requests, os, re, logging, shelve, threading, math, sys from bs4 import BeautifulSoup from os import path from dataclasses import dataclass from abc import ABC from itertools import zip_longest def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x...
# #Author : amit #Created Date : 05-May -2018 # ''' This program demonstrate the creation and some other functionalies like: 1. push 2. push to the left 3. pop 4. pop from the left 5. search an element 6. remove a element by value 7. get the length of the list 8. generator to iterate over the list 9. clear/emp...
"""Support for time series logging.""" __copyright__ = """ Copyright (C) 2020 University of Illinois Board of Trustees """ __license__ = """ 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 withou...
# 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 t...
import os import re import json from pprint import pprint import requests import yaml from pathlib import Path import string def main(): # load cache cache_file = 'src/citations/cache.yml' if os.path.exists(cache_file): with open(cache_file, 'r') as file: cache = yaml.safe_load(file) ...
#!/usr/bin/env python import argparse from copy import deepcopy import rospy from std_msgs.msg import ( Empty, Bool, String, ) import baxter_interface from baxter_core_msgs.msg import ( CollisionAvoidanceState, ) from baxter_interface import CHECK_VERSION class Tuck(object): def __init__(sel...
from .basicgeo import P3, AlongAcc from . import barmesh def BarMeshContourF(bm, bar, node, cizone, contournumber): barcont = [ ] cbar, cnode = bar, node bfullloop = False while True: assert not (cnode.pointzone.izone == cizone) assert cbar.GetNodeFore(cbar.nodeback == cnode).pointzone....
from typing import List, Tuple, Iterable, Union import torch from e3nn import rs class SphericalTensorType: """ The type of a (multi-channel) spherical tensor, i.e. the number of channels of each tensor order. """ multiplicities: Tuple[int] dim: int Rs: List[Tuple[int, int]] def __init__...
""" FiftyOne config. | Copyright 2017-2021, Voxel51, Inc. | `voxel51.com <https://voxel51.com/>`_ | """ import logging import os try: from importlib import metadata as importlib_metadata # Python 3.8 except ImportError: import importlib_metadata # Python < 3.8 import eta import eta.core.config as etac imp...
from queue import PriorityQueue, Empty import collections import math from matplotlib import pylab as plt from matplotlib import ticker # not used # ExeTraceStruct = collections.namedtuple('ExeTraceStruct',['tid','sid','timestamp']) class Task(object): def __init__(self,**kv): self.C = 0 self.D =...
""" Changelog: [1] Builds on top of epi2. [2] Works only for bbox outputs of lvis_test.py. """ ################################################################################ ## Import. ## ###################################################...
# -*- coding: utf-8 -*- """ Created on Mon May 24 14:23:26 2021 @author: bferrari """ #%cd C:\Users\bferrari\Desktop\pessoal\bdp\python import random import matplotlib.pyplot as plt import pandas as pd import numpy as np import networkx as nx from heapq import nlargest as maxq #import heapq as max_q #from python i...
# This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import unittest import struct import os import sys try: from numpy import array import numpy.testing except ImportError: from Bio import ...
import time from collections import deque from random import choice as random_choice from string import hexdigits from typing import cast, Deque, Dict, Sequence, Set from irctokens import build, Line from ircstates import User from ircrobots import Bot as BaseBot from ircrobots import Server as BaseServer from ircsta...
#! /usr/bin/env python3 import sys, time, os import Leap from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture, SwipeGesture import numpy as np import pandas as pd import argparse class LeapMotionListener(Leap.Listener): data = [] finger_names = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']; bone_names = ...
__all__ = ['MicroGridDataFrame', 'MicroGridSeries', 'IDX'] import pandas as pd from pandas import DataFrame, Series from pandas.core.generic import NDFrame from pandas.tseries.frequencies import to_offset import numpy as np from datetime import datetime as DateTime import inspect import re IDX = pd.IndexSlice pd.set_...
import logging import subprocess import sys from os import isatty from typing import Sequence import typer from vimania.db.dal import DAL, Todo, TodoStatus from vimania.environment import config from vimania.todos import Todos _log = logging.getLogger("vimania-plugin.cli") if _log.handlers == []: # avoid adding mu...
#!/usr/bin/env python3 import unittest from unittest.mock import MagicMock, patch from lispy import * class AtomTestCase(unittest.TestCase): def test_int_atom(self): """ Checks that creating an int atom works. """ self.assertEqual(atom('3'), 3) self.assertEqual(atom('5'), 5) def test_...
"""APIs exposed under the namespace ray.util.collective.""" import logging import numpy as np import ray from ray.util.collective import types from ray.util.collective.const import get_nccl_store_name _MPI_AVAILABLE = False _NCCL_AVAILABLE = True # try: # from ray.util.collective.collective_group.mpi_collective_...
# Copyright 2013 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 ...
import csv from collections import defaultdict, Counter from django.db.transaction import atomic from . import daos from . import input_validators def user_can_create_tables(user): return user.is_staff def validate_cell_data(cell_name, cell_value): input_validators.validate_input_text(cell_value) if cel...
import unittest import argparse import itertools from datetime import datetime import src.script as source class TestValidateDate(unittest.TestCase): def test_too_long_date(self): with self.assertRaises(ValueError): source.validate_date('26.06.20191') def test_invalid_date_formats(self):...
# -*- coding:utf-8 -*- from os import makedirs, getcwd from os.path import exists import matplotlib.pyplot as plt import numpy as np from nltk.parse.stanford import StanfordParser from nltk.tokenize import word_tokenize from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score, classification...
import numpy as np def l2_regularization(W, reg_strength): ''' Computes L2 regularization loss on weights and its gradient Arguments: W, np array - weights reg_strength - float value Returns: loss, single value - l2 regularization loss gradient, np.array same shape as W -...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division from collections import defaultdict from typing import DefaultDict, Any, Tuple, Optional import numpy as np import lightgbm from eli5.explain import explain_weights, explain_prediction from eli5._feature_importances import get_feature_importance...
# / \ # [o]<=========== # /===\ # /_____\ # / \ # /_______\ # / \ # /_________\ # # Cedar Sentinel # A Discord Bot for using trained models to detect spam # Built for the Pine64 Chat Network # Copyright 2021-2022 <NAME> (fireTwoOneNine), <NAME> (kj7rrv) # Permission is hereby granted, free o...
# -*- coding: utf-8 -*- import fiona from fiona.crs import from_epsg from io import BytesIO import json import os import shutil import uuid import unicodedata import zipfile from django.db.models.fields.related import ForeignKey, ManyToManyField from django.contrib.gis.db.models.fields import (GeometryField, GeometryC...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import os import os.path as osp import shutil import tempfile import zipfile import mmcv import numpy as np from PIL import Image iSAID_palette = \ { 0: (0, 0, 0), 1: (0, 0, 63), 2: (0, 63, 63), 3: (0, 63, ...
from django.core.exceptions import ValidationError from os import path as fs_path from time import strftime from django.utils.text import slugify from django.utils import six from django.utils.translation import ugettext as _ from django.core.cache import cache from django.conf import settings from django.db import mod...
# This file is copied from https://github.com/qtile/qtile import asyncio import os import shutil import signal import subprocess import time from threading import Thread import libqtile.bar import libqtile.config import libqtile.confreader import libqtile.layout import pytest from dbus_next.aio import MessageBus from ...
import os import pytest from pathlib import Path from unittest import mock from datetime import datetime as dt from src.reporting.report import read_file from src.reporting.report import parse_abbreviations_file from src.reporting.report import parse_time_file from src.reporting.report import get_abs_file_path from src...
""" Author: <NAME> Date: 2020.12.15 """ import numpy as np import torch from torch.optim import Adam import gym import time import math import scipy import argparse from osim_env import MyEnv from env_wrapper import FrameSkip, ActionScale, OfficialObs import ppo_core from ppo import PPOBuffer...
""" Struct and unions. """ from pypy.interpreter.baseobjspace import W_Root from pypy.interpreter.error import OperationError, oefmt from pypy.interpreter.typedef import TypeDef, interp_attrproperty from rpython.rlib import jit from rpython.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong, intmask from rpython...
# Copyright 2016 MongoDB, 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, so...
import os import pytest from numpy import pi, sin, array from moviepy.audio.AudioClip import AudioClip from moviepy.audio.io.AudioFileClip import AudioFileClip from moviepy.utils import close_all_clips from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip from moviepy.video.fx.speedx import spee...
#!/usr/bin/env python # python standard libraries import os from pathlib import Path import sys import socket # third-party packages import numpy as np import setproctitle import torch import wandb # code repository sub-packages from onpolicy.config import get_config from onpolicy.envs.football.Football_Env import Fo...
#!/usr/bin/python #-*- coding: utf-8 -*- # >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>. # Licensed under the Apache License, Version 2.0 (the "License") # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # --- File Name: loss_hdwG.py # --- Creation Date: 19-04-2020 # --- Last Modified: Tue 21 ...
# The MIT License (MIT) # # Copyright (c) 2020 ETH Zurich # # 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...
# ======================================================================= # # Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1 Redistrib...
import pygame import random import time import os import neat import pickle pygame.font.init() BIG_HW = 970 BIG_PAD = 20 SMALL_HW = 170 SMALL_PAD = 2 TILE_HW = 40 STAT_FONT = pygame.font.SysFont("comicsans", 50) WHITE_COLOR = (255, 255, 255) BLACK_COLOR = (0, 0, 0) TILE_2 = pygame.transform.sc...
import os import unittest import copy import numpy as np import numpy.testing as npt import pandas as pd import pandas.testing as pdt from inferelator import workflow from inferelator.tests.artifacts.test_stubs import TaskDataStub from inferelator.regression import amusr_regression from inferelator.utils import Infer...
#!/usr/bin/env python # 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 # # Authors: # - <NAME>, <EMAIL>, 2017 # - <NAME>, <EMAIL>, 2017 import loggi...
# pylint: disable=invalid-name,missing-docstring,redefined-outer-name # -- coding: utf-8 -*- import os import copy import argparse import subprocess import multiprocessing from io import StringIO import yaml GPUs = [0, 1, 2, 3] _HOME_DIR = os.path.abspath(os.path.expanduser(os.environ.get("AWNAS_HOME", "~/awnas"))) ...
#!/usr/bin/env python3 """ Kapranov-Voevodsky 2-vector spaces FAIL FAIL FAIL: too complicated, and i think it's also wrong. See: vect2.py for another attempt. """ import operator from functools import reduce from random import randint import numpy # for the matrix indexing and ops from bruhat import element from...
import json import shutil from collections import defaultdict from pathlib import Path from typing import Dict, List, Union from openpecha import config from openpecha.core.layer import Layer, LayerEnum, PechaMetaData from openpecha.storages import GithubStorage, Storage from openpecha.utils import dump_yaml, load_yam...
# Copyright 2016 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 a...
import gzip, bz2 import snappy from complexity.ncd import ppm_compress_mod, ppmc from complexity.ncd import arithmeticcoding, ppmmodel from complexity.lzc import lzc import contextlib, sys, os import scipy.cluster.hierarchy as hier import numpy as np import matplotlib.pyplot as plt import pylab def NCD(spike_array,com...
import sys from PyQt5.QtCore import QPoint, QSize, Qt, QUrl from PyQt5.QtGui import QIcon, QKeySequence from PyQt5.QtWebKitWidgets import QWebPage, QWebView from PyQt5.QtWidgets import (QApplication, QHBoxLayout, QLabel, QMainWindow, QShortcut, QStatusBar, QTabWidget, QToolBar, ...
# -*- coding: utf-8 -*- """ Created on Sun Feb 14 16:21:44 2016 @author: Oscar """ #Biblioteca para escribir datos en un archivo csv import csv #Biblioteca para funciones matemáticas import math #Importacion de el archivo ocr_dataset import ocr_dataset as caracteristicasimg #Nombre: nuevaInstancia #De...
from __future__ import annotations import os import itertools from typing import Any, Optional, TypeVar import pygame import pygame.freetype from gupb.controller import keyboard from gupb.model import characters from gupb.model import effects from gupb.model import games from gupb.model import tiles from gupb.model i...
import xml.etree.ElementTree as ET import textgrid as tg import re import sys import os from pathlib import Path class Word(object): """word object to keep track of words""" def __init__(self, start, end, label): super(Word, self).__init__() self.start = start self.end = end se...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Date: 2019/9/30 13:58 Desc: 奇货可查网站目前已经商业化运营, 特提供奇货可查-指数数据接口, 方便您程序化调用 注:期货价格为收盘价; 现货价格来自网络; 基差=现货价格-期货价格; 基差率=(现货价格-期货价格)/现货价格 * 100 %. """ from typing import AnyStr import pandas as pd import requests from mssdk.futures.cons import ( QHKC_INDEX_URL, QHKC_INDEX...
"""Module for parallel sampling a batch of rollouts""" from functools import partial import logging import numpy as np import multiprocessing as mp import tensorflow as tf from garage.sampler.base import BaseSampler from garage.sampler.stateful_pool import singleton_pool from garage.sampler.utils import truncate_paths ...
#!/usr/bin/env python3 # # Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. ...
# -*- coding: utf-8 -*- """Implementation of the ``igv_session_generation`` step This step takes as the input the output of the following steps and generates an IGV session XML file that displays the results as genome tracks: - ``ngs_mapping`` - ``variant_annotation`` or ``variant_calling`` ========== Step Input ===...
"""Example working with PyParsing and async for log parsing. ```sh cd Assorted_Snippets poetry run python python/parallel_programming/log_parsing.py ``` Resource Links: - generators: https://masnun.com/2015/11/13/python-generators-coroutines-native-coroutines-and-async-await.html - async queue: https://realpython.co...
# Create your views here. from __future__ import print_function import os from django.conf import settings import zipfile import io import logging from datetime import timedelta import random from django import http from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPa...
#!python import configparser, json, os, shutil, subprocess, time, obspython as obs ### GLOBALS / DEFAULTS props = None settings = obs.obs_data_create_from_json_file_safe(os.path.join(os.path.dirname(__file__), 'config', 'browser_source_default.json'), 'backup') def obslog(lvl, msg): obs.blog(lvl, "BROWSER_SOURCE...
############################################################################### # Server process to keep track of unlinked resources, like folders and # semaphores and clean them. # # author: <NAME> # # adapted from multiprocessing/semaphore_tracker.py (17/02/2017) # * include custom spawnv_passfds to start the proce...
import six import numbers from collections import defaultdict, Counter import numpy as np import scipy.sparse as sp from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, \ _make_int_array, _document_frequency class DeltaTfidfTransformer(TfidfTransformer): def fit(self, X_pos, X_neg, ...
############################################################################## # # Botnar Resaerch Centre # # $Id$ # # Copyright (C) 2020 <NAME> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 <NAME> # # 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 require...
""" Tide Predictor Generates tide predictions using the pytides module. Convert University of Hawaii research quality datasets into tidal harmonic constituents for making predictions on any location that data exists for. Datasets and background info available from: ftp://ftp.soest.hawaii.edu/uhslc/rqds/ "...
# pg template - skeleton for a new pg project import pygame as pg from random import randint vec = pg.math.Vector2 WIDTH = 1024 HEIGHT = 800 FPS = 60 GRIDSIZE = 32 MOB_SIZE = 32 MOB_SPEED = .5 NUM_MOBS = 20 NEIGHBOR_RADIUS = 100 A_WEIGHT = 1.5 C_WEIGHT = 0.8 S_WEIGHT = 1.8 # define colors WHITE = (255, 255, 255) BLAC...
# Copyright 2018-2019 QuantumBlack Visual Analytics Limited # # 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 # # THE SOFTWARE IS PROVIDED "AS IS"...
import os import shutil from mnemonic import Mnemonic from ..device import Device from ..helpers import alias from ..util.descriptor import AddChecksum from ..util.base58 import encode_base58_checksum, decode_base58 from ..util.xpub import get_xpub_fingerprint, convert_xpub_prefix from ..key import Key from ..rpc impor...
import time import keras import numpy as np import tensorflow as tf from keras import backend as K from keras.callbacks import TensorBoard from keras.utils import generic_utils from tqdm import tqdm from nets.frcnn import get_model from nets.frcnn_training import (Generator, class_loss_cls, class_loss_regr...
# Copyright 2019-2020 Xanadu Quantum Technologies 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 applicabl...
# [Attention Is All You Need](https://arxiv.org/pdf/1706.03762.pdf) import tensorflow as tf from tensorflow import keras import numpy as np import utils import time import pickle import os MODEL_DIM = 32 MAX_LEN = 12 N_LAYER = 3 N_HEAD = 4 DROP_RATE = 0.1 class MultiHead(keras.layers.Layer): def __init__(self, ...
from typing import Tuple, Dict, List import numpy as np from panqec.codes import StabilizerCode Location = Tuple Operator = Dict[Location, str] # Location to pauli ('X', 'Y' or 'Z') Coordinates = List[Tuple] # List of locations def on_defect_boundary(Lx, Ly, x, y): """Determine whether or not to defect each bo...
import traceback from typing import NamedTuple from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec from urllib.parse import urlparse from time import sleep from .strategy impor...
#from imports import * import numpy as np import matplotlib matplotlib.use('Agg') import tensorflow as tf config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True session = tf.compat.v1.Session(config=config) import tensorflow_probability as tfp tfd = tfp.distributions import matplotlib.pyplot as p...
import json from django.shortcuts import redirect from django.views.generic.base import TemplateView from django.http import Http404, HttpResponse from django.urls import reverse from infrastructure.models import Project, FinancialYear, BudgetPhase from household.models import HouseholdServiceTotal, HouseholdBillTot...
import logging import random import bson import modularodm.exceptions from django.contrib.contenttypes.fields import (GenericForeignKey, GenericRelation) from django.contrib.contenttypes.models import ContentType from django.core.exceptions import MultipleObjectsReturned...
__author__ = "<NAME>, <NAME>, <NAME>" __copyright__ = "2020 HMK-IDEA-Cryptor" __credits__ = ["<NAME>", "<NAME>", "<NAME>"] __license__ = "MIT" __email__ = "<EMAIL>" import secrets from pckgIDEA.IDEA_Key_Scheduler import IDEA_Key_Scheduler KEY_SIZE = 128 BLOCK_SIZE = 16 # Plaintext = 64bits SUB_KEYS = 6 SHIFT_BITS = ...
import datetime import json import yaml import plistlib from sublime_lib import OutputPanel class DumperProto(object): """Prototype class for data dumpers of different types. Classes derived from this class (and in this file) will be appended to the module's ``get`` variable (a dict) with ``sel...
import krpc import time import datetime import math #Init conn = krpc.connect(name="UI Test") vessel = conn.space_center.active_vessel kerbin_frame = vessel.orbit.body.reference_frame orb_frame = vessel.orbital_reference_frame srf_frame = vessel.surface_reference_frame surface_gravity = vessel.orbit.body.surface_gravi...
#Functions for grabbing US reactor information from the NRC webpage and CA #reactor information from /db/REACTORS_corr.ratdb. The class #NRCClaws scrapes the NRC webpage for reactor information, bundles the data into #dictionary format for pushing to couchDB, and pushes the information to the #reacdb database. #Class c...
from bc16 import bc16_cpu import random class IODevice: def __init__(self): self.io_port = None def read_byte(self): pass def write_byte(self): pass class TerminalPrinter(IODevice): DEFAULT_IO_PORT = 0x1 READY = 0x40 def __init__(self, env): self.env = env ...
from datetime import datetime from django.utils import timezone from django.db import models # Create your models here. from machines.models import Machine class TestBranch(models.Model): """ test branch """ branch_name = models.CharField(max_length=128, unique=True, verbose_name="branch name", help_...
from bokeh.sampledata import us_states, us_counties from bokeh.plotting import figure, show, output_notebook, output_file, save from bokeh import palettes from bokeh.models import ColorBar,HoverTool,LinearColorMapper,ColumnDataSource,FixedTicker, LogColorMapper output_notebook() import re import numpy as np from modeli...
from dataloader import MIDI_Loader,MIDI_Render import numpy as np import os import shutil import random from model import AutoDropoutNN import torch import sklearn.utils from torch.nn import functional as F pitch_num = 130 chord_num = 25 rest_pitch = 128 hold_pitch = 129 none_chord = 24 recog_level = "Mm" train_path =...
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import logging as log import numpy as np from openvino.tools.mo.front.common.partial_infer.utils import is_fully_defined, dynamic_dimension, shape_delete, \ clarify_partial_shape, shape_array, mo_array from openvino.tools.mo.graph....
import logging import argparse from itertools import cycle import random from collections.abc import Sized import pandas as pd import qt as qt from matplotlib.colors import TABLEAU_COLORS from oneibl.one import ONE import ibllib.plots as plots from ibllib.io.extractors import ephys_fpga from ibllib.qc.task_metrics im...
import tensorflow as tf import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(os.path.join(ROOT_DIR)) sys.path.append(os.path.join(ROOT_DIR,'..')) sys.path.append(os.path.join(ROOT_DIR, 'models')) sys.path.append(os.path.join(ROOT_DIR, 'utils')) ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Run gtsrcmaps for a single energy plane for a single source This is useful to parallize the production of the source maps """ from __future__ import absolute_import, division, print_function import os import xml.etree.cElementTree as ElementTree im...
# encoding: utf-8 from typing import Optional import ckan.logic as logic import ckan.authz as authz import ckan.logic.auth as logic_auth from ckan.common import _ from ckan.types import Context, DataDict, AuthResult @logic.auth_allow_anonymous_access def package_create(context: Context, data_dict...
from loader import dp, bot from aiogram import types from aiogram.dispatcher import FSMContext from aiogram import exceptions from utils.misc.read_file import read_txt_file from utils.classes import kb_constructor, timer, regexps from utils.db_api import db_api, tables from utils.models import ages import re @dp.m...
import numpy as np import glob import os from scipy.ndimage import map_coordinates from .utilities import rotate_coordinates, read_image from .filtering import ramp_filter_and_weight from .config import Config from scipy.interpolate import griddata, interp2d, interp1d, RegularGridInterpolator from skimage.io import * f...
import datetime import numpy import theano import fuel from fuel.schemes import ConstantScheme from fuel.transformers import Batch, Mapping, SortMapping, Transformer, Unpack, FilterSources import data fuel.config.default_seed = 123 def at_least_k(k, v, pad_at_begin, is_longitude): if len(v) == 0: v = numpy...
# Import libraries import pandas as pd import numpy as np from diver._shared import _get_boolean_elements ############################## # USEFUL_COLS AUTO-GENERATOR # ############################## def _dtype_detector(features): ''' Automatically detects the following data-types for each column of a feature...
import pygame import random import sys class FighterShip: def __init__(self, background, image, x=500, y=470): self.x = x self.y = y self.size_x = 64 self.size_y = 64 self.max_life = 100 self.current_life = 100 self.is_alive = True self...