text stringlengths 3.07k 22.1k |
|---|
# testDriver.py
"""Volume 1A: Linear Systems. Test driver."""
import signal
from functools import wraps
from matplotlib import pyplot as plt
def _autoclose(func):
"""Decorator for closing figures automatically."""
@wraps(func)
def wrapper(*args, **kwargs):
try:
plt.ion()
re... |
__author__ = 'bptripp'
import csv
import time
import numpy as np
import matplotlib.pyplot as plt
from cnn_stimuli import get_image_file_list
from alexnet import preprocess, load_net, load_vgg
from scipy.signal import fftconvolve
def mean_corr(out):
cc = np.corrcoef(out.T)
n = cc.shape[0]
print('n: ' + st... |
from __future__ import print_function
import bpy
from bpy.types import Operator, Panel, PropertyGroup, WindowManager
from bpy.props import PointerProperty, StringProperty, IntProperty, FloatProperty, BoolProperty
import sys
paths = [
#PYTHON_PATH,
PROJECT_DIR
]
for p in paths:
sys.path.insert(0, p)
from m... |
"""
Helpers for tfrecord conversion.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
class ImageCoder(object):
"""Helper class that provides TensorFlow image coding utilities.
Taken from
https://g... |
"""
Utilities for courses/certificates
"""
import logging
from requests.exceptions import HTTPError
from rest_framework.status import HTTP_404_NOT_FOUND
from django.conf import settings
from django.db import transaction
from courses.constants import PROGRAM_TEXT_ID_PREFIX
from courses.models import (
CourseRunGrad... |
from datetime import datetime
from django import forms
from django.conf.urls.static import static
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpR... |
from __future__ import with_statement
from difflib import SequenceMatcher
import os
from unittest import TestCase
import sys
import django
from django import template
from django.conf import settings
from django.template.loader import render_to_string
from django.template.engine import Engine
import pep8
from sekizai... |
import matplotlib.pyplot as plt
import time, math
import tables
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import transforms
import torchvision.models as models
import h5py
from torch.autograd import Variable
import pandas as pd
import numpy as np
from torch.utils.data i... |
"""Utility to provide submission and comment statistics in a subreddit."""
from __future__ import print_function
from collections import defaultdict
from datetime import datetime
from tempfile import mkstemp
import codecs
import gc
import logging
import os
import re
import time
from praw import Reddit
from prawcore.e... |
from typing import List, Sequence, Tuple
import numpy as np
from deepchem.utils.typing import RDKitAtom, RDKitBond, RDKitMol
from deepchem.feat.graph_data import GraphData
from deepchem.feat.base_classes import MolecularFeaturizer
from deepchem.utils.molecule_feature_utils import get_atom_type_one_hot, \
construct_h... |
# coding=utf-8
# C extractor for code2vec
#
# Copyright 2019 Carnegie Mellon University. All Rights Reserved.
#
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMP... |
# PyDIP 3.0, Python bindings for DIPlib 3.0
#
# (c)2017-2019, Flagship Biosciences, Inc., written by <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licen... |
#!/usr/bin/env python3
"""
VectorDrawable2Svg
This script converts VectorDrawable .xml files to SVG files.
Initial author: <NAME>
Modified by: <NAME>
"""
import argparse
import os.path
from xml.dom.minidom import Document, parse
import traceback
from io import StringIO, SEEK_SET
import logging
logger = logging.getLog... |
# Library of pytorch functions related to convolutional variational autoencoders
import superimport
import os
import time
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import PIL
import imageio
import torch
from torch import nn
from torch.nn import functional as F
import torchvision
fro... |
# %%
import pandas as pd
import numpy as np
import requests
import unicodedata
import string
import re
from fuzzywuzzy import fuzz, process
from bs4 import BeautifulSoup
from tqdm import tqdm
# ----------- UTILITY ---------------
def clean_string(string):
string = unicodedata.normalize('NFKD',string) \
.en... |
import os
import json
import numpy as np
from tqdm import tqdm
import torch
import argparse
from amortized_synthesis.utils import add_args, AverageMeter, stable_smooth_regularizer, rb_state_proj, \
rb_smooth_regularizer, rb_sample_obs, rb_collision_penalty, rb_collision_detection, load_rb_mesh_points_to_opt
from am... |
from urllib.parse import quote_plus
import logging
from typing import List
from dacite import from_dict
from dacite.exceptions import (
DaciteFieldError,
ForwardReferenceError,
MissingValueError,
UnexpectedDataError,
WrongTypeError,
)
from pymongo import MongoClient
from pymongo.errors import Connec... |
# -*- coding: UTF-8 -*-
import os
from unittest import TestCase
import numpy as np
import solvcon as sc
from .. import solver
from .. import testing
from ..parcel.fake._algorithm import FakeAlgorithm
class CustomBaseSolver(solver.BaseSolver):
def __init__(self, **kw):
kw['neq'] = 1
super(Custo... |
import couchdb
import re
from _datetime import datetime
# local_host = "http://ailinz1:unimelb666@localhost:5984"
# local_couch = couchdb.Server(local_host)
# remote_host = "http://admin:admin@172.16.31.10:5984"
# remote_couch = couchdb.Server(remote_host)
def getDB(database):
db_host = "http://ailinz1:unimelb66... |
import sys
import numpy as np
import torch
import torch.nn as nn
from torch.nn import init
import torch.optim as optim
import math
import random
import os
import csv
from pathlib import Path
from model import model
import time
from tqdm import tqdm
TESTLOSS = False
SAVEMODEL = False
def read_input(task... |
# Copyright (c) <NAME> & <NAME>. Licensed under the Apache License 2.0. All Rights Reserved
"""Postprocessors class to transform MDETR output according to the downstream task"""
from typing import Dict
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from util import box_ops
clas... |
"""
Utility that wraps OpenGL textures, frame buffers and render buffers.
"""
from pycompat import *
import contextlib
from OpenGL.GL import *
from qtutil import *
class Texture(object):
"""
Creates a GL texture2D.
The static members below are all color formats at this point in time &
make it only 1 v... |
#Program: A self implemented basic kd_tree algorithm
import numpy as np
import pandas as pd
import math
import time
#class for internal nodes of the kdTree
#holds, cut_dim value at each node, along with cut_point itself for reference.
#left_child points to the left node of the tree, similarly right_child points to th... |
from os import path
import glob
from updater import get_updater
from filter import get_filter
from cache import get_cache
from merge import (FileHunk, MemoryHunk, apply_filters, merge,
make_url, merge_filters)
__all__ = ('Bundle', 'BundleError',)
class BundleError(Exception):
pass
class Bui... |
import milk.supervised.svm
from milk.supervised.svm import svm_learn_smo, svm_learn_libsvm, _svm_apply, learn_sigmoid_constants, svm_sigmoidal_correction
import numpy
import random
import numpy as np
import milk.supervised.svm
import pickle
eps=1e-3
def approximate(a,b):
a=numpy.asanyarray(a)
b=numpy.asanyarray... |
import unittest
import math
import sys
import time
from flaky import flaky
from typed_python import Class, Final, ListOf, Held, Member, PointerTo, pointerTo
from typed_python.test_util import currentMemUsageMb
@Held
class H(Class, Final):
x = Member(int)
y = Member(float)
def f(self):
return sel... |
'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from sklearn.metrics import classification_report
from datasets... |
# Generate order book
# Orders are generated randomly each month of the year to reflect seasonality
# For training, the orders will keep the same probability distribution for
# each training episode, but be stochastically regenerated for each new
# episode. This will keep the statistics of each product consistent.
i... |
"""
Dictionary learning estimator: Perform a map learning algorithm by learning
a temporal dense dictionary along with sparse spatial loadings, that
constitutes output maps
"""
# Author: <NAME>
# License: BSD 3 clause
from __future__ import division
import warnings
from distutils.version import LooseVersion
import ... |
import numpy as np
import torch
import os
from torch.autograd import Variable
from utils.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
class SSRGAN(BaseModel):
def name(self):
return 'SSRGAN'
def init_loss_filter(self, use_gan_feat_loss, use_vgg_loss):
f... |
'''Returns a fact to indicate if this machine can be upgraded to Mojave'''
# Based on
# https://github.com/hjuutilainen/adminscripts/blob/master/
# check-10.12-sierra-compatibility.py
# sysctl function by <NAME>
# https://gist.github.com/pudquick/581a71425439f2cf8f09
# IOKit bindings by <NAME>
# https://gist... |
import nanome
from nanome.api.structure import Complex
from nanome.util import async_callback, Logs
from cairosvg import svg2png
from rdkit import Chem
from rdkit.Chem import AllChem, Draw
import argparse
import asyncio
import base64
import json
import os
import random
import string
import tempfile
import websockets
... |
import numpy as np
from scipy.sparse import csc_matrix, isspmatrix_csc
from scipy.sparse.linalg import eigsh
from tqdm.auto import tqdm
from ..chain import Chain
from ..data import Data
from ..posterior import PosteriorParameter
from ..utils import get_generator
from .parallel import sample_parallel
from .state impor... |
# -*- coding: utf-8 -*-
"""
Resample GEMB cube(s) (y,x,t) onto floating cube (y,x,t).
Notes:
Run code twice: once for SMB and once for Firn.
Edit params for each run and according data resolution.
"""
import warnings
import sys
import h5py
import numpy as np
import xarray as xr
import netCDF4 as nc
import ma... |
import copy
import json
import os
import urllib.parse
import boto3
import hashlib
from io import StringIO
# --------------------------------------------------
# Initializes global variables
# --------------------------------------------------
def init():
global s3, s3_client, stpfn_client, lambda_client, event_cl... |
import numpy as np
from scipy.spatial import Voronoi
from .cvfdutil import get_disv_gridprops
def get_sorted_vertices(icell_vertices, vertices):
centroid = vertices[icell_vertices].mean(axis=0)
tlist = []
for i, iv in enumerate(icell_vertices):
x, y = vertices[iv]
dx = x - centroid[0]
... |
# -*- coding: utf-8 -*-
import requests
from lxml import html
import json
import datetime as dt
import global_settings as gs
import os
if not gs.local:
import boto3
from dynamodb_json import json_util as dyjson
def daterange(start_date, end_date):
"""
Works the same... |
"""
Regex notes:
Get recipe title
(?:^# (.*)\s+)
Get the img tag or whatever is between the title line and the next section
(?:^# .*\s*)(^(?:<.+>\s*?)*?)\s*(?:##[^#])
Get the overview section rows in a single group
(?:^## Overview\s+)(^(?:.*\s*?)*?)\s*(?:##[^#])
Get the entire ingredients sections, including blank... |
# -*- coding: utf-8 -
#
# This file is part of http-parser released under the MIT license.
# See the NOTICE for more information.
import os
import re
import sys
if sys.version_info >= (3,):
import urllib.parse as urlparse
else:
import urlparse
import zlib
from http_parser.util import (b, bytes_to_str, IOrde... |
#coding: utf-8
#Criado por <NAME> em Janeiro/2018
#Usar Python3 ... hora de boas práticas
#simulador de Arduino Fancoil do HEC
#so preciso receber JSON, guardar e ficar enviando a cada 2 segundos
import os, sys, io, time, datetime, string
try:
import serial
except:
import pySerial as serial
#talve... |
from typing import Union, Dict, Optional, List
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
INTEGRATION_CONTEXT_BRAND = "DeHashed"
BASE_URL = "https://api.dehashed.com/"
RESULTS_FROM = 1
RESULTS_TO = 50
class Clie... |
import datetime
# Create your models here.
import logging
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.urls.base import reverse
from six import python_2_unicode_compatible
from django.utils import timezone
from django.utils.functional import cached_property
f... |
#!/usr/bin/python
# -*- coding:utf8 -*-
################################################################################
#
# Copyright (c) 2020 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
# Power by work 2020-06-30 20:50:39
"""
import nump... |
"""CLI CQU 是重庆大学教务系统的命令行界面
"""
import json
import logging
import re
import time
from argparse import ArgumentParser
from datetime import date
from getpass import getpass
from bs4 import BeautifulSoup
from requests import Response
from requests import Session
from .data import HOST
from .data.js_equality import chkpwd... |
import click, os, sys
from baseq.snv import cli
from baseq.snv.qc.cmd import *
@cli.command(short_help="Check the enrichment quality, input: bam, interval and outpath")
@click.argument("bampath")
@click.argument("interval")
@click.argument("outpath")
def enrich_saturation(bampath, interval, outpath):
pass
@cli.co... |
# -*- coding: utf-8 -*-
"""
saltfactories.utils.processes.helpers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Process related helper functions
"""
import errno
import logging
import pprint
import signal
import sys
import time
import weakref
import psutil
from saltfactories.exceptions import ProcessNotStarted
from saltfact... |
#!/usr/env/python
# -*- coding: utf-8 -*-
'''
Script that processes a dataset of rated articles and checks each article's
talk page in order to verify how many templates with importance ratings are
on their talk pages.
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a c... |
# Copyright (c) 2017 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
import os
import sys
sys.path.append(os.getcwd())
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
from workspace.workspace_cls import SENT_WORDID, SENT_LABELID, SENT_WORD_MASK, SENT_ORIGINAL_TXT
import numpy
import random
from torch.uti... |
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QProgressBar, QPlainTextEdit, QMainWindow, QTextBrowser, \
QDialog, QMenu, QAction, QMessageBox, QStatusBar, QSlider, QLabel, QCheckBox, QDialogButtonBox
from PyQt5.QtGui import QIcon, QFont
from PyQt5 import uic, QtGui
import sys
from time import slee... |
import os
import sys
import collections
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
from PIL import Image
import torch
import torchvision
import cv2
import numpy as np
import random
import pathlib
def resize_bbox(bbox,scale_transform):
min_x, m... |
# -*- coding: utf-8 -*-
# Copyright 2017 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 r... |
# -*- coding: utf-8 -*-
from typing import List, Dict, Set, Optional, Type
import six
import attr
import random
import string
from datetime import datetime
from abc import abstractmethod
from loggerFactory import StreamOnlyLogger
from ..status import Status, FINISHED_STATUS_CODE
from ..util import get_all_subclass
c... |
import requests
import hmac
from hashlib import sha1
import json
try:
from urllib.parse import urlencode
except ImportError:
# python2
from urllib import urlencode
CS_URL = "https://hapi.couchsurfing.com"
PRIVATE_KEY = "<KEY>"
class AuthError(Exception):
"""
Authentication error
"""
def _... |
from django.contrib import messages
from django.contrib.auth import authenticate, login, signals, update_session_auth_hash
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.exceptions import PermissionDenied
from django.db.models import Prefetch, Q
from django.dispatch import receiver
from dja... |
"""This file defines base types and common structures for RLlib connectors.
"""
import abc
import gym
import logging
from typing import Any, Dict, List, Tuple
from ray.tune.registry import RLLIB_CONNECTOR, _global_registry
from ray.rllib.policy.policy import Policy
from ray.rllib.policy.view_requirement import ViewRe... |
from scipy.spatial.distance import pdist
class DBSCAN(object):
def __init__(self, eps, min_neighbors, metric='euclidean'):
"""
A re-creation of the DBSCAN algorithm, using only scipy as a dependency.
:param eps: Epsilon, aka the distance between two points to be considered 'neighbors'.
... |
import sys
import os
from ctypes import Structure, c_int32, c_int, c_char_p,\
create_string_buffer, memmove,\
c_void_p, POINTER, byref, c_double, cdll
from ctypes.util import find_library
from kivy.core.image import ImageData
from kivy.graphics.texture import Texture
current_dir =... |
"""
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... |
"""nskipgrams: A lightweight Python package to work with ngrams and skipgrams
Author: <NAME> <<EMAIL>>
License: MIT License
Source: https://github.com/jacksonllee/nskipgrams
"""
from collections import defaultdict, OrderedDict
from itertools import combinations
import pkg_resources
__version__ = pkg_resources.get_d... |
import os
import re
import json
import shutil
from .modeling import BertConfig
from . import data_preprocessing
from .utils import create_path, EOS_TOKEN, get_or_make_label_encoder
class BaseParams():
def __init__(self):
self.run_problem_list = []
self.problem_type = {
'weibo_ner': ... |
from . import bp, forms, models
from flask import render_template, make_response, request, session, redirect, url_for
from flask_login import login_required
# from flask_user roles_required
import datetime
import wtforms as wtf
from app import db
printOrder_columns = ['DateTime', 'Print Design', 'Size', 'Paper Type', ... |
"""A module of functional tests for the events index page and events/past events pages.
TODO:
Refactor most of these tests out into base functional tests.
"""
import os
import pytest
from django.utils.text import slugify
from base_functional_tests import click_obscured, find_and_click_add_button, find_and_click_t... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 3 12:24:08 2020
@author: eilxaix
"""
import math
import nltk
import numpy as np
import re
from collections import Counter
from utils import lemmatize, embed_phrase
from evaluation import get_ranked_kplist, get_ranked_kpidx
from scipy.spatial.distance import cosine
... |
import datetime
import json
import re
import urlparse
import pytest
import httmock
from peregrine import test_settings
class Config(object):
ADMIN_USERNAME = 'iama_username'
ADMIN_PASSWORD = '<PASSWORD>'
ADMIN_TOKEN = 'admin_token'
MEMBER_TOKEN = 'member_token'
SUBMITTER_TOKEN_A = 'submitter_a... |
import datetime
import requests
import json
import re
import os
import csv
from src.models.Uploads import Uploads
from src.models import Emails as Email
from src.views import Logger
BASE = os.getcwd()
LOGGER = Logger.init_logger(__name__)
def clean_filename(course_id: str, fname: str):
"""Cleans up given filenam... |
import asyncio
import contextlib
import json
import jsonpickle
import os
import requests
import sys
import time
import traceback
import websockets
from a2ml.api.utils import fsclient, dict_dig
from a2ml.api.a2ml_credentials import A2MLCredentials
from a2ml.api.utils.file_uploader import FileUploader, OnelineProgressPe... |
import torch
from torchtext import data
from torchtext import datasets
from tvm.relay.test_network import BiLSTM
SEED = 1234
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
TEXT = data.Field(tokenize = 'spacy', include_lengths = True)
LABEL = data.LabelField(dtype = tor... |
"""Implements sensor fusion networks for supervised and self-supervised objectives."""
import torch
import torch.nn as nn
from .models_utils import (
duplicate,
gaussian_parameters,
product_of_experts,
sample_gaussian,
)
class SensorFusion(nn.Module):
"""
Implements traditional SensorFusionNet... |
import json
import os
import pathlib
import time
from typing import Optional, List, Set, Dict, Union
import git
from lab import logger, monit
from lab.internal.configs import Configs, ConfigProcessor
from lab.internal.experiment.experiment_run import Run
from lab.internal.lab import lab_singleton
from lab.internal.lo... |
import random
import sys
import os
import dill
import argparse
import pandas as pd
import numpy as np
from tqdm import tqdm
import itertools
import torch
#from .kalman_filter import NonlinearKinematicBicycle
# sys.path.append("/home/adeshkin/Desktop/shifts/sdc")
from ysdc_dataset_api.utils import get_file_paths, scen... |
"""
Extract sampled paramaters of selected traces and prepare simulation input files with fitted parameters
Outputs:
- 2 csvs with fitting paramerers for a) single best fit and b) n best fits
- 2 csv with samples parameters that can be used as input csv for subsequent simulation (for a and b as above)
- 1 emodl with fi... |
# Copyright 2021 Massachusetts Institute of Technology
#
# @file demon_dataset.py
# @author <NAME>
# @date 2020-10-09 11:55:58 (Fri)
import os
import glob
import random
from PIL import Image
import numpy as np
import torch.utils.data as tud
from utils import depthmap_utils
class DeMoNDataset(tud.Dataset):
"""D... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
import numpy as np
import matplotlib.pyplot as plt
import imageio
import random
import cv2
import os
import re
import pandas as pd
import math
from collections import OrderedDict
import gc
# check if in a ipython enviorment
try:
get_ipython()
from tqdm.notebook import tqdm
except Exception:
from tqdm impor... |
"""
Serial Communications
The implementation of RTU reception driver may imply the management of a lot of interruptions due to the t1.5 and t3.5
timers. With high communication baud rates, this leads to a heavy CPU load. Consequently these two timers must be
strictly respected when the baud rate is equal or lower than ... |
import __init__
import torch
import torch.optim as optim
import statistics
from dataset import OGBNDataset
from model import DeeperGCN
from args import ArgsInit
import time
import numpy as np
from ogb.nodeproppred import Evaluator
from utils.ckpt_util import save_ckpt
from utils.data_util import intersection, process_i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
from caffe import layers as L
from caffe import params as P
__author__ = '<NAME>'
__copyright__ = 'Copyright (c) 2016, <NAME>'
__email__ = '<EMAIL>'
__license__ = 'MIT'
def make_image_label_data(image_list_path, label_lis... |
# coding:utf-8
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import ll1
MAX = 10
class Gui:
def __init__(self, master):
self.init_input = StringVar()
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... |
# Copyright 2021 The T5X 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 applicable law or agreed to in writ... |
import subprocess, os, signal, urllib3, certifi, json, re, traceback, threading, time
class Env:
def __init__(self):
# computed env vars
self.CD_CLUSTER_ID = f"{os.environ['CD_ENVIRONMENT']}/{os.environ['CD_REGION_DASHED']}/{os.environ['CD_CLUSTER_NAME']}"
self.CD_REPO_API_URL = 'https://%... |
import re
from datetime import datetime
from .object import Object
from .utils import df_military_time, day_of_week
from .enum import FileCriteria, BooleanFunction, Application, ScheduleType
class PolicyRule:
def __init__(self, assignment, criteria):
self.assignment = assignment
self.criteria = ... |
import numpy as np
from PIL import Image
import torchvision
import torch
def get_length(svhn_base_dataset):
count = 0
for img,label in svhn_base_dataset:
#print(type(label))
#exit()
count+=1
return count
class TransformTwice:
def __init__(self, transform):
self.trans... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""End-to-end test for afdo_prof_analysis."""
from __future__ import absolute_import, division, print_func... |
#!/usr/bin/env python3
import curses
import curses.textpad
import threading
import time
import textwrap
import collections
import logging
class HCHandler(logging.Handler):
def __init__(self, con):
super().__init__()
self.con = con
self.setFormatter(logging.Formatter(fmt="{levelname}:{name}:{message}", style="{"... |
import torch
from torch.utils import data
import numpy as np
import argparse
import os
from model_config import DOSconfig, BSconfig, TISEconfig
from ssl_mode import SimCLR, BYOL
from models import Net, Pred
from load_data import get_TISE_datasets, get_PhC_datasets, get_unlabeled_datasets
from loss_func import LogLoss,... |
#!/usr/bin/env python
# coding: utf-8
class Vector(list):
def __init__(self, *args, **kwargs):
super(Vector, self).__init__(*args, **kwargs)
for i in range(len(self)):
self[i] = float(self[i])
def __add__(self, b):
return Vector([self[i] + b[i] for i in range(len(self))])... |
from logging import getLogger
from typing import Any, Optional
from pyinaturalist import INAT_BASE_URL, RANKS, Coordinates, Observation
from pyinaturalist_convert import dwc_record_to_observation
from naturtag.constants import (
DATE_TAGS,
HIER_KEYWORD_TAGS,
KEYWORD_TAGS,
OBSERVATION_KEYS,
TAXON_K... |
# pylint: disable=g-bad-file-header
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/... |
#!/usr/bin/env python3
#
# JM, 29 Oct 2018
#
# some subfunctions to do analysis of pydra data
from pydra_misc import * # numpy is loaded here as np
from casl import parameters, spectral, constants
#-------------------------------------------------------------------------------
# generate the eddy momentum quantities ... |
# this is for drawing the experiment figure by generating the
# csv data table:
# data0.data: number of traversed edges;
# data1.data: running time.
# data2.data: running time for trunk size.
import sys
import re
import os.path
import time
import datetime
import csv
import numpy as np
import scipy as sp
import scipy... |
import io
import unittest.mock
import freezegun
import numpy as np
import pandas as pd
import pytest
import functions
def test_git_pull0():
with unittest.mock.patch('git.Repo') as mock_git_repo:
status = functions.git_pull('./.')
mock_git_repo.assert_called_once_with('./.')
assert status is Tru... |
import json
import logging
import os
import zipfile
from enum import EnumMeta
from os import path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
import datacube
from jobtastic import JobtasticTask
from shapely import wkt
from cubequery import get_config
from cubequery.uti... |
"""Functions for reading Jupyter files."""
import json
import re
import nbformat
from . import ParseError
from ._common import RE_JSON
def deserialize(source):
"""Convert ``.jupyter`` string representation to Jupyter notebook.
Lines have to be terminated with ``'\\n'``
(a.k.a. :term:`universal newline... |
import requests
import datetime
from xml.etree.ElementTree import fromstring
from http.client import responses
from . import Api, ParameterException, ApiException
NAMESPACE = "{http://www.collegenet.com/r25}"
class TwentyFiveLive(Api):
"""
Class that optimizes api calls to the CollegeNet 25Live REST interfac... |
"""
Block definitions for all known level formats
Reader for block definitions stored in .yaml files (based on Minecraft X-Ray)
"""
from __future__ import absolute_import
from logging import getLogger
import traceback
from collections import defaultdict, namedtuple, MutableSet
import bisect
import numpy
from m... |
"""Everything related to army value tables go here"""
import numpy as np
from sc2.constants import (
ADEPT,
ARCHON,
AUTOTURRET,
BANELING,
BANSHEE,
BATTLECRUISER,
BROODLING,
BROODLORD,
BUNKER,
CARRIER,
COLOSSUS,
CORRUPTOR,
CYCLONE,
DARKTEMPLAR,
DISRUPTOR,
D... |
#!/usr/bin/python3
import sys
import queue
from typing import Dict, Any, Union
verbosity = 0
fname = 'example.in'
elf_attack = 3
if len(sys.argv) > 1:
fname = sys.argv[1]
if len(sys.argv) > 2:
elf_attack = sys.argv[2]
lines = open(fname).readlines()
wall = '#'
empty = '.'
global_width = len(lines[0])
enemy... |
from typing import Dict, Any, Tuple, Optional, List
from ..params.model import TIME_RANGE_TYPE
from ...util.html import html_element, html_table
from ...util.schema import PropertyDef, TypeDef
FORWARD_MODEL_TYPE = TypeDef(object, properties=[PropertyDef('name', TypeDef(str)),
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cc_licences.py
Script to create cc_licence records. Script can be re-run without creating
duplicate records, but will update/replace existing records.
The --clear is not recommended if books already have cc_licences.
"""
import os
import sys
import traceback
from opt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.