text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
# coding: utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class BCNN(nn.Module):
"""Lidar CNN
Parameters
----------
in_channels : int
Number of input feature channels, by default 8
n_class : int
Number of classes, by defa... |
from abc import ABC, abstractmethod
import logging
import matplotlib
import matplotlib.pyplot as plt
from multiprocessing import cpu_count, Manager
import numpy as np
from numpy.random import RandomState
import pandas as pd
import seaborn as sns
from sklearn.base import BaseEstimator
from typing import Any, Callable, D... |
# -*- coding: utf-8 -*-
import sys
import os
from app.common import definitions, values
from app.tools import logger
import textwrap
GREY = '\t\x1b[1;30m'
RED = '\t\x1b[1;31m'
GREEN = '\x1b[1;32m'
YELLOW = '\t\x1b[1;33m'
BLUE = '\t\x1b[1;34m'
ROSE = '\t\x1b[1;35m'
CYAN = '\x1b[1;36m'
WHITE = '\t\x1b[1;37m'
PROG_OUT... |
# Copyright (c) 2018, Red Hat, 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 requir... |
import operator
import re
import glass.constant as const
from . import nodes as Node
from .utils import smart_split
TOKEN_REGEX = re.compile(
r'''
(\{%.*?%\}|
\{\{.*?\}\}|
\{\#.*?\#\}
)''', re.VERBOSE)
VAR = re.compile(r'''
^[\w_\.]+
''', re.VERBOSE)
STRING = re.compile(r'''
(('.*?')|".*?")(\.\w+)*
... |
"""
Data resource for data exploration
"""
from flask import request, g
from flask_restful import Resource
from sqlalchemy import or_, extract, func, text
import meerkat_abacus.util.epi_week
from meerkat_abacus.model import Data
import meerkat_abacus.util as abacus_util
from meerkat_api.authentication import authentic... |
import matplotlib.pyplot as plt
from scipy import special, optimize, fft as sp_fft
import scipy.io.wavfile as file
import scipy.signal as signal
import operator
import os
import numpy as np
from numpy import (atleast_1d, poly, polyval, roots, real, asarray,
resize, pi, absolute, logspace, r_, sqr... |
# -*- coding: UTF8
import sys
import timeit
import elite
start = timeit.default_timer()
mydb = elite.db()
##################
# options
##################
myStartSystem = "ltt 9810"
maxSunDistance = 1500
sellDist = 160
maxHops = 6
maxJumpDistance = 12.71
maxDeep = 18
minDeep = 16
useSlowMod =... |
import urllib.request,urllib.parse
import os, sys, subprocess
import requests
banner = """
______ ______ __
/_ __/___ __________/ ____/________ _/ /_
/ / / __ \/ ___/ ___/ / __/ ___/ __ `/ __ \\
/ / / /_/ / / / / / /_/ / / / /_/ / /_/ /
/_/ \____/_/ /_/ \____/_/ \__,_/_.___/ ... |
"""empty message
Revision ID: 3_add_housing_units_table
Revises: 2_populate_users_with_base_users
Create Date: 2021-12-01 02:23:11.555694
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '3_add_housing_units_table'
down_... |
import math
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.nn.utils import clip_grad_norm_
from torch.optim import Optimizer
def warmup_cosine(x, warmup=0.002):
s = 0
if x < warmup:
s = 1
return s * (x / warmup) + (1 - s) * (0.5 * (1 + torch.cos(math.pi * x)))
def wa... |
#!/usr/bin/env python3
# Python script for updating the nftables blacklist sets
import os
import subprocess
import sys
import tempfile
import argparse
import textwrap
import urllib.request
import urllib.error
#Binaries
NFT = '/usr/sbin/nft'
#Temp File Header
FILE_HEADER = ('table {} {} {{\n'
'set {} ... |
import re
import sys
import numpy as np
import torch
from rdkit import Chem
from torch.utils.data import Dataset
from tqdm import tqdm
from utils import Variable
class Vocabulary(object):
"""A class for handling encoding/decoding from SMILES to an array of indices"""
def __init__(self, init_from_file=None, ... |
from builtins import object
import logging
from abc import ABCMeta, abstractmethod
from cvfm import constants, exceptions
from pyVmomi import vim, vmodl
from future.utils import with_metaclass
logger = logging.getLogger(__name__)
class VMwareController(object):
def __init__(self, synchronizer, update_handler, l... |
"""
mcpython - a minecraft clone written in python licenced under the MIT-licence
(https://github.com/mcpython4-coding/core)
Contributors: uuk, xkcdjerry (inactive)
Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence
Original game "minecraft" by Mojang Studios (www.m... |
# -*- coding: utf-8 -*-
#
# Copied from https://github.com/fcurella/django-social-share
# Copyright (C) 2011 by <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, i... |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from lib.cpool import TopPool, BottomPool, LeftPool, RightPool
BN_MOMENTUM = 0.1
model_urls = {'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'ht... |
#!/usr/bin/python3
"""Command line tool for the Google Nest Smart Device Management API
You must configure your device as described:
https://developers.google.com/nest/device-access/get-started
which will give you a project_id, client_id, and client_secret. This tool
will do a one time setup to get an access toke... |
from firedrake import *
import numpy as np
import random
from firedrake.petsc import PETSc
from firedrake import COMM_WORLD
try:
import matplotlib.pyplot as plt
plt.rcParams["contour.corner_mask"] = False
plt.close("all")
except:
warning("Matplotlib not imported")
random.seed(222)
nx, ny = 50, 40
Lx,... |
from text_game_maker.game_objects.base import GameEntity
from text_game_maker.materials.materials import Material
from text_game_maker.audio import audio
from text_game_maker.utils import utils
from text_game_maker.messages import messages
class ItemSize(object):
SMALL = 1
MEDIUM = 2
LARGE = 3
VERY_LA... |
import sys
import glob
import os
import cv2
import math
from openpose.body.estimator import BodyPoseEstimator
from openpose.utils import draw_body_connections, draw_keypoints
import numpy as np
def _draw_conn(image, point1, point2, color, thickness=1):
x1, y1, v1 = point1
x2, y2, v2 = point2
if v1 and v2:
... |
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from django_google_maps import fields as map_fields
import tango_with_django_project.settings as settings
from django.core.files.storage import FileSystemStorage
# Storage systsem for certificat... |
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool, ColumnDataSource, CategoricalColorMapper
from iss.init_config import CONFIG
from iss.tools import Tools
from... |
"""Utilities to estimate and evaluate Chebyshev coefficients of a function.
Implementation of Newhall, <NAME>. 1989, Celestial Mechanics, 45, p. 305-310
"""
import numpy as np
__all__ = ['chebeval', 'chebfit', 'makeChebMatrix', 'makeChebMatrixOnlyX']
# Evaluation routine.
def chebeval(x, p, interval=(-1., 1.), doV... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 00:38:18 2018
@author: wangyu
"""
#! /usr/bin/python
#-* coding: utf-8 -*
# __author__ ="tyomcat"
import threading
import time
#import os
import socket
import select
import queue
class socket_cli_Trans():
'''
实现对客户端的socket链接,并接受和发送数据,实现数据的通信过程。请注意这次是实现二... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.views.generic import (DetailView, UpdateView, DeleteView, FormView, View, ListView,
CreateView, RedirectView)
f... |
#!/usr/bin/env python3
import time
import math
import os
import cv2
from collections import namedtuple
from itertools import combinations
import numpy as np
import shm
from vision.modules.base import ModuleBase
from vision.options import IntOption, DoubleOption, BoolOption
from vision import vision_common
options = ... |
# This script is identical to the on for BFSongRepository but with canaries
from collections import defaultdict
import json
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from tqdm import tqdm
import vak.device
import vak.files
from vak.labeled_timebins im... |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# -... |
# mypy: ignore-errors
from collections import Counter
from typing import Callable, Tuple, Dict, Set, Iterator, Sequence, Any, List
from rlo import analytics
from rlo import rewrites
from rlo.node_evaluation_cache import NodeEvaluationCache
from rlo.search_ops import AbstractSearcher
from rlo.tf_model import ModelWrapp... |
#!/usr/bin/env python3
# Copyright 2019 Canonical Ltd.
#
# 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 la... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Description
===========
Quickly edit your wx.pth file in site-packages
License: wxPython/wxWidgets
"""
#-Imports---------------------------------------------------------------------
#--Python Imports.
import os
import sys
import platform
from collections import Ord... |
import pandas as pd
import json
import random
import numpy as np
import warnings; warnings.filterwarnings('ignore')
def clean_data(all_data):
"""
Preprocesses the adult forum user data
"""
all_data = all_data.iloc[: 28831, :]
# drop unnecessary columns
data = all_data.drop(['Location', 'Verif... |
import sys
sys.path.append(".")
sys.path.append("..")
import numpy as np
import os
import sklearn
from sklearn.model_selection import train_test_split
from utils import pickle_object, read_pickle_object
from collections import defaultdict
import pandas as pd
import glob
import json
from data.twin_data_metadata import ... |
import re
import collections
import os
import logging
import yaml
import numpy as np
from doepipeline.designer import ExperimentDesigner
from doepipeline.utils import parse_job_to_template_string
class PipelineGenerator:
"""
Generator class for pipelines.
Given config the :class:`PipelineGenerator` pr... |
#!/usr/bin/env python
# Direct Requirements:
# Twisted
# PyOpenSSL
# service_identity
import json
import textwrap
import smtplib
from email.mime.text import MIMEText
from datetime import date
from datetime import datetime
from datetime import timedelta
from functools import partial
from twisted.python import log
... |
#The calendar master :-)
import Hlokza_Handy_Functions as mf
#this list contains all dates in multiple formats
allDates = []
yearDays = 365.25
allMonths = {"January":31,"February":28,
"March":31,"Aprill":30,"May":31,
"Jun":30,"Jully":31,"August":31,
"September":30,"October":31,
"November":3... |
import struct
import os, sys
import time
import socket
import threading
import re
numLookup = {
0 : " ",
3 : "1",
15: "4",
19: "7",
21: "0",
25: "2",
27: "3",
28: "6",
29: "8",
30: "5",
31: "9"
}
keys = {
'0': 16,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5'... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ""
from keras.layers import Input, merge, Dropout, Dense, Flatten, Activation, Conv2D, concatenate, GlobalAveragePooling2D, Lambda
from keras.layers.convolutional import MaxPooling2D, Convolution2D, AveragePooling2D
from keras.layers.normalization import BatchNormalization... |
#!/usr/bin/env python
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
## ##
## This file forms part of the Underworld geophysics modelling application. ##
## ... |
import seaborn as sns
import numpy as np
import h5py
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from skimage.transform import resize
def initialize_parameters(layers_dims):
np.random.seed(1)
parameters = {}
L = len(layers_dims)
for l in range(1, L):
parameters["W" + str... |
from PIL import Image, ImageDraw
import math
version = "0"
control = ["ü", "å", "É", "/", "?", "O", "§", "o", "à"]
chars = {
'@': [0, 128, 0],
'Δ': [0, 0, 128],
'0': [0, 128, 128],
'¡': [128, 128, 128],
'P': [0, 255, 0],
'¿': [0, 0, 255],
'£': [0, 255, 255],
'_': [0, 0, 135],
'!': [0, 0, 215],
'1': [0, 95,... |
import gzip
import tempfile
from os.path import dirname, join
from collections import Counter
from itertools import chain
from corpustools import add_most_frequent
from corpustools import ContainsEverything
from corpustools import ENGLISH
from corpustools import extract_units, extract_fields
from corpustools import f... |
import sys
import os
from bs4 import BeautifulSoup
def CardString(strCardRaw):
strCardRaw = strCardRaw.lower()
strCardRaw = strCardRaw.replace("x", "z")
assert(len(strCardRaw)==2)
assert(strCardRaw[0] in "eghs")
assert(strCardRaw[1] in "789zuoka")
return strCardRaw.upper()
def solo_payout_schn... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
# https://www.acmicpc.net/problem/12100
# #NYAN NYAN
#░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
#░░░░░░░░░░▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄░░░░░░░░░
#░░░░░░░░▄▀░░░░░░░░░░░░▄░░░░░░░▀▄░░░░░░░
#░░░░░░░░█░░▄░░░░▄░░░░░░░░░░░░░░█░░░░░░░
#░░░░░░░░█░░░░░░░░░░░░▄█▄▄░░▄░░░█░▄▄▄░░░
#░▄▄▄▄▄... |
'''
Accounts GUI
For displaying accounts (IM, email, and social) in the Preference window.
'''
from __future__ import with_statement
import wx
from contextlib import contextmanager
from gui.uberwidgets.umenu import UMenu
from .anylists import AnyRow, AnyList
from .accountdialog import AccountPrefsDialog
f... |
#!/usr/bin/env python
"""Helper class to migrate data."""
from __future__ import division
from multiprocessing import pool
import sys
import threading
from grr.lib import rdfvalue
from grr.lib import type_info
from grr.lib import utils
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import ... |
# MIT License
#
# Copyright (c) 2013 <NAME>
#
# This file is part of excons.
#
# 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
# t... |
import os
import torch
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
from pytorch_lightning import seed_everything, Trainer
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import EarlyStop... |
from functools import partial
import numpy as np
import cv2
import torch
import detectron2
from detectron2.config import get_cfg
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
import pytorchvideo
from pytorchvideo.transforms.functional import (
uniform_temporal_subsample,
sho... |
"""A variant of anchor_head_single.
The differences are as follows:
* two more options: num_convs, GN
* apply two split convs for regression outputs and classification outputs
* when num_convs == 0, this module should be almost the same as anchor_head_single
* in conv_box/cls, the kernel size is modified to 3 instead ... |
from collections import defaultdict
import json
import os
import cv2
from tqdm import tqdm
from config import DemoConfig as C
def load_frame(season, episode, frame_number):
frame_fpath = C.frame_fpath_tpl.format(season, episode, frame_number)
frame = cv2.imread(frame_fpath)
return frame
def generate_f... |
#!/usr/bin/python3
from Camera import Camera
from PIL import ImageTk
from collections import OrderedDict
from tkinter import ttk
import PIL
import cv2
import os
import tkinter as tk
class CameraSetup:
"""Choose camera and default settings"""
def __init__(self, win_name="Camera Setup", win_h=900, win_w=1600,... |
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from torch.quantization.observer import HistogramObserver, MinMaxObserver
if TYPE_CHECKING:
from typing import Tuple
class MinMaxShiftObserver(MinMaxObserver):
def __init__(
self,
dtype=torch.quint8,
qs... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# <NAME>, <EMAIL>
'''
Summary
-------
Setup and configure multiple C/C++ build environments and configure
common C/C++ tools used when cross-compiling. When using this module
the following tools will be loaded and configured autmatically as well:
- cmake
- c... |
from __future__ import unicode_literals
import frappe
import unittest
from frappe.utils import nowdate, add_months, getdate, add_days
from erpnext.hr.doctype.leave_type.test_leave_type import create_leave_type
from erpnext.hr.doctype.leave_ledger_entry.leave_ledger_entry import process_expired_allocation, expire_alloca... |
#! /usr/bin/env python3
#Copyright 2021 <Analog Devices>
#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,... |
import io, os, json
import tempfile, csv, tarfile, shutil
import pandas as pd
from pandas import DataFrame
from utils.spreadsheet import create_annotated_sheet
from requests import post, put
from requests.models import Response
from typing import Tuple, Dict, Optional, NoReturn
'''
This module contains the following f... |
"""Atari Wrappers from OpenAI Baselines"""
import numpy as np
import os
os.environ.setdefault('PATH', '')
from PIL import Image
from collections import deque
import gym
from gym import spaces
import cv2
import tensorflow as tf
import functools
from prescience.labelling import get_property
cv2.ocl.setUseOpenCL(False... |
#!/usr/bin/env python3
## You will have to implement a very primitive machine learning framework. The skeleton is given, you have to fill the
## blocks marked by "## Implement". The goal is to give you a little insight how machine learning frameworks work,
## while practicing the most important details from the class.... |
########
# Copyright (c) 2014-2021 Cloudify Platform Ltd. 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 ... |
import math
# =================================================================================
# =================================================================================
# Spur-gear generation script
# (c) <NAME>, 2012
# Free for all use, including commercial, but do not redistribute.
# Use at your own risk.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# code for python2.7
#
# this node is a motor command generator node for whip bot maneuver.
# It works as interface node for servo.
#
import rospy
import serial
import time
import signal
import sys
import tf
import math
from Tkinter import *
from std_msgs.msg import Int1... |
import torch
from lib.engine.perceptual_loss import PerceptualLoss
from lib.engine.contextual_loss import ContextualLoss
from torch import nn
from torch.nn import functional as F
import torchvision.models.vgg as vgg
import random
# refer to https://chsasank.github.io/vision/_modules/torchvision/models/vgg.html
# c... |
import os
import subprocess
import threading
import tkinter as tk
from tkinter import filedialog, messagebox
from writer import filewrite
from PIL import Image, ImageFilter, ImageTk
colours = ((255, 255, 255, "white"),
(200, 100, 50, "orange"),
(128, 0, 0, "red"),
(0, 255, 0, "green"),... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module where readline is properly configured before prompt_toolkit is loaded.
Summary
-------
In tandem with :file:`../pyreadlineconfig.ini`, keybindings
are set up to attempt adding the standard readline bindings
to Vim insert mode.
Extended Summary
----------------
T... |
'''Contains all the important functions used in the other filess'''
import random
import string
import math
import time
import numpy
import itertools
from mastermindCodeManager import *
'''-----------Functions to get user input--------------'''
def getGameCodeLength():
codeLength = None
whi... |
"""HTML/XHTML/HTML 5 tag builder.
"""
from __future__ import unicode_literals
import collections
import functools
import re
import six
from six.moves.urllib.parse import quote as url_escape
# Literal imports and constants
from ._literal import literal, EMPTY
escape = literal.escape
NL = literal("\n")
BR = literal("<... |
import argparse
import os
from model.al_manager import get_al_manager
from utils.graphs import active_learning_graph
from utils.pickle import save
DEFAULT_BATCH_SIZE = 32
DEFAULT_PERFORM_SHUFFLE = True
DEFAULT_NUM_EPOCHS = 10000
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def bool_arguments(value):
return True i... |
"""Demo code shows how to estimate human head pose.
Currently, human face is detected by a detector from an OpenCV DNN module.
Then the face box is modified a little to suits the need of landmark
detection. The facial landmark detection is done by a custom Convolutional
Neural Network trained with TensorFlow. After tha... |
import numpy as np
import pickle
import time
from random import uniform
import torch
from torchvision import datasets
import torchvision
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
... |
#!/usr/bin/python3
import itertools
import pathlib
import os
import shutil
import subprocess
from concurrent import futures
import plato_pylib.plato.mod_plato_inp_files as platoInp
def executeRunCommsParralel(allRunComms:list, maxThreads:int, quiet=False, noCommsOk=True, checkCall=True):
quietMode = quiet
jobsLef... |
#!/usr/bin/env python3
"""\
Script for managing Zig versions in use.
The script uses and updates the version listed in the README.md file.
current-path can be used to add zig to PATH.
"""
import sys
import json
from argparse import ArgumentParser
from pathlib import Path
import urllib.request
import urllib
import re... |
import warnings
import numpy as np
import scipy as sp
from scipy import stats
import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import utilities
def create_batches(features, y, batchsize):
# Create random indices to reorder datapoints
n = features.shape[0]
p = features.shape[1]
... |
# William
# Generate line graphs for comparison of the average cost of moves comparing player experience and days since release.
from helper_fns import *
import numpy as np
import matplotlib.pyplot as plt
import math, pymongo
from bson import objectid
# Some tunable constants
minimum_played = 3
bucket_count = 15
s1... |
import os
import sys
import numpy as np
import time
import torch
import eeea.utils.utils as utils
import glob
import random
import logging
import argparse
import torch.nn as nn
import eeea.network.genotypes as genotypes
import torch.utils
import torchvision.datasets as dset
import torchvision.transforms as transforms
... |
#!/usr/bin/env python
# coding:utf-8
"""
Author : <NAME>
Contact : <EMAIL>
"""
import os
import sys
import cv2
import time
# import gtts
import numpy as np
import pandas as pd
import mediapipe as mp
import tensorflow as tf
from datetime import datetime
from playsound import playsound
from goprocam import GoProCamera... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from unittest import TestCase
from pprint import pprint
from elasticsearch.exceptions import NotFoundError
from ..client import ElasticClient
from .data import Base, Genre, Movie, get_data
class TestClient(... |
import datetime
from reportlab.pdfbase.pdfmetrics import (getAscent, getDescent)
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from reportlab.platypus.doctemplate import BaseDocTemplate, PageTemplate
from reportlab.platypus.frames import Frame
from reportlab.pdfbase import pdfmetrics
from r... |
import unittest
from maskgen.validation.core import *
from tests.test_support import TestSupport
from maskgen.scenario_model import ImageProjectModel
from maskgen.maskgen_loader import MaskGenLoader
from mock import Mock
from maskgen.software_loader import insertCustomRule
class MockImageGraph:
def __init__(self... |
import inspect
import logging
import os
import string
from pathlib import Path
from collections import defaultdict
import numpy as np
import torch
from pyemd import emd
from torch import nn
from pytorch_pretrained_bert import BertModel, BertTokenizer
from pytorch_pretrained_bert.modeling import BertPreTrainedModel
f... |
import pickle
import pandas as pd
import os
import openai
import numpy as np
import ipdb
import re
from tqdm import tqdm
import time
from transformers import GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
import spacy
import scipy
from data_utils import *
from eval_utils import *
openai.api_key = os... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
def smooth_l1(deltas, targets, sigma = 3.0):
assert deltas.ndimension() == targets.ndimension()
# Reference: https://mohitjainweb.files.wordpress.com/2018/03/smoothl1loss.pdf
sigma2 = sigma * sigma
diffs = deltas - ta... |
#!/usr/bin/env python3
# ----------------------------------------------------------------------------
# Copyright (c) 2020--, <NAME>.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ---------------------------------------------... |
from datetime import date
from django.test import TestCase, Client
from django.utils.translation import activate
from django.urls import reverse
from django.urls.resolvers import URLPattern, URLResolver
from django.urls.exceptions import NoReverseMatch
from www.urls import urlpatterns as urls_www
from urls import urlp... |
########################################################
# POINT POINT GAME
#
# Catégorie : Stratégie
# Auteur : <NAME> (Alchimiste des codes)
# Pseudo : @lChiMi5tE_d0t_toRr€nt
# Compagnie : EnighmaLab
# Date de création : 17/05/2017
# Scène : Player vs Play... |
import logging
import time
import random
from aeternity.transactions import TxSigner
from aeternity.signing import Account
from aeternity.openapi import OpenAPIClientException
from aeternity.exceptions import NameNotAvailable, InsufficientFundsException
from aeternity.exceptions import TransactionHashMismatch, Transac... |
# SeekTruth.py : Classify text objects into two categories
# Written by hatha, aagond, saimorap
# References:
#1. https://stackoverflow.com/questions/18429143/strip-punctuation-with-regex-python
#2. https://docs.python.org/3/library/re.html
#3. https://www.datacamp.com/community/tutorials/python-list-comprehension
#4. ... |
#!/usr/bin/env python3
#
# Copyright (C) 2021 IBM Corporation.
#
# Authors:
# <NAME> <<EMAIL>>
# <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... |
from django.db import models
from django.urls import reverse #Used to generate URLs by reversing the URL patterns
import uuid
from datetime import datetime, date
from django.utils import timezone
from django.core.validators import RegexValidator, MaxValueValidator, MinValueValidator
from decimal import Decimal
from dj... |
"""Tests the arxiv repository
"""
import pytest
import responses
from webminer.entities.arxiv_document import ArxivDocument
from webminer.use_cases.request_arxiv import arxiv_repo as a_repo
arxiv_doc_1 = ArxivDocument(
doc_id="url_1",
url="url_1",
title="title_1",
abstract="abstract_1",
authors=[... |
# ******************************************************************************
# Copyright 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... |
#!/usr/bin/python3
#
# This contains the main pyFvwm class which handles creation
# and management of the pyFvwm configuration database. In
# addition it handles formatting fvwm2rc files and building
# themes.
#
# Ensure that the home directory below is set to the location
# of pyFvwm's data files.
#
import os
impor... |
# Copyright (c) 2006-2011 <NAME> http://garnaat.org/
# Copyright (c) 2011, Eucalyptus Systems, Inc.
#
# 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 ... |
import pickle
import warnings
from abc import ABC, abstractmethod
from typing import Type
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model i... |
from __future__ import absolute_import, unicode_literals
# TODO: Improve API methods docstrings
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.settings impo... |
import os
import logging
from nose.tools import assert_equal
from ckanext.qa.sniff_format import sniff_file_format, is_json, is_ttl, turtle_regex
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('ckan.sniff')
class TestSniffFormat:
@classmethod
def setup_class(cls):
# Assemble a list... |
"""
Script for performing an active learning experiment with a GP on fragment/fingerprint molecular features
"""
import os
import warnings
import argparse
import gpflow
import numpy as np
import pandas as pd
from gpflow.utilities import print_summary
from rdkit.Chem import Descriptors, MolFromSmiles, AllChem
import t... |
import numpy as np
import cv2
from src.align.matlab_cp2tform import get_similarity_transform_for_cv2
# reference facial points, a list of coordinates (x,y)
REFERENCE_FACIAL_POINTS = [ # default reference facial points for crop_size = (112, 112); should adjust REFERENCE_FACIAL_POINTS accordingly for other crop_size
... |
"""
Audio Classifier Tutorial
=========================
**Author**: `<NAME> <https://github.com/winston6>`_
This tutorial will show you how to correctly format an audio dataset and
then train/test an audio classifier network on the dataset. First, let’s
import the common torch packages as well as ``torchaudio``, ``pan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.