text
stringlengths
3.07k
12.6k
from typing import List, Dict, Tuple from aocpy import BaseChallenge, foldl Point = Tuple[int, int] Cave = Dict[Point, int] Basin = List[Point] def parse(instr: str) -> Cave: o = {} for y, line in enumerate(instr.strip().splitlines()): for x, digit in enumerate(line): o[(x, y)] = int(dig...
# -*- coding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2018 <NAME> # # 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 right...
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
import logging import os import pprint import sys import tempfile as tmp from copy import copy from sklearn.utils import shuffle from numpy import squeeze if sys.platform == 'darwin': os.environ['OBJC_DISABLE_INITIALIZE_FORK_SAFETY'] = 'YES' os.environ['JOBLIB_TEMP_FOLDER'] = tmp.gettempdir() os.enviro...
from display_exceptions import NotFound, PermissionDenied from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.forms import modelformset_factory from django.shortcuts import redirect from base.views import rend...
""" Project OCELoT: Open, Competitive Evaluation Leaderboard of Translations """ from difflib import SequenceMatcher from django.contrib import messages from django.core.paginator import Paginator from django.http import Http404 from django.shortcuts import HttpResponseRedirect from django.shortcuts import render fro...
import copy from collections import deque import numpy as np from domainbed.lib import swa_utils class SWADBase: def update_and_evaluate(self, segment_swa, val_acc, val_loss, prt_fn): raise NotImplementedError() def get_final_model(self): raise NotImplementedError() class IIDMax(SWADBase): ...
from itertools import chain import numpy as np from sacred import Ingredient import torch import torch.nn as nn from racer.car_racing_env import feature_size, car_racing_env, image_size from racer.models.agent import Agent from racer.utils import load_pixels, flatten_parameters, build_parameters simple_nn = Ingredien...
from datetime import date import pytest import mock from wtforms.validators import StopValidation, ValidationError import dmutils.forms.validators from dmutils.forms.validators import ( GreaterThan, DateValidator, ) @pytest.fixture def form(): return mock.MagicMock() @pytest.fixture def field(form): ...
from random import randrange import pygame from pygame import mixer import random import math # intial instances of pygame pygame.init() screen = pygame.display.set_mode((800, 600)) # Add background image background = pygame.image.load("assests/mountains03-1920-x-1080_full.png") # Background Music mixer.music.loa...
#!/usr/bin/env python3 import os import subprocess import unittest from btrfs_diff.tests.render_subvols import render_sendstream from tests.temp_subvolumes import with_temp_subvols from ..procfs_serde import serialize, deserialize_untyped, deserialize_int def _render_subvol(subvol: {'Subvol'}): rendered = rende...
import csv import numpy as np from collections import Counter from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import KFold from sklearn.feature_extraction import DictVectorizer from sklearn.metrics import f1_score from sklearn imp...
from django.db import transaction from django.utils.translation import gettext_lazy as _ import django_filters import reversion from rest_framework import exceptions, serializers, viewsets from resources.api.base import NullableDateTimeField, TranslatedModelSerializer, register_view from .models import CateringProdu...
from pypeflow.io import ( syscall, capture, cd, mkdirs, symlink, rm, touch, filesize, exists_and_not_empty) # needed? import contextlib import io import logging import os import pprint import sys if sys.version_info >= (3, 0): NativeIO = io.StringIO else: NativeIO = io.BytesIO LOG = logging...
# Copyright 2014 Cloudbase Solutions Srl # # 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 l...
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import datetime, timedelta import pytest from pytz import timezone from indico.util.date_t...
#!/usr/bin/env python # 2014-07-11 DHT22.py import time import pigpio class sensor: def __init__(self, pi, gpio): """ Instantiate with the Pi and gpio to which the DHT22 output pin is connected. Optionally a LED may be specified. This will be blinked for each successful reading. ...
from django import forms from data.models import RadiosondeMeasurement, WeatherMeasurement, MeasuringDevice from django.forms.widgets import SelectDateWidget from datetime import date, time from visuo_open_source.widgets import SelectTimeWidget, ColumnCheckboxSelectMultiple class WeatherMeasurementForm(forms.Form): ...
import asyncio import logging import socket import websockets from gabriel_protocol import gabriel_pb2 from collections import namedtuple URI_FORMAT = 'ws://{host}:{port}' logger = logging.getLogger(__name__) websockets_logger = logging.getLogger(websockets.__name__) # The entire payload will be printed if this is...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from dataclasses import dataclass, field from typing import List from base_classes import * @dataclass class Group(object): """docstring for Group""" name: str comment: str disabled: bool _id: int = -1 # # new class GroupFactory(BaseFactory): """Factory for...
#!/usr/bin/python from concurrent import futures from optparse import OptionParser from argparse import ArgumentParser from pyroute2 import IPRoute from google.protobuf import json_format import logging import time import json import grpc import sys import srv6_explicit_path_pb2_grpc import srv6_explicit_path_pb2 ...
#!/usr/bin/python3 # Builds maps # NOTES: # - Must be run from content/ import json import os import sys import configparser import config import argparse import multiprocessing import subprocess import shutil argparser = argparse.ArgumentParser(description="Batch compiles all maps") argparser.add_argument('--force...
import tkinter as tk from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) from matplotlib import (pyplot as plt, animation) import threading import time import logging import socket from queue import Queue import artgallery as ag import funcgnss import funcgnss as fg __author__ = '<N...
from tkinter import * import time import random root = Tk() root.title("bb") root.geometry("450x570") root.resizable(0, 0) root.wm_attributes("-topmost", 1) canvas = Canvas(root, width=600, height=600, bd=0, highlightthickness=0, highlightbackground="white", bg="Black") canvas.pack(padx=10, pady=10) score ...
from pepper.brain.LTM_question_processing import create_query from pepper.brain.LTM_statement_processing import model_graphs from pepper.brain.basic_brain import BasicBrain from pepper.brain.infrastructure import Thoughts from pepper.brain.reasoners import LocationReasoner, ThoughtGenerator, TypeReasoner, TrustCalculat...
#!/usr/bin/env pytest # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test HEIF driver # Author: <NAME>, <even dot rouault at spatialys.com> # ##################################################################...
## An Eve optimizer implementation in Chainer # By <NAME> # https://github.com/muupan/chainer-eve # Modified by <NAME> from __future__ import division import math import numpy from chainer import optimizer from chainer.optimizers import adam _default_hyperparam = optimizer.Hyperparameter() _default_hyperparam.alp...
import sys import os import shutil Import("env") # Install GitPython for interacting with remote repositories try: import git except ImportError: env.Execute("$PYTHONEXE -m pip install GitPython") import git ################################# BUILD MACROS ################################# # For each micr...
from os.path import join from numpy import sqrt, pi, linspace, array, zeros from numpy.testing import assert_almost_equal from multiprocessing import cpu_count import pytest from SciDataTool.Functions.Plot.plot_2D import plot_2D from pyleecan.Classes.OPdq import OPdq from pyleecan.Classes.Simu1 import Simu1 from p...
from collections import Counter from imblearn.datasets import make_imbalance from imblearn.metrics import classification_report_imbalanced from imblearn.pipeline import make_pipeline from imblearn.under_sampling import ClusterCentroids from imblearn.under_sampling import NearMiss import matplotlib.pyplot as plt from ...
from random import random import numpy as np from math import e def degrau(u): if u>=0: return 1 else: return 0 def degrauBipolar(u): if u>0: return 1 elif u==0: return 0 else: return -1 def linear(u): return u def logistica(u,beta): return 1/(1 + e*...
# %% """ Tests of the encoder classes """ import numpy as np import pytest import gym from gym_physx.envs.shaping import PlanBasedShaping from gym_physx.encoders.config_encoder import ConfigEncoder from gym_physx.wrappers import DesiredGoalEncoder @pytest.mark.parametrize("n_trials", [20]) @pytest.mark.parametrize("f...
import asyncio import os import rule34 as r34 import discord import wikipedia from discord.ext import commands from italian_dictionary import get_definition from random import randrange class Google(commands.Cog): def __init__(self, client): self.client = client @commands.command(name='wiki') @com...
from AExprs import AExpr, AExprEval from BExpr import * """ General Exception for Boolean Expressions Evaluation """ class BExprEvalException(Exception): pass """ Evaluation of Boolean expressions """ class BExprEval: def __init__(self,state): self.__state = state def one_step_val(sel...
# coding: utf8 __all__ = ['Stream', 'StreamState'] import json import logging from threading import Lock from enum import Enum, unique from threading import Event @unique class StreamState(Enum): """ Define the state of the Stream. Closed : The Stream is closed and ready to be opened. Pendin...
import os import shutil import numpy as np import pandas as pd import scipy.integrate, scipy.stats, scipy.optimize, scipy.signal from scipy.stats import mannwhitneyu import statsmodels.formula.api as smf import pystan def clean_folder(folder): """Create a new folder, or if the folder already exists, delete a...
from hand import * from card import * from player import * test_game = {"tournament_id":"550d1d68cd7bd10003000003", "game_id":"550da1cb2d909006e90004b1", "round":0, "bet_index":0, "small_blind": 10, "current_buy_in": 320, "pot": 400, "minimum_raise": 240, "dealer": 1, "or...
# ================================================================== # =========== Implementação de uma aplicação de rede =============== # DUPLA: <NAME> - MAT<NAME> # ================================================================== """ No TCP é necessário pedir conexão ao servidor """ import socket import pickl...
import numpy as np from PIL import Image import tensorflow as tf import re #ref: https://github.com/tensorflow/models/blob/1af55e018eebce03fb61bba9959a04672536107d/tutorials/image/imagenet/classify_image.py class NodeLookup(object): """Converts integer node ID's to human readable labels.""" def __init__(self, ...
import numpy as np import pyspark.sql.functions as F import pyspark.sql.types as T from pyspark.ml.feature import IDF, Tokenizer, CountVectorizer def isin(element, test_elements, assume_unique=False, invert=False): """ Impliments the numpy function isin() for legacy versions of the library """ ele...
#!/usr/local/bin/python import torch import torch.nn as nn from torch.autograd import Variable import numpy as np from PIL import Image import os, glob, argparse, tqdm from data_loader import get_data from model import get_model #==========================================================================# def create_fol...
from urllib.parse import urlencode from base64 import b64encode from datetime import datetime from functools import partial import operator import pickle import unicodedata import requests from lxml import html import redis import config FB_TOKEN = urlencode({"access_token": config.FB_ACCESS_TOKEN}) FB_API_ROOT = "...
import datetime import json import os import time import requests from flask import render_template, redirect, request, session from app import app import CardReader CONNECTED_NODE_ADDRESS = "http://169.254.62.57:8000" posts = [] pk = None def fetch_posts(isFiltered=True): get_chain_address = "{}/chain".format...
import tensorflow as tf from groupy.gconv.make_gconv_indices import make_c4_z2_indices, make_c4_p4_indices,\ make_d4_z2_indices, make_d4_p4m_indices, flatten_indices from groupy.gconv.tensorflow_gconv.transform_filter import transform_filter_2d_nchw, transform_filter_2d_nhwc def gconv2d(input, filter, strides, ...
import pprint import click import numerapi napi = numerapi.NumerAPI() def prettify(stuff): pp = pprint.PrettyPrinter(indent=4) return pp.pformat(stuff) @click.group() def cli(): """Wrapper around the Numerai API""" pass @cli.command() @click.option('--tournament', default=1, help='...
from datetime import timedelta import os from typing import Dict, List, Optional, Tuple from urllib.parse import urlparse from .base_config import BaseConfig, ConfigError, configfield, Lookup class RegistryConfig(BaseConfig): name: str datasource: str public_url: str repositories: List[str] = [] ...
import os import tensorflow as tf from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as viz_utils from object_detection.builders import model_builder from object_detection.utils import config_util import cv2 import numpy as np from matplotlib import pyplot as plt f...
# This code is licensed under the New BSD License # 2009, <NAME> <<EMAIL>> # For other contacts, visit http://aartemenko.com """ This is a helper to work with MongoDB's documents. Author: <NAME> <<EMAIL>> """ import types from pymongo.dbref import DBRef from mongobongo.attributed import AttributedDict _DEFAULT_OPTI...
#!/usr/bin/python # # Script to clone Geppetto git repositories # If a target directory is not passed as the # first argument, the sourcesdir specified in # config.json is used # If config.json is used, org.geppetto.core, # model, frontend and simulation are # included automatically. # The user can chose to select the ...
#!/usr/bin/env python # Copyright (c) 2019 Diamond Key Security, NFP # 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, #...
import argparse import pdb import laspy import os import shutil import numpy as np from tqdm import tqdm from semantics_recovery import all_path, mkdir def config_parser(): parser = argparse.ArgumentParser( description='Semantic label recovery script.', formatter_class=argparse.ArgumentDefaultsHel...
# Copyright (c) 2020 The Khronos Group 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 ...
from django.shortcuts import render from django.http import JsonResponse from django.core.serializers.json import DjangoJSONEncoder from django.views.decorators.csrf import csrf_exempt from api.tags import method from core import settings import json import numpy as np import pandas as pd class NumpyEncoder(DjangoJ...
""" StarGAN v2 Copyright (c) 2020-present NAVER Corp. This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, US...
from typing import Dict, List, Optional from request.base_handler import SERVICE_ID_FHIR_IDENTIFIER from request.mapper_urls import MapperUrls as Url from utilities import message_utilities SERVICE_ID_FHIR_IDENTIFIER = "https://fhir.nhs.uk/Id/nhsServiceInteractionId" def build_bundle_resource(resources: List[Dict],...
# -*- coding: utf-8 -*- """Data association solver module. Data association is the key to match a list of observed objects and the list of currently tracked items. It can be reduced to linear assignment problem and solved by Hungarian algorithm (or Kuhn–Munkres algorithm). `scipy` package already implements this alg...
"""Console-based sudoku game.""" import pickle import random from typing import List, Optional class SudokuField: """Sudoku game state.""" cells: List[Optional[int]] row_width: int filled_count: int def __init__(self, cells: List[Optional[int]], row_width: int): """Initialize game state....
# Simple HiveMQ Client built with PyCharm # excellent resource here: # https://github.com/eclipse/paho.mqtt.python#id3 import paho.mqtt.client as paho # pip install paho.mqtt from datetime import datetime import time import argparse import random from json import JSONEncoder import json import signal keepRunning = Tr...
''' Created on 3 Oct. 2018 @author: <NAME> - Geoscience Australia Hacky utility to cache EVERYTHING from OPeNDAP & WMS endpoints. WARNING: This will take some time to run to completion and consume a considerable amount of bandwidth. Do NOT try this at home. ''' import os import sys import tempfile import ...
import os import unittest from tempfile import mkstemp from clips import Environment, Symbol, CLIPSError, TemplateSlotDefaultType DEFTEMPLATE = """(deftemplate MAIN::template-fact (slot int (type INTEGER) (allowed-values 0 1 2 3 4 5 6 7 8 9)) (slot float (type FLOAT)) (slot str (type STRING)) (slot symbo...
import logging import pandas as pd from cellpy.utils.batch_tools.batch_core import BaseAnalyzer from cellpy.utils.ocv_rlx import select_ocv_points from cellpy.exceptions import UnderDefined class ICAAnalyzer(BaseAnalyzer): def __init__(self): super().__init__() class EISAnalyzer(BaseAnalyzer): def...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 12 09:45:01 2020 @author: antonio """ import pandas as pd import argparse import warnings ###### 0. Load valid codes lists: ###### def read_gs(gs_path): gs_data = pd.read_csv(gs_path, sep="\t", names=['clinical_case', 'code'], ...
#!/usr/bin/env python ############################################################################## # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompani...
import torch import torch.nn as nn import torch.optim as optim import gensim import pickle import time import numpy import os from tqdm import tqdm from torch.utils.data import TensorDataset from torch.utils.data import DataLoader from perf_model import BiLSTM, AC_BiLSTM, Time_BiLSTM from perf_train import ...
from __future__ import absolute_import, division, print_function import codecs try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict import copy import os import os.path as path import sys import toml import nfldb import nflfan.provider as provider import nflfan.sco...
import copy import json import numpy import cepton_sdk.common.transform from cepton_sdk.common import * _all_builder = AllBuilder(__name__) def _convert_keys_to_int(d, ignore_invalid=False): d_int = {} for key, value in d.items(): try: key = int(key) except: if ignor...
import numpy as np import sys from contextlib import closing from io import StringIO from gym import Env, spaces, utils from gym.utils import seeding UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 def categorical_sample(prob_n, np_random): """ Sample from categorical distribution Each row specifies class probabilitie...
""" Write 'py.test tests.py' in the terminal to test by using the 'pytest' package. For this, change the path in Windows by 'cd pyglobe3d\core\icosalogic\'. """ from pyglobe3d.core.icosalogic.mesh import Mesh from pyglobe3d.core.icosalogic.node import Node from pyglobe3d.core.icosalogic.node_attrs import NodeIndex, Nod...
""" Copyright 2021 Merck & Co., Inc. Kenilworth, NJ, USA. 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 ...
""" Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 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/L...
#!/usr/bin/python from utils.log import log import json import multiprocessing as mp #make python 2 and 3 behave the same for raw input if hasattr(__builtins__, 'raw_input'): input = raw_input data_file = "data.json" #any bot class names to leave off the scoreboard for various reasons. bots_to_skip = ["HumanB...
import cv2 import numpy as np import os import glob import pickle #from sklearn.preprocessing import normalize current_file_path = os.path.dirname(os.path.abspath(__file__)) def save_obj(obj, name ): with open(os.path.join(current_file_path,"calib_result", name + '.pkl'), 'wb') as f: pickle.dump(obj, f) ...
import torch.nn as nn import torch class ConvLSTM_Cell(nn.Module): """ input:[B,in_channels,H,W] hidden:[B,hidden_channels,H,W] Ct:[B,hidden_channels,H,W] :return ht, ct """ def __init__(self, in_channels, hidden_channels, kernel_size=3): super(Co...
""" Main application package Contains the app factory function. """ # Third party imports import dash import dash_bootstrap_components as dbc from flask import Flask from flask.helpers import get_root_path, get_debug_flag from flask_cas import login_required # Local application imports from config import DevConfig, ...
from genologics.entities import Step from config import Config from epp.useq_run_status_mail import run_finished def routeArtifacts(lims, step_uri, input): step = Step(lims, uri=step_uri) current_step = step.configuration.name print(current_step) to_route = {} for io_map in step.details.input_out...
import pickle def audio_condition(): # natural versus narration narration_users = ['user2', 'user4', 'user7', 'user8', 'user10','user14','user16','user18','user20'] natural_users = ['user3','user5','user6','user9','user11','user12','user15','user17','user19'] filename = '../data/narration_users.pkl' ...
""" day 24 of Advent of Code 2018 by <NAME> """ from copy import deepcopy from dataclasses import dataclass from enum import Enum import heapq from itertools import chain import re BOOST = 0 class Team(Enum): IMMUNE = 0 INFECTION = 1 class AttackType(Enum): FIRE = 0 BLUDGEONING = 1 SLASHING = 2 ...
""" Octave ====== Module for working with octaves. The following is an example on how to use :class:`acoustics.octave.Octave`. .. literalinclude:: ../examples/octave.py """ from __future__ import division import numpy as np REFERENCE = 1000.0 """ Reference frequency. """ def band_of_frequency(f, order=1, ref=REF...
#!/usr/bin/env python3 import argparse import readline from subprocess import PIPE, run from sys import exit, stdout import requests from jprint import jprint import signal import json from enum import Enum ES_SEARCH_ENDPOINT = "_search" _input = input class LocationType(Enum): LOCATION_TYPE_UNSPECIFIED = 0 ...
__all__ = [ "to_str", "to_bytes", "strip_punctuation", "to_ascii_str", "is_number", "count_digit", "count_alpha", "count_upper", "count_space", "count_punctuation", "split", "decode_escaped_bytes", "word_ngrams", "sentences", "has_1a1d", ] f...
from kubespawner.reflector import NamespacedResourceReflector from kubespawner.spawner import PodReflector, EventReflector from kubernetes import watch from urllib3.exceptions import ReadTimeoutError from functools import partial import json import threading import time class MultiNamespaceReflector(NamespacedResourc...
import json import logging import multiprocessing.pool from typing import Optional from cda_client import ApiClient, Configuration from cda_client.api.query_api import QueryApi from cda_client.model.query import Query from cdapython.constantVariables import table_version, default_table,project_name from cdapython.Resul...
# connect to registration table # search targets to push # 1. get all the jobs with "job_success" # 2. check if job files are indeed there # 3. get level of theory from job files # 4. check if results table has this job with # same level of theory # launch cantherm job, # push results to results table # main da...
from __future__ import print_function from six.moves import xrange from ortools.constraint_solver import pywrapcp from ortools.constraint_solver import routing_enums_pb2 import urllib.request import json from geopy.distance import vincenty test_20 = { "points": [[10.773687, 106.703263], [10.731158, 106.716759], [...
#!/usr/bin/env python # This program runs as a daemon, collects switch/router interface counter data, and sends # the metrics to Graphite. It also serves a simple HTTP service that organizes links for # the interfaces it monitors, as to create a dashboard of graphs without needing to browse # and click through t...
# -*- coding: utf-8 -*- import time from sklearn import ensemble from sklearn import linear_model from sklearn import naive_bayes from sklearn import neighbors from sklearn import neural_network from sklearn import svm from sklearn import tree from sklearn.metrics import f1_score from sklearn.model_selection import Gri...
# Copyright 2021 Alibaba Group Holding Limited. 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 ...
import os import sys from difflib import SequenceMatcher from pyproj import Proj, transform import numpy as np import pandas as pd def similar(a, b): return SequenceMatcher(None, a, b).ratio() def extract_loc(t_array, gps_data): _xy = gps_data[[0, -1]] pct = ((t_array * 1.0) / np.max(t_array))[:, np.new...
import random import time import threading from ycore.module.module import * from ycore.module.listener import * from ycore.event.event import Events # Refactor.. class AnagramsModule(Module): def __init__(self, chats, betpercent, betamount, wordlist, queue, owner): super().__init__() ...
import numpy as np from sklearn.model_selection import train_test_split, StratifiedKFold import shutil from src.model_torch import train_model_eegnet from src.utils import set_seed from src.utils import single_auc_loging import codecs from functools import reduce import os import sys sys.path.append(os.path.join(os.pa...
""" String representation for various data objects """ from collections import OrderedDict as odict import numpy as np import json import dimarray as da from dimarray.config import get_option def str_attrs(meta, indent=4): return "\n".join([" "*indent+"{}: {}".format(key, repr(meta[key])) for key in meta.keys()])...
import cv2,os import numpy as np from keras.applications.vgg16 import decode_predictions from keras.applications import ResNet50, Xception, InceptionV3, VGG16, VGG19 from keras.preprocessing import image as Image from keras.applications.vgg16 import preprocess_input from tqdm import tqdm from skimage import feat...
import os import gym import time import tqdm import torch import torch.nn.functional as F import numpy as np from rlplay.utils import ToTensor from rlplay.utils import AtariObservation, ObservationQueue, FrameSkip from rlplay.utils import RandomNullopsOnReset, TerminateOnLostLife from rlplay.utils import get_instanc...
from dna_features_viewer import BiopythonTranslator import numpy as np from copy import deepcopy from Bio import SeqIO import flametree import matplotlib.pyplot as plt from geneblocks import DiffBlocks from .biotools import ( annotate_record, sequence_to_biopython_record, sequences_differences_segments, ...
import os from dataclasses import dataclass import imageio import numpy as np import tensorflow as tf from tensorflow.keras import backend as K def get_callbacks(save_path, lr_schedule, prefix=None): """ Creates callbacks. Arguments: save_path: the logs and checkpoints will be stored here. lr_schedule: learni...
import torch import torch.nn as nn import torch.nn.functional as F conv_config = { 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512], 'B': [64, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'C': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512...
from django.shortcuts import render, redirect, reverse from .models import Post, Comment, Rating from django.contrib.auth.mixins import UserPassesTestMixin from django.views.generic import DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.decorators import login_required from django.utils.decorato...
# Copyright 2008-2018 Univa Corporation # # 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...
#!/usr/bin/env python3 import sys import os from scipy.stats import wasserstein_distance from scipy.stats import ks_2samp def compare_fct_mse(input1, input2): fct_dict = dict() with open(input1, "r") as f1: for line in f1: toks = line.split() dst = int(toks[0]) src...
# Copyright 2019 Open End 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 law or agreed to in writing, s...