content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import click
from ..cli import with_context
@click.command('test', short_help='Run a suite of tests to validate the correctness of a book')
@with_context
def test_command(ctx=None):
pass
| python |
import random
class StatesPool:
def __init__(self, capacity = 10000000):
self.capacity = capacity
self.pool = []
self.position = 0
def push(self, state):
if len(self.pool) < self.capacity:
self.pool.append(None)
self.pool[self.position] = state
self.... | python |
#!/usr/bin/python3.6
import os
import re
import sys
import yaml
from glob import glob
from collections import OrderedDict
from typing import Any, List
import numpy as np
import pandas as pd
import lightgbm as lgb
from scipy.stats import describe
from tqdm import tqdm
from sklearn.multiclass import OneVsRestClassif... | python |
import abc
import asyncio
import time
from typing import Awaitable, Callable, List, Optional
import multidict
import yarl
from .base import ClosableResponse, EmptyResponse, Header, Request
from .circuit_breaker import CircuitBreaker
from .deadline import Deadline
from .metrics import MetricsProvider
from .priority im... | python |
description = 'Camini Camera Synchronisation Detector'
group = 'lowlevel'
pvprefix = 'SQ:ICON:CAMINI:'
pvprefix_sumi = 'SQ:ICON:sumi:'
pvprefix_ai = 'SQ:ICON:B5ADC:'
includes = ['shutters']
display_order = 90
devices = dict(
cam_shut = device('nicos.devices.epics.EpicsReadable',
epicstimeout = 3.0,
... | python |
# -*- coding: utf-8 -*-
"""
使用Elman网络(简单局部回归网络)
@author: simon
"""
import sys,time
import getopt
import numpy
import theano
import theano.tensor as T
import matplotlib.pyplot as plt
from collections import OrderedDict
import copy
import utilities.datagenerator as DG
reload(DG)
compile_mode = 'FAST_COMPILE'
theano.co... | python |
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except:
from distutils.core import setup
setup(name='sprinter',
version='1.4.2',
description='a utility library to help environment bootstrapping scripts',
long_description=open('README.rst').read(),
author='Yusuke ... | python |
"""
Script for calculating GMM predictive
"""
import numpy as np
from scipy.stats import norm
import copy
import scipy as sp
from sklearn.mixture import GaussianMixture
from sklearn.mixture.gaussian_mixture import _compute_precision_cholesky
import npl.sk_gaussian_mixture as skgm
def lppd(y,pi,mu,sigma,K): #calcul... | python |
from decimal import Decimal
from django.core import exceptions
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from oscar.core.loading import get_model, get_class
Benefit = get_model("offer", "Benefit")
HiddenPo... | python |
"""
Reordering generator for C source code.
This is an ANTLR generated parse tree listener, adapted to
walk a Python parse tree, randomly introduce multi scale reorderings
and regenerate the source code with these reorderings.
"""
import random
from antlr4 import ParseTreeWalker
from antlr4.tree.Tree import TerminalN... | python |
from __future__ import unicode_literals
from mpi4py import MPI
from .adaptive_calibration import calibration_scale_factor_adaptive
from .dip import dip_scale_factor
from .bandwidth import h_crit_scale_factor
def compute_calibration(calibration_file, test, null, alpha, adaptive=True,
lower_la... | python |
import json
from django import template
from django.contrib.gis.db.models import Extent
from django.contrib.gis.db.models.functions import Envelope, Transform
from django.conf import settings
from django.db.models.functions import Coalesce
from django.urls import reverse
from geotrek.zoning.models import District, Ci... | python |
import copy, unittest
from bibliopixel.project import project
from bibliopixel.animation.sequence import Sequence
from bibliopixel.animation import matrix
from bibliopixel.layout.matrix import Matrix
from bibliopixel.project.data_maker import Maker
def classname(c):
return '%s.%s' % c.__module__, c.__name__
cla... | python |
from pdf2image import convert_from_path
import os
import gc
import cv2
import easyocr
import pandas as pd
import Levenshtein as lev
from datetime import datetime
test_template_data = [{'id': 1, 'name': 'JK agency', 'height': 2338, 'width': 1653,
'product_region': ((167, 473), (503, 1650)),
... | python |
from .visualize import *
from .detection import * | python |
"""
CSC110 Final Project - Analysis of Public Sentiment over New Cases
"""
if __name__ == '__main__':
import app
app.run_app()
| python |
r"""
Special extensions of function fields
This module currently implements only constant field extension.
Constant field extensions
-------------------------
EXAMPLES:
Constant field extension of the rational function field over rational numbers::
sage: K.<x> = FunctionField(QQ)
sage: N.<a> = QuadraticFie... | python |
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from notifications.models import Notification
from notifications.serializers import NotificationSerializer
class Notification_ListOwn_ApiView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_clas... | python |
import os, re, json
import torch
import argparse
import pyhocon
import pickle
from nltk import tokenize
EOS_token = '<EOS>'
BOS_token = '<BOS>'
parallel_pattern = re.compile(r'^(.+?)(\t)(.+?)$')
# swbd_align = {
# '<Uninterpretable>': ['%', 'x'],
# '<Statement>': ['sd', 'sv', '^2', 'no', 't3', 't1', 'oo', 'c... | python |
class Solution:
"""
@param arr: a integer array
@return: return ids sum is minimum.
"""
def UniqueIDSum(self, arr):
# write your code here
table = set()
for a in arr:
while a in table:
a += 1
table.add(a)
return sum... | python |
#!/usr/bin/python
import os
import re
import sys
import argparse
parser = argparse.ArgumentParser(description='JS Fixups')
parser.add_argument('file', help="file to process")
args = parser.parse_args()
file = open(args.file)
text = file.read()
pat = 'HEAP32\[(?P<base>.*)+?P<offset>.*)>>?P<shift>.*)\]'
pat = 'HEAP32... | python |
# Copyright (c) 2019,20-22 NVIDIA CORPORATION & AFFILIATES.
# 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
#
# Unles... | python |
# Andrew Boslett
# Rochester Data Science Consortium
# Email: andrew_boslett@urmc.rochester.edu
# Set options
import arcpy
import os
import csv
import sys
# Set up environments
arcpy.env.overwriteOutput = True
box_dir = 'C:/Users/aboslett/Box'
pers_dir = 'C:/Users/aboslett/Documents'
if not arcpy.Exists(os.path.j... | python |
import unittest
import xmlrunner
import secrets
import pagemodels.videopage
import tests.pickledlogin
import browserconfig
# TEST CATEGORIES
# 1.) Pause Tests
# 2.) Mute Tests
# 3.) Volume Tests
# 4.) Full screen Tests
# 5.) Audio&Subtitles Tests
# 6.) Skip_forward/backward Tests
# 7.) Time/Duration Tests
# 8.) Exit ... | python |
from django.contrib import admin
from .models import Project
class ProjectAdmin(admin.ModelAdmin):
fields = ("name", "public_key", "created_at", "updated_at")
readonly_fields = ("public_key", "created_at", "updated_at")
list_display = ("name",)
def has_add_permission(self, request):
return F... | python |
# Generated by Django 3.2.6 on 2021-08-21 09:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('education', '0018_alter_materialblocks_color'),
]
operations = [
migrations.AlterModelOptions(
name='materialblocks',
... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 18:35:42 2018
@author: Chat
"""
import pip
def install(): # Run this to install the matplotlib dependency.
pip.main(['install', 'matplotlib'])
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import praw
import datetime
# Fixing random state ... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: movie_catalogue.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google... | python |
__all__ = ['atmospheric']
from . import atmospheric
| python |
from spaceone.core.service import *
__all__ = ['HelloWorldService']
@authentication_handler
@authorization_handler
@event_handler
class HelloWorldService(BaseService):
@transaction
@check_required(['name'])
def say_hello(self, params):
helloworld_mgr = self.locator.get_manager('HelloWorldManager... | python |
schema = """
CREATE TABLE IF NOT EXISTS ratings (
rating_id INTEGER PRIMARY KEY, name TEXT UNIQUE, league TEXT, year TEXT, home_advantage REAL, r_squared REAL, consistency REAL, games_played INTEGER, games_scheduled INTEGER, description TEXT, finished INTEGER );
CREATE TABLE IF NOT EXISTS teams (
rating_id INTEGER, te... | python |
# coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 1.4.58
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six i... | python |
# Generated by Django 2.0.2 on 2018-04-11 18:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("jbank", "0021_auto_20180209_0935"),
]
operations = [
migrations.AlterField(
model_name="referencepaymentbatch",
name... | python |
import os
import cv2
import time
def convertImg(Path):
# Read in the image
img = cv2.imread(Path)
# Convert the image to grayscale
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Invert the grayscale image
inverted_gray_image = cv2.bitwise_not(gray_image)
# blur the image by gaussia... | python |
import torch
import typing
import numpy as np
from pathlib import Path
from torchvision import datasets
from sklearn import model_selection
from quince.library.datasets import utils
class HCMNIST(datasets.MNIST):
def __init__(
self,
root: str,
gamma_star: float,
split: str = "t... | python |
import curses
import curses.ascii
from sciibo.graphics import colors
from .field import Field
class Selection(Field):
def __init__(self, y, x, items, selected=0, on_select=None):
super(Selection, self).__init__(y, x, 1, self.item_width(items))
self.items = items
self.selected = selected
... | python |
# Docs: https://docs.google.com/document/d/1AVC-4QqkpMBKVUo306-ojkOKmmcJvRSu1AAQjlbxZ7I/edit
def find_max_consecutive_ones(nums) -> int:
counter = 0
max_count = 0
for num in nums: # [1, 1, 0, 1, 1, 1]
if num == 1:
counter += 1 # 3
else:
max_count = counter if counter ... | python |
from lightning import Lightning
from sklearn import datasets
lgn = Lightning()
imgs = datasets.load_sample_images()['images']
lgn.imagepoly(imgs[0]) | python |
from collections import deque
def solution():
data = open(r'inputs\day10.in').readlines()
print('Part 1 result: ' + str(part1(data)))
print('Part 2 result: ' + str(part2(data)))
# number of points for each character for part 1
error_points = {
')': 3,
']': 57,
'}': 1197,
'>': 25137
}
# num... | python |
import numpy as np
from scipy.constants import c,h,eV
def dThetadE(E,Q):
""" Calculates the bragg angle derivative to energy at a certain Q and
photon Energy"""
return (-*c*h*Q/eV)/(4*np.pi*E**2*np.sqrt(1-(c**2*h**2*Q**2)/(16*np.pi**2*E**2*eV**2)))
| python |
from flask import Flask, g, request, session, redirect, url_for ,current_app
from flask_simpleldap import LDAP
from ldap import filter as pyldap_filter
from ldap import LDAPError as pyldap_LDAPError
from ldap import SCOPE_SUBTREE as pyldap_SCOPE_SUBTREE
import sys
#override the get_user_groups() , cause of our openld... | python |
import requests
from app import Server
from automl import openml_utils
import pandas as pd
import ray
@ray.remote
def send_example(model_id, features, label):
# Make a prediction.
request = {"model_id": model_id, "features": features}
response = requests.post("http://localhost:8000/models/predict", json=... | python |
# name=Arturia Keylab mkII DAW (MIDIIN2/MIDIOUT2)
# url=https://github.com/rjuang/flstudio-arturia-keylab-mk2
# receiveFrom=Arturia Keylab mkII (MIDI)
import version
from arturia import ArturiaController
from arturia_processor import ArturiaMidiProcessor
import arturia_midi
import config
import ui
WELCOME_DISPLAY_IN... | python |
class Rectangle():
l = 0
b = 0
def _init_(self, *s):
if not len(s):
self.l = 0
self.b = 0
elif len(s) == 1:
self.l = self.b = s[0]
else:
self.l = s[0]
self.b = s[1]
def area(self):
return self.l * self.b
obj1... | python |
# Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | python |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2018, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | python |
from typing import Any, Dict
from trench.exceptions import MFAMethodDoesNotExistError
from trench.settings import TrenchAPISettings, trench_settings
class GetMFAConfigByNameQuery:
def __init__(self, settings: TrenchAPISettings) -> None:
self._settings = settings
def execute(self, name: str) -> Dict[... | python |
# Generated by Django 3.1.7 on 2021-07-03 12:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("record_requests", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="recordrequest",
name="estimated... | python |
# -*- coding: utf-8 -*-
"""CSES Problem Set Coin Piles.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/10smn6uwgTZ4dTjcUl24YcliEyzzcZ5fw
a,b
x = 2 from a and 1 from b
y = 2 from b and 1 from a
a = 2x + 1y ------------ (i)
b = 2y + 1x --... | python |
# Generated by Django 3.2.5 on 2021-07-14 03:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import participant_profile.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependenc... | python |
import os
c.NotebookApp.ip='0.0.0.0'
c.NotebookApp.port = int(os.getenv('PORT', 8888))
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python3'
c.NotebookApp.notebook_dir = './'
c.Application.log_level = 0
c.NotebookApp.allow_root = True
c.NotebookApp.terminado_settings = { 'shell_comman... | python |
import logging
from typing import List, Optional, Dict
from uuid import UUID
from sqlalchemy.ext.asyncio.session import AsyncSession
from app.domain.models.Arkivuttrekk import ArkivuttrekkStatus
from app.domain.models.BevaringOverforing import BevaringOverforingStatus
from app.domain.models.Arkivuttrekk import Arkivu... | python |
import math
def binary_search(arr, target):
"""
Performs a binary search
- Time complexity: O(log(n))
- Space complexity: O(1)
Args:
arr (list): List of sorted numbers
target (float): Target to find
Returns:
mid (int): Index of the target. Return -1 if not found
""... | python |
from IPython.display import Image
from IPython.core.display import HTML
import numpy as np
import sympy as sp
import random as r
import time
import matplotlib.pyplot as plt
import ipyturtle as turtle
from scipy.ndimage.filters import gaussian_filter1d
from scipy.signal import savgol_filter | python |
"""
Put your ad videos here
""" | python |
"""Defines current AXT versions and dependencies.
Ensure UsageTrackerRegistry is updated accordingly when incrementing version numbers.
"""
# AXT versions
RUNNER_VERSION = "1.3.1-alpha03"
ESPRESSO_VERSION = "3.4.0-alpha03"
CORE_VERSION = "1.3.1-alpha03"
ANDROIDX_JUNIT_VERSION = "1.1.3-alpha03"
ANDROIDX_TRUTH_VERSION ... | python |
import copy
import numpy as np
import logging
import random
from pprint import pformat
from sklearn.metrics import roc_auc_score
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble._gb import GradientBoostingClassifier, GradientBoostingRegressor
import xgboost as xgb
from sett... | python |
from postDB import Column, Model, types
class UserRole(Model):
"""
User Role Class
Database Attributes:
Attributes stored in the `userroles` table.
:param int user_id: The users Discord ID
:param int role_id: The role ID (Snowflake)
"""
user_id = Column(
... | python |
class Charge:
def __init__(self, vehicle):
self.vehicle = vehicle
def start_charging(self):
return self.vehicle.send_command(
'charge_start'
)
def open_charge_port(self):
return self.vehicle.send_command(
'charge_port_door_open'
)
def s... | python |
#
# PySNMP MIB module GDCUAS7626-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GDCUAS7626-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:19:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | python |
#!/usr/bin/env python3
import glob
import os
import plistlib
import re
import shlex
import subprocess
import tempfile
import yaml
# Colours
BOLD = '\033[1m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
ENDC = '\033[0m'
# Open /dev/null
DEVNULL = open(os.devnull, 'w')
def run(command, ... | python |
from django.utils.safestring import mark_safe
from iommi import Fragment
from iommi.asset import Asset
from iommi.style import (
Style,
)
from iommi.style_base import base
from iommi.style_font_awesome_4 import font_awesome_4
navbar_burger_click_js = Fragment(mark_safe("""\
<script>
$(document).ready(function... | python |
from string import Template
from django.db import models
from mozdns.models import MozdnsRecord, LabelDomainMixin
from mozdns.validation import validate_txt_data
import reversion
class TXT(MozdnsRecord, LabelDomainMixin):
"""
>>> TXT(label=label, domain=domain, txt_data=txt_data)
"""
id = models.... | python |
from django.contrib import admin
from userCalendar.models import Locacao, Checkin, Checkout, Limpeza
# Register your models here.
# Registro do model no admin (para serem administrados)
admin.site.register(Locacao)
admin.site.register(Checkin)
admin.site.register(Checkout)
admin.site.register(Limpeza)
| python |
from typing import TypeVar, MutableMapping
import trio
KT = TypeVar('KT')
VT = TypeVar('VT')
class AsyncDictionary(MutableMapping[KT, VT]):
"""MutableMapping with waitable get and pop.
TODO: exception support using outcome package
"""
def __init__(self, *args, **kwargs):
self._store = dic... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools
setuptools.setup(
name = __import__('mp3sum').__name__,
description = __import__('mp3sum').__description__,
url = __import__('mp3sum').__url__,
version = __import__('mp3sum').__version__,
... | python |
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@classmethod
def friend(cls, origin, friend_name, *args, **kwargs):
return cls(friend_name, origin.... | python |
age = 37
name = 'Bob'
gender = 'male'
hobby = 'cycling'
timeofday = 'at night'
typeofbike = 'giant'
country = 'ireland'
sizeofwheels = '700'
print('{} {} {} was {} when he was {}'.format(timeofday,gender,name,hobby,age))
print('the sun is shining in the sky during the day')
print('{} flew to {} then bough... | python |
# Copyright 2016 Huawei Technologies Co. Ltd. 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
#
# Unles... | python |
# -*- config: utf-8 -*-
import sys
import random
import math
import numpy as np
from block import Block
class Stage(object):
def __init__(self):
self.field = (10 + 2, 20 + 2)
self.board = np.zeros((self.field[1], self.field[0]))
self.generate_wall()
self.bl = Block()
self.... | python |
"""
Problem repository management for the shell manager.
"""
import gzip
import logging
from os import makedirs
from os.path import exists, isdir, join
from shutil import copy2
import spur
from shell_manager.util import FatalException
logger = logging.getLogger(__name__)
def update_repo(args, config):
"""
... | python |
"""
Combine results files generated by `attention_networks_testing.py` on separate
GPUs.
"""
type_category_set = input('Category-set type in {diff, sem, sim, size}: ')
version_weights = input('Version number (weights): ')
id_category_set = f'{type_category_set}_v{version_weights}'
import os
import pandas as pd
from .... | python |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | python |
from dataclasses import dataclass
from typing import Iterator
from models.displayable_pull import DisplayablePull
@dataclass
class DisplayablePulls:
pulls: Iterator[DisplayablePull]
limit: int
def for_output(self) -> str:
ready_pulls = list(filter(lambda p: p.ready, self.pulls))
omitted ... | python |
import os
import sys
import urllib.request
import re
import shutil
LATEST_URL = 'https://bitcoin.jonasschnelli.ch/build/nightly/latest'
BUILD_URL = 'https://bitcointools.jonasschnelli.ch/data/builds/{}/{}'
if os.getenv('TRAVIS_OS_NAME') == 'osx':
ARCHIVE_SNIP = '-osx64.tar.gz'
ARCHIVE_RE = 'bitcoin-0\.[0-9]+\.... | python |
from abc import abstractmethod, ABC
class Transformer(ABC):
"""
Abstract class for transformer over data.
"""
def __init__(self):
self.__name__ = self.__class__.__name__
@abstractmethod
def transform(self, x):
"""
Method to transform a text data.
:param x: (Un... | python |
import os
from statistics import mean
import numpy as np
import matplotlib.pyplot as pyplot
from simtk import unit
from simtk.openmm.app.pdbfile import PDBFile
from foldamers.cg_model.cgmodel import CGModel
from foldamers.parameters.reweight import *
from foldamers.ensembles.ens_build import *
from cg_openmm.simulation... | 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 |
# -*- coding: utf-8 -*-
""" ``itur.utils`` is a utilities library for ITU-Rpy.
This utility library for ITU-Rpy contains methods to:
* Load data and build an interpolator object.
* Prepare the input and output arrays, and handle unit transformations.
* Compute distances and elevation angles between two points on Earth... | python |
import scipy
from numpy import *
from scipy.integrate import *
from consts import *
from numpy.random import randint,random,normal,shuffle
from scipy.stats import gaussian_kde
#from pickleutils import *
try:
from astropysics.coords import ICRSCoordinates,GalacticCoordinates,FK5Coordinates
except ImportError:
pa... | python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from botbuilder.core import CardFactory, MessageFactory
from botbuilder.schema import ActionTypes, Activity, CardAction, HeroCard, InputHints
from . import Channel, Choice, ChoiceFactoryOptions
cla... | python |
class DealResult(object):
'''
Details of a deal that has taken place.
'''
def __init__(self):
self.proposer = None
self.proposee = None
self.properties_transferred_to_proposer = []
self.properties_transferred_to_proposee = []
self.cash_transferred_from_proposer_t... | python |
#!/usr/bin/env python3
#
# Copyright 2011-2015 Jeff Bush
#
# 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 l... | python |
import time, pickle
from meta_mb.logger import logger
from meta_mb.workers.base import Worker
class WorkerData(Worker):
def __init__(self, simulation_sleep):
super().__init__()
self.simulation_sleep = simulation_sleep
self.env = None
self.env_sampler = None
self.dynamics_sa... | python |
# encoding: utf-8
"""
Step implementations for paragraph format-related features.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from behave import given, then, when
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.sha... | python |
line_one = "The sky has given over"
line_one_words = line_one.split() | python |
# Copyright 2020 The PyMC Developers
#
# 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 ag... | python |
PANDA_MODELS = dict(
gt_joints='dream-panda-gt_joints--495831',
predict_joints='dream-panda-predict_joints--173472',
)
KUKA_MODELS = dict(
gt_joints='dream-kuka-gt_joints--192228',
predict_joints='dream-kuka-predict_joints--990681',
)
BAXTER_MODELS = dict(
gt_joints='dream-baxter-gt_joints--510055... | python |
from datetime import datetime
import psycopg2
from app.database_config import init_db
from app.api.v2.models.user_models import UsersModel
from app.api.v2.views.authentication import SignIn
def get_timestamp():
return datetime.now().strftime(("%Y-%m-%d %H:%M:%S"))
class IncidentsModel():
""" Docstring for m... | python |
from pathlib import Path
from classy_config import ConfigValue, register_loader
from classy_config.config import register_config
def _stub_loader(filepath: Path) -> dict:
output = {}
with filepath.open() as f:
for line in f.readlines():
key, value = line.split(">")
output[key... | python |
from veem.configuration import ConfigLoader
from veem.client.payment import PaymentClient
from veem.client.requests.payment import PaymentRequest
from veem.client.authentication import AuthenticationClient
if __name__ == '__main__':
# loading SDK configuration from your yaml file
config = ConfigLoader(yaml_f... | python |
# pylint: disable=missing-module-docstring
from setuptools import setup
# The install configuration lies in setup.cfg
setup()
| python |
"""
===========================================
Comparison of F-test and mutual information
===========================================
This example illustrates the differences between univariate F-test statistics
and mutual information.
We consider 3 features x_1, x_2, x_3 distributed uniformly over [0, 1], the
targ... | python |
from .projects_api import ProjectsApi
from .timer_api import TimerApi
from .workspaces_api import WorkspacesApi
from enum import Enum
class TopLevelApis(Enum):
""" Represents all the top level Apis that can be accessed """
projects = ProjectsApi
timer = TimerApi
workspaces = WorkspacesApi | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | python |
import unittest
from threading import Lock
from dummyserver.server import (
TornadoServerThread, SocketServerThread,
DEFAULT_CERTS,
)
# TODO: Change ports to auto-allocated?
class SocketDummyServerTestCase(unittest.TestCase):
"""
A simple socket-based server is created for this class that is good ... | python |
# Copyright 2018 Northwest University
#
# 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 ... | python |
import logging
from rest_framework import decorators, permissions, status
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from readthedocs.builds.constants import LATEST
from readthedocs.builds.models import Version
from readthedocs.projects.models import Project, Projec... | python |
import luigi
from exaslct_src.lib.build_config import build_config
from exaslct_src.lib.stoppable_task import StoppableTask
# This task is needed because ExportContainerTask and SpawnTestContainer
# requires the releases directory which stores the exported container.
# However, we wanted to avoid that SpawnTestContai... | python |
import matplotlib.pyplot as plt
import random
def compare(*args, width=3, height=3, dataset=None) -> None:
"""
Used to compare matplotlib images to eachother.
Args:
*args: All the images given to the function
width: Used to tell the maximum images you want on one row.
dataset(x,y):... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.