text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''Filter construction and loading.
--------------------------------
`resampy` provides two pre-computed resampling filters which are tuned for either
high-quality or fast calculation:
- `kaiser_best` : 64 zero-crossings, a Kaiser window with beta=14.769656459379492... |
# Copyright (C) 2016 <NAME>. 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
# ========================================... |
# -*- coding: utf-8 -*-
"""
@package tcmi.utils
@copyright Copyright (c) 2018+ <NAME> Institute of the Max Planck Society,
<NAME> <<EMAIL>>
@license See LICENSE file for details.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the ... |
# coding: utf-8
import time
import random
import os
import json
import re
import sys
import subprocess
import threading
sys.path.append(os.getcwd() + "/class/core")
import mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'go-fastdfs'
def getP... |
# 使用 MIT License 进行许可。
# SPDX-License-Identifier: MIT
# 版权所有 © 2020-2021 NKID00
'''转换 CSV 格式的 ECDICT 到 SQLite3 格式'''
from csv import DictReader
from sqlite3 import connect
from time import time
from util import ask_input, ask_output, copy_item, set_item, insert_dict, insert_info
def create_table(cursor, table: str... |
import cv2
import numpy as np
import scipy
import scipy.io as scio
from PIL import Image
import time
import math
import os
import h5py
def get_density_map_gaussian(H, W, ratio_h, ratio_w, points, adaptive_kernel=False, fixed_value=15):
h = H
w = W
density_map = np.zeros([h, w], dtype=np.float... |
import math
import copy
from functools import partial
import paddle
import paddle.nn as nn
from droppath import DropPath
class Identity(nn.Layer):
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
class PatchEmbedding(nn.Layer):
"""Patch Embeddings
... |
import torch
import torch.nn as nn
class PackDecoder(nn.Module):
def __init__(self, ):
super().__init__()
out_channels = 1
ni, no = 64, out_channels
n1, n2, n3, n4, n5 = 64, 64, 128, 256, 512
n1o, n1i = n1, n1 + ni + no
n2o, n2i = n2, n2 + n1 + no
... |
import logging
import os
import sys
from dataclasses import dataclass
from datetime import datetime
from subprocess import Popen
from tempfile import TemporaryDirectory
from typing import List, Optional, Sequence
import requests
from dataclasses_json import dataclass_json # type: ignore
from requests import Response
... |
import torch
import random
import numpy as np
from copy import deepcopy
from torch.utils.data._utils.collate import default_collate
class Collator(object):
def __init__(self, fn_list):
self.fn_list = []
for k, v in fn_list:
self.fn_list.append(eval(k)(**v))
def collate_fn(self, ba... |
# Create Ultrasound Segmentation Batch Generator Class
import keras.utils
import scipy.ndimage
import numpy as np
def scale_image(image, factor):
if len(image.shape) == 2:
image = image[:, :, np.newaxis]
height, width, depth = image.shape
zheight = int(np.round(factor * height))
zwidth = int... |
import os
import gc
import sys
import click
import pickle
import random
import sklearn
import hyperopt
import numpy as np
import pandas as pd
from pprint import pprint
from datetime import datetime
from hyperopt import fmin, tpe, hp, STATUS_OK
from config import read_config, KEY_FEATURE_MAP, KEY_MODEL_MAP
from utils i... |
#!/usr/bin/env python3
## Description: Pulls IOCs from pastes from monitored authors and adds them to MISP as events with attributes.
## Author: <NAME>
## Date: 28 June 2018
## Instructions: populate the usernames.conf-file with the username of pastebin-authors you want to fol... |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: <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
#
#... |
#! /usr/bin/env python3
import numpy as np
import argparse
from collections import Counter
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import eigsh
from scipy.stats import kstest as KS
from sklearn.preprocessing import scale
from scipy.stats import chi2, norm
##########################################... |
"""Functions that handle saving and loading of checkpoints."""
import os
from collections import OrderedDict
import torch
import vmb.utils.logging as logging
logger = logging.get_logger(__name__)
def get_checkpoint_in_path(path):
names = os.listdir(path) if os.path.exists(path) else []
names = [f for f in ... |
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import os
import requests
import math
from urllib import parse
from django.shortcuts import render
from django.conf import settings
def search_candidates(query):
"""Searches the data API for candidates matching the query"""
path = os.path.join(settings.FEC_API_VERSION, 'candidates', 'search')
url = pars... |
import argparse
import json
import os
import sys
# We need to make sure we know where our SSL certificates are.
# See https://stackoverflow.com/questions/34358935/python-treq-fails-with-twisted-openssl-error-due-to-empty-trust-store-on-windows
import certifi
os.environ["SSL_CERT_FILE"] = certifi.where()
import attr
i... |
import torch
import mmcv
from mmcv.runner import load_checkpoint, obj_from_dict
from mmcv.parallel import scatter, collate, MMDataParallel
from mmdet import datasets
from mmdet.core import eval_cvc_mr, eval_caltech_mr, eval_kaist_mr
from mmdet.datasets import build_dataloader
from mmdet.models import build_detector
imp... |
#!/usr/bin/env python
"""
Module for generating gmsh post processing files for use as background meshes.
Elements have the form:
[[coords], data]
or
[[coords], [data]]
"""
import sys
def ReadMsh(filename):
"""
Reads a gmsh msh file. Returns a list of node coordinates, and a dictionary of
elements each with... |
import os
from .gk_operators import GK_Operators
"""
Param_input_options = []
Param_inout_options = ['VALUE']
Param_output_options = []
FV_input_options = Param_input_options+['LB','UB','CRITICAL', 'DMAX', 'DMAXHI',
'DMAXLO', 'FSTATUS', 'LOWER','MEAS',
... |
"""
Animate the algorithms.
Visualize the performed chasing accross iterations.
Each animation consists basically of 6 modular building blocks:
1. The algorithm (of course).
2. A setup for the figure and axis of the underlying pyplot plot.
3. An init() function that plots the basic canvas of each single p... |
import re
import os
import glob
import shutil
import distutils.dir_util
import filecmp
class Error(OSError):
pass
class Action():
@classmethod
def read(cls, file_name, mode='r', buffering=-1, encoding='utf-8', errors=None, newline=None, closefd=True, opener=None):
'''File read'''
with open... |
# coding=utf-8
# Copyright 2019 The Weak Disentangle Authors.
#
# 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 applica... |
#
import argparse
from pprint import pprint
import numpy as np
from glob import glob
import pandas as pd
import os
import random
import dill
import progressbar
import numpy as np
import torch
from pytorch_lightning import seed_everything
import matplotlib.pyplot as plt
import scipy
from datasets import *
from model imp... |
from flask import Flask, render_template
from sqlalchemy import create_engine, MetaData, Table, Column, DECIMAL, Integer, String
import boto3
import os
import time
from flask import request
# ugly globals but this isn't MVC so I don't have a good way to share data across pages atm
numfiles = ""
bucket = ""
region = ""... |
"""Fisher's exact tests on various targets."""
import os
import pandas as pd
import scipy.stats as stats
from typing import List, Tuple
from C import (
DIR_RESULTS_ALGORITHMS, LINSOL_DCT, NONLINSOL_DCT, SOLALG_DCT, ATOL_RTOLS)
# Number of failures and successes for every setting
failures = {}
successes = {}
for ... |
import random
import functools
from collections import defaultdict
from .core import (calc_edge_weight_float, calc_node_weight_float, jitter_dict,
ContractionTree, PartitionTreeBuilder, oset)
from .hyper import register_hyper_function
def oe_to_igraph(inputs, output, size_dict,
we... |
import os
import time as t
import sys
import argparse
import colorama
import pyfiglet
from colorama import init
from colorama import Fore
from termcolor import cprint
from datetime import datetime
import datetime as dt
init()
parser = argparse.ArgumentParser()
args = parser.parse_args()
def pscan():
cls()
... |
from functools import partial
from typing import List, Optional, Type
from structlog import get_logger
from ...artifact_context import ArtifactContext
from ...helpers import get_associated_step
from ...metaprogramming import camel_to_snake, snake_to_camel
from ...naming import FEATURES_CLS_SUFFIX, INDEX_CLS_SUFFIX, T... |
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2018-2022 <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 ri... |
########################################################################################################################
# Imports
########################################################################################################################
import numpy as np
import pandas as pd
import matplotlib.pyplot as p... |
# Copyright (c) 2015. Mount Sinai School of Medicine
#
# 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 logging
import typing
import gym
import tella
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.utils import obs_as_tensor
from stable_baselines3.common.preprocessing import is_image_space
import numpy as np
import torch
logger = logging.get... |
# initial data input
infilename = "./day8.txt"
# record which marks item already visited
VISIT_MARK = {"vis", 0}
def readfile():
with open(infilename, "rt", encoding="utf-8") as file:
inlist = [line.strip() for line in file]
return inlist
def parse_input(inlist=readfile()):
data_list = [] # li... |
import bottle
import requests
import json
import os
import logging
# constant representing the API version supported
# keys off HEADER X-Broker-Api-Version from Cloud Controller
X_BROKER_API_VERSION = 2.3
X_BROKER_API_VERSION_NAME = 'X-Broker-Api-Version'
# UPDATE THIS FOR YOUR ECHO SERVICE DEPLOYMENT
service_base = ... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from hyperparameters import *
class G(nn.Module):
def __init__(self):
super(G, self).__init__()
self.loss = nn.BCELoss()
self.fc1 = nn.Linear(G_INPUTS, 8 * MODEL_COMPLEXITY * NB_CHANNELS)
self.fc2 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import unittest
from parameterized import par... |
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from ecantina_project import constants
from api.models.ec.organization import Organization
from api.models.ec.store import Store
from api.models.ec.customer import Customer
from api.models.ec.employee import Employee
fr... |
from PIL import Image
from log import *
class PNGimage:
new_data = []
tumple_out = []
module_log = logs(5)
data_offset = 4
def __init__(self, src_file, result_file):
self.Im = Image.open(src_file)
self.Im = self.Im.convert("RGBA")
self.datas = self.Im.getdata()
sel... |
from django.db.models import Sum
from fastrunner import models
from fastrunner.utils.parser import Format
from djcelery import models as celery_models
def get_counter(model, pk=None):
"""
统计相关表长度
"""
if pk:
return model.objects.filter(project__id=pk).count()
else:
return model.obje... |
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "COSAL"
from utils import logger, cache
from utils.lib import O
from mos.helpers import contexter
from mos.search_store import code_store
from mos.search import contextual
from mos.search.tree import java_tree, py_... |
import itertools
import json
from dataclasses import dataclass
from typing import (Any, Dict, Iterable, List, Mapping, Optional, Tuple, Type,
Union)
from nonebot.adapters import Message as BaseMessage
from nonebot.adapters import MessageSegment as BaseMessageSegment
from nonebot.typing import overr... |
import argparse
import codecs
import csv
import email.parser
import os
import io
import re
import site
import subprocess
import sys
import zipfile
def run():
parser = argparse.ArgumentParser(description='Recreate wheel of package with given RECORD.')
parser.add_argument('record_path',
h... |
import io
import numpy as np
import tensorflow as tf
from librosa import effects
from utils import spectrogram2wav, plot_test_alignment
from train import Graph
from hyperparams import Hyperparams as hp
import tqdm
import re
def load_vocab():
char2idx = {char: idx for idx, char in enumerate(hp.vocab)}
idx2cha... |
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
import pprint
import ipaddress
from neutronclient.v2_0 import client as neutronclient
from telebot.plugins import openstackutils
def str_to_bool(s):
"""Convert from specific string to bool value"""
if s == 'True' or s == 'true':
return True
elif s == 'False' or s == 'false':
return False
... |
import argparse
from collections import OrderedDict
import datetime as dt
import os
import re
import sys
import numpy as np
import spacepy.datamodel as dm
import spacepy.pybats.bats as bts
import pyvista as pv
import vtk
def timeFromFilename(outname):
'''Get timestamp from SWMF/BATSRUS output file
Supports "... |
# Copyright 2019, Offchain Labs, 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 ... |
import requests
import datetime
import pandas as pd
def time2period(s):
return int(datetime.datetime.strptime(s,'%Y-%m-%d').timestamp()-18000)
def getprice(ticker):
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.21... |
"""Contains classes and Enums for managing transactions
"""
"""
© Copyright 2020-2021 University of Surrey
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyrig... |
import bottle
import datetime
import functools
import html.parser
import json
import os
import re
import time
from . import model
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
DB_PATH = os.path.join(ROOT_DIR, 'db.sqlite3')
STATIC_DIR = os.path.join(ROOT_DIR, 'static')
app = bottle.Bottle()
bottle.TEMPLATE_P... |
from __future__ import print_function
import numpy as np
import random
import json
import networkx as nx
version_info = list(map(int, nx.__version__.split('.')))
major = version_info[0]
minor = version_info[1]
def run_random_walks(G, nodes, walk_len=None, num_walks=None):
"""
Runs an unbiased random walk on... |
"""Module to create blockchain."""
import datetime as date
import hashlib
import json
from django.core import serializers
from monsters.models import Monster
import monsters.scripts.stories as story
from ..tasks import p_o_w
class Block(object):
"""Create a block that gets appended to our blockchain."""
d... |
#importing libraries
from tkinter import ttk
from tkinter.messagebox import showinfo
import cv2
from tkinter import *
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files\Tesseract-OCR\ocrtesseract.exe'
#Create an instance of tkinter frame or window
root =Tk()
root.title("IDENTIFYING ... |
"""Configure Utilities"""
import inspect
from itertools import product
from typing import List
from types import ModuleType
from hydra.experimental import compose, initialize
from omegaconf import DictConfig
from omegaconf.listconfig import DictConfig, ListConfig
import torch
from torch import optim as optim
from torc... |
from sqlalchemy.sql import sqltypes
from sqlalchemy.dialects import postgresql
from sqlalchemy import inspect
from sqlalchemy.orm import ColumnProperty
from cornflake import fields, serializers
class ModelSerializer(serializers.Serializer):
type_map = {
sqltypes.String: fields.StringField,
sqltyp... |
from jinja2 import Environment, FileSystemLoader
import os
import shutil
TEMPLATE = os.path.dirname(os.path.abspath(__file__)) + '/template/'
def generate_cpp_xillybus_interface(component):
env = Environment(loader=FileSystemLoader(TEMPLATE, encoding='utf8'))
xillybus = []
for com in component.module["communication... |
# Copyright (C) 2019-2021, <NAME>.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import torch
import torch.nn as nn
from holocron.nn import GlobalAvgPool2d
from .resnet import ResNet, _ResBlock
from .ut... |
import collections
import json
import os
import re
import subprocess
import sys
import traceback
import pytest
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, script_dir)
from test_common import *
from environment import appmock, common, docker
from appmock_client import AppmockClient
PER... |
import numpy as np
from numpy import ma
from pyindi import *
from scipy import ndimage, sqrt, stats, misc, signal
pi = PyINDI(verbose=False)
# define 2D gaussian for fitting PSFs
def gaussian_x(x, mu, sig):
shape_gaussian = np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
return shape_gaussian
def f... |
import os
import matplotlib.pyplot as plt
from music21 import *
import networkx as nx
import numpy as np
import powerlaw
import warnings
warnings.filterwarnings("ignore")
def get_musics(path_to_musics_folder="music/", verbose=True):
musics_available = [filename for filename in os.listdir(path_to_musics_folder) i... |
import os
import socket
from unittest import TestCase, main
import warnings
import eventlet
from eventlet import greenio, util, hubs, greenthread, spawn
from tests import skip_if_no_ssl
warnings.simplefilter('ignore', DeprecationWarning)
from eventlet import api
warnings.simplefilter('default', DeprecationWarning)
... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
import csv
import os
import pprint
import glob
import args_helper
import tools_helper
import file_helper
from datetime import datetime
from datetime import timezone
# pretty printer
pp = pprint.PrettyPrinter(indent=4)
def convert_data(data):
if isinstance(data, str):
if data.isdigit():
retur... |
import inspect
import logging
import traceback
import sys
from functools import wraps, update_wrapper, partial # Todo!
from timeit import default_timer as timer
from typing import Callable, Any, TypeVar, cast
default_log_level = logging.DEBUG
'''
Override for default logging level.
'''
default_performance_measure =... |
import socket
import sys
import time
#import numpy as np
"""
remote_donkey is a client server socket based coms for allowing donkeys to talk to each other over the network
this usage designed and tested wtih two pi's connected by ethernet on the same platform\vehicle.
Specific use case:
I have two pi's on my donkey. ... |
import os,sys
import numpy as np
import pandas as pd
import pmagpy.ipmag as ipmag
from pyskew.utilities import check_dir,dt_to_dec
from datetime import datetime
from geographiclib.geodesic import Geodesic
def split_m88t(h88tf,m88tf,data_directory="aeromag_data"):
check_dir(data_directory)
h88t_df = pd.read_csv... |
"""
Copyright (c) 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import absolute_import
from atomic_reactor.cachito_util import (
CachitoAPI, CachitoAPIInvalidRequest, CachitoAPIRequest... |
#!/usr/bin/env python
#
# This code is part of the binding affinity prediction tools distribution
# and governed by its license. Please see the LICENSE file that should
# have been included as part of this package.
#
"""
Binding affinity predictor based on Intermolecular Contacts (ICs).
<NAME> , JPGLM Rodrigues, <NA... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from hashlib import md5
from utils import (parse_dict_header, parse_authorization_header,
parse_authenticate_header, Authorization, WWWAuthentication,
H, HA1, HA2, response)
class UtilsTestCase(unittest.TestCase):
... |
import obspython as obs
from pynput.mouse import Controller # python -m pip install pynput
c = Controller()
get_position = lambda: c.position
__version__ = "1.0.0"
def apply_scale(x, y, width, height):
width = round(width * x)
height = round(height * y)
return width, height
def lerp(mi... |
import functools
import networkx as nx
from socialchoice import util
from socialchoice.ballot import BallotBox
def optional_score(ranking_method):
"""Adds a flag to include or remove the score from a ranking method that returns a list of 2-tuples,
where the first element is the candidate, and the second ele... |
from math import sqrt
from ..utils.data_types import Moments
class IncrementalAttribute:
def __add__(self, other):
raise NotImplementedError
def get(self):
raise NotImplementedError
class Area(IncrementalAttribute):
def __init__(self, area=1):
self.area = area
def __add__(s... |
import xml.etree.ElementTree as ET
from .util import FlowModInfo, RuleInfo
import pox.openflow.libopenflow_01 as of
import re
def multiwordReplace(text, wordDic):
"""
take a text and replace words that match a key in a dictionary with
the associated value, return the changed text
"""
rc = re.compi... |
""" This converts the build configuration files into something usable by the
manager """
from time import strftime, gmtime
import ConfigParser
import pprint
from runtools.runtime_config import RuntimeHWDB
from awstools.awstools import *
class BuildConfig:
""" This represents a SINGLE build configuration. """
... |
from komparse.ast import Ast
from .scope_manager import ScopeManager
from .symtab_entry import Kind, SymtabEntry, FuncEntry, \
ParamEntry, VarArgEntry
class DefinitionFinder(object):
def walk_ast(self, ast, scope, scope_mgr):
self._scope = scope
self._scope_mgr = scope_mgr
self._curr_a... |
from filehash import FileHash
from io import BytesIO
import os, json
import logging
logger = logging.getLogger(__name__)
def to_sql_field(s):
filter1 = s.replace(".","_").replace(" ","_")
filter2 = ''.join(e for e in filter1 if e.isalnum() or e=='_')
return filter2
def to_sql_value(s):
if isinstance(s, str): ret... |
import collections
from functools import wraps
from typing import Any, Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from . import REPR_INDENT
__all__ = [
"to_buffer",
"BufferBase",
"ExponentialMovingAverage",
"ScalarSmoother",
"VectorSmo... |
#####################################################################
# #
# double_import_denier.py #
# #
# Copyright 2018, <NAME> ... |
# 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 ag... |
# Stdlib imports
import logging
import math
import random
# Third party imports
import numpy as np
# Application imports
from .utils import LazyStr
logger = logging.getLogger(__name__)
def greedy(list_of_state_action_values, params):
# twice as fast as
# np.random.choice(np.flatnonzero(actions == np.max(ac... |
from lark import Transformer
class DebugTransformer(Transformer): # pragma: no cover
def __init__(self):
super().__init__()
def __default__(self, data, children, meta):
print("Node: ", data, children)
return data
class TransformerSkeleton(Transformer): # pragma: no cover
"""Pr... |
import time
import pandas as pd
import numpy as np
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of th... |
import torch
import torch.nn as nn
import timm
from pg_modules.blocks import FeatureFusionBlock
def _make_scratch_ccm(scratch, in_channels, cout, expand=False):
# shapes
out_channels = [cout, cout*2, cout*4, cout*8] if expand else [cout]*4
scratch.layer0_ccm = nn.Conv2d(in_channels[0], out_channels[0], k... |
# -*- coding: utf-8 -*-
from nltk.corpus import brown
import sklearn
from sklearn.model_selection import train_test_split
import tensorflow as tf
import numpy as np
import numpy.random as random
import itertools
random.seed(42)
## Install data by running the following code:
#import nltk
#nltk.download('brown')
#nlt... |
import requests
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point, Polygon, MultiPoint, MultiPolygon
from shapely.ops import nearest_points
from collections import defaultdict
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'... |
"""Core methods for building Tiramisu networks."""
from keras import backend as K
from keras.layers import Activation
from keras.layers import BatchNormalization
from keras.layers import Concatenate
from keras.layers import Conv2D
from keras.layers import Conv2DTranspose
from keras.layers import Dropout
from keras.laye... |
# -*- coding: utf-8 -*-
# @Time : 2018/8/23 22:18
# @Author : zhoujun
import sys
import six
import lmdb
from PIL import Image
import cv2
import numpy as np
import torch
from torch.utils.data import DataLoader
from utils import punctuation_mend, get_datalist
from base import BaseDataSet
class ImageDataset(BaseDat... |
import logging
import re
from django.conf import settings
from django.shortcuts import reverse
from rest_framework import serializers
from accounts.models import Account
from jobs.models import Job, JobMethod, Queue, Worker, WorkerHeartbeat, Zone
from manager.api.helpers import get_object_from_ident
from manager.api.... |
from flask import Flask, render_template, request
from flaskext.mysql import MySQL
import os
import funcs.data as data
app = Flask(__name__,template_folder='static')
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = os.environ['user']
app.config['MYSQL_DATABASE_PASSWORD'] = os.environ['password']
app.conf... |
import jittor as jt
from jittor import nn, Module
import numpy as np
import sys, os
import random
import math
from jittor import init
from model import Model
import jittor.transform as trans
from CIFAR10 import *
from ErrorBarUtil import *
from vgg_16 import VGG_16
from vgg_11 import VGG_11
from mini_vgg import MINI_VG... |
import logging
from constants import RANDOM_SEED, MONITOR_RESPONSE_TIME
import numpy as np
import time, datetime
import matplotlib
from uuid import uuid4
matplotlib.use('Agg')
import uuid
from ml.feature_extraction import FeaturesWrapper
from db.data_handlers import MongoBufferedReader
from ml.targets import TargetPic... |
# Dependencies
import pygame as pg
import os, sys
# Constants
FLOOR_W = 50
FLOOR_H = 64
# Colors
BLACK = (0,0,0)
WHITE = (255,255,255)
GRAY = (90,90,90)
LIGHTPURP = (200,200,230)
GREEN = (0,230,0)
ORANGE = (235,70,180)
# Sprites: Credit to SpiderDave from OpenGameArt.org
sprites = []
def load_sprites... |
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import spline
from scipy.optimize import minimize
import numpy as np
from scipy.misc import imread,imsave
from skimage.draw import line
from primitive import image_error
import os
import skimage.feature
import skimage.color
import scipy.ndimage.mo... |
import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.test import TestCase
from chainablemanager import ChainableManager
class BookManager(ChainableManager):
class QuerySetMixin:
def published_in(self, year):
return self.filter(year=year)
... |
import logging
from io import IOBase, StringIO, BytesIO
from copy import deepcopy
from lxml import etree
class Extractor(object):
def __init__(self, target_class):
# logging convenience methods
self.logger = logging.getLogger("extractor")
self.info = self.logger.info
self.debug... |
#### FOR THE SCRIPTS/HELPER FUNCTIONS TO WORK, THE exiftool.exe FILE MUST BE IN THE SAME LEVEL DIRECTORY AS THIS SCRIPT ####
#### exiftool.exe MUST ALSO BE EXECUTABLE - IF THERE IS A PERMISSION DENIED ERROR, TRY CHANGING THE PERMISSIONS WITH THIS COMMAND: >chmod +777 exiftool.ex... |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
\file MCModel.py
\brief Definition of the network architecture MCDeNoiser2 for weight
computation for each point.
\copyright Copyright (c) 2019 Visual Computing group of Ulm University,
Germany. See... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.