text stringlengths 3.07k 12.6k |
|---|
from typing_extensions import final
from contextlib import AsyncExitStack
from typing import TYPE_CHECKING, List, Type, Optional
import pytest
from nonebug.base import BaseApp
from ..call_api import ApiContext
from .model import (
Model,
Paused,
Finished,
Rejected,
RulePass,
IgnoreRule,
R... |
#!/usr/bin/env python3
import subprocess
import os
import sys
import csv
import sys
import glob
auto_detect_redline = True
redline_path = "redline" # Overwride here if no auto detect
redline_paths = [
"redline",
"C:/Program Files/REDCINE-X PRO One-Off 64-bit/redline",
"C:/Program Files/REDCINE-X PRO 64-bit/redlin... |
"""
"""
from datetime import datetime
import numpy as np
def map_load_collection(id, process):
""" Map to load_collection process for ODC datacubes.
Creates a string like the following:
dc = oeop.load_collection(odc_cube=datacube,
**{'product': 'B_Sentinel_2',
... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin classic theme
This class can also be used as base class for other themes -
if you make an empty child class, you will get classic behaviour.
If you want modified behaviour, just override the stuff you
want to change in the child class.
@copyright: 200... |
import logging
log = logging.getLogger(__name__)
from functools import partial
import datetime as dt
import os.path
from pathlib import Path
import subprocess
from atom.api import Atom, Bool, Enum, List, Typed, Unicode
import enaml
from enaml.qt.qt_application import QtApplication
with enaml.imports():
from psi.... |
from PIL import Image
import numpy as np
import os
import edit
import filters
import cv2
def load_image(directory):
# add image
try:
pillow_image = Image.open(directory)
except Exception as Import_error:
raise Exception(Import_error)
width, height = pillow_image.size
file_size = os... |
"""Log analysis and reporting"""
from base64 import b64decode
import datetime
import json
import logging
import os
import re
import urllib
from zlib import decompress, MAX_WBITS
# Import our dependencies
import vendored
import requests
LOG = logging.getLogger()
LOG.setLevel(logging.INFO)
LOG.info('Loading function... |
import os.path
import telegram
import redis
import gettext
import configparser
from functools import wraps
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'... |
#! /usr/bin/env python2
"""
sql2uri service takes your sql and runs it against a backend you registered
in the sql-lambda service and outputs it to gdrive.
"""
from os import environ as env
from json import dumps, loads
import boto3
from flask import Flask, jsonify, request
from pynamodb.exceptions import (
Updat... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
# This script processes the joint reaction loads and computes the
# minimum and maximum bounds for a given joint of interest. The
# subject directory, the folder containing the joint reaction results
# form perform_joint_reaction_batch.py, the joint of interest and the
# mass of the subject must be provided.
#
# @autho... |
import itertools
from dataclasses import dataclass
from typing import Sequence, Set, List, Tuple
from sudoku_solver.board.board import Board
from sudoku_solver.board.cell import Cell
from sudoku_solver.shared.preview import Preview, IndicatorLevel, HighlightedPosition
from sudoku_solver.shared.puzzle import ValuePosit... |
"""
Glance API shims. See `Glance HTTP API
<https://developer.openstack.org/api-ref/image/v2/index.html>`_
"""
import textwrap
from hammers.osrest.base import BaseAPI
API = BaseAPI('image')
def images(auth, query=None):
"""
Retrieves all images, filtered by `query`, if provided.
Doesn't support pagina... |
"""Module for de-duplicating arrays of strings."""
import re
from typing import List, Optional, Union
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
STOP_TOKE... |
"""
Copyright (C) 2013-2016 <NAME>.
Licensed under the Apache 2.0 License (see LICENSE file).
optional.py
~~~~~~~~~~~
Optionally loaded constraints.
"""
import pyomo.core as po
def ramping_rate(model):
"""
Ramping rate constraints.
Depends on: node_energy_balance, node_constraints_build
"""
... |
from typing import List
from sample_metadata.apis import SampleApi, AnalysisApi
from sample_metadata.models import (
NewSample,
AnalysisModel,
AnalysisUpdateModel,
SampleType,
AnalysisType,
AnalysisStatus,
)
INPUT_PROJECT = 'test_input_project'
OUTPUT_PROJECT = 'test_output_project'
aapi = ... |
"""
Script that take TypeRefHash for .NET files and Project GUID.
Author: <NAME>
Twitter: Joseliyo_Jstnk
Version: 0.1
trh: https://github.com/GDATASoftwareAG/TypeRefHasher
"""
import os, configparser, subprocess, hashlib, sqlite3
import database_sqlite
import dash
import dash_core_components as dcc
import dash_html_com... |
import warnings
import numpy as np
import pandas as pd
from utils import n_func_maker
from utils import FitLSQ
from utils import Evaluation
from scipy.integrate import trapz
np.set_printoptions(precision=6, suppress=True)
# Define the base function
def _lorentzian(x, a, g, d):
r"""Lorentzian distribution fucn... |
import logging
import os
import random
import sendgrid
from sendgrid.helpers.mail import *
from flask import render_template, flash, redirect, request
from twilio.twiml.messaging_response import MessagingResponse
from app import app
from app.forms import SignupForm, UnsubscribeForm, BugReportForm
from utils import u_... |
# scarps the product detail from flipkart page
import argparse
import time
from bs4 import BeautifulSoup
from requests import get
import sys
import csv
import json
import sys, os
import re
# comment below line for when running from main
def readConfigFile(callFromMain):
JsonFile=None
if callFromMain:
... |
from random import (randint,
randrange,
choice,
)
import pandas as pd
import numpy as np
from DataGeneration.fake_generation import make_generator
# All following functions are used for generation of random date
# and put it into pandas.DataFrame object. I... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import with_statement
from collections import defaultdict
import numpy as np
class EventSentenceGenerator(object):
def __init__(self, event_domain,... |
from .BasicComponents import *
from .locals import *
from os.path import join as j_path
class StateComponent(StatesComponent, VelocityComponent):
def __init__(self):
super(StateComponent, self).__init__()
self.state = ShStates.MOVE
# Create sensor-rects. Their values aren't definitive - they're updated in th... |
#!/usr/bin/env python
# -*- 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 ... |
import computers
import gameio
import os
import game
class Save:
name = ""
save_info = {}
history = []
def __init__(self, name, save_info, history):
self.name = name
self.save_info = save_info.copy()
self.history = history.copy()
def store(self, info_file, history_file, c... |
import tensorflow as tf
import numpy as np
from tqdm import tqdm
eps = np.finfo(np.float32).eps
# Predefined function to build a feedforward neural network
def build_mlp(input_placeholder,
output_size,
scope,
n_layers=2,
size=500,
activation=tf.ta... |
""" NSRDB data module
This script downloads the data from the NSRDB from NREL for a specific
location in the world. This toolfunction with an input dictionary with
the parameters to request the data.
This script requires `pandas` and `request` to be insalled within the python
environment you are running this script
... |
import urllib.parse
import urllib.request
import lxml
from pyquery import PyQuery as pq
WEBSOC_URL = 'https://www.reg.uci.edu/perl/WebSoc/listing'
TERM = '2021-03'
S_DEPARTMENTS = {
'AC ENG', 'AFAM', 'ANATOMY', 'ANESTH', 'ANTHRO', 'ARABIC', 'ARMN', 'ART',
'ART HIS', 'ARTS', 'ARTSHUM', 'ASIANAM', 'BANA', 'BATS... |
import os
import torch
import torch.utils.data as data
import torchvision
from torchvision import transforms
import torchvision.transforms.functional as TF
import numpy as np
from PIL import Image, ImageFilter
import json
import random
import cv2
import pickle
# We remove ignore classes.
FINE_DICT = {0:-1, 1:-1, ... |
# todo爬取关于疫情的微博
# todo 权威媒体:央视微博、人民日报、环球网、澎湃新闻
# todo 省市级 建委:
import re
import time
from selenium import webdriver
from config import CCTV_WEB_URL, CCTV_M_WEIBO_URL
from mongo import update_news, fond_one
from utils import parser_weibo_time
import threading
import platform
def spider_cctv_web_single(page):
page_u... |
from pathlib import Path
import os.path
import pandas as pd
from astropy import units as u
import numpy as np
MSUN = 1.989e33
CLIGHT = 2.99792458e10
def read_sph_out(pathtosnapshot):
arepo_out_file = Path(pathtosnapshot) / "ejectasnapshot.dat"
column_names = ['h (i)', 'x (i)', 'y (i)', 'z (i)', 'vx (i)', 'v... |
"""Main module."""
import logging
from asyncio import sleep as async_sleep
from datetime import datetime, timedelta
from enum import Enum, auto
from time import perf_counter_ns, sleep
from typing import Any, Callable
logger = logging.getLogger(__name__)
class IntervalDeltaType(Enum):
"""Defined types of interva... |
"""
Crawl the 25w data again to find the 上映时间,电影名称(含不同版本),导演,演员,类别, comments
"""
import time
import random
import threading
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
import redis
import urllib3
import requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
ua = User... |
import math
from typing import Tuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops.einops import rearrange
from torch import FloatTensor, LongTensor
from .pos_enc import ImageRotaryEmbed, ImgPosEnc
# DenseNet-B
class _Bottleneck(nn.Module):
def __i... |
from math import floor
import torch
from .Base import PINN
from .Wang2020 import LambdaAdaptive, M4, M2
from .MLP import Davies2021, MLP_PINN
from utils.operator import gradient
# Gradient-enhanced physics-informed neural networks for forward and inverse PDE problems
# <NAME>, <NAME>, <NAME>, <NAME>
# The author propo... |
#!/usr/bin/env python3
"""
Let's do it properly with a double ring.
Update: it turned out to be very slow for Part 2.
However, the double ring implementation could be re-used.
"""
from typing import List, Optional, Tuple
class Node:
def __init__(self, value: int) -> None:
self.value: int = value
... |
#
# add_bounding_boxes_to_megadb.py
#
# Given pseudo-jsons containing the bounding box annotations made by iMerit, add them to
# a list of entries from the MegaDB sequences table.
import os
import json
from collections import defaultdict
import urllib
from tqdm import tqdm
import ct_utils
# the category map that c... |
# -*- coding: utf-8 -*-
"""reporter to export aggregates to a file"""
import json
import pandas as pd
from lizard_raster_reducer.fetching import clean_unicode
pd.set_option("display.max_colwidth", -1)
def fill_alarm_reports(alarm_columns, df, date_times):
"""create and fill dataframes with alarm data"""
rep... |
# encoding: utf-8
"""
API Connector to the Ghent University Academic Bibliography
===========================================================
`Ghent University Academic Bibliography`_ contains all the scientific publications by
UGent_ Researchers. The API_ is public and pretty straight forward.
To use the API in Pyt... |
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.db import transaction
from django.shortcuts import get_object_or_404
from django_pglocks import advisory_lock
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.decorators import action
... |
#!/usr/bin/env python
import git
from gooey import Gooey, GooeyParser
from tagged_document import TaggedDocument, TagQuery
from source_document import SourceDocument
import logging
from argparse import ArgumentParser
import sys
import os
from source_document import WORKSPACE_REF
SOURCE_FILE_EXTENSIONS = [
"swif... |
############### THIS PROGRAM COMPUTES AN EXAMPLE OF LOGISTIC REGRESSSION ##################
# A dataset is read into X1,X2 which contains results for two student exams,
# and Y which contains the labels 1 and 0 for admission/rejection in a grad school.
import numpy as np
import os
import time
import pandas as pd
impor... |
"""Extract information from nginx config files.
"""
from serverscripts.six.moves.urllib.parse import urlparse
import argparse
import copy
import json
import logging
import os
import re
import serverscripts
import sys
VAR_DIR = "/var/local/serverscripts"
NGINX_DIR = "/etc/nginx/sites-enabled"
GIT_URL = re.compile(
... |
# ----------- LSTM --------------
import os,pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from keras.models import Model,save_model,load_model,model_from_json,model_from_yaml
from keras.layers import Activation, LSTM, Dense, Dropout, Inpu... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... |
import unittest
from xmlrpclib import *
import sys
import topology
from topology.representation import getPajekRepr
from topology import graphBuilder
from betweenness import *
def withretry(f):
def new_f(*args):
time.sleep(0.05)
try:
return f(*args)
except:
time.sleep(10)
... |
import string, itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
def heatmap(df, imshow=True, zlabel='z', ax=None, cax=None, cbarkwargs=dict(), cbarlabelkwargs=dict(), **kwargs):
"""Plot a heat-map of a pivoted data frame with automatic labeling of axes.... |
from collections import defaultdict
import pygame
from .utils import make_async
ANY_KEY = 'any_key'
class Keyboard():
def __init__(self):
self.pressed_keys = set()
self.released_keys = set()
self.keys_pressed_this_frame = set()
self.keypress_callbacks = defaultdict(list)
... |
#!/usr/bin/python3
import os
import sys
import argparse
import re
version = "1.1"
show_warnings = True
weight_precision = 1
assignment_precision = 3
final_precision = 3
class Assignment:
def __init__(self, name="", earned=-1.0, total=-1.0):
self.name = name
self.earned = earned
self.total = total
def __repr_... |
import pandas as pd
import matplotlib.pyplot as plt
import torch
import numpy as np
from pathlib import Path
from tqdm.auto import tqdm, trange
from rcmodel import *
from main import initialise_model, RayActor
opt_id = 0
weather_data_path = '/home/benf/LSI/Data/Met Office Weather Files/JuneSept.csv'
csv_path = '/home... |
""" This script processes the dataset to create a data file of images,
explanations, and ground truth regions that can be consumed by shared interest.
"""
import base64
import json
import os
from io import BytesIO
import cv2
import explanation_methods
import nltk
nltk.download('wordnet')
import numpy as np
import rast... |
# =============================================================================
# IMPORT SCIPY MODULES
# =============================================================================
import numpy as np
from tabulate import tabulate
from numba import jit
class RotationHelper:
def transformCompl(self,S,th,**kwargs):... |
import logging
from tempfile import mkstemp
import urllib
import urlparse
def url(base, seg, query=None):
"""
Create a URL from a list of path segments and an optional dict of query
parameters.
"""
def clean_segment(segment):
"""
Cleans the segment and encodes to UTF-8 if the segme... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import argparse
import ConfigParser
import logging
import math
from api_utils import ModelAPI, SaliencyAPI
class ComputeSaliency( object ):
"""
Distinctiveness and saliency.
Compute term distinctiveness and term saliency, based on
the term probability di... |
import numpy as np
import h5py
import time
import copy
from random import randint
############################
# SINGLE HIDDEN LAYER #
# MULTIPLE KERNELS #
############################
# Elementwise ReLU nonlinearity to produce the hidden layer
def sigma(Z):
return np.maximum(Z, 0, Z)
# Convolut... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 16:35:53 2019
@author: technosap
"""
import ctypes
import mmap
import time
import math
from modular_client import ModularClient # for nozzle control
class SHMEMFicTracState(ctypes.Structure):
"""
This class represents the FicTrac tracking state. These are th... |
## main.py version 0.2.0
import logging
import numpy as np
import json
import cv2
import arm
import PLC
import vision
import color as c
import color_clf as cclf
print("CONFIGUE")
basket = {}
with open("mainConfig.json", "r") as config_file:
config = json.load(config_file)
x_yellow = 100
y_yellow = 0
... |
import copy
import os
import re
import numpy as np
from rdkit import Chem
import rdkit.Chem.Descriptors
from rdkit.Chem.rdchem import BondType
bond_types = (0, BondType.SINGLE, BondType.DOUBLE, BondType.TRIPLE) # 0 for NO_BOND.
def convert_radical_electrons_to_hydrogens(mol):
"""
Converts radical electrons... |
from GUI.resources.colors import *
from tkinter import *
class GridGUI(Frame):
def __init__(self, master, func, **kw):
super().__init__(master, **kw)
self.__root = Tk()
self.__root.minsize(250, 90)
self.height = self.__root.winfo_height()
self.width = self.__root.winfo_widt... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from .common import (
get_item_or_404 as _get_item_or_404,
get_box_or_404 as _get_box_or_404,
item_state_conflict as _item_state_conflict,
get_receipt,
)
from ..ajax_util import AjaxError, RET_BAD_REQUEST, RET_CONFLICT
from ..ch... |
#
# This file is taken from the NEST standard examples
#
# Copyright (C) 2004 The NEST Initiative
#
import nest
from scipy.special import lambertw
import numpy
from numpy import exp
import time
def computePSPnorm(tauMem, CMem, tauSyn):
a = (tauMem / tauSyn)
b = (1.0 / tauSyn - 1.0 / tauMem)
t_max = 1.0... |
import numpy as np
import os
import tensorflow as tf
from tqdm import tqdm
import ujson as json
from model import Model
from util import get_batch_dataset
from util import get_dataset
from util import get_record_parser
# for debug, print numpy array fully.
# np.set_printoptions(threshold=np.inf)
os.environ["CUDA_V... |
'''
<NAME>
<EMAIL>
Lab section: B56
CA: <NAME>
Assignment9
Phone: 6079532749
'''
'''
Write a complete program that, given a literal list of tuples consisting of (name, list of grades) pairs
(i.e., the first line of your main should simply be: gradeList = )
prints out a table showing the number of scores and score ave... |
import random
import queue
# ............................................................................
# N O D E
# ............................................................................
# a node is completely identified by its number
# use abbreviation n for node
... |
from time import time
import numpy as np
from kdtree import KDTree
from franka_robot import FrankaRobot
class SimpleTree:
def __init__(self, dim):
self._parents_map = {}
self._kd = KDTree(dim)
def insert_new_node(self, point, parent=None):
node_id = self._kd.insert(point)
se... |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten, Reshape
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils i... |
"""
Find duplicate files.
"""
import os
import sqlite3
import subprocess
from datetime import datetime
from pathlib import Path
from typing import List
import click
from loguru import logger
from more_itertools import chunked
from tqdm import tqdm
def add_timestamp_to_fn(fn: Path) -> Path:
"""
Append a times... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import time
from tqdm import tqdm
import numpy as np
import cv2
import tensorflow as tf
import picpac
import fcn_nets as nets
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_... |
import argparse
import os
from time import sleep
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from src.tac import infolog
from src.tac.core.tacotron.synthesizer import Synthesizer
from src.tac.hparams import hparams, hparams_debug_string
from src.tac.infolog import log
from src.tac.preprocessing.a... |
# Payout:
# 0,0 => A+1
# 1,1 => A+3
# 0,1 or 1,0 => B+2
# Find the mixed strategy Nash equilibrium by reinforcement learning
# Unsolved
import random
from math import exp
strategy_a = 0.5
strategy_b = 0.5
games_payout_a = 0
games_payout_b = 0
games_cards_a = [0, 0]
games_cards_b = [0, 0]
total_game_count = 0
total_... |
#Written by: <NAME> - D4Vinci ( Dr0p1t-Framework )
import sys
from os.path import *
global G, Y, B, R, W , M , C , end
def set_colors():
global G, Y, B, R, W , M , C , end
if sys.platform.startswith('win'):
# Windows deserve coloring too :D
try:
import win_unicode_console , colorama
win_unicode_console.ena... |
import sys
print('Encoding of file should be UTF-8')
print('Length of arguments: ', len(sys.argv))
print("Argument 0 (command without arguments):", sys.argv[0])
if len(sys.argv) > 1:
print('First argument:', sys.argv[1])
else:
print('No arguments')
# complex numbers and exponentiation (liczby zespolone i pot... |
# Experiments for Section 5.5 - Restricted Boltzmann machines, learning and sampling
# Training and testing for 2s only and comparing with LP
import os
import sys
import time
import numpy as np
from jax import random
from pmap.rbm_modeling import learn, sample
from pmap.mmd import logMMD
from pmap.rbm_modeling_lp imp... |
from .ami_reader import AmiReader
from .ami_dataclasses import SymbolEntry, SymbolData
from .ami_construct import Master, SymbolConstruct
from pathlib import Path
import os
def symbolpath(root, symbol):
return os.path.join(root, f"{symbol[0].lower()}/{symbol}")
class AmiDataBase:
def __init__(self, folder, ... |
# Copyright 2020 Google Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils import shuffle
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import cross_validate
from sklearn.metrics import (make_scorer,
accuracy_score,
recall_score,
... |
"""
アノテーション仕様を出力する
"""
import argparse
import logging
import sys
from typing import Any, Dict, List, Optional
import annofabcli
import annofabcli.common.cli
from annofabcli import AnnofabApiFacade
from annofabcli.common.cli import AbstractCommandLineInterface, ArgumentParser, build_annofabapi_resource_and_login
from ... |
#!/usr/bin/env python3.8
from password import User
def create_password(fname,lname,phone,email):
'''
Function to create a new password
'''
new_password = User(fname,lname,phone,email)
return new_password
def save_passwords(password):
'''
Function to save password
'''
password.save_... |
from __future__ import print_function
import numpy as nx
svd = nx.linalg.svd
class Point:
def __init__(self, x0, x1, x2, x3=None):
if x3 is None:
x3 = 1.0
self.data = nx.array([x0, x1, x2, x3], nx.Float)
def __repr__(self):
return "Point" + repr(tuple(self.data))
def... |
import os
import numpy as np
from matplotlib import pyplot as plt
from scipy.io import wavfile
from data_config import PREFIX_OUTPUT, BANNED_ID, BANNED_ID_BY_FEAT, \
key_col, \
EXPORT_IMAGE, \
EXTRACTED_DATA_PATH, \
APPLY_MFCC, \
NFFT_CHUNK_SIZE, \
NUM_FILTER
from utils import _normalize_path,... |
# Copyright 2016 Internap.
#
# 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, so... |
"""Kraken Maya - Maya Builder module.
Classes:
Builder -- Component representation.
"""
# import json
import logging
from kraken.log import getLogger
# from kraken.core.kraken_system import ks
from kraken.core.objects.object_3d import Object3D
import pymel.core as pm
logger = getLogger('kraken')
logger.setLevel(... |
import tensorflow as tf
class ConvAttention(tf.keras.Model):
def __init__(
self, n_filters, n_heads=8, use_bias=False,
kernel_size=1, normalize_layer=tf.keras.layers.LayerNormalization,
with_skip_connection=True, return_attention=False
):
assert (n_filters % n_heads) == 0
... |
"""
Allows the project to interact to graphql using both graphene 2.1.8 and 3.0.0b7.
Other function to preserve backwards compatibiolity may be added in the future
"""
import itertools
from typing import Dict, Optional, Callable, Union
from graphene import Schema
from graphene.types.schema import TypeMap
def get_gra... |
from django.db import models
from projects.models import Project, ProjectManager
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from properties.models import DockerText
import os
import platform
from docker import Client
from docker.tls import TLSConfig
from io import BytesIO
import json
clas... |
# import sys, os
#
# sys.path.append(os.pardir)
# from dataset.mnist import load_mnist
# from common.functions import *
# from common.gradient import numerical_gradient
#
# def get_data():
# (x_train, t_train), (x_test, t_test) = \
# load_mnist(normalize=True, flatten=True, one_hot_label=True)
# return ... |
from django.db.models import Q
from django.forms.utils import flatatt
from django.template.loader import render_to_string
from django.utils.html import format_html, format_html_join
from django.utils.translation import gettext as _
from wagtail.core import blocks
from wagtail.core.blocks import PageChooserBlock
from w... |
# coding=utf-8
from django.test import TestCase
from django.test import Client
from orders.models import Item, Order, ItemOrder, Discount
from django.utils import timezone
class ItemTestCase(TestCase):
def test_real_price(self):
knakworst = Item.objects.get(name="Knakworst")
friet = Item.objects.g... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 7 13:54:29 2020
@author: saman
"""
#from __future__ import division
import numpy as np
#from ffprobe import FFProbe
import argparse
import re
import pandas as pd
def test_model(bitrate, coding_res, framerate, clss):
# set the ... |
"""
mlperf inference benchmarking tool
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import json
import os
import sys
import torch
from shutil import copyfile
import intel_pytorch_extension as ipex
try:
dlrm_dir_path = os.enviro... |
"""Add 'confess*' tables
Revision ID: 0f780af615ef
Revises: <PASSWORD>
Create Date: 2017-10-14 14:23:35.966456
"""
from alembic import op # type: ignore
import sqlalchemy as sa # type: ignore
from typing import Tuple, List, Dict, Any # noqa
from mypy_extensions import TypedDict
from pathlib import Path
from json i... |
#! /usr/bin/env python
import argparse
import sys
import os
try:
import pandas as pd
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.dates import DateFormatter
plt.style.use('seaborn-whitegrid... |
""" various constants for silicon bulk substrates """
from .utils import SiMemo
from scipy.constants import (
e, pi, k, h, m_e, hbar, epsilon_0,
value as sc_value)
import numpy as np
kb_eV = sc_value('Boltzmann constant in eV/K')
eps_si = 11.68 * epsilon_0
eps_siox = 3.9 * epsilon_0
@SiMemo
def E_g_Si_Caia... |
"""Middleware for compression"""
from typing import Mapping, List, Optional
from bareutils import (
header,
CompressorFactory,
compression_writer_adapter,
make_deflate_compressobj,
make_gzip_compressobj,
DecompressorFactory,
compression_reader_adapter,
make_gzip_decompressobj,
make... |
import discord
from discord.ext import commands
import json, asyncio
orange=discord.Color.orange()
class Mod(commands.Cog):
def __init__(self,bot):
self.bot=bot
@commands.command()
@commands.has_permissions(administrator=True)
async def embed(self, ctx):
await ctx.message.delete()
await ctx.s... |
import torch.nn as nn
import math
from lib.core.config import cfg
# ---------------------------------------------------------------------------- #
# Bits for specific architectures (ResNeXt50, ResNeXt101, ...)
# ---------------------------------------------------------------------------- #
def MobileNetV2_body():
r... |
"""
Markdown processor
==================
Markdown parser with a number of sane defaults that resembles
GitHub-Flavoured Markdown (GFM).
GFM exists because normal markdown has some vicious gotchas. Further reading:
http://blog.stackoverflow.com/2009/10/markdown-one-year-later/
This Markdown processor is used by :fun... |
import numpy as np
from hats import *
def permuted_index(n, strata=None):
if strata is None:
perms = np.random.permutation(n)
else:
perms = np.array(range(n))
elems = np.unique(strata)
for elem in elems:
inds = perms[strata == elem]
if len(inds) > 1:
... |
"""This module contains simple helper functions """
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
from logging import getLogger, StreamHandler, DEBUG, basicConfig, Formatter, INFO
from pathlib import Path
import logzero
def make_mask(cfg, img):
"""numpy型のmas... |
import cftime
import numpy as np
import pandas as pd
import xarray as xr
from xclim.indices import generic
class TestSelectResampleOp:
def test_month(self, q_series):
q = q_series(np.arange(1000))
o = generic.select_resample_op(q, "count", freq="YS", month=3)
np.testing.assert_array_equal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.