content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import pytest
from geonotebook.kernel import Remote
@pytest.fixture
def remote(mocker):
protocols = [{'procedure': 'no_args',
'required': [],
'optional': []},
{'procedure': 'required_only',
'required': [{"key": "a"}, {"key": "b"}],
... | python |
import serial
import time
import datetime
import numpy as np
import csv
from pathlib import Path
import random as random
myFile = Path('BigHouse.csv')
if not myFile.exists():
with open('BigHouse.csv','a', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=';',
quotechar='|', quoting=csv... | python |
import curses
from itertools import islice, izip
from .pad_display_manager import PadDisplayManager
from .rate import get_rate_string
SESSIONS_HEADER = "| Idx | Type | Details | RX Rate | TX Rate | Activity Time "
SESSIONS_BORDER = "+-----+------+-------------... | python |
import binascii
import collections
import datetime
import hashlib
from urllib.parse import quote
from google.oauth2 import service_account
def generate_signed_url(
service_account_file,
bucket_name,
object_name,
expiration,
http_method="GET",
query_parameters=None,
headers=None,
):
es... | python |
import unittest
from number_of_islands.solution import Solution
class TestSolution(unittest.TestCase):
def test_solution(self):
self.assertEqual(0, Solution().num_islands(
None))
self.assertEqual(0, Solution().num_islands(
[[]]))
self.assertEqual(1, Solution().num... | python |
from subprocess import PIPE, run
my_command = "["ipconfig", "/all"]"
result = run(my_command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.stdout, result.stderr)
input("Press Enter to finish...") | python |
import connexion
#app = connexion.FlaskApp(__name__)
app = connexion.AioHttpApp(__name__)
app.add_api("swagger/openapi.yaml")
application = app.app | python |
import time
import board
import displayio
import adafruit_ssd1325
displayio.release_displays()
spi = board.SPI()
oled_cs = board.D5
oled_dc = board.D6
oled_reset = board.D9
display_bus = displayio.FourWire(
spi, command=oled_dc, chip_select=oled_cs, reset=oled_reset, baudrate=1000000
)
time.sleep(... | python |
from yahoofinancials import YahooFinancials
import pandas as pd
import datetime as dt
def get_downloader(start_date,
end_date,
granularity='daily',):
"""returns a downloader closure for oanda
:param start_date: the first day on which dat are downloaded
:param end_date: the la... | python |
# Python script for generatign panda_drv.h from *DRV entries in registers
# configuration file.
from __future__ import print_function
import sys
from parse_indent import parse_register_file
registers = parse_register_file(sys.argv[1])
base, fields = registers['*DRV']
base = int(base)
print('''\
/* Register definit... | python |
import setuptools
setuptools.setup(
name="cinemasci",
version="0.1",
author="David H. Rogers",
author_email="dhr@lanl.gov",
description="Tools for the Cinema scientific toolset.",
url="https://github.com/cinemascience",
packages=["cinemasci",
"cinemasci.cdb",
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 16:34:40 2020
@author: skyjones
"""
import os
import re
import pandas as pd
from glob import glob
import nibabel as nib
import numpy as np
import shutil
out_csv = '/Users/manusdonahue/Documents/Sky/volume_testing/volume_comparisons_fastonly.... | python |
#!/usr/bin/env python
"""
===========
{PROG}
===========
----------------------------------------------------
Compute exponentially weighted moving average
----------------------------------------------------
:Author: skipm@trdlnk.com
:Date: 2013-03-15
:Copyright: TradeLink LLC 2013
:Version: 0.1
:Manual section: 1
... | python |
import os
import sys
import time
import WareHouse
import ConfigLoader
import PythonSheep.IOSheep.PrintFormat as PrintSheep
import PythonSheep.IOSheep.InputFormat as InputSheep
from Commands.HelpDocument import HelpDocument
from Commands.ReloadConfig import ReloadConfig
from Commands.OpenConfig import OpenConfig
# 初... | python |
from movelister.core.context import Context
def reopenCurrentFile():
"""
Reopens current file. All variables made before this will be
invalid. Make sure to initialize them too.
"""
frame = Context.getFrame()
frame.loadComponentFromURL(getUrl(), "_self", 0, ())
def getUrl():
"""
Retur... | python |
#!/usr/bin/env python3
# Copyright 2020 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... | python |
import sys
import os
import redis
from Bio import SeqIO
def main(argv):
# Put stuff in JSON config file
r=redis.Redis()
batch = 1000;
itera = 0
checkID = ""
pipeline=r.pipeline()
handle = open( argv[0], "r")
for record in SeqIO.parse(handle, "fasta") :
pipeline.set( str( record.id ), str( ... | python |
from peewee import CharField, IntegerField
from core.db.db import BaseModel
class Materials(BaseModel):
name = CharField(unique=True)
type_id = IntegerField()
class Meta:
table_name = 'materials'
| python |
from keras import backend
from keras.constraints import Constraint
from keras.initializers import RandomNormal
from keras.layers import Dense, Conv2D, Conv2DTranspose, BatchNormalization, Activation, Reshape, LeakyReLU, \
Dropout, Flatten
from keras.models import Sequential, load_model
from wasserstein import wass... | python |
import events
import io
import json
import os
from executors.python import run as python_run
from executors.workflow import run as workflow_run
from . import utils
from girder_worker.utils import JobStatus, StateTransitionException
from girder_worker import config, PACKAGE_DIR
# Maps task modes to their implementati... | python |
import os
from urllib.parse import urlparse
from boxsdk import OAuth2, Client
from django.conf import settings
from swag_auth.base import BaseSwaggerDownloader, BaseAPIConnector
from swag_auth.oauth2.views import CustomOAuth2Adapter
class BoxAPIConnector(BaseAPIConnector):
def __init__(self, token):
sup... | python |
from typing import List, Optional, Dict, Iterable
from fhirclient.models.codeableconcept import CodeableConcept
from fhirclient.models.encounter import Encounter
import fhirclient.models.patient as fhir_patient
from fhirclient.models.fhirreference import FHIRReference
from transmart_loader.loader_exception import Load... | python |
from datetime import datetime
import django
import factory
from django.utils import timezone
from api.cases.enums import CaseTypeEnum
from api.compliance.enums import ComplianceVisitTypes, ComplianceRiskValues
from api.compliance.models import OpenLicenceReturns, ComplianceSiteCase, CompliancePerson, ComplianceVisitC... | python |
#!/usr/bin/env python3
"""某青空文庫の実験用コード。
参考:
<https://github.com/ozt-ca/tjo.hatenablog.samples/tree/master/r_samples/public_lib/jp/aozora>
<https://tjo.hatenablog.com/entry/2019/05/31/190000>
AP: 0.945
Prec: 0.88742
Rec: 0.86312
実行結果:
```
[INFO ] Accuracy: 0.892 (Error: 0.108)
[INFO ] F1-macro: 0.894
[INFO ] ... | python |
import FWCore.ParameterSet.Config as cms
from SimG4Core.Configuration.SimG4Core_cff import *
g4SimHits.Watchers = cms.VPSet(cms.PSet(
MaterialBudgetVolume = cms.PSet(
lvNames = cms.vstring('BEAM', 'BEAM1', 'BEAM2', 'BEAM3', 'BEAM4', 'Tracker', 'ECAL', 'HCal', 'VCAL', 'MGNT', 'MUON', 'OQUA', 'CALOEC'),
... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2013, David Stygstra <david.stygstra@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_v... | python |
import datetime
import struct
import time
from sakuraio.hardware.commands import CommandMixins, CMD_ERROR_NONE
from sakuraio.hardware.exceptions import CommandError, ParityError
SAKURAIO_SLAVE_ADDR = 0x4f
def calc_parity(values):
parity = 0x00
for value in values:
parity ^= value
return parity
... | python |
from django.apps import AppConfig
class RidersportalAppConfig(AppConfig):
name = 'ridersportal_app'
| python |
#!/usr/bin/env python
import os, imp
def main(args):
if len(args) == 0:
print "Usage: python launch.py [args...]"
return
launch_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"auth_server.py")
auth_server = imp.load_source("auth_server", launch_path)
... | python |
"""Given two dictionaries for weights, find pairs of matching weights"""
import argparse
import io
import pathlib
import sys
import numpy as np
def find_matching_weights(filepath0, filepath1):
dict0 = np.load(io.BytesIO(filepath0.read_bytes()), allow_pickle=True).item()
dict1 = np.load(io.BytesIO(filepath1.r... | python |
prestamo_bolivares = float(input(" prestamo de Bolivares: "))
intereses_pagados = float(input("porcentaje de los intereses pagados: "))
tasa_interes_anual = round(((intereses_pagados * 100) / (prestamo_bolivares * 4)), 10)
print(f"El porcentaje de cobro anual por el prestamo de {prestamo_bolivares:,} Bolivares durant... | python |
import os
from os.path import join
from nip.config import defaults
def get_basename():
return os.path.basename(os.getcwd().rstrip('/'))
def directory_is_empty(target_dir):
if os.path.exists(target_dir):
for _, folders, files in os.walk(target_dir):
return False if (files or folders) els... | python |
# simple script to delete duplicated files based on scene id (NOTE MUST MANUALLY ADJUST
# file_name SLCING DEPENDING ON PRODUCT!!!)
# Author: Arthur Elmes, 2020-02-25
import os, glob, sys
def main(wkdir, product):
print("Deleting duplicates in: " + str(wkdir) + " for product: " + str(product))
if product == ... | python |
"""
Utility functions
"""
import logging
import os
import sys
def get_func(func_name, module_pathname):
"""
Get function from module
:param func_name: function name
:param module_pathname: pathname to module
:return:
"""
if sys.version_info[0] >= 3:
if sys.version_info[1] >= 6:
... | python |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | python |
import dynamixel_sdk as sdk
from typing import Union, Tuple, Any
from enum import Enum
from .connection import Connection
from .register import Instruction, AX, MX
from .util import validate_response
class MotorType(Enum):
AX = 1
MX = 2
class Motor:
def __init__(
self, conn: Connection, id: int... | python |
import sys
import os
import time
import cPickle as pickle
import tensorflow as tf
import numpy as np
import utils.reader as reader
import models.net as net
import utils.evaluation as eva
#for douban
#import utils.douban_evaluation as eva
import bin.train_and_evaluate as train
import bin.test_and_evaluate as test
# ... | python |
# -*- coding: utf-8 -*-
from importlib import import_module
from wsgiref.util import FileWrapper
from django.conf import settings
from django.http import HttpResponse, StreamingHttpResponse
from django.utils.encoding import smart_text, smart_bytes
class DjangoDownloadHttpResponse(StreamingHttpResponse):
... | python |
from ..IPacket import IPacket
from ..DataStructures.GamePoint import GamePoint
class UseItem(IPacket):
"Sent by client to use an item"
def __init__(self):
self.time = 0
self.slotID = 0
self.init = GamePoint(0,0)
self.target = GamePoint(0,0)
self.projectileID = 0
... | python |
import json
import sqlite3
with open('../data_retrieval/acm/acm_paper_doi.json') as data_file:
data = json.load(data_file)
connection = sqlite3.connect('scholarDB.db')
with connection:
cursor = connection.cursor()
count = 0
for row in data:
journal_category = row['journal category']
a... | python |
import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init
from mmedit.models.common import GCAModule
from mmedit.models.registry import COMPONENTS
from ..encoders.resnet_enc import BasicBlock
class BasicBlockDec(BasicBlock):
"""Basic residual block for decoder.
For decoder, we use ConvTranspose2d... | python |
from http import HTTPStatus
from flask import Blueprint, request
from injector import inject
from edu_loan.config.dependencies import Application
from edu_loan.domain.event_flow_service import EventFlowService, EventFlowServiceException
from edu_loan.domain.serializers import SerializerException, EventFlowSerializer... | python |
print('Hello, Word!')
print()
print(1 + 2)
print(7 * 6)
print()
print("The end", "or is it?", "keep watching to learn more about Python 3") | python |
import typing
import pytest
from terraform import schemas, unknowns
@pytest.mark.parametrize(
"schema,value,expected_value",
[
pytest.param(schemas.Block(), None, None, id="empty",),
pytest.param(
schemas.Block(
attributes={
"foo": schemas.Attr... | python |
import os
from setuptools import setup, find_packages
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='... | python |
'''
This file is a part of Test Mile Arjuna
Copyright 2018 Test Mile Software Testing Pvt Ltd
Website: www.TestMile.com
Email: support [at] testmile.com
Creator: Rahul Verma
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 ... | python |
n = int(input("INSIRA O NUMERO DE TERMOS DA PA: "))
pt = int(input("INSIRA O 1° TERMO DA PA: "))
r = int(input("INSIRA A RAZÃO DA PA: "))
print("*"*40)
print("OS TERMOS DA PA SÃO")
calc = pt + ( n - 1 )*r
for i in range(pt, calc+r, r):
print(f'{i}',end='->')
soma = n * (pt + calc) // 2
print()
print(">A SOMA DOS TE... | python |
from typing import Any, Dict
import argparse
import logging
import pathlib
import random
import sys
from pprint import pprint
import pandas as pd
import torch as th
import numpy as np
try:
from icecream import install # noqa
install()
except ImportError: # Graceful fallback if IceCream isn't installed.
... | python |
# pylint: disable=invalid-name,missing-docstring,protected-access
# Generated by Django 2.2.13 on 2020-06-26 20:41
from django.db import migrations
from django.db import models
import leaderboard.models
class Migration(migrations.Migration):
dependencies = [
('leaderboard', '0014_submission_s... | python |
import config
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.optimizers import Adam
from sklearn.preprocessing import LabelBinarizer
import numpy as np
cfg = config.Config... | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Load cookies from FireFox, to be used by Requests etc.
import sqlite3
from sqlite3 import Error
from sys import platform
import os
def _getFireFoxCookieFile(profileName="default"):
"""Locate FireFox cookies.sqlite file. Supply optional profile name"""
ffbasedir = No... | python |
from .utilities import git_status_check, git_commit, relabel_rs, add_rs_msg
import shutil
import click
import os
@click.command("gnote")
@click.argument("label")
@click.option("-m", "--msg", required=True,
help="msg to add to exp")
def cli(label, msg):
"""creates a new mutation from existing experim... | python |
import sys
import os
import re
import unittest
try:
from unittest.mock import patch
except ImportError:
from mock import patch
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import cantools
def remove_date_time(string):
return re.sub(r'.* This file was generated.... | python |
import math
import numpy as np
import matplotlib
matplotlib.use('SVG')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x1 = 2.
x = np.linspace(0, x1, 100)
ax.plot(x, np.exp(x), linewidth=2, label = '$x(t)$')
N = 4
h = x1 / N
sx = np.linspace(0, x1, N + 1)
sy = [(1 + h)**n for n in range(N + 1)]
ax.plot... | python |
import logging
import os
import settings
import data_manager
from policy_learner import PolicyLearner
if __name__ == '__main__':
stock_code = '005930' # 삼성전자
model_ver = '20210526202014'
# 로그 기록
log_dir = os.path.join(settings.BASE_DIR, 'logs/%s' % stock_code)
if not os.path.isdir(log_dir):
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-07-03 17:09
from __future__ import unicode_literals
from django.db import migrations
import waldur_core.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0033_unique_instance_backend_id'),
]
ope... | python |
#!/usr/bin/env python
# coding=utf-8
import argparse
import os
import os.path as op
from Buzznauts.models.baseline.alexnet import load_alexnet
from Buzznauts.utils import set_seed, set_device
from Buzznauts.analysis.baseline import get_activations_and_save
from Buzznauts.analysis.baseline import do_PCA_and_save
def ... | python |
import pytest
from deepdiff import DeepDiff
from stift.parser import Parser, ParserError, ParseTypes
class TestParser:
def test_simple(self):
s = r"""b("a",s[0])"""
parsed = Parser(fmtstr=False).parse(s)
expected = [
[
{
"type": ParseTypes.f... | python |
# -*- coding: utf-8 -*-
import wx.lib.scrolledpanel
import util
import rmodel
import os
import numpy
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import \
NavigationToolbar2WxAgg as ToolBar
from matplotlib.figure import Figure
import rt... | python |
str2score = {
"a" : 1,
"b" : 3,
"c" : 3,
"d" : 2,
"e" : 1,
"f" : 4,
"g" : 2,
"h" : 4,
"i" : 1,
"j" : 8,
"k" : 5,
"l" : 1,
"m" : 3,
"n" : 1,
"o" : 1,
"p" : 3,
"q" : 10,
"r" : 1,
"s" : 1,
"t" : 1,
"u" : 1,
"v" : 4,
"w" : 4,
"x... | python |
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)#Create empty dictionary
def insertEdge(self, v1, v2):
self.graph[v1].append(v2)#Add v2 to list of v1
self.graph[v2].append(v1)#Add v1 to list of v2
def printGraph(self):
... | python |
# Copyright 2020 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, ... | python |
#!/usr/bin/env python
#coding:utf-8
# Author : tuxpy
# Email : q8886888@qq.com.com
# Last modified : 2015-09-08 14:04:23
# Filename : websocket.py
# Description :
from __future__ import unicode_literals, print_function
import base64
import struct
import hashlib
from gale.escape import utf8
from g... | python |
"""Defines all views related to rooms."""
from flask import jsonify
from flask import session
from flask_login import current_user
from flask_socketio import Namespace, emit, join_room
from sqlalchemy import sql
from sqlalchemy.orm.exc import NoResultFound
from authentication.models import User
from base.views import ... | python |
from matplotlib.dates import date2num, num2date
from matplotlib.colors import ListedColormap
from matplotlib import dates as mdates
from matplotlib import pyplot as plt
from matplotlib.patches import Patch
from matplotlib import ticker
from functions.adjust_cases_functions import prepare_cases
from functions.general_u... | python |
from discord.ext import commands
import globvars
from mafia.util import check_if_is_host
class Start(commands.Cog):
"""Contains commands related to starting the game
"""
def __init__(self, bot):
self.bot = bot
@commands.command(
name='start'
)
@commands.check(check_if_is_hos... | python |
# ---------------------------------LogN Solution-------------------------
def logbase2(n):
m = 0
while n > 1:
n >>= 1
m += 1
return m
def CountBits(n):
m = logbase2(n)
if n == 0:
return 0
def nextMSB(n, m):
temp = 1 << m
while n < temp:
te... | python |
from __future__ import absolute_import, division, print_function, unicode_literals
from typing import List, Tuple, Dict
import collections
import json
import logging
import math
import os
import sys
from io import open
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from torch.nn.parameter imp... | python |
import socket
import select
import time
import logging
import string
class controller(object):
def __init__(self,ipaddr):
self.ipaddr=ipaddr
self.reply_message=None
print "init controller"
self.connect()
def connect(self):
netAddr=(self.ipaddr, 4001)
self... | python |
'''demux.py
a simple c-o band demultiplexer
'''
import meep as mp
import meep.adjoint as mpa
import numpy as np
from autograd import numpy as npa
from autograd import tensor_jacobian_product, grad
from matplotlib import pyplot as plt
import nlopt
import argparse
mp.quiet()
# ---------------------------------------- #... | python |
from functools import wraps
import hmac
import hashlib
import time
import warnings
import logging
import requests
logger = logging.getLogger(__name__)
class BitstampError(Exception):
pass
class TransRange(object):
"""
Enum like object used in transaction method to specify time range
from which to g... | python |
"""
Adaptfilt
=========
Adaptive filtering module for Python. For more information please visit
https://github.com/Wramberg/adaptfilt or https://pypi.python.org/pypi/adaptfilt
"""
__version__ = '0.2'
__author__ = "Jesper Wramberg & Mathias Tausen"
__license__ = "MIT"
# Ensure user has numpy
try:
import numpy
excep... | python |
import scipy.io.wavfile;
#Preprocessing the data
#We have all the wavFiles to numpy arrays for us to
#preprocess on multiple computers while we trained
#on the much faster computer at the time
def convertNumpyToWavFile(filename, rate, data):
wavfile.write(filename, rate, data);
| python |
# Copyright (c) 2015-2020 by the parties listed in the AUTHORS file.
# All rights reserved. Use of this source code is governed by
# a BSD-style license that can be found in the LICENSE file.
import sys
import numbers
from collections.abc import MutableMapping, Sequence, Mapping
import numpy as np
class DetDataV... | python |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time : 2021/8/2 11:52
# @Author : NoWords
# @FileName: validators.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_even(value):
"""
偶数验证器
:param value:
:return:
"""
... | python |
from jsonpickle import encode as json_encode
from requests import post as http_post, get as http_get
from Client.Logger import logger
class Shipper(object):
"""
Responsible for sending hardware_objects_lib.Computer objects
to the centralized server which handles these data.
"""
def __init__(self, host, port, ti... | python |
#!/usr/bin/env python
# @Copyright 2007 Kristjan Haule
'''
Classes to handle reading/writing of case.indmf* files.
'''
import operator, os, re
from copy import deepcopy
from scipy import *
from numpy import array, log
import wienfile
from utils import L2str, L2num
qsplit_doc = ''' Qsplit Description
------ ----... | python |
""" Implements distance functions for clustering """
import math
from typing import Dict, List
import requests
from blaze.config.environment import EnvironmentConfig
from blaze.evaluator.simulator import Simulator
from blaze.logger import logger as log
from .types import DistanceFunc
def linear_distance(a: float, ... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-20 15:34
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import F
def draft_title(apps, schema_editor):
Page = apps.get_model('wagtailcore', 'Page')
Page.objects.all().update(draft_title=F(... | python |
import json
import os
import subprocess as sp
from batch.client import Job
from .batch_helper import short_str_build_job
from .build_state import \
Failure, Mergeable, Unknown, NoImage, Building, Buildable, Merged, \
build_state_from_json
from .ci_logging import log
from .constants import BUILD_JOB_TYPE, VERS... | python |
from os.path import isfile
from time import time
import joblib
import numpy as np
import pandas as pd
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score
from tqdm.auto import tqdm
from src.fair_random_forest import Fair... | python |
#!/usr/bin/env python
"""
Kyle McChesney
Ruffus pipeline for all things tophat
"""
# ruffus imports
from ruffus import *
import ruffus.cmdline as cmdline
# custom functions
from tophat_extras import TophatExtras
# system imports
import subprocess, logging, os, re, time
# :) so i never have to touch excel
import p... | python |
__title__ = "playground"
__author__ = "murlux"
__copyright__ = "Copyright 2019, " + __author__
__credits__ = (__author__, )
__license__ = "MIT"
__email__ = "murlux@protonmail.com"
from enum import Enum
"""
This file is used to define state constants for the systems operation.
"""
class State(Enum):
"""
Bot a... | python |
import os
import sys
import pytest
from pipsi import Repo, find_scripts
@pytest.fixture
def repo(home, bin):
return Repo(str(home), str(bin))
@pytest.mark.parametrize('package, glob', [
('grin', 'grin*'),
('pipsi', 'pipsi*'),
])
def test_simple_install(repo, home, bin, package, glob):
assert not hom... | python |
from unittest import TestCase
from moneyed import Money
from pytest import raises
from billing.total import Total, TotalSerializer, TotalIncludingZeroSerializer
class TotalTest(TestCase):
def test_unique_currency(self):
with raises(ValueError):
Total([Money(0, 'USD'), Money(0, 'USD')])
... | python |
import json, os, parse, re, requests, util
import urllib.parse
def parseinfo(text):
items = parse.parse(text)
infos = [i for i in items if i[0] == 'template' and i[1].startswith('Infobox')]
if len(infos) == 0:
return None, None
_, name, data = infos[0]
name = re.sub('^Infobox ', '', name)
return name, data
... | python |
import awkward
import numpy
import numba
import hgg.selections.selection_utils as utils
import hgg.selections.object_selections as object_selections
import hgg.selections.lepton_selections as lepton_selections
import hgg.selections.tau_selections as tau_selections
import hgg.selections.photon_selections as photon_sele... | python |
'''
Created on 14 Sep 2011
@author: samgeen
'''
import EventHandler as Events
from OpenGL.GLUT import *
# TODO: Can we have circular imports? How does that work? Works fine in C++!
# We really need this in case we have more than one camera.
# Plus firing everything through the event handler is tiring
#from Camera imp... | python |
import os
import socket
import time
from colorama import Fore, Back, Style
def argument(arg):
switcher = {
1: "-A -sC -sV -vvv -oN Output/nmap", #Os scanning,Version detection,scripts,traceroute
2: "-O -V -oN Output/nmap", #OS Detection ,Version scanning
3: "-F --open -Pn -oN Output/nmap",... | python |
class Solution:
def average(self, salary) -> float:
salary.sort()
average = 0
for i in range(1, len(salary)-1):
average += salary[i]
return float(average/(len(salary)-2))
| python |
# Simple and powerful tagging for Python objects.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: March 11, 2018
# URL: https://github.com/xolox/python-gentag
"""Simple and powerful tagging for Python objects."""
# Standard library modules.
import collections
import re
# External dependencies.
from h... | python |
class MediaAluno:
notas = []
def add_notas(self, nota):
self.notas.append(nota)
def calcula_notas(self):
soma = 0
for x in self.notas:
soma += x
media = (soma / len(self.notas))
return media
# def soma(self):
# return sum(self.notas)
if __name... | python |
#!/bin/env python
###################################################################
# Genie - XR - XE - Cli - Yang
###################################################################
import time
import logging
# Needed for aetest script
from ats import aetest
from ats.utils.objects import R
from ats.datastructures.... | python |
import http
import logging
import sys
import time
from collections import abc
from copy import copy
from os import getpid
import click
TRACE_LOG_LEVEL = 5
class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a l... | python |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import common
import time
from common import TestDriver
from common import IntegrationTest
from decorators import NotAndroid
from decorators import ChromeVer... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 19-1-19
def check(array: list, middle):
c = 0
for i in range(middle, len(array)):
if array[i] != array[middle]:
break
c += 1
for i in range(middle, -1, -1):
if array[i] != array[middle]:
break
... | python |
from unittest import TestCase
from django.http.request import MediaType
from simple_django_api.request import Request as HttpRequest
class MediaTypeTests(TestCase):
def test_empty(self):
for empty_media_type in (None, ''):
with self.subTest(media_type=empty_media_type):
media_... | python |
from .main import run | python |
from os.path import abspath
from os.path import dirname
with open('{}/version.txt'.format(dirname(__file__))) as version_file:
__version__ = version_file.read().strip()
| python |
import time, numpy, pytest
from rpxdock import Timer
def test_timer():
with Timer() as timer:
time.sleep(0.02)
timer.checkpoint('foo')
time.sleep(0.06)
timer.checkpoint('bar')
time.sleep(0.04)
timer.checkpoint('baz')
times = timer.report_dict()
assert numpy.allclose(times[... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.