content stringlengths 5 1.05M |
|---|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
# @file
# @author Neil Vaytet
import numpy as np
import scipp as sc
import scipp._utils as su
def test_label_var_with_unit():
var = sc.Variable(['x'], values=np.random.random(10), unit=sc.units.m)
asser... |
"""
Main file to launch training and testing experiments.
"""
import yaml
import os
import argparse
import numpy as np
import torch
from config.project_config import Config as cfg
from train import train_net
from export import export_predictions, export_homograpy_adaptation
# Pytorch configurations
torch.cuda.empty... |
import threading
import cv2
from config_utils.ConfigManager import *
from app_utils.functions import move_mouse, mouse_click, mute, play, next_track, vol_up, vol_down
from img_utils.imgprocessor import ImageProcessor
ALGO_SIMPLE = 0
ALGO_ADV = 1
debug_display = True
# model goes to model/output_graph.pb
# labels ... |
#
# Copyright (c) 2009-2016, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El
m = 2000
n = 4000
k = 3000
testMehrotra = Tru... |
import logging
from huobi import SubscriptionClient
from huobi.model import *
from huobi.base.printobject import PrintMix, PrintBasic
logger = logging.getLogger("huobi-client")
logger.setLevel(level=logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(level... |
import torch
import ubelt as ub
class RandomDataset(torch.utils.data.Dataset):
"""
A torch dataset
Simple black-on-white and white-on-black images.
Example:
RandomDataset(modes=5)[0]
"""
def __init__(self, num=10, shape=(3, 32, 32), modes=None):
self.num = num
self.s... |
import os
import sys
import time
from tkinter import *
from tkinter import font
class StopWatch:
def __init__(self):
self.start_time = self.elapsed_time = 0.0
self.has_started = False
self.master = Tk()
self.master.withdraw()
self.master.title('StopWatch')
self.mas... |
from abc import abstractmethod
from hklearn_genetic.utils import ProblemUtils
from hklearn_genetic.Evaluators.IEvaluator import IEvaluator
from pymop.factory import get_problem
import numpy as np
class BaseRastrigin(IEvaluator):
def __init__(self, rank : float = 100., dim = 2):
self.rank = rank
se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
### Set up Django path
import sys, os
projectpath = os.path.abspath('../../')
if projectpath not in sys.path:
sys.path.append(projectpath)
sys.path.append(os.path.join(projectpath, 'democratica/'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'democratica.settings'
from... |
"""Provides facilities for computing statistical and systematic uncertainties.
"""
# System imports
from uuid import uuid4
from math import sqrt
# Six imports
from six.moves import range
# ROOT imports
from ROOT import TH1, TGraphAsymmErrors
# owls-hep imports
from owls_hep.calculation import HigherOrderCalculatio... |
import json
from unittest import TestCase
from pbx_gs_python_utils.utils.Dev import Dev
from pbx_gs_python_utils.utils.Files import Files
from pbx_gs_python_utils.utils.Misc import Misc
from pbx_gs_python_utils.utils.Zip_Folder import Zip_Folder
class Test_Zip_Folder(TestCase):
def test__using_with__no_params(s... |
#!/usr/bin/env python
import time
import struct
from sys import exit
try:
import requests
except ImportError:
exit("This script requires the requests module\nInstall with: sudo pip install requests")
# import blinkt
from rainbowhat import rainbow as blinkt
blinkt.set_clear_on_exit()
def hex_to_rgb(col_hex... |
import os
import sys
import logging
import argparse
from Tkinter import (
Tk,
Button,
Canvas,
Scrollbar,
VERTICAL,
HORIZONTAL,
RIGHT,
LEFT,
TOP,
BOTTOM,
BOTH,
Y,
X,
N, S, E, W,
TclError,
Menu,
)
import tkFileDialog
from ttk import (
Frame,
Style,... |
import collections
import typing
from pathlib import Path
import yaml
def get_all_texts_from_file(path: Path) -> typing.Dict[str, str]:
with Path.open(
path,
mode="r",
encoding="utf-8",
) as f:
return yaml.load(f, yaml.SafeLoader)
def get_language(language_code: typing.Optio... |
def flip_case(phrase, to_swap):
"""Flip [to_swap] case each time it appears in phrase.
>>> flip_case('Aaaahhh', 'a')
'aAAAhhh'
>>> flip_case('Aaaahhh', 'A')
'aAAAhhh'
>>> flip_case('Aaaahhh', 'h')
'AaaaHHH'
"""
# Flipping capital functionality:
new_s... |
"""
an example of a simple bomb
"""
from glitterbomb import GlitterBomb
bomb = GlitterBomb(name="simple")
secret_number = 5
bomb.print("The bomb has a knob.")
decision = bomb.prompt("Do you turn the knob? (yes/no): ")
if decision == "yes":
secret_number += 3
elif decision == "no":
secret_number -= 3
else:
... |
from django.shortcuts import render
from shop.models import products,Order
from django.core.paginator import Paginator
# Create your views here.
def index(request):
""" search """
product_objects = products.objects.all()
item_name = request.GET.get('item_name')
if item_name != '' and item_name is not... |
"""Plot radial distribution function
"""
from particle.particle_system import ParticleSystem, read_particle_sys
from particle.particle_spec_catalog import read_particle_spec_catalog
from simulation.trajectory import Trajectory
from analysis.gr import Gr
import sys
import numpy as np
import matplotlib.pyplot as plt
im... |
# -*- coding: iso-8859-1 -*-
# Maintainer: joaander
from hoomd import *
from hoomd import md
context.initialize()
import unittest
import os
def create_empty(**kwargs):
snap = data.make_snapshot(**kwargs);
return init.read_snapshot(snap);
# test the constrain.sphere command
class constraint_sphere_tests (unit... |
class Robotagent(object):
def __init__(self, specs, initialState, initialInput, controllerPID):
self.t = 0
self.dt = 1
self.mass = specs["mass"]
# State
self.Xposition = initialState[0]
self.Yposition = initialState[1]
# Control Variable
... |
import numpy as np
import cv2
import time
cam=cv2.VideoCapture('testcasem4.mp4')
ret=True
tk=0
while ret:
try:
ret,frame=cam.read()
retval, threshold = cv2.threshold(frame, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imshow... |
# Generated by Django 3.0.7 on 2020-06-16 02:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('shops', '0002_auto_20200616_0048'),
]
operations = [
migrations.CreateModel(
... |
from __future__ import division
import os
import sys
import array
import numpy as np
from . import Tools
####### Check for h5py to Read AMR data ######
try:
import h5py as h5
hasH5 = True
except ImportError:
hasH5 = False
class pload(object):
def __init__(self, ns, w_dir=None, datatype=None, level = 0,... |
import numpy as np
import itertools
s = '''3
10000 3000 -5000
-2000 4000 10000'''
(a,b) = (b for b in s.split('\n')[1:])
(a,b) = ([int(i) for i in a.split()], [int(i) for i in b.split()])
a = np.array(a)
b = np.array(b)
# for i in range(300):
# a = np.append(a,a)
# b = np.append(b,b)
# print(a... |
from sqlalchemy import Column, Integer, String, Index
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
import random
Base = declarative_base()
class MarkovEntry(Base):
__tablename__ = 'markov'
id = Column(Integer, prim... |
# Dynamic Programming solution for Fibonacci numbers
#######################
# #
# Recursive solution #
# #
#######################
def fib(num):
if num < 2:
return num
cache = [-1 for _ in range(num + 1)]
cache[0] = 0
cache[1] = 1
r... |
import numpy as np
from scipy.integrate import solve_ivp
# from functools import partial
# from .Ten_Tusscher_2004 import computeRates_with_activation as \
# tt_computeRates_with_activation
# from .Ten_Tusscher_2004 import initConsts_with_adjustments as \
# tt_initConsts_with_adjustments
# from .Ten_Tusscher_2004 imp... |
from flask import Flask, render_template,url_for,request
app = Flask(__name__)
@app.route('/')
def profile():
return "We can not only write strings in this flask program but can also integrate various programs in it"
@app.route('/login')
def login():
return render_template('Login.html')
@app.route('/login/p... |
from muzero.environment.action import Action
from muzero.environment.player import Player
from muzero.mcts.node import Node
from gym import core
from typing import List
import numpy as np
import tensorflow as tf
class Game:
"""
A single episode of interaction with the environment.
"""
def __init__(self, environ... |
from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
from .models import DimSumItem
from .forms import AddItemForm, RawItemForm
def dimsum_detail_view(request):
queryset = DimSumItem.objects.all()
return render(request, "dim_sum/detail.html", {'items': queryset})
... |
from __future__ import division
import collections
import numpy
import nltk
from nltk.util import ngrams
from metrics.utils import stemmer, tokenizer, stopset, normalize_word
from scipy import spatial
import six
###################################################
# Pre-Processing
###################################... |
class GetShape:
"""
Transform used to inspect the data in the data dictionary. This transform prints the shape of the data contained
in the specified fields of the data dictionary.
.. code-block:: python
from eisen.transforms import GetShape
tform = GetShape(['image', 'label'])
... |
import numpy as np
import pandas as pd
# import pyreadstat
# import pyreadr
from sklearn.preprocessing import Normalizer, MinMaxScaler
class TelecomHelper:
def __init__(self):
pass
def read_csv(self, data, missing_values=[]):
try:
if data.endswith('.csv'):
df = pd.read_csv(data)
... |
from discord.ext import commands
import asyncio
import discord
class Mod(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.guild_only()
@commands.has_guild_permissions(kick_members=True)
async def kick(self, ctx, member_id, *, reason=None):
if not ctx.guild.me.guild_permis... |
import json
import pytest
from django.conf import settings
from model_mommy import mommy
@pytest.fixture
def award_data_fixture(db):
mommy.make("awards.TransactionNormalized", id=1, award_id=1, action_date="2010-10-01", is_fpds=True, type="A")
mommy.make(
"awards.TransactionFPDS",
transaction... |
import os
from dotenv import load_dotenv
from pika import BlockingConnection, ConnectionParameters
load_dotenv()
class DeliveryMan:
def __init__(self):
self._connection = BlockingConnection(ConnectionParameters(os.environ.get('RABBIT_MQ_ADD')))
self._channel = self._connection.channel()
se... |
print('='*10, 'Desafio 30', '='*10)
numero = int(input('Digite um numero qualquer: '))
resultado = numero % 2
if resultado == 0:
print('O número é par.')
else:
print('O numeró é ímpar.')
print('='*10, 'Desafio 30', '='*10)
|
"""
Tasks to perform on identities, options are
EnforceCompliance (deletes on flag true or reports on non compliant RGs)
DeleteGroups (deletes specified groups from specified sub)
"groupCompliance" : {
"taskOutputDirectory" : "./logs/group_compliance",
"availableTasks" : {
"EnforceCom... |
import copy
import os
import shutil
import uuid
from django.conf import settings
from faker import Faker
fake = Faker()
MOCK_AUTHORIZATION_CODE = "mock"
MOCK_EMAIL = fake.email()
MOCK_ORIGIN_URL = "http://an-origin-url"
MOCK_GRANTS = [{"title": "Grant1", "funder_id": "12345"}, {"title": "Grant2", "funder_id": "5678... |
""" Contains GUI elements to adjust and leverage the imported objects. """
|
import RPi.GPIO as GPIO
import time
# refer to pins by the Broadcom SOC channel
GPIO.setmode(GPIO.BCM)
# Pin 19 will sense for button pushing
button = 19
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# The LED
led = 21
GPIO.setup(led, GPIO.OUT)
while True:
input_state = GPIO.input(button) # sense the bu... |
from django.utils.translation import ugettext_lazy as _
def generate_menu(request):
language = request.LANGUAGE_CODE
return {'menu': [
{'url': '/%s/about/' % language, 'name': _('about')},
{'url': '/%s/calendar/' % language, 'name': _('calendar')},
{'url': 'http://www.flickr.com/phot... |
'''
Hard-coded Gestures to test integration of
LEDs and Motors.
'''
import pexpect
import time
NL = '\n'
print ('Press Ctrl-C to quit.')
led = pexpect.spawn('sudo PYTHONPATH=".build/lib.linux-armv6l-2.7" python LEDLogic.py')
print "initializing LEDs."
time.sleep(5)
print "initializing LEDs done."
while True:
pr... |
"""
BNGL Import
------------
This module provides all necessary functionality to import a model specified
in the :term:`BNGL` format.
"""
from pysb.importers.bngl import model_from_bngl
from .pysb_import import pysb2amici
def bngl2amici(bngl_model: str, *args, **kwargs) -> None:
r"""
Generate AMICI C++ fil... |
import pytest
from stellar_sdk.account import Thresholds
from stellar_sdk.asset import Asset
from stellar_sdk.call_builder import FeeStatsCallBuilder
from stellar_sdk.call_builder.accounts_call_builder import AccountsCallBuilder
from stellar_sdk.call_builder.assets_call_builder import AssetsCallBuilder
from stellar_sd... |
#!/usr/bin/env python
# IMPORT
import argparse
import os
# PARSERS ENUM
PARSERS_ENUM = {
'SETUP': 'setup',
'TASKS': 'tasks',
'FOO_BAR': 'foo_bar',
}
# DEBME PARSER
parser = argparse.ArgumentParser(
prog='debme',
description='''debme is an app used to deploy a fully configured debian environment
... |
"""
Copyright 2013 Rackspace
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
dist... |
import numpy as np
import scipy
import scipy.sparse.linalg
from scipy.sparse.linalg import ArpackNoConvergence, ArpackError
import time
# local package imports
from SamplingPattern import SamplingPattern
from defaults import base_sz
from utils import ft, ift, ft2, ift2
from PatternEvaluator import PatternEvaluator
... |
def mutate_string(string, position, character):
# method_#1
#str_list = list( string )
#str_list[position] = character
#str_modified = ''.join(str_list)
str_modified = mutate_string_method2( string, position, character)
return str_modified
# method_#2
def mutate_string_method2(string, p... |
from colorama import Fore, Style, init; init()
from threading import Thread, Lock
import os, requests, time
lock = Lock()
def Printer(color, past, text, proxy):
lock.acquire()
print(f'{Fore.LIGHTWHITE_EX}[{color}{past}{Fore.LIGHTWHITE_EX}] {text} ~ {proxy.split("://")[1]}.')
lock.release()
class MrHook:
... |
import pytest
from django.test import TestCase
from organisations.models import Organisation
from projects.models import Project
from projects.tags.models import Tag
@pytest.mark.django_db
class TagsTestCase(TestCase):
def setUp(self) -> None:
self.organisation = Organisation.objects.create(name="Test Or... |
from django.contrib import admin
from .models import Blog, Like
admin.site.register(Blog)
admin.site.register(Like)
|
# -*- coding: utf-8 -*-
import os
from jinja2 import nodes
from jinja2.ext import Extension
from jac.base import Compressor
from jac.compat import u
class CompressorExtension(Extension):
tags = set(['compress'])
def __init__(self, *args, **kwargs):
super(CompressorExtension, self).__init__(*args, ... |
# -*- coding: utf-8 -*-
__author__ = """Larissa Triess"""
__email__ = "larissa@triess.eu"
import numpy as np
label_names = [
[0, "unlabeled"],
[1, "outlier"],
[10, "car"],
[11, "bicycle"],
[13, "bus"],
[15, "motorcycle"],
[16, "on-rails"],
[18, "truck"],
[20, "other-vehicle"],
... |
from direct.gui.DirectGui import DirectButton, DirectLabel, DGG
from direct.task.Task import Task
from toontown.toon import ToonDNA
from toontown.toonbase import ToontownGlobals, TTLocalizer, ToontownTimer
import GloveNPCGlobals, time
class GloveShopGui:
def __init__(self):
self.index = 0
self.id ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import unittest
import mock
import postdoc
# Just a reminder to myself that if I set DATABASE_URL, it will mess up the
# test suite
if 'DATABASE_URL' in os.environ:
exit('Re-run tests in an environment without DATABASE_URL')
class Conne... |
import gym
import random
import numpy as np
class ReplayMemory:
def __init__(self, size, batch_size, frame_history=4):
super(ReplayMemory, self).__init__()
self.size = size
self.batch_size = batch_size
self.frame_history = frame_history
self.memory = []
self.pos = 0... |
# to test udp communication between client and server
# sending
import socket
UDP_IP = "192.168.1.238"
UDP_PORT = 5005
MESSAGE = "TRUE"
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
# receiving
# import socket
# UDP_I... |
"""https://open.kattis.com/problems/cold"""
def main():
n = int(input())
temps = list(map(float, input().split()))
count = 0
for t in temps:
if t < 0:
count += 1
print(count)
if __name__ == '__main__':
main() |
#
# 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 copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
# Generated by Django 3.2.6 on 2022-01-03 14:34
from django.db import migrations, models
import django.db.migrations.operations.special
def populate_name(apps, schema_editor):
"""
Populate the name field for all existing scratches
"""
Scratch = apps.get_model("coreapp", "Scratch")
for row in Scrat... |
from mugen import MusicVideoGenerator
from tests import DATA_PATH
def test_music_video_generator__creates_music_video(shinsekai_source):
generator = MusicVideoGenerator(audio_file=f'{DATA_PATH}/audio/soft.mp3', video_sources=[shinsekai_source])
music_video = generator.generate_from_events(generator.audio.bea... |
from pyvisdk.esxcli.executer import execute_soap
from pyvisdk.esxcli.base import Base
class IscsiAdapterDiscoveryStatictarget(Base):
'''
Operations that can be performed on iSCSI statictarget discovery
'''
moid = 'ha-cli-handler-iscsi-adapter-discovery-statictarget'
def add(self, adapter, address,... |
#!/usr/bin/env python
import lsb_release
import subprocess
import sys
required_ubuntu_version = "16.04.2"
def isSortVsupported():
command = 'echo -e "1.1.1\n1.1.2" | sort -V'
ps = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = ps.communicate()
if len(ou... |
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models... |
from semquery import SemEHRES
import utils
import json
def get_doc_by_id(p, doc_id):
for d in p['articles']:
if d['erpid'] == doc_id:
return d['fulltext']
return None
def retrieve_doc_by_id(doc_id, es, index_name='epr_documents', full_text_field='body_analysed'):
d = es.get_doc_detai... |
#!/usr/bin/env python
"""A single file that holds all vmchecker relative-path info"""
import os
class VmcheckerPaths:
"""A class that encompases all the paths inside a vmchecker
instalation"""
def __init__(self, root):
"""Create a vmchecker paths object.
Accepts only one argument
... |
import os
from cfn_custom_resource import CloudFormationCustomResource
from _metadata import CUSTOM_RESOURCE_NAME
REGION = os.environ['AWS_REGION']
def split_resource_id(resource_id):
parts = resource_id.split('/')
user_pool_id = '/'.join(parts[0:-1])
provider_name = parts[-1]
return user_pool_id,... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
import seq2seq.data.config as config
import pack_utils._C as C
class Revert_varlen(torch.autograd.Functio... |
'''Create a Thread using sub class or we can say by extending the 'Thread' class'''
from threading import Thread
class MyThread(Thread):
def run(self):
i = 0
while i <= 10:
print(i)
i += 1
t = MyThread()
t.start() |
from grid import Grid
import numpy as np
rewards = np.array([
[-1, -1, -1, 40],
[-1, -1, -10, -10],
[-1, -1, -1, -1],
[10, -2, -1, -1]
])
terminal_states = [(0, 3), (3, 0)]
gamma = 0.9
grid = Grid(rewards, terminal_states, gamma)
grid.run(10, verbose=True)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Time: O(n + m)
# Space: O(1)
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
def length(head):
if not head:
... |
# MIT License
#
# Copyright (c) 2020 University of Oxford
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify... |
# -*- coding: utf-8 -*-
"""
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
import awsecommerceservice.models.bin
class SearchBinSet(object):
"""Implementation of the 'SearchBinSet' model.
TODO: type model description here.
Attributes:
... |
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
import cv2
from gym.envs.classic_control import CartPoleEnv
class HeadlessCartPoleEnv(CartPoleEnv):
def _rotate(self, point, rad):
x, y = point
x_ = math.cos(rad) * x - math.sin(rad) * y
... |
"""
The Ball class.
"""
import tkinter as tk
import random;
class Ball:
ballCollide = False;
def __init__(this, canvas, x=0, y=0):
this.x = x; this.y = y;
s=[-1,1];
random.shuffle(s); this.xdir = s[0]*0.175;
random.shuffle(s); this.ydir = s[0]*0.175;
this._canvas = canvas;
this.obj = canvas... |
from django.db import models
from django.utils.html import mark_safe, format_html_join
from django.utils.functional import cached_property
import json
from jsonfield.fields import JSONField
from cms.models import CMSPlugin
from cms.plugin_pool import plugin_pool
from cms.utils.placeholder import get_placeholder_conf
... |
from .app import *
from .blueprint import *
from .config import SnowDDLConfig
from .engine import SnowDDLEngine
from .formatter import SnowDDLFormatter
from .settings import SnowDDLSettings
from .error import SnowDDLExecuteError, SnowDDLUnsupportedError
from .parser import *
from .resolver import *
from .version import... |
# Generated by Django 2.2.2 on 2019-06-08 08:16
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webhooks', '0003_message_topic'),
]
operations = [
migrations.AddField(
model_name='topic'... |
from flask.ext.wtf import Form
from flask.ext.uploads import *
from wtforms import TextField, RadioField, DateField, FileField, PasswordField
from wtforms.validators import DataRequired, Required, InputRequired
from wtforms import validators
from flask_wtf.file import FileField, FileAllowed, FileRequired
class Signup... |
"""
Classification per condition with probability average across tasks.
"""
import numpy as np
from pylab import plt
from pyriemann.tangentspace import TangentSpace
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.cross_validation import LeaveOneL... |
__version__ = "0.3.1"
from .sklearn import BertClassifier
from .sklearn import BertTokenClassifier
from .sklearn import BertRegressor
from .sklearn import load_model
from .sklearn import SUPPORTED_MODELS
from .utils import OnlinePearson, OnlineF1
|
"""Utilities for use in templates.
The jsfunc method replaces - with _ to allow for proper java script
function names.
"""
|
import turtle # import turtle library
import time
import sys
import collections
blockSize = 24
class Coin(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("yellow")
self.penup()
self.speed(0)
... |
#!/usr/bin/env python
"""
_StageOutError_
General Exception class for JC modules
"""
import inspect
import sys
from WMCore.WMException import WMException
ErrorDefinitions = {
60311 : "GeneralStageOutFailure",
60315 : "StageOutInitError",
}
class StageOutError(WMException):
"""
_StageOutErr... |
from math import ceil
import numpy as np
from .food import Food
class Environement(object):
"""The Environement class where the blob are evolving"""
def __init__(self, h, w, *args):
self.h = h # dementions of the environement
self.w = w #
self.food_board = np.empty((h,w), dtype=Food) # matrixs where the food i... |
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django.http import JsonResponse, HttpResponse
from django.contrib import messages
from accounts.models import Userinfo, PhoneVerification
from django.contrib.auth.models import User # auth_user
from allaut... |
from hpctool import ComsolMPIWorker, MPISolver
from Comsol2dAcoustics import *
if __name__ == '__main__':
model = SquaresModel()
myWorker = ComsolMPIWorker(model, file_path,
mph_options={'classkit': True},
client_kwargs={'cores': 1,
... |
from bleson.core.types import Device, Advertisement, BDAddress
from bleson.interfaces.adapter import Adapter
import threading
# These are the same, just to keep the dual adapter test happy, for now.
FAKE_DEVICE_ADDR = 'b1:eb:1e:b1:eb:1e'
FAKE_ADV_ADDR = FAKE_DEVICE_ADDR
class BluetoothAdapter(Adapter):
def __in... |
'''
Verify correct field and URL verification behavior
for not and nocase modifiers.
'''
# @file
#
# Copyright 2021, Verizon Media
# SPDX-License-Identifier: Apache-2.0
#
Test.Summary = '''
Verify correct field and URL verification behavior for
equals, absent, present, contains, prefix, and suffix
with not, nocase, a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to convert plain text wikipedia documents to conll format.
The documents are processed using as labels the entites in urls_dir.
"""
from __future__ import unicode_literals, print_function
import argparse
import cPickle as pickle
import os
import sys
from bs4 im... |
import ast
from collections import defaultdict
from typing import ClassVar, DefaultDict, List, Mapping, Sequence, Type, Union
from typing_extensions import final
from wemake_python_styleguide.compat.aliases import AssignNodes
from wemake_python_styleguide.compat.functions import get_assign_targets
from wemake_python_... |
import unittest
import envi.memory
class Memory(unittest.TestCase):
def setUp(self):
self.mem = envi.memory.MemoryObject()
def test_getMaxReadSize(self):
mmaps = [(0, envi.memory.MM_READ, None, 0x1000 * b'\x41'),
(0x1000, envi.memory.MM_READ, None, 0x500 * b'\x42'),
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 25 12:07:48 2018
@author: liukang
"""
from sklearn.linear_model import LogisticRegression
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
import warnings
warnings.filterwarnings('ignore')
result_total=pd.DataFrame()
#target subgroup
dise... |
"""Hermes MQTT server for Rhasspy ASR using Mozilla's DeepSpeech"""
import gzip
import logging
import threading
import typing
from dataclasses import dataclass, field
from pathlib import Path
from queue import Queue
import networkx as nx
import rhasspyasr_deepspeech
from rhasspyasr import Transcriber, Transcription
fr... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import numbers, math
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
# from PyTorch
def _get_inverse_affine_matrix(center, angle, translate, scale, shear):
# Helper method to compute inverse matrix for affine transformation
... |
from setuptools import setup
import os
def get_version(path):
fn = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
path, "__init__.py")
with open(fn) as f:
for line in f:
if '__version__' in line:
parts = line.split("=")
return part... |
#!/usr/bin/env python
import socket
import urllib.parse
from datetime import datetime
import requests
import requests.exceptions as reqexc
import sqlalchemy.exc as sqlexc
from tsa import stdoutn
from tsa.lib import html
from tsa.models import Endpoint, create_session
from tsa import logging
logger = logging.getLogger... |
# Copyright 2017-2019 Mateusz Klos
#
# 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... |
# -*- coding: utf-8 -*-
"""
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
>>> os.chdir(datadir)
"""
from __future__ import print_functi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.