text stringlengths 3.07k 22.1k |
|---|
"""Adds support for virtual Wiser Home"""
import asyncio
import datetime
import logging
from enum import Enum
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME,
ATTR_TEMPERATURE,
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVI... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
import copy
from .databunch import *
from .evaluate import *
def to_numpy(X):
try:
return arr.data.cpu().numpy()
except: pass
return arr
class ptarray(np.ndarray):
_metadata = ['_pt_scal... |
from enum import Enum, auto
from .authorship import Authorship
from .rank import Rank, NomCode
from .namepart import NamePart
from .util import nameformatter
class State(Enum):
COMPLETE = auto()
PARTIAL = auto()
NONE = auto()
class ParsedName:
""" Class holding the different parts of the name once i... |
import pandas as pd
import numpy as np
import sys
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 200)
"""
T.J.Blätte
2019
"""
"""
To count the number of reads mapped to each sequencing index
combination, as inspired by the Illumina white paper on
index hopping. Indices used by default are ... |
"""
Version of the fairseq-interactive feature that can be used within scripts without the need to call to a subprocess :)
"""
import fileinput
from collections import namedtuple
import os
import sys
import math
import numpy as np
import torch
from fairseq import checkpoint_utils, options, tasks, utils
from fairseq.... |
from __future__ import print_function
# Local
from user import User
from group import Group
from api import get_messages
from files import save_messages, load_messages
from constants import UID_TO_NAME
# Libs
import numpy as np
import math
from matplotlib import pyplot as plt
import networkx as nx
fro... |
from __future__ import division
import re
import sys
from multiprocessing import cpu_count
from os import path, sep as os_sep
from canaryd_packages import six
from canaryd.subprocess import get_command_output
def get_ps_cpu_stats():
'''
Uses ps + awk to total CPU usage, then divide by # CPUs to get the fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Tuple
import numpy
import torch
from torch import nn
from torch.distributions import Categorical
from torch.nn import CrossEntropyLoss, MSELoss
from draugr.torch_utilities import to_tensor
from draugr.writers import Writer
from neodroid.utilities impor... |
# -*- coding: utf-8 -*-
"""
Author: <NAME>
Date: 10.09.2018
# Description
This file adds reactions from Sco4 based on the mapping of reactions and metabolites.
"""
import cobra
import pandas as pd
from collections import defaultdict
import re
import logging
def add_reactions(sco4_model, scoGEM, reaction_mapping_fn,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_read_sdf
----------------------------------
Tests for `read_sdf` module.
"""
import unittest
import os
from qm_utils.qm_common import (list_to_file, diff_lines, silent_remove, write_csv, capture_stdout, create_out_fname,
process_c... |
import base64
import json
import os
import uuid
from pathlib import Path
import boto3
import yaml
from flask import (
Blueprint,
flash,
redirect,
render_template,
request,
send_file,
)
# from preview_generator.manager import PreviewManager
from tinydb.operations import delete
from ..utils.son... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.parallel # for multi-GPU training
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
from api import config_fun
import train_helper
from api import meter
import os
# ... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
def create_table_weights (files_names, directory):
'''
'''
weights = pd.DataFrame()
file_number = 1
for f in files_names:
df = pd.read_csv (os.path.join (
directory , f), d... |
import json
import os
import re
from pyBaiduPan.exceptions import *
from pyBaiduPan.login import baidu_pan_login
from pyBaiduPan.config import get_config, DEFAULT_CONFIG
import logging
from itertools import count
import pickle
import shutil
from hashlib import md5
from functools import partial
from base64 import b64enc... |
import logging
from copy import deepcopy
from typing import List, Dict, Union, Set
import csv
import requests
import json
import sys
from datetime import datetime, timezone
from pathlib import Path
import pyexcel_ods3
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.... |
from pprint import pprint
import nltk
import numpy as np
import pandas as pd
from nltk.stem.porter import PorterStemmer
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.linear_model import Ridge, S... |
import re
import pyodbc
from compare_results import handle_exception_in_file, process_multiple_resultsets
from datetime import date, datetime, time
from decimal import Decimal
from uuid import UUID
from xml.dom.minidom import parseString
from utils.config import config_dict as cfg
from utils.base import handle_babel_ex... |
# -*- coding: utf-8 -*-
import numpy as np
from skimage import morphology
from skimage import segmentation
from skimage.filters.rank import median
from skimage.morphology import disk
from skimage import measure
import pandas as pd
import matplotlib.pyplot as plt
import logging
from scipy import ndimage as ndi
from sci... |
# Copyright 2021 Google LLC
#
# 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, ... |
import random
import requests
import youtube_dl
import discord
import json
import os
import dotenv
import asyncio
from asyncio import sleep
from discord.ext import commands, tasks
from dotenv import load_dotenv
client = discord.Client()
client = commands.Bot(command_prefix="!")
client.remove_command("help")
load_do... |
from collections import OrderedDict
import numpy as np
import torch
from torch import nn
from torch.nn import Module
from pytorch_widedeep.wdtypes import * # noqa: F403
from pytorch_widedeep.models.tab_mlp import MLP
class BasicBlock(nn.Module):
def __init__(self, inp: int, out: int, dropout: float = 0.0, resi... |
#!/usr/bin/env python
from __future__ import division
from past.utils import old_div
import os.path
import math
from nineml import units as un
from pype9.simulate.common.units import UnitHandler as BaseUnitHandler
from pype9.simulate.nest.units import UnitHandler as NestUnitHandler
from nineml.abstraction import (
... |
#############################################
# Code modified from ray.rllib.rollout.py
# Code modified from ray.rllib.agent.trainer.py
#############################################
import copy
import collections
from gym import wrappers as gym_wrappers
from ray.rllib.env import MultiAgentEnv
from ray.rllib.env.base_... |
import numpy as np
import matplotlib
# matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
import json
import sys
import math as M
from scipy.interpolate import interp1d
from itertools import groupby
import seaborn as sns
import os
import glob
import numpy
from pylab import rcParams
color_list = ['b', 'r', '... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
# Copyright 2013 The Mozilla Foundation <http://www.mozilla.org/>
#
# 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 appl... |
import logging
import time
import requests
import math
from io import BytesIO
from . import logs
from .ve_utils import get_chunks, is_notebook
if is_notebook():
from tqdm import tqdm_notebook as tqdm_list
from tqdm import tnrange as trange
else:
from tqdm import tqdm as tqdm_list
from tqdm import tran... |
"""Module to work with channels.
It provides a general class to work with channels. Channels is the general term
that refers to the points where signal comes from, it's an abstract concept.
Electrodes, magnetometer, axiometers and gradiometers are the actual recording
devices measuring the signal. For example, in the ... |
from difflib import SequenceMatcher
import numpy as np
import pandas as pd
from scipy.stats.stats import pearsonr
import collections
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
import pprint
import pickle
from scipy.spatial.distance import cosine
#import treetaggerwrapp... |
"""Module time_hdr.
========
time_hdr
========
With **@time_box**, you can decorate a function to be sandwiched between start
time and end time messages like this:
:Example: decorate a function with time_box
>>> from scottbrian_utils.time_hdr import time_box
>>> @time_box
... def func2() -> None:
... print('2... |
import random
import time
import numpy as np
import pytest
from beamngpy import BeamNGpy, Scenario, Vehicle, setup_logging, ProceduralCube
from beamngpy.beamngcommon import BNGValueError, BNGError
from beamngpy.sensors import Camera, Lidar, Damage, Electrics, GForces, State
from beamngpy.sensors import IMU, Ultrasoni... |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import metrics
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn import tree
from sklearn import metrics
from sklearn import svm
from sklearn.mode... |
"""
MIT License
Copyright (c) 2020 PyKOB - MorseKOB in Python
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, me... |
import copy
from board_parser import get_board
from gui import keep_pygame, init_gui, update_cells, update_screen
from line_solver import grandmother, subtract_req, get_line_with_hint, sum_req, fix_boundaries
EDGES_COLOR = (0, 0, 0)
CHOSEN_COLOR = (204, 204, 204)
CELL_COLOR = (255, 255, 255)
NUMBERS_COLOR = (0, 0, 0)... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy.stats import f #fisher
from . import dv, zero_finding
import lmfit
LinAlgError = np.linalg.LinAlgError
from .base_functions import (_fold_exp,
_coh_gaussian,
_fold_exp_and_coh)
import scipy.linalg as linalg... |
import numpy as np
# 0 empty, 1 X, 2 O
# Classe - Nó (Tabuleiro)
class NodeBoard:
# ------------
# Construtor
def __init__(self):
self.state_board = None # Estado do tabuleiro - Mapeamento de posições
self.playerX_win = False # Indica o X como vencedor
self.playerO_win = F... |
# -*- coding: utf-8 -*-
import functools
import json
import logging
import re
from annotator import auth, es, store
import elasticsearch
import flask
from oauthlib.oauth2 import BearerToken
from pyramid import security
from pyramid.authentication import RemoteUserAuthenticationPolicy
from pyramid.httpexceptions import... |
# -*- coding: utf-8 -*-
"""A sample implementation of SHA-1 in RPython.
See also the pure Python implementation in lib_pypy/sha.py, which might
or might not be faster than this one on top of CPython.
Framework adapted from <NAME>'s MD5 implementation by
<NAME> and <NAME>. SHA-1 implementation based direc... |
import tables, numpy, dashi
def histload(hdf, where):
"""
dashi.histload with optional normalization
"""
h = dashi.histload(hdf, where)
node = hdf.getNode(where)
if 'count' in node._v_attrs:
h /= node._v_attrs['count']
print('norm: %.1f' % node._v_attrs['count'])
return h
# Monkey-patch some handy feature... |
import pygame
pygame.init()
win = pygame.display.set_mode((500, 480))
pygame.display.set_caption("First Game")
bg = pygame.image.load('images/bg.jpg')
clock = pygame.time.Clock()
score = 0
class player(object):
walkRight = [pygame.image.load('images/R1.png'), pygame.image.load('images/R2.png'), ... |
# We use Google's Constraint Programming solver to solve each puzzle in a second or two.
# Find it at https://developers.google.com/optimization/cp/
from ortools.constraint_solver import pywrapcp
# Map 1 data
#Width = 11
#Height = 8
#Islands = ((0,2),(1,4),(1,7),(2,0),(2,1),(2,3),(2,5),(2,6),(3,0),(3,2),(3,5),(3,6),... |
"""
Copyright (c) 2019 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublice... |
import random
import matplotlib.pyplot as plt
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import pandas as pd
import streamlit as st
st.set_option("deprecation.showPyplotGlobalUse", False)
@st.cache
def load_data():
return pd.read_csv("Adult_Census_Incom... |
# Copyright (c)2015 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality o... |
# coding: utf-8
# # Simple Reinforcement Learning with Tensorflow: Part 3 - Model-Based RL
# In this iPython notebook we implement a policy and model network which work in tandem to solve the CartPole reinforcement learning problem. To learn more, read here: https://medium.com/p/9a6fe0cce99
#
# For more reinfo... |
#!/usr/bin/env python
import argparse
import ncluster
import os
IMAGE_NAME = 'pytorch.imagenet.source.v7'
INSTANCE_TYPE = 'p3.16xlarge'
NUM_GPUS = 8
ncluster.set_backend('aws')
parser = argparse.ArgumentParser()
parser.add_argument('--name', type=str, default='imagenet',
help="name of the current... |
# -*- coding: UTF-8 -*-
#
# Copyright 2015-2022 <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/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
# -*- coding: utf-8 -*-
import config
import math
import numpy as np
from collections import deque
import copy
from utils import create_satellite_image
#TODO: rewrite this part of code in C/C++
class Particle:
""" Particle with some physical properties and state variables: position and velocity """
def __in... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.postgres.search import SearchVector
from testing.models import *
from testing.testing_logic import *
from users.decorators import allowed_mails
@login_required(login_url='lo... |
# -*- coding: utf-8 -*-
""" Geo conversion tools
Convert from/to shapefile/vector/geometry
from/to raster/array
"""
import os
import warnings
from tempfile import NamedTemporaryFile
import numpy as np
import pyproj
import rasterio
from rasterio import features
from rasterio.transform import Affine
from osgeo import... |
"""Schedule management library."""
# +--------- minute (0 - 59)
# | +--------- hour (0 - 23)
# | | +--------- day of the month (1 - 31)
# | | | +--------- month (1 - 12)
# | | | | +--------- day of the week (0 - 7) (Sunday to Saturday; 7 is also Sunday)
# * * * * *
import sys
import os
import datetime
import socket
f... |
#!/usr/bin/env python3
from __future__ import print_function
__author__ = '<NAME>'
import sys
import re
import os
code = '00000000000000000000000000000000'
labels = {}
def nop(inst):
return '0' * 32
def mov(inst):
inst = inst.lower()
if inst[3] == 'r':
i = 3
while i < len(inst):
... |
import json
import os
import pickle
import sys
from datetime import datetime
from WikiData import WikiData
from indexers import RelationCollection
from indexers import TimeIndex
# POI to test with
person = '<NAME>'
startTime = datetime.now()
SkipList = ['P1412', 'P910', 'P103', 'P155', 'P31', '... |
"""AES-like functions."""
import enum
from cascada.bitvector.core import Constant, Term
from cascada.bitvector.operation import BvComp, BvNot
from cascada.bitvector.context import Memoization
from cascada.abstractproperty.property import make_partial_propextract
from cascada.bitvector.ssa import RoundBasedFunction
... |
# Copyright 2017 The Bazel Authors. 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 la... |
# The MIT License
#
# Copyright (c) 2019 ForAI (http://for.ai)
# Copyright (c) 2017 OpenAI (http://openai.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including... |
#-------------------------------------------------------------------------------
#
# Spherical Harmonic Coefficients.
#
# Author: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2018 EOX IT Services GmbH
#
# Permission is hereby granted, free of charg... |
from collections import defaultdict
from pathlib import Path
from textwrap import dedent
import networkx as nx
import numpy as np
from Qiber3D import Render, Figure, IO
from Qiber3D import config, helper
class Segment:
"""
Class representing the small element in a network
:param point: ordered list of ... |
import sys
import yaml
import re
import json
import logging
import time
import kraken.cerberus.setup as cerberus
import kraken.kubernetes.client as kubecli
import kraken.invoke.command as runcommand
# Reads the scenario config and creates a temp file to fill up the PVC
def run(scenarios_list, config):
failed_pos... |
import logging
import os
import subprocess
import threading
import time
from collections import OrderedDict
from configparser import SectionProxy
from shlex import quote
from tempfile import mkstemp
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
from redun.executors import aws_utils
from redun... |
# ! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2019, NVIDIA CORPORATION. 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/licen... |
# This test generates all variants of wmma intrinsics and verifies that LLVM
# generates correct instructions for them.
# RUN: python %s > %t.ll
# RUN: llc < %t.ll -march=nvptx64 -mcpu=sm_70 -mattr=+ptx60 | FileCheck %t.ll
from itertools import product
from string import Template
def make_wmma_slice_ty(abcd, itype):... |
from abc import ABC as _ABC
from abc import abstractproperty as _abstractproperty
from datetime import datetime as _datetime
from typing import Any as _Any
from typing import Dict as _Dict
from typing import List as _List
from typing import Optional as _Optional
from typing import Union as _Union
from . import convert... |
"""Tools for training and testing a model."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pycls.core.builders as builders
import pycls.core.checkpoint as cp
import pycls.core.config as config
import pycls.core.logging as logging
import pycls.core.meters as meters
import pycls.core.net ... |
"""Admin console models."""
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from simple_history.models import HistoricalRecords
class BaseSupportModel(models.Model):
"""Base model for all helper models in admin_console."""
display_in_form = ... |
"""
Module to calculate Gaussian covariance using the Improved NKA method implemented using NaMaster.
"""
import time
from collections import namedtuple
import healpy as hp
import numpy as np
import pymaster as nmt
# Simple class to keep this understandable
PowerSpectrum = namedtuple('PowerSpectrum', ['zbin_1', 'zb... |
import os
import torch
import torchvision.transforms.functional as F
from utils import set_work_directory, download_and_extract, UnNormalize
from torch.utils.data import Dataset, DataLoader
from pytorch_lightning import LightningDataModule
from torchvision import transforms as trforms
from PIL import Image
# Converts ... |
from collections import UserList, UserDict
from contextlib import contextmanager
from functools import partial
def fnv32a(text):
h = 0x811c9dc5
for c in text:
h = ((h ^ ord(c)) * 0x01000193) & 0xffffffff
return h
def numbered_columns(array):
# Can't use `not array` because numpy interprets i... |
from discord.ext.commands import Cog
from discord.ext.commands import command,cooldown,BucketType
from aiohttp import request
from discord.ext.commands.errors import MissingRequiredArgument
from discord import Embed
import datetime
import random
class Fun(Cog):
def __init__(self,bot):
self.bot=bot
@command(name="... |
# Imports here
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import time
import copy
from collections import OrderedDict
import argparse
parser = argp... |
import numpy as np
import matplotlib.pyplot as plt
# Physical Constants
m = 0.1 #kg
Ixx = 0.00062 #kg-m^2
Iyy = 0.00113 #kg-m^2
Izz = 0.9*(Ixx + Iyy) #kg-m^2 (Assume nearly flat object, z=0)
dx = 0.114 #m
dy = 0.0825 #m
g = 9.81 #m/s/s
DTR = 1/57.3; RTD = 57.3
# Simulation time and model parame... |
from actstream.actions import follow
from actstream.models import Follow
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_extensions.db.models import TitleSlugDescriptionModel
from guardian.s... |
# Copyright (c) 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Proof for adding all remaining non-special avx1 ops."""
import proof_tools
from proof_tools import MnemonicOp
from proof_tools import OpsProd
... |
import PySide2.QtWidgets as qtw
from PySide2.QtCore import Qt, QTimer
from PySide2.QtGui import QIntValidator
from pkg_resources import resource_filename
no_ans = '''
border-radius: 10px;background-color: #ffa7a1;font-size:18pt;padding:5px;
'''
ans = '''
border-radius: 10px;background-color: #a1ffb2;font-size:18pt;pa... |
import os
import unittest
import datetime
import numpy as np
import flap
import flap_w7x_webapi as webapi
# -------------------------------------INDEPENDENT FUNCTIONS FROM FLAP--------------------------------------------------
def test_basic():
# Getting ECRH data by giving the exact time
ecrh = ... |
"""
ESIM NLI model
TODO: Remove inits
"""
import sys
# 100x larger recursion limit is needed for ESIM
sys.setrecursionlimit(100000)
def flip01(x):
return x.transpose((1, 0, 2))
import theano
import theano.tensor as T
from theano import tensor
import logging
logger = logging.getLogger(__file__)
from blocks.brick... |
from unittest.mock import patch
from django.conf import settings
from django.test import TestCase, override_settings
from django.contrib.auth import get_user_model
from django.contrib.sessions.middleware import SessionMiddleware
from graphql_jwt.testcases import JSONWebTokenClient
# from user_center.models import Sho... |
from cached_property import cached_property
from datetime import datetime
from onegov.core.layout import ChameleonLayout
from onegov.core.static import StaticFile
from onegov.gazette import _
from onegov.gazette.collections import CategoryCollection
from onegov.gazette.collections import GazetteNoticeCollection
from on... |
__author__ = 'Todd.Hay'
# -------------------------------------------------------------------------------
# Name: main_trawl_analyzer.py
# Purpose: Main entry into the Trawl Analyzer software
#
# Author: Todd.Hay
# Email: <EMAIL>
#
# Created: November 2, 2016
# License: MIT
#------------... |
import os
import shutil
import numpy as np
from config_training import config
from scipy.io import loadmat
import numpy as np
import h5py
import pandas
import scipy
from scipy.ndimage.interpolation import zoom
from skimage import measure
import SimpleITK as sitk
from scipy.ndimage.morphology import binary_dilation,gen... |
import numpy as np
import json
from os.path import join
import pandas as pd
import torch
import logging
import tempfile
import subprocess as sp
from datetime import timedelta
from time import time
from itertools import combinations
from pyrouge import Rouge155
from pyrouge.utils import log
from rouge import Rouge
f... |
'''
CISC106 Module that includes some basic helper functions such as assert_equal().
Versions:
0.2 - 2019-JAN-02, Modified by <NAME>
+ Renamed functions to be in line with common Python convention
+ Packaged into an actual library on PyPI, with tests and stuff.
+ Replaced type(X) checks with isinstance
+ Changed s... |
import math
import random
import copy
import time
# import matplotlib.pyplot as plt
now = time.time()
euc = True
file_name = input()
data = open(file_name)
data = data.read()
data = data.split("\n")
if data[0] != "euclidean":
euc = False
n = int(data[1])
class cities:
index = int(0)
x = int(0)
y = i... |
import sys
import os
from os import remove
from os.path import join, dirname, realpath, exists
import numpy as np
def load_body_data(smpl_data, idx=0):
cmu_keys = []
for seq in smpl_data.files:
if seq.startswith('pose_'):
cmu_keys.append(seq.replace('pose_', ''))
name = sorted(cmu... |
#!/usr/bin/env python3
from snowfakery.generate_mapping_from_recipe import mapping_from_recipe_templates
from snowfakery.output_streams import (
DebugOutputStream,
SqlOutputStream,
JSONOutputStream,
CSVOutputStream,
ImageOutputStream,
GraphvizOutputStream,
MultiplexOutputStream,
)
from snowf... |
import argparse
import numpy as np
import matplotlib.pyplot as pyplot
import matplotlib
from matplotlib.ticker import ScalarFormatter
from astropy.table import Table
import astropy.units as u
# from dust_extinction.shapes import P92
from dust_extinction.averages import (
RL85_MWGC,
RRP89_MWGC,
I05_MWAvg,... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
#
# Copyright (c) 2021 Averbis GmbH.
#
# This file is part of Averbis Python API.
# See https://www.averbis.com for further info.
#
# 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:... |
import torch.nn as nn
import torch
import math
from torch.nn import init
import torch.nn.functional as F
# 2D Conv
def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes,
kernel_size=1, stride=stride, padding=0,
bias=False)
def conv2x2(in_pl... |
from math import ceil
import random
from scipy.io import loadmat
from scipy import signal
import numpy as np
import os
from PIL import Image
from matplotlib.pyplot import get_cmap
import shutil
def butter_highpass_filter(data, cutoff=1, fs=128, order = 5):
''' -> Used to remove the low frequency signals causing b... |
from abc import ABC
from typing import Any, List, Optional, Union
import lxml
import pandas as pd
from .. import cache
from ..datahelpers.column_mapper import BattingStatsColumnMapper, ColumnListMapperFunction, GenericColumnMapper
from ..enums.fangraphs import (FangraphsBattingStats, FangraphsFieldingStats, Fangraphs... |
# CODE ADAPTED FROM: https://github.com/MIC-DKFZ/nnUNet/blob/master/nnunet/network_architecture/generic_UNet.py
from torch import nn
import torch
import numpy as np
import torch.nn.functional
class InitWeights_He(object):
def __init__(self, neg_slope=1e-2):
self.neg_slope = neg_slope
def __call__(... |
# -*- coding:utf-8 -*-
# --
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --
import datetime
from nagare.i18n import _
from nagare.namespaces.xhtml i... |
# coding: utf-8
# rescal.py - python script to compute the RESCAL tensor factorization
# Copyright (C) 2013 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of... |
"""
The sample handler is a multi purpose python script for reading, converting and writing audio samples to use with the
microcontroller based sample playback player. Its required to use this in combination with an audio tool like audacity
and the binary2header converter which is also included in the project.
Pre... |
#
# MIT License
#
# Copyright (c) 2022 GT4SD team
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... |
import re
from datetime import datetime
from pathlib import Path
from re import Pattern
from typing import List
import fitz
import spacy as spacy
from fitz.fitz import Page, Rect
import pdf_redactor
NLP = spacy.load("en_core_web_sm", exclude=["parser"]) # Speeds up loading
NLP.enable_pipe("senter")
SECTIONS = [
... |
import os
import sys
import shutil
import argparse
from functools import (
wraps,
partial
)
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import mne
import braindecode
import wandb
from utils.utils import (
make_dir,
read_yaml,
AttrDict,
Color,
write_js... |
''' handles all the activity coming out of the server '''
import re
from django.db import IntegrityError, transaction
from django.http import HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from requests import HTTPError
from bookwyrm import activitypub
from bookwyrm import mod... |
import torch
import torch.nn as nn
class SEBlock(nn.Module):
def __init__(self, in_channels, out_channels, net_mode='2d'):
super(SEBlock, self).__init__()
if net_mode == '2d':
self.gap = nn.AdaptiveAvgPool2d(1)
conv = nn.Conv2d
elif net_mode == '3d':
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.