text stringlengths 957 885k |
|---|
<reponame>bennuttall/piwheels
# The piwheels project
# Copyright (c) 2017 <NAME> <https://github.com/bennuttall>
# Copyright (c) 2017 <NAME> <<EMAIL>>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redist... |
from django.test import TestCase
import sys
import pytest
class Test_MixStyle(TestCase):
# unittest style
@classmethod
def setUpClass(cls):
print('mix style (unittest) - setup > {}'.format(sys._getframe().f_code.co_name))
@classmethod
def tearDownClass(cls):
pri... |
"""xiRT main module to run the training and prediction."""
import argparse
import logging
import os
import pickle
import sys
import time
from datetime import datetime
import numpy as np
import pandas as pd
import yaml
from xirt import __version__ as xv
from xirt import features as xf
from xirt import predictor as xr... |
#!/usr/bin/env python
#description:Linkedin employee search module#
from colorama import Fore,Back,Style
import os,sys
import urllib
import requests
import re,string
class module_element(object):
def __init__(self):
self.title = "Linkedin gathering : \n"
self.require = {"enterprise":[{"value":"","required":"ye... |
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
from pathlib import Path
from shutil import copyfile
import numpy as np
from numpy.testing import assert_allclose
import pandas as pd
import pytest
import mne
from mne.channels import make_standard_montage
from mne.channels.montage import... |
<reponame>WongLynn/vnpy_Amerlin-1.1.20<filename>vnpy/trader/gateway/ctpGateway/ctpGateway.py
# encoding: UTF-8
'''
vn.ctp的gateway接入
考虑到现阶段大部分CTP中的ExchangeID字段返回的都是空值
vtSymbol直接使用symbol
'''
import os
import json
from copy import copy
from datetime import datetime, timedelta
import pandas as pd
from vnpy.api.ctp impor... |
import torch
from torch import nn
from torch.autograd import Function
from .voxel_layer import (dynamic_point_to_voxel_backward,
dynamic_point_to_voxel_forward)
class _dynamic_scatter(Function):
@staticmethod
def forward(ctx, feats, coors, reduce_type='max'):
"""convert kit... |
<gh_stars>10-100
#!/usr/bin/env python
#################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding cop... |
#importing libraries
import turtle
import random
import time
#creating turtle screen
screen = turtle.Screen()
screen.title('SNAKE GAME')
screen.setup(width = 900, height = 750)
screen.tracer(0)
turtle.bgcolor('#f0e4d7')
turtle.speed(5)
turtle.pensize(4)
turtle.penup()
turtle.goto(-310,250)
turtle.pendown()
turtle... |
<filename>avalanche/benchmarks/scenarios/online_scenario.py<gh_stars>0
################################################################################
# Copyright (c) 2022 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See ... |
<reponame>rdo-infra/ci-conf
#!/usr/bin/env python
import csv
import json
import os
import re
import sys
import time
from datetime import datetime
from io import StringIO
from tempfile import mkstemp
import click
import dlrnapi_client
import requests
import yaml
from dlrnapi_client.rest import ApiException
from jinja2... |
'''
Neural networks. Forward propagation in an already trained network in TensorFlow 2.0. Computing the regularised cost function.
TF 2.0:
sigmoid_step_option 0-4 all take 0.1-0.2 sec.
<NAME>
09-19/03/2018, 31/01-07/02, 04/03/2020
'''
import numpy as np
import scipy.io # to open Matlab's .mat files
import tensorflow... |
<filename>pyxllib/debug/specialist/tictoc.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : 陈坤泽
# @Email : <EMAIL>
# @Date : 2020/09/20
import time
import timeit
from humanfriendly import format_timespan
from pyxllib.text.pupil import shorten, listalign
from pyxllib.algo.pupil import natural_sort, Va... |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: MG4Lidar Reading Driver testing.
# Author: <NAME> <even dot rouault at mines dash paris dot org>
#
################################################################... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 08:48:00 2019
Recreated from <NAME>
@author: nikkicreange
"""
#!/usr/bin/python
# See http://maggotroot.blogspot.ch/2013/11/constrained-linear-least-squares-in.html for more info
'''
A simple library to solve constrained linear least square... |
<gh_stars>0
from flask import render_template,redirect,url_for,abort,request,flash
from app.main import main
from .forms import UpdateProfile,CreateBlog
from flask_login import login_required,current_user
from ..email import mail_message
from app.models import User,Blog,Comment,Follower
from ..import db
from app.reques... |
<reponame>MrEliptik/PaperWithCodeScrapper
import urllib
import requests
from bs4 import BeautifulSoup as bs
from validator_collection import checkers
class Scraper:
def __init__(self):
self.rootURL = 'https://paperswithcode.com'
self.trendingPapersURL = self.rootURL
self.latestURL = 'https:... |
<reponame>davidlrobinson/sentdex-blob<filename>env.py
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
import cv2
import matplotlib.pyplot as plt
import time
from blob import Blob
SIZE = 10
N_EPISODES = 5
MOVE_REWARD = -1
ENEMY_REWARD = -300
FOOD_REWARD = 25
SHOW_EVERY = 1
class Blo... |
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.core.mail import send_mail
from detention_notifier.models import Detention, DetentionMailer, Offense, Code, DetentionErrorNotification
from acade... |
<reponame>noooway/exj
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from ExerciseRunning import *
class ExerciseRunningInputWidget( GridLayout ):
... |
import warnings
import numpy as np
import networkx as nx
from scipy.stats import logistic
from mossspider.estimators.utils import fast_exp_map
def uniform_network(n, degree, pr_w=0.35, seed=None):
"""Generates a uniform random graph for a set number of nodes (n) and specified max and min degree (degree).
Add... |
<reponame>JIAQING-XIE/Google_NLP_DL
import re
import torch
import numpy as np
from sklearn.model_selection import train_test_split
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
from stanfordcorenlp import StanfordCoreNLP
path = r'C:\\Users\\11415\\Desktop\\stanford-cor... |
from enum import Enum
from typing import List, Union, Tuple, Optional, Iterator
from smbus2 import SMBus
class PinMode(Enum):
output = 0
input = 1
class PCA9536Pin:
"""A single pin of the PCA9536 GPIO expander."""
def __init__(self, device: "PCA9536", index: int):
"""Initialise the PCA9536... |
<reponame>genmeblog/twixtbot
#! /usr/bin/env python
""" Shared Memory Message Passing Protocol """
# python
import argparse
import collections
import mmap
import multiprocessing
import os
import select
import socket
import struct
import sys
debug = False
# mine
import timestat
IntPacker = struct.Struct("<L")
QUERY_A... |
<gh_stars>0
# -*- coding: utf-8 -*-
import csv
from datetime import datetime, timedelta
import string
try:
import cStringIO as StringIO
except ImportError:
import StringIO
import locale
try:
locale.setlocale(locale.LC_ALL, 'en_US')
except locale.Error:
pass
from gluon.dal import Field
from gluon.html i... |
<gh_stars>0
"""
validataclass
Copyright (c) 2021, binary butterfly GmbH and contributors
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
import re
from typing import Any, Optional, Union
from .string_validator import StringValidator
from validataclass.exceptions ... |
<filename>tests/test_scanner.py
import pytest
from utils.scanner import StringScanner
@pytest.fixture
def scanner():
src = 'Hello, world!'
return StringScanner(src)
class TestScanner:
def test_init(self):
src = 'Hello, world!'
scanner = StringScanner(src)
assert scanner.text == s... |
<gh_stars>1-10
import numpy as np
import nibabel
import pytest
from nilearn._utils.testing import write_tmp_imgs
from nilearn.decomposition.dict_learning import DictLearning
from nilearn.decomposition.tests.test_canica import _make_canica_test_data
from nilearn.image import iter_img, get_data
from nilearn.input_data i... |
<reponame>kirylkrauchuk/redistimeseries
import time
from RLTest import Env
import time
def assert_msg(env, msg, expected_type, expected_data):
env.assertEqual(expected_type, msg['type'])
env.assertEqual(expected_data, msg['data'])
def test_keyspace():
sample_len = 1024
env = Env()
with env.getC... |
<reponame>daojiaxu/semeval_11
import os
import numpy as np
# from semeval.datasets import pre_deal
import pre_deal_bert
import new_pre_deal
from keras.preprocessing import sequence
from mxnet.contrib import text
from transformers import BertTokenizer
import pandas as pd
from bert_serving.client import BertCl... |
import asyncio
import socket
import threading
import time
from collections import deque
from contextlib import suppress
from btclib_node.constants import NodeStatus, P2pConnStatus
from btclib_node.p2p.address import NetworkAddress, to_ipv6
from btclib_node.p2p.connection import Connection
from btclib_node.p2p.messages... |
<filename>app/core/migrations/0011_auto_20200903_2018.py
# Generated by Django 3.0.10 on 2020-09-03 20:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0010_orgunit_is_hqunit'),
]
operations = [
... |
<reponame>KrishnanS2006/HackDefyProject<gh_stars>1-10
from flask import Flask, render_template, redirect, url_for, request, flash, session
from flask_socketio import SocketIO
from flask_socketio import send, emit, join_room, leave_room
from data import *
import random
app = Flask(__name__)
app.secret_key = b'_5#y2L"F... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... |
import unittest
import functools
from ..symbol_type import SymbolType
from ..lex_token import Token
from ..syntax_nonterminal import Nonterminal
from ..syntax_productions import productionList
# todo, 把formatter改写为一个类
# Config
isKeepComment = True
isKeepGap = True
class Indenter:
IndentWidth = 4
def __in... |
<reponame>zeta1999/OpenJij
# Copyright 2019 Jij Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or a... |
# -*- coding: utf-8 -*-
"""
"""
import pytest
import sqlalchemy as sa
from pynuget import db
def test_count_packages(session):
session.add(db.Package(name="pkg_2", latest_version="0.0.1"))
session.commit()
assert db.count_packages(session) == 2
def test_search_packages(session):
# Test with no arg... |
import re
from lxml.etree import XMLSyntaxError
from galaxy.tool_util.verify import asserts
from galaxy.util import (
asbool,
parse_xml_string,
unicodify,
)
def assert_is_valid_xml(output):
""" Simple assertion that just verifies the specified output
is valid XML."""
try:
parse_xml_s... |
import re
import uuid
from mapswipe_workers.auth import firebaseDB
from mapswipe_workers.definitions import CustomError, logger
def remove_all_team_members(team_id):
"""Remove teamId attribute for all users of the team."""
fb_db = firebaseDB() # noqa E841
try:
# check if team exist in firebase
... |
<reponame>nickpartner-goahead/resilient-community-apps<gh_stars>10-100
# -*- coding: utf-8 -*-
"""Tests using pytest_resilient_circuits"""
import pytest
from resilient_circuits.util import get_config_data, get_function_definition
from resilient_circuits import SubmitTestFunction, FunctionResult
from mock import patch ... |
<gh_stars>1-10
import sys
sys.path.append("../../utils")
import numpy as np
from scipy.ndimage import convolve, distance_transform_edt
from utils.gaussian_kernel import getGaussianKernel
def _funcHeavyside(x, eps=1.):
''' Return a value of the H(x); heavyside function
'''... |
<reponame>NeonOcean/Environment<filename>S4/S4 Library/simulation/gsi_handlers/animation_archive_handlers.py
import itertools
from animation.animation_utils import clip_event_type_name
from gsi_handlers.gameplay_archiver import GameplayArchiver
from sims4.gsi.schema import GsiGridSchema, GsiFieldVisualizers
from sims4.... |
import typing as t
import discord
from discord.ext.commands import Cog, Context, command, has_any_role
from bot import constants
from bot.bot import Bot
from bot.decorators import in_whitelist
from bot.log import get_logger
from bot.utils.checks import InWhitelistCheckFailure
log = get_logger(__name__)
# Sent via D... |
"""Call arbitrary API endpoints."""
import json
import click
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer import utils
SPLIT_TOKENS = [
('in', ' IN '),
('eq', '='),
]
def _build_filters(_filt... |
# coding: utf-8
from django.core import mail
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django_factory_boy import auth
from journalmanager import models as jmodels
from journalmanager.tests import modelfactories
from editorialmanager import no... |
import logging
from typing import Optional
import xbmcaddon
import os
from .kodi_rpc import get_item_info, get_properties
from .periodic_updater import PeriodicUpdater
from .preferences import Preferences
ADDON = xbmcaddon.Addon()
logger = logging.getLogger(ADDON.getAddonInfo('id'))
def same_audio(audio1, audio2) ... |
import logging
import syslog
from passlib.hash import sha512_crypt
import ajenti
import ajenti.usersync
from ajenti.api import *
def restrict(permission):
"""
Marks a decorated function as requiring ``permission``.
If the invoking user doesn't have one, :class:`SecurityError` is raised.
"""
def d... |
<filename>monitoring/monitorlib/scd.py<gh_stars>1-10
import math
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Literal
from .typing import ImplicitDict, StringBasedDateTime
import s2sphere
import shapely.geometry
from monitoring.monitorlib import geo
TIME_FORMAT_CODE = 'RF... |
<filename>src/server.py<gh_stars>0
import numpy as np
import sys
import os
import random
from collections import defaultdict
from bottle import route, run, response, abort, static_file, request, redirect
import mimetypes, base64
from decorators import gzipped, session_logged
from index import Index
if len(sys.argv) ... |
<filename>evology/bin/gp/gp_bin/gp.py
import operator
import math
import random
import numpy as np
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
from deap import gp
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import graphviz_layout
import networ... |
"""
Residential Efficiency outputs
------------------------------
output functions for Residential Efficiency component
"""
import os.path
import aaem.constants as constants
from aaem.components import comp_order
import aaem_summaries.web_lib as wl
from pandas import DataFrame
COMPONENT_NAME = "Residential Energy E... |
<reponame>frank-chris/ScrapingTwitterPostsOnPolitics<filename>scripts/calc_answers.py
"""
<NAME> (<EMAIL>)
Script to find the answers for the Assignment 1 question from the scraped CSVs
"""
usage = "Usage:\n\n\
\
python3 calc_answers.py DIR_PATH\n\n\
\
* DIR_PATH: \n\
path to the directory which contains the scraped C... |
<gh_stars>0
import datetime, time
import re
import sys
try:
import simplejson as json
except ImportError:
import json
from dogshell.common import report_errors, report_warnings, CommandLineClient
def prettyprint_event(event):
title = event['title'] or ''
handle = event.get('handle', '') or ''
dat... |
<gh_stars>100-1000
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.core.management import call_command
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"""
Load the two statuses.
"""
... |
<filename>disp/database/api.py
"""
Module for providing a MongoDB database (collection) interface for AIRSS searches
"""
import os
import zlib
import enum
from logging import getLogger, INFO, WARNING
import hashlib
import time
from datetime import datetime, timedelta
from monty.serialization import loadfn
from firewor... |
<filename>Federated_Learning/paper_model/FedAvg/tensorflow/Models.py<gh_stars>0
import os
import tensorflow as tf
import numpy as np
from dataSets import DataSet
class Models(object):
def __init__(self, modelName, inputs):
self.inputs = inputs
self.model_name = modelName
if self.model_name... |
# Copyright 2020-present <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 or agreed ... |
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance ... |
<reponame>brzx/pydataloader
#!/usr/bin/python
# -*- coding: utf-8 -*-
import targetTools
import beatbox, pdb
import datetime
class SFDCTools(targetTools.TargetTools):
def __init__(self, credential, log):
self.credential = credential
self.log = log
def getConnection(self):
... |
<gh_stars>1000+
import pytest
from schematics.models import Model
from schematics.types import IntType, StringType
from schematics.types.compound import ModelType, ListType
from schematics.exceptions import DataError
from schematics.util import ImportStringError
def test_simple_embedded_models():
class Location(... |
<gh_stars>0
import imageio
from imgaug import augmenters as iaa
import math
import random
from tensorflow.keras.preprocessing.image import ImageDataGenerator
class Augmentor(object):
def __init__(self):
self.function = self._get_augmentor()
def _get_augmentor(self):
return iaa.Sequential(
... |
import numpy as np
import tensorflow as tf
#import keras
from tensorflow import keras
import pickle
import os
from utils import preprocess_flags
from utils import data_folder,kernel_folder,arch_folder,results_folder
def main(_):
FLAGS = tf.compat.v1.app.flags.FLAGS.flag_values_dict()
FLAGS = preprocess_flags... |
<reponame>openprocurement/openprocurement.auctions.flash<gh_stars>0
# -*- coding: utf-8 -*-
import unittest
from openprocurement.auctions.core.tests.base import snitch
from openprocurement.auctions.core.tests.blanks.chronograph_blanks import (
# AuctionSwitchAuctionResourceTest
switch_to_auction,
# Auctio... |
#!/usr/bin/env python
# _*_coding:utf-8_*_
import sys
import pandas as pd
import numpy as np
import rpy2
import rpy2.robjects
from rpy2.robjects import numpy2ri
numpy2ri.activate()
r = rpy2.robjects.r
r.library('Peptides')
GROUPS_SA = ['ALFCGIVW', 'RKQEND', 'MSPTHY'] #solventaccess
GROUPS_HB = ['ILVWAMGT', 'FYSQCN', ... |
<reponame>trer/bombots
import os
import pygame as pg
class TexMan: # Texture Manager
def __init__(self, scale):
mod_dir = os.path.dirname(__file__)
filename = os.path.join(mod_dir, 'res', 'bb_sprites.png')
self.spr = pg.image.load(filename).convert_alpha()
self.src_scale = 32 # ... |
<filename>squall/routing/path.py
import inspect
import re
from collections import Counter
from typing import Any, Callable, Dict, List, Optional, Tuple
from urllib.parse import urljoin
from squall import convertors, params
PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
class Path:
... |
<reponame>KnowingNothing/akg-test
from collections import namedtuple
import os
import logging
def get_block_str_from_config(config: namedtuple):
block_param = ""
if "block_x" in getattr(config, "_fields"):
block_param += str(config.block_x) + " "
if "block_y" in getattr(config, "_fields"):
... |
import json
import math
import pandas as pd
from scipy import stats
from lib.settings import DATA_DIR
from lib.characters import ALL_NAMES
from lib.episodes import getSequentialEpisodeNumber
raw_comments = pd.read_csv(DATA_DIR / "comments.csv")
raw_mentions = pd.read_csv(DATA_DIR / "character-mentions.csv")
raw_sent... |
<reponame>Waterpine/dataprep-1
"""
This file defines palettes used for EDA.
"""
from bokeh.palettes import Category10, Category20, Greys256, Pastel1, viridis
BRG = ["#1f78b4", "#d62728", "#2ca02c"]
CATEGORY10 = Category10[10]
CATEGORY20 = Category20[20]
GREYS256 = Greys256
PASTEL1 = Pastel1[9]
VIRIDIS = viridis(256)
R... |
<gh_stars>0
from common.services import cointainer_web3 as web3
import logging
import sha3
logger = logging.getLogger('watchtower.ingester.tasks')
WETH_CONTRACT_ADDRESS = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
ZX_PROXY_CONTRACT = '0xdef1c0ded9bec7f1a1670819833240f027b25eff'
k = sha3.keccak_256()
k.update('With... |
<filename>PixivDownloader.py
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 16 19:38:14 2019
AIに食わせる画像を探すためにpixivpyをやります。
タグで探せるようにつくります。
とりあえずクラス化しました。
"""
from pixivpy3 import AppPixivAPI
from pixivpy3 import PixivAPI
import os
class PixivDownloader :
def __init__(self):
self.pixiv... |
#--------ESRI 2010-------------------------------------
#-------------------------------------------------------------------------------
# Copyright 2010-2013 Esri
# 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... |
import cv2
import numpy as np
class Thresholds:
def __init__(self):
self._HLS_H_THRESHOLD = (100, 255)
self._HLS_L_THRESHOLD = (100, 255)
self._HLS_S_THRESHOLD = (100, 255)
self._SOBEL_THRESHOLD = (20, 100)
self._SOBEL_KERNEL = 3
self._GRAD_MAG_THRESHOLD = (30, 170)
... |
<gh_stars>0
import json
from collections import defaultdict
from typing import List, Dict, Any, Union
import numpy as np
from py_lex import EmoLex
import torch
from torch.utils.data import Dataset
from pytorch_gleam.data.datasets.base_datasets import BaseDataModule
from pytorch_gleam.data.collators import MultiClas... |
from threading import Timer, Thread
""" @Todos
- Create a method that will call the stop method when the process exits. Because the timer thread continues to run
even if the main program/thread is killed by keyboard interrupt, which means that the stop method is never called.
- Create a method that allow... |
# -*- coding: utf-8 -*-
# Модуль переменных параметров настройки "Общие данные для расчета динамики"
# (таблица "Динамика": com_dynamics) RastrWin3
class ComDynamics:
"""
"""
table: str = 'com_dynamics'
table_name: str = '"Общие данные для расчета динамики"'
Tras: str = 'Tras' # Время расчета (T... |
<filename>apps/webapp/views.py
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.views import generic
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
fro... |
<filename>lib/meshrenderer/gl_utils/window.py
# -*- coding: utf-8 -*-
# flake8: noqa
import cyglfw3 as glfw
from OpenGL.GL import *
from OpenGL.GL.NV.bindless_texture import *
class Window(object):
def __init__(
self,
window_width,
window_height,
samples=1,
window_title="",... |
from multiprocessing import Process, Queue
from langumo.building import Builder
from langumo.utils import (AuxiliaryFile, AuxiliaryFileManager, colorful,
SentenceSplitter)
from typing import Iterable
class Parser:
def prepare(self, raw: AuxiliaryFile):
pass
def extract(self... |
<filename>tests/test_controllers.py
from pilco.controllers import RbfController, LinearController, squash_sin
import numpy as np
import os
import tensorflow as tf
import oct2py
octave = oct2py.Oct2Py()
dir_path = os.path.dirname(os.path.realpath("__file__")) + "/tests/Matlab Code"
octave.addpath(dir_path)
from gpflow ... |
from tw.api import Widget
from tw.forms import CalendarDatePicker, CalendarDateTimePicker, TableForm, DataGrid
from tw.forms.fields import (SingleSelectField, MultipleSelectField, InputField, HiddenField,
TextField, FileField, PasswordField, TextArea, Label)
from formencode.schema import S... |
import datetime
import dateutil.tz
import pytz
import requests_mock
import warnings
try:
import zoneinfo
except ImportError:
from backports import zoneinfo
from exchangelib.errors import UnknownTimeZone, NaiveDateTimeNotAllowed
from exchangelib.ewsdatetime import EWSDateTime, EWSDate, EWSTimeZone, UTC
from ex... |
<filename>test/test_im.py
import unittest
from unittest.mock import patch, PropertyMock, MagicMock
from os import path
from src import im
from io import BytesIO
THUMB_LENGTH = str(290)
IMAGE_PNG = 'kosys.png'
def with_image(name, consumer):
p = path.dirname(__file__) + '/fixture/images/' + name
with open(p, ... |
<reponame>hwpplayers/ironic<filename>ironic/tests/unit/drivers/test_ipmi.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
<reponame>servoz/capsul
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import shutil
import unittest
import tempfile
import sys
import six
from traits.api import File
from capsul.api import Process, Pipeline, Switch, get_process_instance
class Identi... |
import scrapelib
import datetime
import os
import re
from collections import defaultdict
from billy.scrape import ScrapeError
from billy.scrape.bills import BillScraper, Bill
from billy.scrape.votes import Vote
from billy.scrape.utils import convert_pdf
import lxml.html
def action_type(action):
# http://www.scs... |
<reponame>thechiragthakur/Data-Science-Using-Python<gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# # ASSIGNMENT 1
# Pima Indians Diabetes Database.
# It consists 768 tuples each having 9 attributes.
# In[1]:
import pandas as pd
#imported the dataset given to us
pid=pd.read_csv("C:\\Users\\Micontroller Lab N16\... |
<filename>preprocessor/preprocessor.py<gh_stars>0
import os
import random
import json
import tgt
import librosa
import numpy as np
from tqdm import tqdm
import audio as Audio
from text import grapheme_to_phoneme
from utils.tools import read_lexicon
from g2p_en import G2p
random.seed(1234)
class Preprocessor:
d... |
<filename>supervision/ssim.py
# code from https://github.com/Po-Hsun-Su/pytorch-ssim
import torch
import numpy
import math
def __gaussian__(kernel_size, std, data_type=torch.float32):
gaussian = numpy.array([math.exp(-(x - kernel_size//2)**2/float(2*std**2)) for x in range(kernel_size)])
gaussian /= num... |
# -*- coding: utf-8 -*-
model = {
'tlh': 0,
"e' ": 1,
'gh ': 2,
"i' ": 3,
" 'e": 4,
"u' ": 5,
' vi': 6,
'atl': 7,
"a' ": 8,
' gh': 9,
'ej ': 10,
' ho': 11,
' ch': 12,
' mu': 13,
' tl': 14,
'nga': 15,
'mey': 16,
"wi'": 17,
"be'": 18,
'an ': 19,
'ch ': 20,
'gan': 21,
'chu': 22,
'lh ': 23,
'ing': ... |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
<gh_stars>10-100
#!/bin/python
import argparse
import os
import glob
import json
import shutil
import urllib.parse
import re
import bs4 as bs
import subprocess
def get_path(url: str):
urlpath = urllib.parse.urlparse(url).path
match = re.search(r"^(/books/\d+)?/(.+?)(/content|/encrypted/\d+)?$", urlpath)
p... |
<reponame>wubinbai/argus-freesound
import torch
from torch import nn
import torch.nn.functional as F
class ChannelAttention(nn.Module):
def __init__(self, in_planes, ratio=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPo... |
<filename>src/wikidated/_utils/seven_zip_archive.py
#
# Copyright 2021-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
#
# Unles... |
<reponame>NeoBryant/Brain_Image_Segmentation
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
#%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib
def truncated_normal_(tensor, mean=0, std=1):
... |
<reponame>doubleDragon/quantApi
# coding=utf-8
import requests
import hmac
import time
import urllib
import hashlib
class Client(object):
"""Represents a Poloniex exchange"""
base_url = 'https://poloniex.com/'
def __init__(self, api_key=None, secret=None):
"""
Args:
api_key (... |
<filename>WassersteinGAN/src/utils/data_utils.py
import cv2
import glob
import h5py
import imageio
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
import numpy as np
import os
from scipy import stats
from keras.datasets import mnist, cifar10
from keras.optimizers import Adam, SGD, RMSprop
from ke... |
import socketserver
import os
import threading
import time
import datetime
import sqlite3 as lite
import sys
import random
import string
HOST ='192.168.53.12'
PORT = 5050
class MyTCPHandler(socketserver.StreamRequestHandler):
#id = 0
#def readline(self):
# server.request_line= self.rfile.readline().... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.