text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import datetime as datetime
date = datetime.datetime.now().date()
currentYear = date.year
def plot_exposure(years, book, market, CMV, currentYear):
"""
Plots a single book vs. market gap analysis.
# INPUT -----... |
"""
A module for representing first order logical formulas, as given in Language, Proof, and Logic by
Barwise and Etchmody.
Formulas can be created using the classes described in this module. For convenience, conjunctions,
disjunctions, and negations can also be created using ``&``, ``|``, and ``~`` respectively. This... |
# 标准模块
import os
import sys
import json
import datetime
from prettytable import PrettyTable
RESULT = {}
FIELDS = ("name", "age", "tel", "email")
# -----------------------------------------------------------------登录操作
def loginAuto(username,password):
USERINFO = ("1", "1")
if username == USERINFO[0] and pass... |
import pandas as pd
from PIL import Image, ImageOps
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from skimage import io
import torch
import matplotlib.pyplot as plt
pd.set_option("display.max_columns", 1000)
pd.set_option("display.max_rows", 1000)
#----... |
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats
from statsmodels.graphics.gofplots import qqplot_2samples as qq
from linear_regressions import normalize_data
plt.rcParams['svg.fonttype'] = 'none'
def plot_hist(x, y, name=None, params=None... |
import asyncio
import csv
import random
import discord
from discord.ext import commands
PATH = 'cog/study/english.csv'
class Question():
def __init__(self, PATH, question_language: str, answer_language: str):
self.path = PATH
self.question_lang = question_language
self.an... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import uuid
import logging
from sqlalchemy import event
from werkzeug.routing import UnicodeConverter
from flask.ext.sqlalchemy import SQLAlchemy
from . import ALLOWED_QUERY_FIELDS, SUFFIX_CONTAINS
from .. import ap... |
# CENG 487 Assignment1 by
# <NAME>
# October 2021
from lib.factory import create_cube, create_triangle
from lib.polygon import Polygon
from lib.vec3d import Vec3d
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import time
import sys
# translation vectors for the models
cube_translator = Ve... |
# -*- coding: utf-8 -*-
import os
import sys
import logging
import ipdb
from importlib.abc import SourceLoader
import requests
from git import Repo
from importlib.abc import MetaPathFinder
from packyou import find_module_path_in_cloned_repos
MODULES_PATH = os.path.dirname(os.path.abspath(__file__))
GITHUB_REPOSIT... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from typing import NamedTuple
#DEFINITIONS-----------------------------------------... |
import codecs, sys, datetime
from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import showerror
global filename, timeOrdered, lifetimeOrdered, subjectTimes
filename = ""
timeOrdered = []
lifetimeOrdered = []
subjectTimes = []
class SubjectFrame(Frame):
global filename
def __init__... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from lib.utils import euclidean_dist
class VanillaMemoryBank(nn.Module):
def __init__(self, dim=2048, K=16384):
super(VanillaMemoryBank, self).__init__()
self.K = K
# transposed feature for efficient matmul
... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from keras.models import Sequential
from keras.layers.core import Activation, Dense, Flatten
from keras.layers.convolutional import Conv2D
from keras.optimizers import Adam
from scipy.misc import imresize
import collections
import numpy as np
impor... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: github.com/openconfig/gnoi/file/file.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import AsyncIterable, AsyncIterator, Iterable, List, Optional, Union
import betterproto
import grpclib
from .. import common as _c... |
# This file is part of the Indico plugins.
# Copyright (C) 2002 - 2019 CERN
#
# The Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License;
# see the LICENSE file for more details.
from __future__ import unicode_literals
from flask import session
from flask... |
#!/usr/bin/env python3
# coding: utf-8
REQUIREMENTS = "google-api-python-client numpy httpx python-dotenv"
__doc__ = f'''
cliTube plays Internet-Music from CLI on Windows with preinstalled VLC
It builds Tube-URLS from artist & title arguments
requires a GOOGLE_YOUTUBE_API_KEY set as dotenv or environment variable
... |
'''
Created on Sep 12, 2011
@author: Nich
'''
vowels = ('a', 'e', 'i','o', 'u') #fuck y
double_vowels = ('ea', 'ee', 'oo', 'ou')
def makeVariants(word):
variants = []
return variants
def makeInflections(word):
inflections = {}
if word.category == "NOUN":
#do plural
inflections["plura... |
import pytest
import warnings
from pypac.parser import MalformedPacError, PACFile, parse_pac_value, proxy_url
class TestPacFile(object):
"""
Tests for acceptance and rejection of PAC file JavaScript.
"""
@pytest.mark.parametrize(
"value",
[
"",
" ",
... |
# -*- coding: utf-8 -*-
"""
cstrace.json 의 기본형식에서 parent - child 구조를 없애고, 컴파일 플래그의 경로들을 절대 경로로 만드는 등의
후처리 작업을 처리한다.
"""
import sys
import json
import argparse
import re
import os
import glob
from collections import OrderedDict
import cslib
def get_open_list_for_child(opened_from_child_list: list):
opened = []
... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
#This program gathers and stores information from the coin market cap website to be displayed in the gui
#Class to hold company information
class Company:
def __init__(self):
self.name = None
self.rank = None
self.pricechange... |
# Copyright (c) 2021 <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 rights to use, copy, modify, merge, publish,
# distribute... |
"""
Loads event information from the supporting data files
for use in the dashboard time series graphs.
"""
import os, math
import pandas as pd
ANNOUNCEMENTS_CSV = os.path.join(os.path.dirname(__file__), '..', 'data', 'announcements.csv')
EVENTS_CSV = os.path.join(os.path.dirname(__file__), '..', 'data', 'health_even... |
"""Configuration file (powered by YACS)."""
import os
import sys
import argparse
from yacs.config import CfgNode
# Global config object
_C = CfgNode(new_allowed=True)
cfg = _C
# -------------------------------------------------------- #
# Data Loader options
# ------------------------------------------------------... |
from collections import namedtuple
import json
import sharknado
import unittest
from bson import ObjectId
from datetime import datetime, timedelta
from tornado import escape, gen
from tornado.escape import to_unicode
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase
from six.moves.urllib.p... |
import json
import logging
import unittest
from unittest import mock
from sdc.rabbit import MessageConsumer, QueuePublisher
from sdc.rabbit.exceptions import BadMessageError, RetryableError
from sdc.rabbit.exceptions import PublishMessageError, QuarantinableError
class DotDict(dict):
__getattr__ = dict.get
cl... |
"""
Created by Epic at 11/1/20
"""
from custom_types import CogType, ExtendedClient
from asyncio import Lock, sleep
from speedcord.http import Route
class DefaultDict(dict):
def __init__(self, default, *args, **kwargs):
self.default_value = default
super().__init__(*args, **kwargs)
def __get... |
import re
INDENT = " "
NEW_LINE_INDENT = "\n%s" % INDENT
HEAD_TEXT = """
from sqlalchemy import create_engine, Column
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite://')
Session = sessionmaker(bind=engine)
session = Session()
Base = ... |
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing
from datetime import datetime
from PIL import Image as im
def to_pandas(data, normalize=True, ... |
"""
credit: <NAME>
This is a python utility module usually for my machine learning project.
Support both python 2.6+ and 3.3+.
function:
- time
- logging
- argparse across module
problems:
- set_defaults override, add_argument no sense, check before override??
- create newline logger
http://stac... |
import sys
import os
import subprocess
import requests
import andr
import timeago
import datetime
from time import sleep
api = andr.api()
adb_dir = andr.set_adb_dir()
aid = andr.get_aid()
def options():
pin = {
"_id": "",
"pin_range": [],
"pin_list": [],
"embedded_numbers": [],
... |
# Copyright 2015-2016 F5 Networks 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 torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
from config.cartpole_config import load_args
from environment.load_environment import load_env
from draw_plot.draw_plot import draw_plot
import numpy as np
from collections import... |
import torch
import torch.nn as nn
import rdkit.Chem as Chem
import torch.nn.functional as F
from reaction_utils import get_mol_from_smiles
from nnutils import *
ELEM_LIST = ['C', 'N', 'O', 'S' 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe', 'Al', 'I', 'B', 'K', 'Se', 'Zn', 'H', 'Cu', 'Mn', 'unknown']
BTYPE_L... |
''' Utility functions for printing internal data structures'''
import psutil
import os
from immunopeptide.util_genomic import to_adj_list
# Pretty prints a splicing graph
# splice_graph: <spladder.modules.classes.Splicegraph>
def print_splice_graph(splice_graph):
nvertices = splice_graph.vertices.shape[1]
p... |
import abc
from autosar.base import (AdminData, SpecialDataGroup, SpecialData, SwDataDefPropsConditional, SwPointerTargetProps)
from autosar.element import DataElement
def _parseBoolean(value):
if value is None:
return None
if isinstance(value,str):
if value == 'true': return True
e... |
# -*- coding: utf-8 -*-
import math,string,itertools,fractions,heapq,collections,re,array,bisect
class CtuRobots:
def maxDist(self, B, cost, cap):
N = len(cost)
pqr = [(cap[i], cost[i]) for i in range(N)]
pqr = sorted(pqr)
f = [[0.0 for b in range(B+1)] for n in range(N)]
f... |
import data_sort
from dt_thread import TreeThread
# from dt import Decision_Tree
from random import randint
import time
import math
# TODO: Change prints to write to file and run on adult_data_big
start_time = time.time()
training_data = [
['Green', 3, 'Apple'],
['Red', 3, 'Apple'],
['Red', 1, 'Grape'],
... |
""" Implementation of all available options """
from __future__ import print_function
def train_opts(parser):
# Transformer or Seq2Seq
parser.add_argument('--model-choice', required=True, help="transformer or seq2seq")
# Common training options
group = parser.add_argument_group('Training_options')
... |
# Copyright 2018 coMind. 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 agree... |
#!/usr/bin/env python3
import argparse
import hashlib
import json
import sys
import time
from binascii import hexlify
from bisect import bisect
from datetime import timedelta
from multiprocessing import Queue, Event, Process
from pprint import pprint
from queue import Empty
from asn1crypto.core import Sequence
from s... |
import torch
import torch.nn as nn
import pytorch_lightning as pl
from torchmetrics import RetrievalNormalizedDCG, RetrievalPrecision
from transformers import BertConfig, BertModel
from .Tokenizer import TensorTokenizer
from .metrics import RetrievalHIT
from .modeling_bert2D import BertModel2D
class SequenceTransfor... |
# -*- coding: utf-8 -*-
import traceback
import ast
import asyncio
import random
import datetime
import re
import aiohttp
import json
import discord
import datetime
from discord.ext import commands, tasks
from discord import Embed, utils, User, File, Attachment
class command(commands.Cog):
def __in... |
#!/usr/bin/env python3
import os
import glob
import re
import json
import pymongo
from pymongo import MongoClient
from bs4 import BeautifulSoup as bs
PATH = os.getcwd() + '/results'
COLLECTION_NAME = "companies"
client = MongoClient("localhost", 27017)
db = client["icris"]
db.drop_collection(COLLECTION_NAME)
db.cre... |
import gym
import matplotlib.pyplot as plt
import numpy as np
import IPython
from gym import spaces
from .rrt import RRT
class ToyGridEnv(gym.Env):
EMPTY = [255, 255, 255]
WALL = [0, 0, 0]
AGENT = [0, 255, 0]
GOAL = [0, 0, 255]
def __init__(self):
# Set this in SOME subclasses
s... |
# Adapted from python made by <NAME>
#
# Copyright 2017 <NAME>
# Licensed under the Apache License, Version 2.0.
# See http://www.apache.org/licenses/LICENSE-2.0 for the full text.
#
# This file is based on
# https://github.com/swagger-api/swagger-ui/blob/4f1772f6544699bc748299bd65f7ae2112777abc/dist/index.html
# ... |
""" Implements DenseNet.
References:
- Huang et al. Densely Connected Convolutional Networks. 2017
- https://github.com/bearpaw/pytorch-classification/blob/master/models/cifar/densenet.py
- https://github.com/liuzhuang13/DenseNet/blob/master/models/densenet.lua
"""
import math
import torch
import torch.nn as nn
impo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Universidad Nacional Autonoma de Mexico / Facultad de Ingenieria
# Inteligencia Artificial
# Alumnos:
# <NAME>
# <NAME>
# <NAME>
# <NAME>
# Hecho en Python 3.3
import os
def cls(): # Funcion para limpiar pantalla en cualquier S.O.
if os.name == 'ce' or 'n... |
import torch
import torch.nn
import torch.nn.functional as F
from typing import Optional
from .multi_head_attention import AttentionMask, MultiHeadAttentionBase
import framework
import math
class RelativeAttentionBase(MultiHeadAttentionBase):
def __init__(self, state_size: int, n_heads: int, dropout: float):
... |
#!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import os
import sys
import argparse
import ConfigParser
import platform
from fabric.api import local, run
from fabric.state import env
from fabric.context_managers import settings, lcd
from contrail_provisioning.common.base import... |
import cv2
import mediapipe as mp
import time
import mouse
class FaceMeshDetector():
def __init__(self, staticMode=False, maxFaces=1, minDetectionCon=0.5, minTrackCon=0.5):
self.staticMode = staticMode
self.maxFaces = maxFaces
self.minDetectionCon = minDetectionCon
self.minTrackCon... |
import pickle
#import matplotlib.pyplot as plt
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import pickle
def read_res(fname):
f=open(fname,'rb')
R=pickle.load(f)
val = R['val_acc']
test = R['test_acc']
best_idx=np... |
# 定数
hw = 8
hw2 = 64
dy = [0, 1, 0, -1, 1, 1, -1, -1]
dx = [1, 0, -1, 0, 1, -1, 1, -1]
black = 0
white = 1
legal = 2
vacant = 3
# 座標(y, x)が盤面内にあるかを見る関数
def inside(y, x):
return 0 <= y < hw and 0 <= x < hw
# オセロのクラス
class othello:
# 初期化
def __init__(self):
# 盤面の状態 0: 黒 1: 白 2: 合法手 3: ... |
"""
处理文本的CNN
"""
import numpy as np
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
DEBUG = 0
# The Text ResBlock
class BasicResBlock(nn.Module):
def __init__(self,input_channels, hidden_channels):
super(BasicResBlock, self).__in... |
import os
import errno
import torch
from torch.utils.data import Dataset
from sklearn.model_selection import train_test_split
from utils.sequence_utils import *
class ChrDataset(Dataset):
"""Chromosome dataset, obtained from http://hgdownload.soe.ucsc.edu/goldenPath/hg38/chromosomes/
attributes:
... |
import pandas as pd
import os
import numpy as np
def load_vec(emb_path, nmax=50000):
vectors = []
word2id = {}
with open(emb_path, 'r', encoding='utf-8', newline='\n', errors='ignore') as f:
next(f)
for i, line in enumerate(f):
word, vect = line.rstrip().split(' ', 1)
... |
import matplotlib.pyplot as plt
from torch.autograd.variable import Variable
import pickle
import os
import torch
import torch.nn as nn
import torch.utils.data as data
from model import plotKeypointsOverOutputModel, Model
from const import IMAGES_FOLDER, IMAGES_FOLDER_TEST, ANNOTATION_FILE_TEST, MAIN_FOLDER
from data... |
"""Command Context is how we construct the command line for a command which may
have variables that need to be rendered.
"""
import operator
import re
from functools import reduce
from tron.utils import timeutils
def build_context(object, parent):
"""Construct a CommandContext for object. object must have a prop... |
# Copyright 2016 Brigham Young University
#
# 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 argparse
import os
from os.path import exists, join
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
import torchvision.transforms as transforms
from dataloader.dataset import TestDataset, TrainDataset
from model.generator impo... |
# coding=utf-8
"""
Byte pair encoding utilities from GPT-2.
Original source: https://github.com/openai/gpt-2/blob/master/src/encoder.py
Original license: MIT
This is the modified version from fairseq:
https://github.com/pytorch/fairseq/blob/master/fairseq/data/encoders/gpt2_bpe_utils.py
DEFAULT_ENCODER_JSON = 'https... |
import networkx as nx
import itertools
"""
This is an implementation of the IC* (Inductive Causation with latent
variables) algorithm as described in _Causality_ by <NAME>, 2000.
"""
try:
xrange
except NameError:
xrange = range
class SearchException(Exception):
pass
class IC():
def __init__(self, in... |
import pytest
import os.path
from StringIO import StringIO
from whoiscache.parsers import parse_dump, parse_updates
from whoiscache import parsers
from whoiscache import types as T
def _open_resource(name):
return open(_resource_path(name))
def _resource_path(name):
return os.path.join(os.path.dirname(__... |
"""
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import atexit
import os
import time
from contextlib import contextmanager
from selenium.common.exceptions import (WebDriverException,
StaleElementReferenceException)
from selenium.webdriv... |
import uuid
from django.conf import settings
from django.db import models
from django.db.models import Manager
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from apps.component.models import Component
from apps.org.models impo... |
import mxnet as mx
import mxnet.ndarray as nd
import mxnet.gluon as gluon
import mxnet.gluon.nn as nn
import mxnet.autograd as ag
import symbol_utils
def ConvBlock(channels, kernel_size, strides, **kwargs):
out = nn.HybridSequential(**kwargs)
with out.name_scope():
out.add(
nn.Conv2D(channe... |
from time import strftime, gmtime, sleep, time
from os import makedirs, getcwd, unlink, path
from urllib.parse import urlencode
from re import findall as regex
from html import unescape
from json import loads
import requests, sys
host_headers = {
'Host': 'chan.sankakucomplex.com',
'User-Agent': 'Mozilla/5.0 (W... |
class Grafo:
def __init__(self):
self.vertices = []
self.arestas = {}
self.pesos = {}
def adiciona_vertice(self,valor):
self.vertices.append(valor)
self.arestas[valor] = []
def adiciona_aresta(self,origem,destino,peso):
if origem not in sel... |
#!/usr/bin/env python3
#
# Copyright 2019 SystemLight
# https://github.com/SystemLight/madtornado
#
# # # # # # # # # # #
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.httpserver import HTTPServer
from tornado.options import define, options
import qrcode
import os
import json
... |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import random
first_HL = 128
def conv3x3(in_channels, out_channels, stride=1):
"""3x3 kernel size with padding convolutional layer in ResNet BasicBlock."""
return nn.Conv2d(
in_channe... |
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from website.models import Contest, Exam, Problem, Score, Competitor, TaskScore, Task, MiniRoundTotal, MiniRoundScore
from website.utils import log, per_pa... |
"""Python Script Template."""
import numpy as np
from ..utilities import plot_helpers
import matplotlib.pyplot as plt
# sklearn library
from sklearn.datasets import make_regression
from sklearn.linear_model import Ridge, Lasso
from sklearn.pipeline import make_pipeline
from sklearn.pipeline import Pipeline
from sklear... |
from datetime import datetime, date
from django.urls import reverse
from caseworker.cases.constants import CaseType
from caseworker.cases.forms.finalise_case import approve_licence_form
from caseworker.cases.objects import Case
from caseworker.cases.services import get_application_default_duration
from caseworker.cor... |
import operator
import time
import collections
import table
RATE_HISTORY = 10 # Look at up to last N samples to calculate "recent rate"
TIME_FUNCTION = time.time # So that we can stub it for unit testing
def secs_to_dmhs_str(secs):
mins = 0
hours = 0
days = 0
if secs >= 60.0:
m... |
# adapted from: https://github.com/lucidrains/vit-pytorch/blob/main/vit_pytorch/vit.py
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils import checkpoint
from einops import rearrange, repeat
class PreNorm(nn.Module):
def __init__(self, dim, fn):
super().__init__()
... |
#!/usr/bin/python
import json
import socket
import logging
import binascii
import struct
import argparse
import random
class ServerMessageTypes(object):
TEST = 0
CREATETANK = 1
DESPAWNTANK = 2
FIRE = 3
TOGGLEFORWARD = 4
TOGGLEREVERSE = 5
TOGGLELEFT = 6
TOGGLERIGHT = 7
TOGGLETURRETLEFT = 8
TOGGLETURRETRIGHT... |
import os
from torch.utils.data import Dataset,DataLoader
import torch
import torch.nn as nn
from sklearn.metrics import f1_score
def build_corpus(split, make_vocab=True, data_dir="data"):
"""读取数据"""
assert split in ['train', 'dev', 'test']
word_lists = []
tag_lists = []
with open(os.path.join(da... |
import time
from typing import Any, Dict, List, Optional
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from . import logging
from .access_permissions import BaseAccessPermissions
from .autoupdate import AutoupdateElement, inform_changed_data, inform_elements
from .rest_api impor... |
"""GitLab metric source."""
import asyncio
import itertools
from abc import ABC
from datetime import datetime
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, cast
from urllib.parse import quote
from dateutil.parser import parse
from base_collectors import SourceCollector, UnmergedBranchesSourceCo... |
import json
from django.db import transaction
from django.http import HttpResponse
import commonware.log
from tastypie import fields, http
from tastypie.authorization import Authorization
from tastypie.resources import ALL_WITH_RELATIONS
from tastypie.serializers import Serializer
import amo
from amo.decorators impo... |
from __future__ import unicode_literals
from django.contrib.auth.models import Group, AnonymousUser
from django.contrib.contenttypes.models import ContentType
from django.template import Template, Context, TemplateSyntaxError
from django.test import TestCase
from guardian.compat import get_user_model, template_debug_... |
import cgi
import os.path
import re
import urllib
import urlparse
import tornado.escape
def load_basic_parameters(handler, prefix="", url=""):
uri = url if url else handler.request.uri
# Hmmm, some servers send UTF-8 percent encoded and some don't...
uri = tornado.escape.url_unescape(uri)
# XXX WTF?? it's dou... |
from pandas.util.py3compat import StringIO
import numpy as np
from pandas.core.api import Series, DataFrame
import pandas.stats.common as common
from pandas.util.decorators import cache_readonly
def fama_macbeth(**kwargs):
"""Runs Fama-MacBeth regression.
Parameters
----------
Takes the same argume... |
import time
from rdkit import Chem
from rdkit.Chem import rdmolops
from rdkit.Chem.MolStandardize import rdMolStandardize
from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers
from rdkit.Chem.EnumerateStereoisomers import StereoEnumerationOptions
import datamol as dm
from ._structural import IsomerEn... |
# Copyright 2018 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 l... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
"""Numeric integration of data coming from a source sensor over time."""
import logging
from decimal import Decimal, DecimalException
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAM... |
import logging
import os
import re
import shutil
import subprocess
import sys
from cluster_vcf_records import vcf_record, vcf_file_read
def syscall(command):
logging.debug(f"Run command: {command}")
completed_process = subprocess.run(
command,
shell=True,
stderr=subprocess.PIPE,
... |
# Copyright (c) 2017 <NAME>. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import itertools
from cui.util import deep_put
from cui import core
from cui import symbols
class WindowBase(object):
"""
The base class for al... |
'''
COCO to SA conversion method
'''
import json
import logging
import threading
from pathlib import Path
import cv2
import numpy as np
from .coco_api import _maskfrRLE, decode
from ..sa_json_helper import _create_pixel_instance, _create_sa_json
from ....common import (
blue_color_generator, hex_to_rgb, id2rgb, ... |
import os
import random
import time
from shutil import copyfile
import matplotlib.pyplot as plt
import torch
from stable_baselines3.common.callbacks import EvalCallback, BaseCallback
from stable_baselines3.common.logger import configure
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common... |
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import accuracy_score, recall_score, roc_auc_score, roc_curve, auc, precision_score
def get_tpr_specific_fpr(fpr, tpr, s_fpr=0.01):
for i, fp in enumerate(fpr):
if fp > s_fp... |
from flask import Flask, jsonify, request, Response
from bson import objectid
from database.db import initialize_db
from database.models import Photo, Album
import json
from bson.objectid import ObjectId
import os
import urllib
import base64
import codecs
app = Flask(__name__)
# database configs
app.config["MONGODB_S... |
from typing import Any, List, Optional
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from pydantic import EnumError, StrRegexError
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.requests import Request
from fastapi_contrib.common.responses i... |
import logging
import attr
from aiohttp import web
from . import constants
from .annotations import DictStrStr
from .data import get_config, Resource
from .utils import (
get_resource_or_404,
get_resource_or_410,
on_upload_done,
parse_upload_metadata,
)
from .validators import check_file_name, validat... |
#!/usr/bin/env python
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import argparse
import json
import logging
import os
import shutil
import subprocess # nosec
import sys
import tempfile
from typing import Optional
from onefuzztypes.enums import OS, ContainerType, TaskType
from onefuzzt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Iterator, Sequence, Tuple
from matplotlib import animation
from draugr.drawers.mpl_drawers.mpldrawer import MplDrawer
from draugr.numpy_utilities import recursive_flatten_numpy
__author__ = "<NAME>"
__doc__ = """
Created on 27/04/2019
@author: cnhei... |
"""
Special PNG process output for hillshades.
Writes inverted hillshade into alpha channel of black image, so that hillshade
can be used as overlay over other data.
output configuration parameters
-------------------------------
mandatory
~~~~~~~~~
path: string
output directory
optional
~~~~~~~~
nodata: inte... |
# "Hey, Django! Look at me, I'm an app! For Serious!"
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils.encoding import force_unicode
from django.utils.text import capfirst
from haystack.exceptions import NotHandled, SpatialError
try:
from geopy imp... |
import cv2
import numpy as np
def calculate_local_stats(im, map_m, map_s, winx, winy):
im_sum, im_sum_sq=cv2.integral2(im, cv2.CV_64F) #diffrent parameters sdepth & sqdepth -- BEWARE
wxh = int(np.floor(winx/2))
wyh = int(np.floor(winy/2))
x_firstth = wxh
y_firstth = wyh
y_lastth = im.shape[0] ... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.