text stringlengths 957 885k |
|---|
import os
from yaml import CLoader as Loader
from importlib.machinery import SourceFileLoader
utils = SourceFileLoader("utils", "./molecule/common/tests/utils.py").load_module()
testinfra_hosts = utils.get_testinfra_hosts()
def check_conf_file(conf_file, instance_id, conf):
assert conf_file.exists
assert c... |
import socket
import struct
PROXY_TYPE_SOCKS4 = 1
PROXY_TYPE_SOCKS5 = 2
PROXY_TYPE_HTTP = 3
_defaultproxy = None
_orgsocket = socket.socket
class ProxyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class GeneralPro... |
<reponame>ctrlcctrlv/fonttools
from fontTools.misc.py23 import *
from fontTools import unicodedata
import pytest
def test_script():
assert unicodedata.script("a") == "Latn"
assert unicodedata.script(unichr(0)) == "Zyyy"
assert unicodedata.script(unichr(0x0378)) == "Zzzz"
assert unicodedata.script(un... |
<reponame>Blockwise/crix-client-py
import json
import hmac
from datetime import datetime
from typing import List, Optional, Tuple, AsyncIterator
from aiohttp import ClientSession
from .client import APIError
from .models import Ticker, Resolution, NewOrder, Order, Symbol, Depth, Trade, Account, Ticker24, VolumeFee
c... |
<filename>LeetCode-All-Solution/Python3/LC-INTERVIEW-0406-Successor-LCCI.py<gh_stars>0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-INTERVIEW-0406-Successor-LCCI.py
@Author : [... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... |
<gh_stars>0
import pandas as pd
import numpy as np
import psycopg2
import pmdarima as pm
import plotly
import plotly.graph_objs as go
from plotly.offline import *
from Graph import *
import plotly.io as pio
pio.renderers.default = 'notebook'
# Connect to database
conn = psycopg2.connect(host='localhost', port=5432, d... |
import pytest
import esmvalcore.preprocessor
from esmvalcore.preprocessor import _download
@pytest.mark.parametrize(
'variable, cmd',
[
(
{
'dataset': 'CanESM2',
'ensemble': 'r1i1p1',
'exp': 'historical',
'mip': 'Amon',
... |
"""
Test all things related to the ``jedi.cache`` module.
"""
import os
import pytest
import time
from pathlib import Path
from parso.cache import (_CACHED_FILE_MAXIMUM_SURVIVAL, _VERSION_TAG,
_get_cache_clear_lock_path, _get_hashed_path,
_load_from_file_system, _Node... |
# -*- test-case-name: twisted.web.test.test_web -*-
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
from cStringIO import StringIO
from twisted.python import failure
import html
import resource
import linecache
import string, re
import types
def redirectTo(URL, request):
r... |
<gh_stars>10-100
#
# BitBake Tests for runqueue task processing
#
# Copyright (C) 2019 <NAME>
#
# SPDX-License-Identifier: GPL-2.0-only
#
import unittest
import os
import tempfile
import subprocess
import sys
import time
#
# TODO:
# Add tests on task ordering (X happens before Y after Z)
#
class RunQueueTests(unitte... |
import inspect
import json
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render, HttpResponseRedirect
from webapp.controller.common import *
from webapp.forms.SystemMessageForm import SystemMessageForm
from webapp.models import *
from webapp.utils.form_t... |
<reponame>dirkgomez/voice-skill-sdk
#
# voice-skill-sdk
#
# (C) 2020, Deutsche Telekom AG
#
# This file is distributed under the terms of the MIT license.
# For details see the file LICENSE in the top directory.
#
#
import sys
import unittest
from json import loads
from logging import makeLogRecord, INFO
from unittest.... |
<reponame>datphan/moviecrab<filename>app/people/datastore.py
from abc import abstractmethod, ABCMeta
from datetime import datetime
from flask_security.utils import encrypt_password
from ..datastore import SQLAlchemyDatastore
from ..utils import fix_docs
class PeopleDatastore(object):
"""Abstract PeopleDatastore... |
<reponame>reip-project/reip-pipelines<gh_stars>0
from interface import *
from plasma import save_data, load_data, save_meta, load_meta, save_both, load_both
import pyarrow as pa
import numpy as np
import pyarrow.plasma as plasma
import multiprocessing as mp
import time
import copy
class UniqueID:
_id = 0
@st... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
from django import forms
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
from . import models
from django.contrib.auth.password_validation import password_validators_help_texts
User = get_user_model()
class UserLoginForm(forms.Form):
username = forms.CharField(... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Roles_lkup(models.Model):
rolename=models.CharField(max_length=255)
rolenamesort=models.SmallIntegerField()
def __str__(self):
return self.rolename
class Meta:
db_table='role'... |
<filename>crosshair/enforce_test.py
import abc
from contextlib import ExitStack
import unittest
import sys
import pytest
from crosshair.condition_parser import Pep316Parser
from crosshair.enforce import EnforcedConditions
from crosshair.enforce import PostconditionFailed
from crosshair.enforce import PreconditionFail... |
<gh_stars>0
# flups.io: tools for reading and writing files
import re
import logging
import numpy as np
from .calib import load_latest, calibration
logger = logging.getLogger(__name__)
def read_asc(fname):
"""
Read a single `asc` file, the ASCII format from Andor Solis.
"""
logger.debug("Loading `.asc... |
<reponame>CorentinAmbroise/pynet<filename>pynet/utils.py
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from django.utils.encoding import force_str
"""
test_django-teryt
------------
Tests for `django-teryt` modules module.
"""
from django.test import TestCase
from django.... |
# -*- coding: utf-8 -*-
import sqlite3
from unicorns.Unicorn import Unicorn
def setup():
'''
Creates a database, empties it and populates it with four unicorns.
'''
conn = sqlite3.connect('unicorns.db')
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS unicorns")
c.execute("CREAT... |
import logging
import os
from typing import Dict
from ilkbyte.exception import ConfigurationError
from ilkbyte.session import IlkbyteAPISession
from ilkbyte.utils import PowerAction, DNSRecordType
logger = logging.getLogger(__name__)
class Ilkbyte(object):
def __init__(self, host: str = None, secret_key: str = ... |
<reponame>matveymisyura-mango/vosk-server
# Copyright (c) 2020 <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 ... |
"""Contains the classes and functions for scraping a yahoo finance option page."""
from enum import Enum
from itertools import cycle
from typing import Iterable, List, Optional, Tuple, Union
import pandas
from pandas import DataFrame
import pendulum
from pendulum.datetime import DateTime
from pydantic import BaseMode... |
# Copyright 2019 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... |
# -----------------------------------------------------------------------------
# Imports:
# -----------------------------------------------------------------------------
import os
import dpa
from dpa.action import Action, ActionError, ActionAborted
from dpa.env.vars import DpaVars
from dpa.location import Location... |
<gh_stars>0
import pytest
from xchainpy.xchainpy_litecoin.client import Client
from xchainpy.xchainpy_util.asset import Asset
from xchainpy.xchainpy_client.models import tx_types
from xchainpy.xchainpy_litecoin.utils import MIN_TX_FEE
class TestLiteCoinClient:
phrase = 'atom green various power must another rent ... |
import os
import re
import platform
import subprocess
from collections import OrderedDict
from .base import Base
from deoplete.util import charpos2bytepos, expand, getlines, load_external_module
load_external_module(__file__, 'sources/deoplete_go')
from cgo import cgo
from stdlib import stdlib
try:
load_externa... |
# -*- coding: utf-8 -*-
"""03C_Keras_API.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/Hvass-Labs/TensorFlow-Tutorials/blob/master/03C_Keras_API.ipynb
# TensorFlow Tutorial #03-C
# Keras API
by [<NAME>](http://www.hvass-labs.org/)
/ [GitHub](... |
from __future__ import print_function
import tensorflow as tf
from termcolor import colored
from openrec.tf1.legacy.modules.interactions import Interaction
class PointwiseMSE(Interaction):
"""
The PointwiseMSE module minimizes the pointwise mean-squre-error [ctm]_ as follows (regularization terms \
are no... |
<filename>tests/hwsim/test_tnc.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# TNC tests
# Copyright (c) 2014-2015, <NAME> <<EMAIL>>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import os.path
import hostapd
from utils import HwsimSkip, alloc_fail, fail_test, wait... |
<reponame>alxcord/my_public_scripts<filename>HANA/hana_extract/hana_extract.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 1 12:18:15 2017
@author: <NAME>
Script para executar um ou mais consultas SQL num banco de dados HANA
Ajustes
"""
import pyhdb, optparse, time
import csv, sys, termios
... |
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.http.response import JsonResponse
from django.contrib.auth.models import User, Group
from django.utils.crypto import get_random_string
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import ... |
<reponame>ArqiSoft/ml-services
import gc
import re
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
class Param:
def __init__(self,charset,char_to_int,int_to_char,smiles_len):
self.charset = charset
self.char_to_int = char_to_int
self.int_to_char... |
# Copyright (c) SenseTime Research and its affiliates. All Rights Reserved.
import random
import torch
import torchvision
from torchvision.transforms import functional as F
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, target=None):
... |
<reponame>hmlewis-astro/ARCTIC_ERMINE<gh_stars>0
"""
ARCTIC_phot.py
<NAME>
<EMAIL>
2020
Automatic reduction pipeline for transit photometry with the Astrophysical Research Consortium Imaging Camera (ARCTIC) at Apache Point Observatory (APO).
to use:
python ARCTIC_phot.py path/to/your/data
OR place ARCTIC... |
from __future__ import annotations
from dippy.core.caching.cacheable import Cacheable
from dippy.core.models.guild import *
from dippy.core.timestamp import Timestamp
from gully import Gully
class Guild(Cacheable):
def __init__(self, model: GuildModel):
self._model = model
self._change_event_strea... |
"""
Module which interprets textX model based on viewX model and generates preview.html file
with Cytoscape.js graph model used for visualization of textX model. The preview.html file is hosted on file server
and can be loaded with multiple clients (regular internet browser or Visual Studio Code extension) and previewe... |
"""Queryset optimization. """
import logging
import typing
import django.db.models as djm
import graphql
import graphql.language.ast as ast_
import phrases_case
if typing.TYPE_CHECKING:
class OptimizationOption(typing.TypedDict):
"""
Optimization option dict.
See :doc:`/optimize` for mor... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
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... |
<filename>backgammon.py
import lib.dice as dice
import lib.state as state
import lib.stateTreeNode as stateTreeNode
import lib.learning as learning
import lib.plotResults as plotResults
import lib.move as move
from lib.strategies import linTransform as lin_transform_strategy
from lib.strategies import heuristic
from l... |
<filename>scripts/zone_analysis.py
"""
Analysis zones:
- vicinity of new metro stations, defined by walking distance to station
- vicinity of old metro stations, --||--
- areas relying on feeder bus (west metro), areas not in vicinity of metro stations and with direct bus to Kamppi
- commuter train station vicinities
-... |
import dxx
import numpy as np
class TestDtype:
def test_from_filename(self):
mock_filename = "mock.DSB"
assert dxx.Dtype.DSB == dxx.Dtype.from_filename(mock_filename)
def test_list_names(self):
assert ["DSA", "DFA", "DDA", "DSB", "DFB", "DDB"] == dxx.Dtype.list_names()
def test_b... |
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013, Red Hat, 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/LI... |
from shutil import copyfile
import numpy as np
import sys_simulator.general as gen
from time import time
from sys_simulator.dqn.agents.dqnAgent import ExternalDQNAgent
from sys_simulator.dqn.externalDQNFramework import ExternalDQNFramework
from sys_simulator.parameters.parameters import DQNAgentParameters
import torch
... |
from view import *
from model import Model
import os
import sys
import datetime
MAX_NAME_CHARS = 20
MAX_DESC_CHARS = 150
STARTING_INDEX = 1
class Controller:
"""
The middle man. Operates on model and updates the view to show information to user.
"""
OPTIONS = {'1': 'Add Todo Item',
'2'... |
import argparse
import socket
import sys
import signal
import traceback
from toolset.benchmark.benchmarker import Benchmarker
from toolset.utils.scaffolding import Scaffolding
from toolset.utils.audit import Audit
from toolset.utils import cleaner
from toolset.utils.benchmark_config import BenchmarkConfig
from toolset.... |
<reponame>nachonacho2/SIPEC
# SIPEC
# MARKUS MARKS
# RUN FULL INFERENCE
import os
import sys
import operator
import cv2
from SwissKnife.masksmoothing import MaskMatcher
from SwissKnife.poseestimation import heatmap_to_scatter, custom_binary_crossentropy
sys.path.append("../")
from argparse import ArgumentParser
imp... |
from setuptools import setup
import sys
import wx
APP = "batchcalc/zbc.py"
AUTHOR = "<NAME>"
AUTHOR_EMAIL = "<EMAIL>"
DESCRIPTION = "Script for calculating batch composition of zeoliteis"
LICENSE = open('LICENSE.txt').read()
NAME = "batchcalc"
URL = "https://bitbucket.org/lukaszmentel/batchcalc"
VERSION = "0.2.1"
YEA... |
#!/usr/bin/env python
import os
import os.path
import glob
import landsat8_metadata
import math
bandList = ['B01','B02','B03','B04','B05','B09','B06','B07']
def process_tgz(context, path, dir=os.getcwd()):
context["aot_window_size"] = 500
list_intermediate_save_file = []
# ------------------... |
<reponame>InternetNZ/irma-fab-integration<gh_stars>0
#!/usr/bin/env python3
import argparse
import json
import datetime
import time
import logging
import qrcode
import requests
import subprocess
RELYING_PARTY_ID = ""
RELYING_PARTY_NAME = ""
RELYING_PARTY_LOGO = ""
RELYING_PARTY_API = ""
API_KEY = ""
IRMA_TOKEN = ""
I... |
# Copyright 2021 Universität Tübingen, DKFZ and EMBL for the German Human Genome-Phenome Archive (GHGA)
#
# 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... |
"""
masks.py
Provides functions which create specialized footprints or masks which are
subsequently fed as inputs to functions in scipy.ndimage.filters module.
AUTHOR: <NAME>
DATE: 5/17/2013
"""
import numpy as np
from scipy.ndimage import filters
import math
def getDeriv(image, weights=[3./16, 10./16, 3./16], axes... |
<reponame>roberamy/CS467_Animal_Adoption<filename>admin.py
###############################################################################
#
# Author: <NAME>, <NAME>, <NAME>
# Email: <EMAIL>
# Course: CS467_400_W2021
#
# Description: Routes for admin page
#
# Ref: https://werkzeug.palletsprojects.com/en/1.0.x/utils/
#... |
<gh_stars>1-10
import cv2
import numpy
import platform
import plateRecog
import SimpleCV
import time
import socket
import databaseConstants as const
class SpearHUD:
def __init__(self, hudPath, maskPath, scanHudPath, camResolution=(1920, 1080),
camIndex=1, displayResolution=(960, 540), windowName=... |
from django.apps import apps
import os, os.path
import collections
import zlib
from importlib import import_module
# set up the logger
import logging
log = logging.getLogger('django_mako_plus')
################################################################
### Special type of list used for url params
class U... |
import json
import sys
import falcon
import pytest
from falcon import testing
from ward.main import Ward
@pytest.fixture()
def client():
app = falcon.App()
ward = Ward(app=app)
return testing.TestClient(app)
def test_base_ward_initialization():
ward = Ward()
assert ward.packaged is False
a... |
import os
import sys
import sysconfig
def reset_tzpath(to=None):
global TZPATH
tzpaths = to
if tzpaths is not None:
if isinstance(tzpaths, (str, bytes)):
raise TypeError(
f"tzpaths must be a list or tuple, "
+ f"not {type(tzpaths)}: {tzpaths!r}"
... |
from ..common.grange import Grange
class RecordDigIS(Grange):
def __init__(self, genome_name, chrom, genome_seq, genome_len, qid, sid, qstart, qend, start, end, strand, acc, score, evalue):
self.qid = qid
self.sid = sid
self.qstart = qstart
self.qend = qend
self.acc = acc
... |
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
if __package__ is None:
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
import json
import os
import os.path
import posixpath
from collections import defaultdict, namedtuple
t... |
"""
BrowserUp Proxy
___ This is the REST API for controlling the BrowserUp Proxy. The BrowserUp Proxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ # noqa: E501
The version of the OpenAPI document: 1.0.0
Genera... |
#!/usr/bin/env python
"""Command line tool for interaction with YI Dashcam"""
import argparse
import enum
import sys
import time
from . import __version__, YIDashcam, YIDashcamException
from .config import Option, option_map, PhotoResolution
def format_config(option, value):
return "{0}: {1}".format(
op... |
<reponame>LawrenceMMStewart/Optimal_Transport_MIT<gh_stars>1-10
#tests for ot1d.py
import pytest
from ot.ot1d import *
import numpy as np
def precision_eq(a,b):
return (np.abs(a-b)<1e-14).all()
def tensor_precision(a,b):
return tf.reduce_sum((a-b)**2)<1e-14
def test_ttu1d_5k():
#tests transform to uniform 1d
µ1... |
import argparse
import logging
import yaml
from medcat.cdb_maker import CDBMaker
from medcat.utils.make_vocab import MakeVocab
from medcat.cat import CAT
from medcat.config import Config
from medcat.utils.loggers import add_handlers
from pathlib import Path
# Create Logger
logger = logging.getLogger('__package__')
lo... |
<reponame>fountain111/Algorithm-
import entropy
import numpy as np
class ID3_trees():
'''
ID3
'''
def __init__(self):
#self.label = label
return
def _create_dataSets(self):
dataSet = [[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
... |
# -*- coding: utf-8 -*-
"""
A Cell object represents a place in the environment where an organism could
reside. If that Cell is occupied by an organism, the Cell object also defines
that organism.
"""
__author__ = "<NAME> <<EMAIL>>"
__credits__ = "<NAME>"
import random
from seeds.SEEDSError import *
class Cell(ob... |
"""
Binomial distribution
---------------------
"""
import mpmath
from ..fun import logbinomial
__all__ = ['pmf', 'logpmf', 'cdf', 'sf', 'mean', 'var']
def _validate_np(n, p):
if p < 0 or p > 1:
raise ValueError('p must be in the range [0, 1]')
if n < 0:
raise ValueError('n must be a nonne... |
<filename>SComplexity/scrape.py<gh_stars>1-10
# Scientific readability project
# authors: other authors,
# ...,
# <NAME>
# https://github.com/russelljjarvis/
# <EMAIL>
# <NAME>
# <EMAIL>
from numpy import random
import os
from bs4 import BeautifulSoup
import pickle
import _pickle as cPickle #Using cPickle will result ... |
<gh_stars>1-10
"""Switch platform for Hyperion."""
from __future__ import annotations
import functools
from typing import Any, Callable
from hyperion import client
from hyperion.const import (
KEY_COMPONENT,
KEY_COMPONENTID_ALL,
KEY_COMPONENTID_BLACKBORDER,
KEY_COMPONENTID_BOBLIGHTSERVER,
KEY_COMP... |
import pandas as pd
import numpy as np
from sklearn.base import TransformerMixin
import scipy
def close(X: np.ndarray):
if X.ndim == 2:
return np.divide(X, np.sum(X, axis=1)[:, np.newaxis])
else:
return np.divide(X, np.sum(X, axis=0))
def nancov(X, method='replace'):
"""
Generates a ... |
<filename>download.py
import json
import sys
import cgi
import os
import datetime
from do_authentication import authenticate
from do_http_get import do_get
##############################################################################################################
# First Step: Get the config data from config.json ... |
<filename>hypothesis_generator/er_mlp/er_mlp_imp/er_mlp_max_margin.py<gh_stars>1-10
"""
Filename: er_mlp_max_margin.py
Authors:
<NAME> - <EMAIL>
<NAME> - <EMAIL>
Description:
Construct ER MLP using max margin loss and perform train, evaluation, and test.
To-do:
"""
# standard imports
import logging as lo... |
#
# Autogenerated by Thrift Compiler (0.9.3)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
import apache.airavata.model.appcatalog.computeresource.ttypes
import apache.airavata.model.data.m... |
<gh_stars>1-10
import os
from typing import List, Optional
import cv2.cv2 as cv2
import dlib
import numpy as np
from facepy import config
from facepy.view import geometry_renderer
from . import img
from .detector import RawModel, StaticFaceDetector
from .geometry import Landmarks, Point
class FeatureExtractor:
... |
import os
import numpy as np
import matplotlib.pylab as plt
import matplotlib
import xlrd
from matplotlib import rcParams
from matplotlib.colors import LinearSegmentedColormap
from matplotlib import cm
def split_data(data):
result = list()
temp = data.split("\t")
for i in range(len(temp)):
if tem... |
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... |
# stdlib
from collections import deque
from datetime import datetime, timedelta
from io import TextIOBase
from smtplib import SMTPException
from typing import Deque
# lib
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.core.mail.backends.smtp import EmailBackend
from dja... |
<gh_stars>0
##############################################################
##
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.colors import ListedColormap as lcm
from matplotlib import ticker
try:
from palettable.colorbrewer... |
<gh_stars>1-10
import datetime
import pytz
from dateutil.relativedelta import relativedelta
from fast_pyspark_tester.sql.casts import get_time_formatter, get_unix_timestamp_parser
from fast_pyspark_tester.sql.expressions.expressions import Expression, UnaryExpression
from fast_pyspark_tester.sql.types import DateType... |
import yaml
# Model definition lists
### elements ###
# Definition
# the indices 0 1 2 3 4 5 6 7 8
listElementField = ['id', 'name', 'description', 'creationDate', 'version', 'type', 'parentId', 'path', 'refId']
ELEMENT_ID = 0
ELEMENT_NAME = 1... |
#! /usr/bin/env/python 3.0
#
# Running this script will update the batch and make files that compile the test cases
# for each CWE into a separate .exe or executable file. This script also edits source code
# and header files needed for a successful compilation with these files.
#
#charm
import os
import shutil
import... |
# babelizer.py - API for simple access to babelfish.altavista.com.
# Requires python 2.0 or better.
#
# See it in use at http://babel.MrFeinberg.com/
"""API for simple access to babelfish.altavista.com.
Summary:
import babelizer
print ' '.join(babelizer.available_languages)
print babeliz... |
<reponame>Kramer84/StochasticProcessSensitivityAnalysis<gh_stars>1-10
import gc
import os, sys, re
import time
import numpy as np
import pandas as pd
import warnings
import openturns as ot
if not sys.warnoptions:
warnings.simplefilter("ignore")
import matplotlib as mpl
mpl.use('Qt4Agg')
from matplotlib.figure i... |
from itertools import izip_longest
outpath = "redd-test/"
dir = "redd-test/house_1/"
with open(dir+'channel_5_6.dat') as f3,\
open(dir+'channel_6_7.dat') as f4, open(dir+'channel_7_5.dat') as f5, open(dir+'channel_8_5.dat') as f6,\
open(dir+'channel_9_3.dat') as f7, open(dir+'channel_11_9.dat') as f8, open(d... |
<filename>tests/common/utils/test_http_utils.py<gh_stars>0
import os
import responses
import requests
from unittest import mock
from checkov.common.util.http_utils import request_wrapper
@responses.activate
@mock.patch.dict(os.environ, {"REQUEST_MAX_TRIES": "5", "SLEEP_BETWEEN_REQUEST_TRIES": "0.01"})
def test_reque... |
import numpy as np
import pandas as pd
import scipy
import os
import json
from functools import partial
from tqdm import tqdm
import torch
import torch.utils.data as data
from sklearn.model_selection import train_test_split
COUGHVID = "/home/shubham/datasets/coughvid/public_dataset"
metadf = pd.read_csv(os.path.join... |
<reponame>takuyakawanishi/kldmwr
import matplotlib.pyplot as plt
from matplotlib import lines, rc
#from matplotlib.ticker import MaxNLocator
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
import numpy as np
#import pandas as pd
#import sys
#import wa... |
#!/usr/bin/env python2
import re
import pprint
import subprocess
descs = {
"double": "Double",
"galvanic_mock": "Galvanic-mock",
"mock_derive": "Mock_Derive",
"mock_it": "Mock-it",
"mockall": "Mockall",
"mockers": "Mockers",
"mockiato": "Mockiato",
"mocktopus": "Mocktopus",
"pseudo... |
<reponame>Ardavans/sHDP
from __future__ import division
import numpy as np
import abc, os
from nose.plugins.attrib import attr
from ..util import testing
class DistributionTester(object):
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def distribution_class(self):
pass
@abc.abstractprope... |
import logging
from datetime import datetime
from zensols.cli import OneConfPerActionOptionsCliEnv
from zensols.garmdown import (
Manager,
Backuper,
SheetUpdater,
Reporter,
AppConfig,
)
class InfoCli(object):
def __init__(self, config, detail=False, limit=None):
self.mng = Manager(conf... |
<filename>pyccel/ast/omp.py
# coding: utf-8
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. ... |
<gh_stars>1-10
import inspect
import json
from collections import OrderedDict
from pathlib import Path
import random
import pandas as pd
import hashlib
import numpy as np
from scipy.stats.mstats import gmean
import xgboost as xgb
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import Logi... |
import torch.nn as nn
from torch.nn import MultiheadAttention
import torch.nn.functional as F
class TransformerEncoderLayer(nn.Module):
r"""TransformerEncoderLayer is made up of self-attn and feedforward network.
This standard encoder layer is based on the paper "Attention Is All You Need".
<NAME>, <NAME>, <NAME>... |
<filename>ig_bot/tests/test_scraping.py
from unittest import mock
from igramscraper.exception import InstagramException
import pytest
from ig_bot.factories import AccountFactory
from ig_bot.scraping import (
account_by_id,
account_by_username,
exponential_sleep,
followed_accounts,
MaxRateLimitingR... |
import pytest
from platon_env.chain import Chain
from platon_env.base.host import Host
from platon_env.node import Node, NodeOpts
# host = Host('10.10.8.209', 'juzhen', 'Juzhen123!')
# node_id = '35bb5daad814fe902030cba6fd2d3ec60906dab70ba5df4d42a19448d300ab203cfd892c325f6716965dd93d8de2a377a2806c9703b69b68287577c70f... |
import argparse
parser = argparse.ArgumentParser(description='Tune and train a model')
# Use multiprocessing to call get_data in parallel
parser.add_argument('--pool-data-acquisition', '-mpdata', action='store_true')
# Turns out Tensorflow doesn't play well with multiprocessing; for now, phenotypes should only be leng... |
# -*- coding: utf-8 -*- #
import numpy as np
import matplotlib.pyplot as plt
class Neuron():
def __init__(self, x, y, color='k', text=''):
self.x = x
self.y = y
self.color = color
self.text = text
def draw(self, neuron_radius=0.5):
circle = plt.Circle(
(sel... |
<reponame>hkamran80/IpBlacklister
import asyncio
import os
import re
import json
import datetime
import aiohttp
import aiosqlite
from yarl import URL
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
def log(message: str, file="ip_blacklister.log") -> None:
file = os.path.join(PROJECT_ROOT, file)
wit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.