text stringlengths 3.07k 22.1k |
|---|
from handler.base_plugin import BasePlugin
import json
import motor.motor_asyncio
class sdict(dict):
"""Dictionary with field `changed`. `changed` is True when any element was
accessed."""
def __init__(self, *args, **kwargs):
self.changed = False
super().__init__(*args, **kwargs)
d... |
from cort.core import corpora
import codecs
import re
import os
import sys
def read_corpus():
dev_all = 'data/conll-2012-flat/dev-all/all.v4_auto_conll'
dev_small = 'data/conll-2012/v4/data/development/data/english/annotations//mz/sinorama/10/ectb_1010.v4_auto_conll'
with codecs.open(dev_all, 'r', "utf-8")... |
#!/usr/bin/python
#
# file: callattendant.py
#
# Copyright 2018 <NAME> <<EMAIL>>
#
# 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... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020, University of Southampton
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE.md file in the project root for full license information.
"""
import math
import os
from pathlib import Path
import pandas as pd
from auv_nav.tools.interpolate import in... |
import torch
import neural_network_lyapunov.gurobi_torch_mip as gurobi_torch_mip
import neural_network_lyapunov.utils as utils
import neural_network_lyapunov.mip_utils as mip_utils
import neural_network_lyapunov.relu_to_optimization as relu_to_optimization
class ControlAffineSystemConstraintReturn:
"""
The re... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 1 18:09:27 2021
@author: lukas
"""
import cv2
import dlib
import numpy as np
import timeit
import utils
import queue
import multiprocessing
import pathlib
import argparse
import time
def _create_parser():
parser = argparse.ArgumentParser()
parser.add_argument(... |
import os
import unittest
import logging
import tempfile
import subprocess
from .base_utils import (HAS_PBCORE,
pbcore_skip_msg,
get_temp_file,
get_temp_dir)
from pbcommand.resolver import (resolve_tool_contract,
... |
# -*- coding: utf-8 -*-
#
from io import BytesIO
import rdflib
import requests
from flask import render_template, url_for
from rdflib import URIRef, Literal, BNode
from requests import Session
from lxml import etree
from geofabric import _config as config
from geofabric.helpers import gml_extract_geom_to_geojson, \
... |
"""
lexical array set operations
these operations are based upon the one dimensional array set operations
from numpy.lib.arraysetops, but generalised to work for sets of m-tuples,
where each element is stored as a row of a 2d m by n array, using numpy's
'lexsort' lexical sorting function.
"""
import numpy
def unique... |
#!/usr/bin/env python
# coding: utf-8
# # Optimization
# In[101]:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# These are some parameters to make figures nice (and big)
#%matplotlib inline
#%config InlineBackend.figure_format = 'retina'
params = {'legend.fontsize': 'x-large',
... |
#!python2
# Workflow to clean, split and standardize coverage shapefiles
# Need Python 2.7 and ArcPy
import arcpy, logging, sys
from os import path, sep, makedirs, removedirs, getpid, listdir, remove
from datetime import date, datetime
from shutil import copy, rmtree
arcpy.env.overwriteOutput = True #overwrite existi... |
#!/usr/bin/env python
import os
import traceback
import ipaddr as ipaddress
import csv
import string
from operator import itemgetter
from itertools import groupby
import yaml
from collections import defaultdict
DOCUMENTATION = '''
module: test_facts.py
version_added: 2.0.0.2
short_description: get lab testbed and tes... |
from fastai.vision import ImageSegment, Image
from fastai.vision.image import open_image, show_image, pil2tensor
from fastai.vision.data import SegmentationProcessor, ImageList
from fastai.layers import CrossEntropyFlat
from fastai.basic_train import LearnerCallback
import torch
import warnings
import PIL
import numpy ... |
# -*- coding: utf-8 -*-
##
# Copyright 2018 University of Bristol - High Performance Networks Research
# Group
# All Rights Reserved.
#
# Contributors: <NAME>, <NAME>, <NAME>
# Muqaddas, <NAME>, <NAME> and <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in c... |
import os
import sys
import tempfile
import pytest
import json
from contextlib import contextmanager
from geventhttpclient import HTTPClient
from gevent.ssl import SSLError #@UnresolvedImport
import gevent.pool
import gevent.server
import gevent.pywsgi
from six.moves import xrange
listener = ('127.0.0.1', 54323)
@co... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def spectral_norm(module, mode=True):
if mode:
return nn.utils.spectral_norm(module)
return module
def Normalize(in_channels, mode):
if mode == 'IN':
return nn.InstanceNorm2d(in_channels)
elif mode == 'GN':
r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import deeptools.mapReduce as mapReduce
from deeptools import bamHandler
from deeptools import utilities
import sys
debug = 0
def getFractionKept_wrapper(args):
return getFractionKept_worker(*args)
def getFractionKept_worker(chrom, start, end, b... |
# Sample code from http://www.redblobgames.com/pathfinding/
# Copyright 2014 <NAME> <<EMAIL>>
#
# Feel free to use this code in your own projects, including commercial projects
# License: Apache v2.0 <http://www.apache.org/licenses/LICENSE-2.0.html>
class SimpleGraph:
def __init__(self):
self.edges... |
import re
from dataclasses import dataclass
from enum import Enum
from fnmatch import fnmatch
from typing import ClassVar, Mapping, Optional, Sequence, Union
class PolicyError(ValueError):
pass
class RuleError(ValueError):
pass
class InsecureRule(RuleError): # pragma: nocover
def __init__(
... |
#!/usr/bin/env python3
# This tests methods of saving 12-bit cv2 images files, which are represented as numpy arrays,
# in parallel to 8-bit jpeg files. Pickling and shared memory methods are used. Various
# numbers of and sizes of images are tested. Using random images is not reflective of
# compression of normal i... |
import pygame
from card import Card
__all__ = ['rgb',
'Button', 'infoButton', 'game_buttons', 'pos_from_center',
'PygamePlayer', 'PygameTable']
rgb = {"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"yellow": (255, 255, 0),
"white": (255, 255, 255),
... |
import torch
from torch import nn
import math
from spinflow.nets import MLP
def init_weights(net, init='ortho'):
net.param_count = 0
for module in net.modules():
if isinstance(module, (nn.Conv1d, nn.Conv2d, nn.Linear,
nn.ConvTranspose2d, nn.ConvTranspose1d)):
... |
# coding: utf-8
# ## Importing: Please convert .ipynb files to .py files to import successfully
# # Setting up environment
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.tsatools import detrend
from statsm... |
import json
import matplotlib.pyplot as plt
import sys
import os
from matplotlib.backends.backend_pdf import PdfPages
from random import randrange
import re
import traceback
from datetime import datetime
import argparse
import operator
def buildGapChart(data, name, namei):
"""
data = {
'gap' :[]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME> (<EMAIL>)
# @Date: 2019-03-04
# @Filename: healpix.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: <NAME> (<EMAIL>)
# @Last modified time: 2019-03-13 15:01:07
import healpy
import numpy
i... |
import numpy as np
import pygame, sys
from numpy import sin,cos
import drawSvg as draw
pygame.init()
def info(d,datalabel,x,y,textsize,textcolor,datacolor):
d.append(draw.Text(datalabel, textsize, x,y, center=False, fill=textcolor,stroke=textcolor, stroke_width=0))
d.append(draw.Line(x-50, y+textsize/4, x-5, y+te... |
"""
Various functional tests for TLS networking.
Most are taken from other test files and adapted.
"""
import asyncio
import pytest
from distributed import Client, Nanny, Queue, Scheduler, Worker, wait, worker_client
from distributed.core import Status
from distributed.metrics import time
from distributed.utils_test ... |
import argparse
import json
import logging
import os
import subprocess
import time
from typing import Any, Tuple, Optional
import yaml
from mir.commands import base
from mir.tools import utils as mir_utils
from mir.tools.code import MirCode
from mir.tools.errors import MirRuntimeError
class CmdInfer(base.BaseComman... |
import sqlite3
import tensorflow as tf
import random
import numpy as np
from matches import Matches
con = sqlite3.connect("tba.db")
print("Database Connected")
cur = con.cursor()
cur.execute("SELECT * FROM matches WHERE rowid=2345")
print(cur.fetchone())
batch_size = 1
def getScoreData(): #15373 matches
sam... |
import asyncio
import datetime
import json
import aiofiles
import discord
import gspread.exceptions
import gspread_asyncio
from discord.ext import commands
from oauth2client.service_account import ServiceAccountCredentials
from pytz import timezone
from alttprbot.alttprgen.preset import get_preset
from alttprbot.data... |
import sys
from os.path import dirname, abspath, join
import numpy as np
path = dirname(abspath(__file__))
root = dirname(dirname(path))
sys.path.append(root)
from examples import Problem
from examples.hardware.model import diamondRobot
# Default nodes are the "end effector (1354)" and the "elbows (726, 139, 1445, ... |
import threading
import time
from collections import deque
from spry.progress import Counter, ProgressTracker, SpeedLimiter
from spry.utils import (
STATE_CHECK, unit_pair_to_bytes
)
class Streamer:
def __init__(self, remote_path, local_path, section, tracker, limiter, counter, timeout):
self.remote... |
"""
Object finding and measuring ellipticity
========================================
This script provides a class that can be used to analyse VIS data.
One can either choose to use a Python based source finding algorithm or
give a SExtractor catalog as an input. If an input catalog is provided
then the program assume... |
# 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
# d... |
# Copyright 2019 PerfKitBenchmarker 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 appli... |
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
TODO:
- Speed tests, need to be certain the looping on all telescopes is not killing
performance
- Introduce new weighting schemes
- Make intersect_lines code more readable
"""
import numpy as np
import itertools
import astropy.units as u
from ctapip... |
from concurrent.futures import ThreadPoolExecutor
from pydash import py_
from cv2 import cv2
import numba
import time
import re
import pathlib
import numpy
import os
import shutil
import typing
import dataclasses
import typing
import argparse
import sys
# ffmpeg的帧编码从1开始
# render_subtitle渲染所得文件的帧编号也从1开始
... |
import logging
import argparse
import sys, os
from datetime import datetime
from progressbar import *
from struct import pack_into
from array import array
from netaddr import *
sys.path.insert(0, os.path.abspath('..'))
from Utils.Constants import Constants
from Utils.Utils import Utils
constants = Constants()
utils_ =... |
from application import app
from flask import Response, request
import logging
import requests
import json
import traceback
import kombu
import re
import json
import datetime
from datetime import timedelta
def check_bankreg_health():
return requests.get(app.config['BANKRUPTCY_DATABASE_API'] + '/health')
applicat... |
import typing as t
from typing import TYPE_CHECKING
from simple_di import inject
from simple_di import Provide
import bentoml
from bentoml import Tag
from bentoml.exceptions import BentoMLException
from bentoml.exceptions import MissingDependencyException
from ..models import PKL_EXT
from ..models import SAVE_NAMESP... |
import sys
import traceback
import pkgutil
from celery.task import Task, PeriodicTask
from celery.utils.log import get_task_logger
from celery.app.registry import TaskRegistry
import logging
logr = logging.getLogger(__name__)
import engines
from scanworker.exception import *
# DON't import masterworker or anything fr... |
"""
Tests for dnstools module.
"""
from __future__ import print_function
import pytest
pytestmark = pytest.mark.django_db
from dns.resolver import NXDOMAIN, NoAnswer
from ..dnstools import (add, delete, update, query_ns, rev_lookup, update_ns,
SameIpError, DnsUpdateError, FQDN)
# see also ... |
'''
AAA lllllll lllllll iiii
A:::A l:::::l l:::::l i::::i
A:::::A l:::::l l:::::l iiii
A:::::::A l:::::l l:::::l
... |
import ipdb
import yaml
import os
import sys
from shutil import rmtree
import argparse
from time import sleep
from subprocess import Popen, PIPE
from pathlib import Path
from typing import List
from e3sm_to_cmip import resources
DESC = '''test the output of the e3sm_to_cmip package from
two git branches and run a... |
import smart_imports
smart_imports.all()
class TestPowerStorage(storage.PowerStorage):
TARGET_TYPE = tt_api_impacts.OBJECT_TYPE.PERSON
def __init__(self, targets_ids, **kwargs):
super().__init__(**kwargs)
self._test_targets_ids = targets_ids
def _tt_targets_ids(self):
return ... |
from copy import deepcopy
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, normal_init
from mmcv.ops import DeformConv2dPack, DeformConv2d
from mmdet.core import get_bbox_dim
from mmdet.models.builder import HEADS, build_head
from ..base_dense_head import BaseDenseHead
class AlignConv(nn.Module):... |
from __init__ import *
from utils import *
def cov_plot(dataset, sequence, scan_ref, scan_in):
base_path = os.path.join(Param.results_path, sequence, str(scan_ref))
T_gt = dataset.get_data(sequence)
T_init = SE3.mul(SE3.inv(T_gt[scan_ref]), T_gt[scan_in])
T_mc, T_init_mc = dataset.get_mc_results(sequ... |
import json
import logging
import zlib
from bitstring import BitArray, BitStream, ConstBitStream
import cv2
from bitglitter.utilities.compression import compress_bytes
from bitglitter.utilities.encryption import encrypt_bytes, get_sha256_hash_from_bytes
def calibrator_header_render(image, block_height, block_width,... |
"""
Code to parallelize gym environments obtained from
https://github.com/openai/baselines/blob/b5be53dc928bc19c39bce2a3f8a4e7dd0374f1dd/baselines/common/vec_env/subproc_vec_env.py
It has been modified to deal with PyTorch Tensors and Variables.
"""
import logging
try:
import roboschool
except ImportError as e:
... |
#!/usr/bin/python
#
# Copyright (c) 2019 Hewlett Packard Enterprise Development LP
#
# 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 re... |
import time, operator
import numpy as np
from collections import namedtuple
from .. import board_utils, win_state_utils
from .. import models
from ..utils import timeit
from .transposition_table import TTable, State
def get_max_score(n_rows, n_cols):
return n_rows * n_cols
def get_utility(state, max_score):
... |
#ckwg +28
# Copyright 2019 by Kitware, 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 conditi... |
#!/usr/bin/env python2
import sys, os, StringIO, clang.cindex
type_conv = {
clang.cindex.TypeKind.VOID: 'void',
clang.cindex.TypeKind.LONG: 'long',
clang.cindex.TypeKind.ULONG: 'unsigned-long',
clang.cindex.TypeKind.LONGLONG: 'integer64',
c... |
"""
Copyright 2014-2016 University of Illinois
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 writ... |
"""
PyQt Graphical User Interface
<NAME> - 08/31/2019
Frontend of the map conversion. This code communicates with the backend program used to take maps downloaded from 'terrain.party'
and produce a .csv file with associated heights of each pillar to display map to scale. Running this code opens a new window with
inpu... |
import argparse
import itertools
import json
import pathlib
import re
import sqlite3
import sys
import time
from datetime import datetime
import bitmath
import pandas as pd
from elasticsearch import (Elasticsearch, ElasticsearchException,
RequestsHttpConnection)
from shodan import APIError, ... |
import ui_common as uic
import userauth
import ezidapp.models
import stats
from datetime import datetime
import ui_search
from collections import *
import csv
import StringIO
from django.utils.translation import ugettext as _
NO_CONSTRAINTS = True
@uic.user_login_required
def dashboard(request):
"""
ID Issues... |
import os
import shutil
import cv2
import numpy as np
import torch
from natsort import natsorted
from sewar.full_ref import ssim
import imgproc
from model import HDRNet
def delete_background(image_dir: str) -> None:
print("Delete background.....")
# 粗筛法
image_file_names = natsorted(os.li... |
# Copyright 2021 <NAME> <EMAIL>
#
# 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 writin... |
# encoding: utf-8
from Storm.Localized import Strings as LocalizedStrings
from Storm.GameData import Catalog
from Storm.DepotIndex import DepotIndex
from Storm.DepotCataFile import DepotCataFile, TYPE_NONE, TYPE_PRODUCTS, TYPE_LICENSES
from sys import argv
from os.path import exists
def print_utf8(text):
... |
'''
@ <NAME> (<EMAIL>)
January 2016
Generals.io Automated Client - https://github.com/harrischristiansen/generals-bot
Generals Bot: Base Bot Class
'''
import logging
from Queue import PriorityQueue
import random
import threading
import time
from client import generals
from viewer import GeneralsViewer
# Opponent... |
import bpy
from mathutils import *
from math import *
import bmesh, random, time, os, sys, os.path
from .Global import svglob
#START
last_view = Vector([0, 0, 1])
did_render = False
def getKey(shapeview, key):
for sk in shapeview.skeys:
if sk.shapekey == key:
return sk
ret = shapev... |
from collections import defaultdict
import requests
from scoville.mvt import Tile
def _fetch_http(url):
"""
Fetch a tile over HTTP.
"""
res = requests.get(url)
# TODO: retry? better error handling!
if res.status_code != requests.codes.ok:
print('Got tile response %d for %s' % (res.... |
import os
import numpy as np
import pandas as pd
from skimage.morphology import opening
from skimage.morphology import cube
from skimage.feature import blob_log
from skimage.filters import median
from skimage.draw import circle_perimeter
from msbrainpy.base import extraListNesting, getSubsections
from msbrainpy.chain i... |
import json
import os
import shutil
import numpy as np
from django.http import FileResponse
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import ResNet50.json_to_dict as jtd
import ResNet50.test_back_end as resnet
from demoConnec... |
import os
import time
import socket
import select
import ssl
import logging
from taky.config import app_config as config
from .router import COTRouter
from .client import TAKClient, SocketTAKClient, SSLState
from .mgmt import MgmtClient
def build_srv(ip_addr, port):
if ip_addr is None:
ip_addr = ""
... |
import vtk
from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase
from vtk.util import vtkConstants, numpy_support
import numpy
from .widget import MutableDataSet, DataContainer, DataArray
array_lut = {}
container_lut = {}
widget_lut = {}
_std_attribute_indices = {
vtk.vtkDataSetAttributes.SCALARS: 'Sca... |
# File: autotester/html.py
# Author: <NAME>
# Date: 20NOV2016
#
# Description:
# This file contains the HTML generation code for the autotester.
# This includes generating the initial HTML file as output of the
# python run, and the javascript that builds the results at runtime
# in the browser.
#
from org.transcryp... |
#
# * This library is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation; either
# * version 2.1 of the License, or (at your option) any later version.
# *
# * This library is distributed in the hope that ... |
# Copyright 2022 Quantapix 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 applicable l... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 11 13:21:21 2016
@author: nhuynh
"""
from enum import Enum;
import utilities;
import mmRef;
import TrainLine;
defPaxFlowsPath = '../user inputs/defaultPaxFlowAtStns/';
trainLines = [];
stnTimetables = {};
stnDefPaxFlows = {};
def getPrevStop(crnStopN... |
#! /usr/bin/env python
"""Run a YOLO_v2 style detection model on test images."""
import argparse
import colorsys
import imghdr
import os
from subprocess import call
import random
import numpy as np
from keras import backend as K
from keras.models import load_model
from PIL import Image, ImageDraw, ImageFont
import cv... |
from zipfile import ZipFile
from jawa.cf import ClassFile
from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor
from parsimonious.exceptions import ParseError
from .mavenversion import ComparableVersion
DEPENDENCY_GRAMMAR = Grammar(r"""
start = dependencies?
dependenci... |
import discord
from discord.ext import commands
import collections
import aiohttp
import inspect
import traceback
from contextlib import redirect_stdout
from PythonGists import PythonGists
import io
'''Module for an embeded python interpreter. More or less the same as the debugger module but with embeds.'''
... |
import os
import numpy as np
import matplotlib.pyplot as plt
from .ddpg_lib import *
class DQNAgent(object):
"""docstring for DQNAgent"""
def __init__(self, sess, pa):
self.sess = sess
self.user_id = pa.id
self.state_dim = pa.state_dim
self.action_dim = pa.action_dim
s... |
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.core.validators import EMPTY_VALUES
from django.db.models.query import QuerySet
from django.utils import six
from django.utils.trans... |
import matplotlib.dates as mdates
import numpy as np
np.set_printoptions(threshold=3)
np.set_printoptions(suppress=True)
from numpy import genfromtxt
import matplotlib.pyplot as plt
from scipy.stats import norm
from sympy import Symbol, symbols, Matrix, sin, cos
from sympy import init_printing
from sympy.utilities.cod... |
# Purpose: DXF file testing and opening
# Created: 05.01.2018
# Copyright (C) 2018-2020, <NAME>
# License: MIT License
# Local imports to avoid cyclic import
from typing import TextIO, TYPE_CHECKING, Union, Sequence
import base64
import io
from ezdxf.tools.standards import setup_drawing
from ezdxf.lldxf.const import DX... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The main script for scraping the FIRDS XML data. Contains functions
for iterating through each week in a reference time period, fetching the
relevant XML files, analysing the contents and building a CSV file with
aggregated data about the benchmark rates.
"""
import ... |
"""
EVE ESI (public API) layer
"""
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Any, Dict, Optional
import logging
import re
from dateutil import parser
import mongoengine as me
import pydantic as pdt
from requests import request, Response
from sni.conf import CONFIGURATION as conf
fr... |
import random
import numpy as np
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
from utils.data_structures import SegmentTree, MinSegmentTree, SumSegmentTree
class ExperienceReplayMemory:
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
... |
from fastai.core import *
from fastai.torch_imports import *
from fastai.dataset import Transform
from fastai.layer_optimizer import LayerOptimizer
from fastai.sgdr import CircularLR_beta
from .modules import ConvBlock
from .generators import GeneratorModule
from .dataset import ImageGenDataLoader
from collections impo... |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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 requir... |
from enum import Enum
class AttackType(Enum):
ANTIAIR_ONLY = 11 #Doesn't hit characters on the ground? Very rare, appears on Alisa's chainsaw stance f+2
THROW = 10 #this is only the attack type *during* the throw animation
LOW_UNBLOCKABLE = 9 #Yoshimitsu's 10 hit combo 2 has one
HIGH_UNBLOCKABLE... |
from __future__ import print_function
import os
import torch
import torch.optim as optim
import torch.backends.cudnn as cudnn
import argparse
import torch.utils.data as data
from data import WiderFaceDetection, detection_collate, preproc, cfg_mnet, cfg_re50,ohemDataSampler
from layers.modules import MultiBoxLoss
from l... |
import os
import csv
import time
from pathlib import Path
import fire
import clip
import torch
import torchvision
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from alive_progress import alive_bar
from PIL import Image
from ribs.archives import CVTArchive, GridArchive
from ribs.emitters i... |
# -*- coding: utf-8 -*-
""" Class to generate signals with continous-time Markov chains
@author: <EMAIL>
"""
# %%
import numpy as np
import random
import scipy.linalg
import itertools
def _solve_least_squares(a, b):
rcond = None
solution = np.linalg.lstsq(a, b, rcond=rcond)[0]
return solution
class C... |
from __future__ import print_function
import time
from pddlstream.algorithms.scheduling.plan_streams import OptimisticPlanSolver
from pddlstream.algorithms.algorithm import parse_problem
from pddlstream.algorithms.common import SolutionStore, stream_plan_complexity
from pddlstream.algorithms.constraints import PlanCo... |
# slimDNS
# Simple, Lightweight Implementation of Multicast DNS
# Copyright 2018 <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
#
# Un... |
'''
The scATAC-seq data comes as three files, P1, P2 and the barcode, and there is no UMI
You can just align P1 and P2 with your favourite aligner (we prefer STAR with these settings):
****
teopts=' --outFilterMultimapNmax 100 --winAnchorMultimapNmax 100 --outSAMmultNmax 1 --outSAMtype BAM SortedByCoordinate --twopa... |
#!/usr/bin/env python
import click
from importlib import import_module
from .common import submit_options
def _load_dependencies():
global yaml, sys, requests, json, os, http
yaml = import_module('yaml')
sys = import_module('sys')
requests = import_module('requests')
json = import_module('json')
... |
from time import time
from .net_utils import *
def train_model(opt,model, dataloaders,writer):
since = time()
print_step = opt['tsk_set'][('print_step', [10,4,4], 'num of steps to print')]
num_epochs = opt['tsk_set'][('epoch', 100, 'num of training epoch')]
continue_train = opt['tsk_set'][('continue... |
"""Utilities for pytorch NN package"""
#pylint: disable=no-member, invalid-name
import torch as th
from torch import nn
from ... import DGLGraph
from ...base import dgl_warning
def matmul_maybe_select(A, B):
"""Perform Matrix multiplication C = A * B but A could be an integer id vector.
If A is an integer ve... |
from __future__ import print_function
from __future__ import absolute_import
# Copyright (c) 2015-2016, Danish Geodata Agency <<EMAIL>>
# Copyright (c) 2016, Danish Agency for Data Supply and Efficiency <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee ... |
# coding= utf-8
# Copyright (c) 2015 Rackspace, 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 o... |
from fractions import Fraction
import itertools
from math import sqrt
from unittest.mock import Mock, patch
import pytest
from omnidice import drv
from omnidice.drv import DRV, p
from omnidice.expressions import Atom
def test_sample():
"""
DRV with float probabilities uses random(). With Fraction uses randr... |
# Copyright 2013 Cisco Systems, 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 o... |
import functools
import logging
import os
from contextlib import contextmanager
from datetime import timedelta
from alembic import command
from alembic.config import Config
from sqlalchemy import create_engine
from sqlalchemy.orm.session import Session
from sqlalchemy.pool import NullPool
from sqlalchemy.sql import an... |
import numpy as np
from scipy import special, optimize, spatial
import matplotlib.pyplot as plt
from sklearn import mixture
from sklearn import preprocessing
from sklearn.decomposition import PCA
from MulticoreTSNE import MulticoreTSNE as TSNE
from umap import UMAP
def stratefied_sampling(index, label, prob, size):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.