text stringlengths 3.07k 12.6k |
|---|
__all__ = [
"abs",
"sin",
"cos",
"log",
"exp",
"sqrt",
"pow",
"floor",
"ceil",
"round",
"as_int",
"as_float",
"as_str",
"as_factor",
"fct_reorder",
"fillna",
"qnorm",
"pnorm",
"dnorm",
"pareto_min",
"stratum_min",
]
from grama import m... |
"""
************************************************************************************************
*********************** Segmented --> Labeled ***********************************
************************************************************************************************
Label the Data with 1(FOG... |
"""File providing support to read and calibrate temperature measurements."""
import logging
import math
from statistics import mean, stdev
import sys
from machine import Pin
import uasyncio as asyncio
import dht
from analog_in import Ads1115, AnalogInESP32
LOG = logging.getLogger('temperature')
LOG.setLevel(logging.I... |
from __future__ import print_function
import io
import os
import sys
cur_path = os.path.abspath(os.path.dirname(__file__))
root_path = os.path.split(cur_path)[0]
sys.path.append(root_path)
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import joblib
f... |
from locust import events
import time
import csv
import re
import logging
import random
import string
import json
import socket
from logging.handlers import RotatingFileHandler
from datetime import datetime
from util.conf import JIRA_SETTINGS, CONFLUENCE_SETTINGS, AppSettingsExtLoadExecutor
from util.project_paths impo... |
"""
.. module:: phylo
:synopsis: a collection of phylo reloated stuffs (PhyloCSF, Phylo60)
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import subprocess
import gzip
import os
import errno
import math
import sys
import csv
import time
import collections
import functools
from functools import partial, reduce
from oper... |
"""
Copyright (c) 2021 <NAME> (<EMAIL>)
Distributed under the MIT software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
This script converts DXF files to PNG file.
Usage:
python main.py -i input.dxf -o output.png
or
python main.py --input input.dxf ... |
import requests, os, os.path
from .. import modules
CONFIG_PREFIX = "death"
TWITCH_API = 'https://api.twitch.tv/kraken/'
AVERAGE_DEATHS = 731
def print_num(n):
places = ['thousand', 'million', 'billion', 'trillion', 'quadrillion']
if n == 0:
return 'zero'
elif n < 100:
... |
import datetime
import factory
import pytest
from django.utils import timezone
from pytest_factoryboy import register
from forms.models import Form
from leasing.enums import (
ContactType,
LeaseAreaType,
LocationType,
PlotSearchTargetType,
TenantContactType,
)
from leasing.models import (
Cont... |
#!/usr/bin/env python3
# This file is part of ODM and distributed under the terms of the
# MIT license. See COPYING.
import calendar
import datetime
import dateutil
import json
import os
import sys
import time
from hashlib import sha1
import pypandoc
import odm.cli
from odm.boxnote import BoxNote
from odm.db impo... |
import random
import numpy as np
from typing import List, Union, Optional
class Deck:
"""
A bass class that defines and interface for a Iowa Gambling Task card deck.
"""
def __init__(self, seed: Optional[int] = None):
"""
Abstract class to represent a deck of Iowa Gambling Task cards... |
import sqlite3
from sqlite3 import Error
import json
import pandas as pd
import os
def conn_and_cursor():
conn = cursor = None
try:
conn = sqlite3.connect('db.sqlite3')
cursor = conn.cursor()
except Error as e:
print(e)
return conn, cursor
def get_all_countries():
conn, c... |
"""
Command line utility for accessing SKA SDP configuration.
Usage:
sdpcfg [options] (get|watch) <path>
sdpcfg [options] [watch] (ls|list) [values] [-R] <path>
sdpcfg [options] delete [-R] <path>
sdpcfg [options] (create|update) <path> <value>
sdpcfg [options] edit <path>
sdpcfg [options] process <workflo... |
#!/usr/bin/env python3
import requests
import json
import os
from time import sleep, time
import sqlite3
from argparse import ArgumentParser
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def is_bot_game(g):
return g["players"]["white"]["ui_class"] == "bot" \
or g["p... |
# -*- coding: utf-8 -*-
try:
import Tkinter as tkinter
import Tix as tix
import ttk
except ImportError:
import tkinter
from tkinter import tix
from tkinter import ttk
import os
TkdndVersion = None
# dnd actions
PRIVATE = 'private'
NONE = 'none'
ASK = 'ask'
COPY = 'copy'
MOVE = 'move'
LINK = 'li... |
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_noop, ugettext as _
from djangular.views.mixins import JSONResponseMixin, allow_remote_invocation
from corehq import toggles, priv... |
import galaxy_pulp
from django.conf import settings
from django_filters import filters
from django_filters.rest_framework import filterset, DjangoFilterBackend, OrderingFilter
from rest_framework import viewsets
from rest_framework.decorators import action as drf_action
from rest_framework.exceptions import NotFound
fr... |
import numpy as np
import argparse
from pathlib import Path
import json
from tqdm import tqdm
import ftfy
import logging
from logging.config import fileConfig
import spacy
import torch
import torch.nn as nn
from torchtext import data, datasets
from transformer.load import load_vocab, load_model
class AttentionIter... |
# Owner(s): ["oncall: distributed"]
# Copyright 2019 <NAME>
#
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import torch
from torch.distributed.pipeline... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 ETH Zurich, <NAME>
import numpy as np
import matplotlib.pyplot as plt
from morinth.source_terms import BalancedSourceTerm, EquilibriumDensityInterpolation, UnbalancedSourceTerm
from morinth.grid import Grid
from morinth.euler import Euler, PointMassGravity
from mori... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 3 18:13:01 2019
@author: Funato
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 13:48:14 2019
@author: <NAME>
"""
#このプログラムは自由に使用、改変していただけますが、それにより生じた、またそれを利用したことにより生じたいかなる損害についても責任を負いません。
import numpy as np
import mnist
import matplotlib.pyplot as plt
train_img... |
import datetime
import re
from billy.utils.fulltext import pdfdata_to_text, text_after_line_numbers
from billy.scrape.utils import url_xpath
from .bills import UTBillScraper
from .legislators import UTLegislatorScraper
from .committees import UTCommitteeScraper
from .events import UTEventScraper
metadata = {
'name... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvolutionalBlock(nn.Module):
def __init__(self, input_dim=128, n_filters=256, kernel_size=3, padding=1, stride=1, shortcut=False, downsample=None):
super(ConvolutionalBlock, self).__init__()
self.downsample = downs... |
from functools import lru_cache
import yaml
import sqlalchemy
from sqlalchemy.orm.relationships import RelationshipProperty
__version__ = (1, 0, 0)
class Store:
'''Simple key-value store
Key might be a dot-separated where each name after a dot
represents and attribute of the value-object.
'''
... |
class Line(object):
# Line class. mainly used for intersection check.
def __init__(self, point1, point2):
self.point1 = point1
self.point2 = point2
def intersect_with(self, another_line):
"""Check another_line intersect with itself or not.
Args:
another_line (L... |
import random
import os
import sys
from pathlib import Path
from math import cos, sin, radians, hypot, ceil
# import basic pygame modules
import pygame as pg
from lagmenot.player import Player, PlayerWithoutSprite, InputCmd, create_one_tick_input
from lagmenot.server import Server, PredictMsg
assets_dir = Path(os.pat... |
from flask import Flask, render_template, request, redirect, url_for, session
from flask_session import Session
from flask_googlemaps import GoogleMaps
from flask_googlemaps import Map
from googlemaps import convert
import pymongo
import googlemaps
import random
import uuid
client = pymongo.MongoClient(
"mongodb+s... |
import win32api, win32con, win32gui, win32ui
import ctypes
from typing import List
import threading
import time
import string
import uuid
import ctypes
import queue
from screengrid import rectangle, win32_contants
def draw_loop(_queue: queue.Queue):
while True:
try:
canvas = _queue.get(block=Tr... |
from django.utils.decorators import method_decorator
from rest_framework.viewsets import ModelViewSet, GenericViewSet, mixins
from rest_framework import status
from rest_framework.response import Response
from rest_framework.permissions import DjangoModelPermissions
from fastrunner import models, serializers
from Fast... |
import urllib
import dash_html_components as html
import pandas as pd
from matscholar_web.constants import rester
from matscholar_web.search.common import (
big_label_and_disclaimer_html,
common_results_container_style,
no_results_html,
)
"""
Functions for defining the results container when materials su... |
"""
Extensions to the Mailbox and System classes for simulating message and/or
node failures.
"""
from collections import namedtuple
import random
from paxos import SystemConfig
from paxos.messages import ClientRequestMsg, AdjustWeightsMsg
from paxos.sim import Mailbox
from paxos.test import DebugMailbox
class Fail... |
#!/usr/bin/env python3
import argparse
from sys import exit, stdout
import ctypes
x86_shellcode = (b"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53"
b"\x89\xe1\x31\xd2\xb0\x0b\xcd\x80\x31\xc0\xb0\x01\x31\xdb\xcd\x80")
# Shellcode from exploit-db
#arm_shellcode = (b"\x01\x30\x8f\... |
# -*- coding: utf-8 -*-
"""
@author: nicolas.posocco
"""
from scipy.integrate import quad
from multiprocessing import Pool
import numpy as np
import tqdm
import os
from KDEpy import FFTKDE
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
class Model1D(object):
def __init__(self, targ... |
# Copyright (c) 2019 Science and Technology Facilities Council
# All rights reserved.
# Modifications made as part of the fparser project are distributed
# under the following license:
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condi... |
#!-*-coding:utf-8-*-
# !@Date: 2018/8/7 22:12
# !@Author: <NAME>
# !@github: bigfoolliu
from tkinter import *
class show:
num_info_hash = {}
char_info_hash = {}
num_char = {}
char_num = {}
def __init__(self):
self.root = Tk()
self.root.title("ASCII码查询")
# self.root.geom... |
DEFAULT_ORDER_BY_TYPE = 'DESC'
TRANSACTION_LEARN = 'learn'
TRANSACTION_PREDICT = 'predict'
TRANSACTION_CLUSTER = 'cluster'
TRANSACTION_NORMAL_SELECT = 'normal_select'
TRANSACTION_NORMAL_MODIFY = 'normal_modify'
TRANSACTION_BAD_QUERY = 'bad_query'
TRANSACTION_SHOW_DATASOURCES = 'show_datasources'
TRANSACTION_DROP_MODE... |
"""
detect.py
~~~~~~~
Functions for detecting drifting samples, write the closest family for each sample in the testing set.
"""
import os
os.environ['PYTHONHASHSEED'] = '0'
from numpy.random import seed
import random
random.seed(1)
seed(1)
from tensorflow import set_random_seed
set_random_seed(2)
import tensorflow... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 13 22:53:38 2017
@author: HCHO
"""
# 数据库信息
import psycopg2
connection = psycopg2.connect(database="postgres", user="postgres", password="<PASSWORD>", host="localhost", port="5432")
cur = connection.cursor()
# 创建列表
def CreateDetectTable(pointDataName):
cur.execute('... |
from copy import deepcopy
import random
import networkx as nx
import nxtools as nxt
# Copyright(C) 2011 by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
# BSD license.
__author__ = """\n""".join(['<NAME> (<EMAIL>)',
'<NAME> (<EMAIL>)'])
def spectral_modularity_... |
from ksc.alpha_equiv import (
are_alpha_equivalent,
hash_with_alpha,
ExprHashedWithAlpha,
)
from ksc.expr import Const, Let, Var
from ksc.parse_ks import parse_expr_string
from ksc.type_propagate import type_propagate_decls, type_propagate
from ksc.type import Type
def test_alpha_equivalence():
exp1 =... |
import inspect
from copy import copy
from typing import Sequence, Callable, Optional, Iterable
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_kalman.internals.batch import Batchable
from torch_kalman.internals.utils import infer_forward_kwargs
from torch_kalman.process.utils.design_m... |
import numpy as np
from scipy import stats
from tune._utils import (
assert_close,
normal_to_continuous,
normal_to_discrete,
normal_to_integers,
uniform_to_choice,
uniform_to_continuous,
uniform_to_discrete,
uniform_to_integers,
)
def test_uniform_to_continuous():
assert 10 == unif... |
from telegram.inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from genshinbot.database import get_uid
from pprint import pprint
from telegram import Update, InputMediaPhoto, user
from telegram.ext import CallbackContext, callbackcontext
from genshinbot.constants.strings import ME_STATS_SUMMARY, CHAR_SUMMARY, vi... |
"""
Getters, setters, and loaders of config. Config includes e.g. SSH
authentication stuff, port numbers to use, etc.
There are two layers of config provided: config loaded from file via
``refresh_cfg``, and runtime-provided overrides to those. The getters given
below will enforce that ordering. The user provides over... |
#!/usr/bin/env python
############################################################################
#
# Copyright 2020 Samsung Electronics 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... |
# -*- coding: utf-8 -*-
# reference: https://pytorch.org/vision/stable/_modules/torchvision/models/resnet.html
import numpy as np
import hennlayer
# %% layer generation functions
def conv3x3(in_ch, out_ch, stride=1, groups=1, padding=1):
# todo: add no-bias version
return hennlayer.Conv2d(in_ch, out_ch, 3, s... |
import tensorflow as tf
import yaml
import os
import numpy as np
import matplotlib.pyplot as plt
import soundfile as sf
import re
from tensorflow_tts.inference import AutoConfig
from tensorflow_tts.inference import TFAutoModel
from tensorflow_tts.inference import AutoProcessor
# Load Chinese Models
tacotron2 = TFAu... |
#!usr/bin/env python
# -*- coding: utf-8 -*-
import re, copy, time, logging, logging.handlers
from common import base_dir, log_dir, conference_acm, journal_acm, get_html_text, init_dir, download_paper_info
from util import get_random_uniform
# 保存下载文件的目录
root_dir = base_dir + 'acm/'
# 程序运行日志文件
logfile = log_dir + 'log_... |
# -*- coding: utf-8 -*-
import datetime
from django.template.defaultfilters import slugify
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, NoReverseMatch
from django.db import models
from django.utils.translation import ugettext_laz... |
import math
import pyglet
from pyglet.gl import *
def cube_vertices(x, y, z, n):
"""
Return the vertices of the cube at position x, y, z with size 2*n.
"""
return [
x - n, y + n, z - n, x - n, y + n, z + n, x + n, y + n, z + n, x + n,
y + n, z - n, # top
x - n, y - n, z - n, x... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from autoslug import AutoSlugField
from django.utils import timezone
from django.urls import reverse
import json
import datetime
from ckeditor.fields import RichTe... |
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib import messages
from django.db.models.base import ObjectDoesNotExist
from . forms import *
from .models import *
# ... |
from keras.models import Model
from keras.layers import Dense, Input, Reshape, Flatten, dot, RepeatVector, concatenate
from keras.layers.embeddings import Embedding
from keras import optimizers
import sys
import gzip
import numpy as np
import keras.backend as K
from keras.layers.core import Lambda
from collections impo... |
from re import A, T
def get_hamming_distance(dna1, dna2):
total = 0
dna1_list = list(dna1)
dna2_list = list(dna2)
if dna1[0] != dna2[0]:
total += 1
if dna1[1] != dna2[1]:
total += 1
if dna1[2] != dna2[2]:
total += 1
if dna1[3] != dna2[3]:
total += 1
if dn... |
'''
This program will simulate leveling a DnD character, showing their ending HP, and stats.
'''
import argparse
import csv
import json
import re
import time
from openpyxl import load_workbook
from pandas import DataFrame
from src import classes, util
def import_race_data(file_path):
'''
This method imports d... |
#!/usr/bin/env python3
import logging
import en_core_web_sm
# Third Party
from spacy.tokens import Doc as spacy_doc
from textacy.extract import ngrams, noun_chunks
from toolz.sandbox.core import pluck
from asrtoolkit.alignment.align_utils import (
Extractor,
dict_to_segments,
word_lattice_to_lines,
)
fr... |
#!/usr/bin/env python2
import random
import math
import copy
from Spell import *
class Pokemon:
def __init__(self, name, baseHp, lifePerLevel, attack, attackPerLevel, baseDef, defencePerLevel, spells, elements):
self.level = 1
self.exp = 0
self.name = name
self.baseHp = baseHp
... |
import numpy as np
from keras.callbacks import Callback
import tensorflow as tf
import keras.backend as k
from keras.losses import mean_squared_error, binary_crossentropy, categorical_crossentropy
###########################################################################################################################... |
#!/usr/bin/env python3
__author__ = "<NAME>"
try:
import requests
from subprocess import Popen, PIPE
import os
import re
from argparse import ArgumentParser
from time import sleep
except ImportError as err:
print(err)
class msg(object):
WHITE = u"\u001b[38;5;255m"
BLACK = u"\u001... |
import os
import time
import numpy as np
import argparse
from bayeso import constants
from bayeso.utils import utils_bo
import bo
import automl
parser = argparse.ArgumentParser(description='')
parser.add_argument('-d', '--dataset', type=str)
parser.add_argument('-s', '--surrogate', type=str)
parser.add_argument('-i... |
import argparse
import os
from tqdm import tqdm
from chamfer_distance import ChamferDistance
from training.gan_model import GANModel
from PIL import Image
# from torchvision import transforms
import cv2
import numpy as np
import torch
from training import networks
from torchvision import transforms
from options impor... |
from abc import ABC, abstractmethod
import numpy as np
from scipy import fftpack
class Codec(ABC):
'''
Codec is an abstract class which every
CODEC (Shift, DCT, Quantization, etc.)
class is derived from.
A subclass of Codec should implement
both ENCODE and DECODE method. Otherwise,
a... |
import io
import sys
import json
import random
import string
import tempfile
import unittest
import contextlib
from typing import IO, Iterator
from pathlib import Path
from unittest import mock
from . import (
MatchData,
NUM_ZONES,
REPO_ROOT,
SimpleTee,
Resolution,
tee_streams,
read_match_d... |
"""
TXFMTrackService
(C) 2015
<NAME>
"""
import redis
import re
from pymongo import MongoClient
from collections import OrderedDict
from time import strptime, strftime
class Cache:
def __init__(self, host="redis", port="6379", db="0"):
self.storage = redis.StrictRedis(host=host, port=port, db=db)
... |
# -*- coding: utf-8 -*-
import logging
from pathlib import Path
import pandas as pd
import numpy as np
import scipy
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import normalize
import gensim
from utils import task_to_df
# ----------------------------------------... |
"""
A class to convert dates to a standard format.
We use years as our unit, but could also use seconds.
Convert the collection date to a number. We take todays date, and then convert relative to that
it allows dates pre-unix-epoch.
We set our epoch to 01/01/0001 and then add one year (we don't have anything in 0 BC... |
import argparse
import os
import json
import xml.etree.cElementTree as ET
import logging
import numpy as np
import sys
sys.path.insert(0,'common')
from transforms3dbatch import *
from utils.quaternion import *
def parse_motions(path):
xml_tree = ET.parse(path)
xml_root = xml_tree.getroot()
xml_motions = x... |
"""
Django settings for web_omics project.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
from configurations import Configuration, values
from django.c... |
from typing import List
from numpy import ndarray
import matplotlib.pyplot as plt
import threading
# import tensorflow as tf
from PIL import Image, ImageTk
import PySimpleGUI as sg
from config import *
import evaluate
import utility
# Global variables
input_values = [] # Input values for evaluator (ex. image paths)... |
# -*- coding: utf-8 -*-
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from networkapi.ambiente.models import Ambiente
from networkapi.ambiente.models import IPConfig
from networkapi.api_pools import exceptions
from networkapi.infrastructure.datatable import build_... |
from random import seed
from random import randrange
from csv import reader
# Load a CSV file
def load_csv(filename):
file = open(filename, "rt")
lines = reader(file)
dataset = list(lines)
return dataset
# Convert string column to float
def str_column_to_float(dataset, column):
for row in dataset:... |
from pathlib import Path
import pytest
import cloudpickle as cp
from .utils import multiply
from ..helpers import hash_value, hash_function, save, create_pyscript
from .. import helpers_file
from ..specs import File, Directory
def test_save(tmpdir):
outdir = Path(tmpdir)
with pytest.raises(ValueError):
... |
from telethon import events
from iahr.config import IahrConfig
from iahr.commands.default.localization import localization
from iahr.utils import AccessList, EventService
from typing import Union, Mapping, Sequence
##################################################
# Constants
#######################################... |
from pybulletgym.envs.scene_abstract import SingleRobotEmptyScene
from gym_mujoco_xml_env import PybulletMujocoXmlEnv
import gym, gym.spaces, gym.utils, gym.utils.seeding
import numpy as np
import os, sys
class PybulletInvertedPendulum(PybulletMujocoXmlEnv):
swingup = False
force_gain = 12 # TODO: Try to find out wh... |
# Copyright 2020 Simone <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except
# in compliance with the License.You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
# 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... |
from torch.autograd import Variable
import torch
class Batch_Features:
def __init__(self):
self.batch_length = 0
self.batch = None
self.word_features = 0
self.char_features = 0
self.label_features = 0
self.Origin_sentence_length = 0
@staticmethod
def cuda(f... |
from netCDF4 import Dataset
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
#--------------------------------------------------------
def L2_norm(numerical, analytical, nPoints, areaCell):
norm = 0.0
denom = 0.0
for iPoint in range(0,nPoints):
norm += a... |
import os
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
from train_embed.utils_experiment import load_model as load_embed_model
from train_filter.utils_experiment import load_model as load_filter_model
from build_graphs import filter_one_neighborhood, ... |
import time
import threading
import itertools
import numpy as np
import serial
from bokeh.models.sources import ColumnDataSource
from bokeh.plotting import figure, curdoc
from bokeh.layouts import column, row, layout, widgetbox, Spacer
from bokeh.palettes import Dark2_5 as palette
from bokeh.models import Tex... |
"""
Preprocessor and data importer from Pair Reports data. This assumes the database has been created with the proper
models and the data exist in the project directory in /ubc-pair-grade-data.
"""
from app import create_app
from config import Config
from app.models import PAIRReportsGrade as PRG, TableauDashboardGrad... |
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from django.urls.base import reverse_lazy
from django.views.generic.ba... |
import MeCab
def mecab_list(text):
tagger = MeCab.Tagger("-Ochasen")
wakati = MeCab.Tagger('-Owakati')
tagger.parse('')
node = tagger.parseToNode(text)
word_class = []
word_noun = []
word_adjective = []
re = 0
wm = wakati.parse(text)
ww = wm.split(' ')
while n... |
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from spharm import Spharmt
import pyshtools as pysh
import seaborn as sns
from .base import EvaluationMethod
def _plot_spectrum_200(data):
fig, ax = plt.subplots(figsize=(5.5, 2.75))
for name, spectru... |
import logging
import json
from functools import partial
from typing import Dict
import aiohttp
import async_timeout
_LOGGER = logging.getLogger(__name__)
BASE_URL = "https://api.meural.com/v0/"
async def authenticate(
session: aiohttp.ClientSession, username: str, password: str
) -> str:
"""Authenticate... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch_sparse import coalesce
from utils.num_nodes import maybe_num_nodes
# from num_nodes import maybe_num_nodes
def filter_adj(row, col, edge_attr, mask):
return row[mask], col[mask], None if edge_attr is None el... |
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.utils import Bunch
from dku_model_fairness_report.constants import DkuFairnessConstants
class ModelFairnessMetric(object):
@staticmethod
def get_available_metric_names():
return [ModelFairnessMetric.demographic_parity.__name... |
"""Functions to run commands and capture output."""
import os
import shutil
import sys
import textwrap
import traceback
from contextlib import contextmanager
from io import StringIO
from typing import Callable, Optional, Tuple, Union
import colorama
from ansimarkup import ansiprint
from jinja2 import Environment
fro... |
import json
import logging
import sys
from swiftclient.exceptions import ClientException
import utils
from common import swift
from common.config import settings
from common.logger import getLogger
logger = getLogger(__name__)
def apply_status(package_list, status):
"""
Add or update status to packages in a... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import re
import sys
from datetime import datetime, timedelta
from .ffmpeg import make_screenshot, make_moment
from .danmu_analysis import make_moment_danmu, get_topN_moments
from .ffmpeg import make_thumb_video
sys.path.append('..')
from utils.common import log_pr... |
import re
import textwrap
from typing import AbstractSet, Iterable, Optional, Tuple
from rich.console import RenderableType
from rich.highlighter import RegexHighlighter
from rich.padding import Padding
from rich.table import Table
from rich.text import Text
from httpie.cli.constants import SEPARATOR_GROUP_ALL_ITEMS
... |
import sys
import os
INPUTFILE_DIR = "/home/rickysuave/Documents/OSUClasses/VLSILab/FasterCap_main/InputFiles/"
# PROCESSFILE UNITS
LI1_THICK = 0.25
M2_THICK = 0.3
M3_THICK = 0.3
M4_THICK = 0.3
M5_THICK = 0.3
M6_THICK = 0.9
# CAP_MODEL UNITS
#LI1_THICK = 0.1
#M2_THICK = 0.36
#M3_THICK = 0.36
#M4_THICK = 0.845
#M5_TH... |
"""
This script adds a specific column to the `bug_type_entropy_projectname_old` tables. The added column contains the number of lines deleted in the SHA in which each file was modified.
But there's a catch. The column equals -1 if the line that was modified is a bug (because since it's a buggy line, it is going to b... |
# -*- coding: utf-8 -*-
import uuid
from datetime import date, datetime, timedelta
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.contrib.postgres.search import SearchVector, SearchVectorField
from django.contrib.postgres.indexes import BrinIndex
from django.db import mo... |
##############################################################
## To test the F3DASM, install the path to the package ##
## to the local python envionment as follows: ##
## pip install -e . ##
##############################################################
impo... |
import pytest
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
from pkg_resources import resource_filename
import crystalmapping.utils as utils
plt.ioff()
IMAGE_FILE = resource_filename("crystalmapping", "data/image.png")
def test_reshape():
"""Test reshape in a snaking... |
#!/usr/bin/env python3
from datetime import datetime, timedelta
from io import StringIO
import os
import matplotlib
import yaml
from dicttoxml import dicttoxml
from flask import Flask, jsonify, request, Response, abort, render_template
from flask_caching import Cache
import meteo
from meteo import data as md
matplot... |
from typing import Any, Optional, Type
from django import forms
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages import error, info, success
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http import Http404, HttpRequest, HttpResponse, HttpRes... |
import numpy
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import TORCH
def parameter_count(model: nn.Module):
total = 0
for parameter in model.parameters():
total += numpy.prod(parameter.shape)
return int(total)
def dense_net(in_channels: int,
out_chan... |
from PIL import ImageGrab, Image
import os
import pyautogui
import time
from Game import Game
from Card import Card
from Rank import Rank
from Stack import Stack
from statistics import mean, stdev
CARD_IMAGES = r'res/'
class Board():
default_delay = 0.1
square_size = 15
vertical_spacing_with_square = 15
hori... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.