content stringlengths 5 1.05M |
|---|
from django.db import models
# Create your models here.
class Language:
ENGLISH = 'en'
CHINESE = 'zh'
# TRANSMISSION: Automatic,MANUAL,other
LANGUAGES = (
(ENGLISH, 'English'),
(CHINESE, 'Chinese'),
)
class Page(models.Model):
title = models.CharField(max_length... |
from ... pyaz_utils import _call_az
def list(lab_name, resource_group, expand=None, filter=None, orderby=None, top=None):
'''
Required Parameters:
- lab_name -- The name of the lab.
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults grou... |
from collections import namedtuple
Weather = namedtuple('Weather', 'time,weather_code,weather_desc,weather_icon,' + \
'cur_temperature,min_temperature,max_temperature,' + \
'humidity,air_quality,air_quality_icon') |
import scipy.io
from scipy.io import loadmat, savemat
import itertools
import numpy as np
import math
from math import pow, sqrt
import argparse
from copy import deepcopy
def Fitting_Texture(tex_Cp, confidence_alpha, tex_B, tex_U):
Confidence_a = []
for i in range(0,len(confidence_alpha)):
Confidence_a.append(co... |
__version__ = "0.36.7"
from .api import *
|
from django.urls import path
from main import views
urlpatterns = [
path('home/', views.homepage, name='home'),
path('items/', views.itemspage, name='items'),
path('login/', views.loginpage, name='login'),
path('logout/', views.logoutpage, name='logout'),
path('register/', views.registerpage, name=... |
#!/usr/bin/env python
from blinkylib import blinkytape, blinkycolor
from blinkylib.patterns import streak
import time
bt = blinkytape.BlinkyTape('/dev/tty.usbmodem1421')
pattern = streak.Streak(bt, blinkycolor.ORANGE, 20)
pattern.setup()
while pattern.animated:
pattern.animate()
time.sleep(pattern.timebase_s... |
from datetime import datetime
from typing import List
from pydantic import BaseModel, validator
from app.auth.schemas import UserPublic
from app.categories.schemas import GetCategory
from app.schemas import Paginate, Votes
class VideoBase(BaseModel):
""" Video base """
title: str
description: str
cla... |
from PyQt5.QtWidgets import QApplication
from .Vista_lista_actividades import Vista_lista_actividades
from .Vista_lista_viajeros import Vista_lista_viajeros
from .Vista_actividad import Vista_actividad
from .Vista_reporte_compensacion import Vista_reporte_compensacion
from .Vista_reporte_gastos import Vista_reporte_gas... |
from __future__ import print_function
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
import matplotlib.gridspec as gridspec
import six
try:
import cPickle as pickle
except BaseException:
import pickle
from exfor_tools import *
# Define drawing functions... |
import requests
API_URL = "/api/v1"
LOCATION_URL="/api/v1/locations/"
DEVICE_URL = "/api/v1/devices/"
RESET_STRING="reset"
def get(url, user_name, password):
url = url + DEVICE_URL
auth=(user_name, password)
response = requests.get(url, auth=auth).json()
return response
def get_by_id(url, user_name, ... |
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class BaseOrderingSerializer(serializers.Serializer):
"""
Serializer to order a model with respect to a foreign key owner.
"""
order = serializers.ListField(
child=serializers.IntegerField(),
... |
import click
import sys
from html.parser import HTMLParser
from html import escape
@click.command()
@click.version_option()
@click.argument("input", type=click.File("r"), required=False)
def cli(input):
"""
CLI tool for stripping hidden form values from an HTML document
You can pipe HTML into this tool:
... |
import re
class RolloverHelper:
def __init__(self, instrument, **kwargs):
self.instrument = instrument
re_include = kwargs.get('option_code_include', [])
self.re_option_code_include = []
for pattern in re_include:
self.re_option_code_include.append(re.compile(pattern... |
#!/usr/bin/env python
"""This module loads the python Grammar (2.3, 2.4 or 2.5)
helper functions are provided that use the grammar to parse
using file_input, single_input and eval_input targets
"""
from pypy.interpreter import gateway
from pypy.interpreter.error import OperationError
from pypy.interpreter.pyparser.err... |
from Pyro5.api import expose
@expose
class TestClass(object):
def div(self, arg1, arg2):
return arg1 / arg2
def error(self):
raise ValueError('a valueerror! Great!')
def error2(self):
return ValueError('a valueerror! Great!')
def othererr(self):
raise RuntimeError('a... |
import math
import torch
import torch.nn as nn
from torch.nn import Module, init, Linear, Conv2d
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
class MaskedLinear(Linear):
#__constants__ = ['bias', 'in_features', 'out_features']
def __init__(s... |
import os.path
import sys
import textwrap
import numpy as np
import pandas as pd
from argparse import (
ArgumentParser,
RawDescriptionHelpFormatter
)
from math import floor, log2
# Includes the parent directory into sys.path, to make imports work
sys.path.append(
os.path.join(
os.path.dirname(
... |
"""Test the Connection Component."""
from datetime import datetime, timedelta
from hashlib import sha1
from unittest.mock import patch
from aiohttp import web
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
import pytest
from masterthermconnect import (
Connection,
MasterThermAuthenticationE... |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2016 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
from django.conf import settings
import basket
from celery import task
@task(default_retry_delay=30 * 60) # Retry once every 30 minutes.
def newsletter_subscribe(email, **kwargs):
try:
basket.subscribe(email, settings.BASKET_FLICKS_LIST, **kwargs)
except basket.BasketException, e:
raise news... |
def get_attr_by_type(node, type):
for attr in node.attributes:
if attr.type == type:
return attr
return None
|
# -*- coding: utf-8 -*-
# Copyright 2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# import pychrome
import os
import subprocess
import asyncio
# import websockets
from ichrome import AsyncChrome,AsyncChromeDaemon
from ichrome import Chrome
import time
def start_chrome():
chrome_exe_path = r'E:\workspace\movie_center_ui\chrome-win-80'
os.chdir(chrome_exe_path)
os.putenv("GOOGLE_API_KEY"... |
import pdb
import math
import torch
import scipy.stats
class GPMarginalLogLikelihood(object):
def __init__(self, x, y, kernel):
self._x = x
self._y = y
self._kernel = kernel
self._kyInv = None
self._logdetKy = None
self._lastParams = None
def _computeKyInvAndL... |
N = int(input())
K = int(input())
X = int(input())
Y = int(input())
if N >= K:
print(K * X + (N - K) * Y)
else:
print(N * X) |
import copy
import re
from collections import OrderedDict
import discord
from discord.ext import commands
from utils import checks
class FancyHelp(commands.HelpCommand):
def __init__(self, **options):
self.name = options.pop('name', 'Bot')
template = options.pop('template', None)
self.gr... |
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def can_paginate(self, operation_name: str = None):
"""
C... |
import logging
from mock import Mock
from slippinj.cli.ssh import SSHClient
import pytest
class TestSSHClient:
def test_path_where_private_keys_files_are_stored_can_be_got(self):
ssh_client = SSHClient(Mock(), self.__generate_test_logger(), '/test')
assert '/test/unit.pem' == ssh_client.get_pem... |
#!/usr/bin/python3
#
# NPIFetch.py -
import argparse
import json
import logging
from sys import exit
import openpyxl
from openpyxl.styles import PatternFill
import requests
__author__ = 'k maddux'
class NPIFetch:
"""
Queries the npi registry and checks the data against an excel file.
... |
def two_sum(nums, target):
d = {}
for i, num in enumerate(nums):
diff = target - num
if diff in d:
return [d[diff], i]
d[num] = i
|
# -*- coding: utf-8 -*-
""" définir les informations de langue """
DEFAULT_LOCALE = "fr"
DIRECTION = "ltr"
|
#! /usr/bin/env python
# ------------------------------------------------------------------------ 79->
# Author: ${name=Kelcey Damage}
# Python: 3.5+
#
# 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 Lice... |
from rest_framework import filters
class CustomSearchFilter(filters.SearchFilter):
search_param = 'q'
|
from .work import open_app |
# Version 1: DP, Time: O(n^2), Space: (n^2)
class Solution:
"""
@param s: the maximum length of s is 1000
@return: the longest palindromic subsequence's length
"""
def longestPalindromeSubseq(self, s):
if len(s) < 2:
return len(s)
"""
https://www.youtube.com/wat... |
import pytest
import random
ray = pytest.importorskip("ray")
import rx
import rx.operators as ops
from rx.subject import Subject
import rxray
def test_defaults():
data = range(200)
ray.init()
result = rx.from_(data).pipe(
rxray.distribute(
lambda: rx.pipe(ops.map(lambda i: i*2)),
... |
class TestBase:
def setup(self):
pass
# setup() before each test method
def test_1(self):
from tributary.base import StreamNone
assert not StreamNone()
|
# -*- coding: utf-8 -*-
###############################################################################
# This file is part of metalibm (https://github.com/kalray/metalibm)
###############################################################################
# MIT License
#
# Copyright (c) 2018 Kalray
#
# Permission is here... |
from django.db import models
from django.utils import timezone
# Create your models here.
class ResponseLog(models.Model):
ResponseTime = models.DurationField()
Url = models.CharField(max_length=255)
Name = models.CharField(max_length=50)
ResponseCode = models.CharField(max_length=3)
queried_at ... |
from abc import ABC, abstractmethod
import rj_gameplay.eval as eval
import argparse
import py_trees
import sys
import time
import numpy as np
from typing import Optional
import stp.skill as skill
import stp.role as role
import stp.action as action
import stp.rc as rc
from rj_msgs.msg import RobotIntent, PathTargetMot... |
from flask import Flask, jsonify, request, make_response, abort
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to Comics"
@app.route('/eshan/api/v1.0/superheroes', methods=['GET'])
def get_superheroes():
return jsonify({'superheroes': superheroes})
@app.route('/eshan/api/v1.0/superher... |
import os
import time
from os import path
import random
import asyncio
import shutil
from pytube import YouTube
from youtube_dl import YoutubeDL
from .. import converter
import youtube_dl
import shutil
import psutil
from pyrogram import Client
from pyrogram.types import Message
from pyrogram.types import Voice
from sys... |
from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form_class, ReduceMixinForm)
... |
import datetime
import pytest
from wkz.file_helper.auto_naming import (
_get_coordinate_not_null,
_get_daytime_name,
_get_sport_name,
)
def test__get_daytime_name():
assert _get_daytime_name(datetime.datetime(2020, 1, 1, 0)) == "Late Night"
assert _get_daytime_name(datetime.datetime(2020, 1, 1, ... |
"""
Pipeline code for training and evaluating the sentiment classifier.
We use the Deepmoji architecture here, see https://github.com/bfelbo/DeepMoji for detail.
"""
import re
import codecs
import random
import numpy as np
import sys
import json
import argparse
import pandas as pd
import glob, os
import matplotlib.pyla... |
import math
nav = open('input').read().splitlines()
print(nav)
x, y = (0, 0) # x (east-west), y (north, south)
w_x, w_y = (10, 1)
angle = 0
for instr in nav:
t, n = (instr[0], int(instr[1:]))
if t in ['N', 'S']:
w_y += n if t == 'N' else -n
elif t in ['E', 'W']:
w_x += n if t == 'E' else... |
import sqlite3
from flask import current_app
import traceback
class Connect():
# 数据库连接类,上下文管理
def __init__(self, file_path='./database/arcaea_database.db'):
"""
数据库连接,默认连接arcaea_database.db
接受:文件路径
返回:sqlite3连接操作对象
"""
self.file_path = file_path
def __ente... |
#!/usr/bin/env python
import askap.analysis.data
import os
from optparse import OptionParser
import askap.parset as parset
from math import *
from numpy import *
from askap import logging
logger = logging.getLogger(__name__)
############
def getMPIxdim(numNodes):
'''
Return the x-dimension that fits with t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-18 11:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('basicviz', '0087_experiment_has_magma_annotation'),
]
... |
# coding=utf-8
# Copyright 2020 The Tensor2Robot 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 ... |
import os
from utils import check_dir
data_path = './'
txtdir_path = './data/txt'
class1_path = data_path + ''
class2_path = data_path + ''
check_dir(txtdir_path)
class1_list = os.listdir(class1_path)
class2_list = os.listdir(class2_path)
class1_num = len(class1_list)
class2_num = len(class2_list)
train_file = op... |
# library imports.
import numpy as np
# RLBot imports.
from rlbot.agents.base_agent import BaseAgent, SimpleControllerState
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.structures.quick_chats import QuickChats
# RLU imports.
# from RLUtilities
# Local file imports.
import data
... |
'''
Author: Francisco Arenas
Creation Date: October 6th, 2021
Last Modfication Date: October 6th, 2021
File with all art printing-related operations.
'''
def print_main_menu() -> None:
print("""
_________________________________________
/ Welcome to the Synergy Logistics \\
| system. Please, select an opti... |
#!/usr/bin/env python
import io
import os
import sys
from codecs import open
from shutil import rmtree
from setuptools import setup, Command
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = '\n' + f.read()
class PublishC... |
#!/usr/bin/env python
# Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ... |
import scrapy
import json
from csvmanager import CsvManager
import os
class ArticleSpider(scrapy.Spider):
name = "articles"
start_urls = ["https://futurism.com/tag/feature/"]
posts = []
# def start_requests(self):
def parse(self, response):
page = response.url.split("/")[-2]
fil... |
#!/usr/bin/env python3
#
# provinces.py
#
# provinces.py is part of a web application written in Python and using
# Streamlit as the presentation method.
#
"""countries page shows graphs about various countries cases"""
import datetime
from datetime import timedelta
import matplotlib.pyplot as plt
import matplotlib.... |
from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
while True:
o = sense.get_orientation()
pitch = o["pitch"]
roll = o["roll"]
yaw = o["yaw"]
print("pitch {0} roll {1} yaw {2}".format(pitch, roll, yaw))
|
# Generated by Django 2.0.1 on 2018-02-21 07:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0011_auto_20180220_1438'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='skin_type... |
#!/usr/bin/python
# $Id: splitreads.py,v 1.3 2009/03/06 18:58:49 rumble Exp $
import sys
from utils import *
if len(sys.argv) != 3 and len(sys.argv) != 4:
print >> sys.stderr, "usage: %s [--paired | -p] <reads_per_file|pairs_per_file> <fasta_file>" % (sys.argv[0])
sys.exit(1)
if sys.argv[1] == '--paired' or sys.ar... |
import numpy as np
from astropy import units as u
from .regressor_classifier_base import RegressorClassifierBase
from sklearn.ensemble import RandomForestRegressor
class EnergyRegressor(RegressorClassifierBase):
"""This class collects one regressor for every camera type -- given
by `cam_id_list` -- to get a... |
from datetime import datetime
import logging
from market.coingecko.coingeko_api import CoinGeckoAPI
logger = logging.getLogger(__name__)
api_mgr = CoinGeckoAPI()
if __name__ == "__main__":
coin_id = 'bitcoin'
dtm = datetime(2020, 1, 1)
data = api_mgr.get_coin_history_by_id(coin_id, dtm.strftime("%d-%m-%... |
'''
Simple http server for Angular.
'''
import http.server
import os
import socketserver
PORT = 8000
class AngularHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def send_head(self):
path = self.translate_path(self.path)
# Return top index.html if request file not exist, or 404 will re... |
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'connectquatro/?$', consumers.ConnectQuatroConsumer),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2021 Alibaba Group Holding 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-... |
import sys
# This is needed to make the "pytest" command able to import from our
# working directory. Note that "pytest" must be run from the repo root.
sys.path.insert(0, ".")
|
"""
Clone Client Model One
Author: Min RK <benjaminrk@gmail.com>
"""
import random
import time
import zmq
from kvsimple import KVMsg
def main():
# Prepare our context and publisher socket
ctx = zmq.Context()
updates = ctx.socket(zmq.SUB)
updates.linger = 0
updates.setsockopt(zmq.SUBSCRIBE, '')... |
# Generated by Django 2.2 on 2019-04-16 07:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_auto_20190415_2123'),
]
operations = [
migrations.AlterModelOptions(
name='post',
options={'ordering': ('... |
import argparse
import os
import mp3gain
import track_history
import webm2mp3
from downloader import download
def _read_arguments():
parser = argparse.ArgumentParser(description='The script to download audio tracks (webm) from YouTube playlist')
parser.add_argument("url",
help="URL of... |
#!/usr/bin/python2.7
"""
Copyright (C) 2014 Reinventing Geospatial, Inc.
This program 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.
This ... |
from toolbox import io
import toolbox
import numpy as np
#-----------------------------------------------------------------------
# useful functions
#-----------------------------------------------------------------------
@io
def spike(dataset, **kwargs):
'''add spike to dataset'''
pass
... |
# Single source package version.
__version__ = "0.0.1"
|
from kfp.components import InputPath, OutputPath
def get_tech_indi(
# date_ref: str,
adj_price_dataset_path: InputPath('DataFrame'),
techini_dataset_path: OutputPath('DataFrame'),
):
from stockstats import StockDataFrame as Sdf
# from sklearn.preprocessing import MaxAbsScaler
from sklearn.preprocessing ... |
from pybbn.graph.edge import JtEdge
from pybbn.graph.jointree import JoinTree
from pybbn.graph.node import SepSet
class Transformer(object):
"""
Transformer. Transforms a list of cliques into a join tree.
"""
@staticmethod
def transform(cliques):
"""
Transforms the cliques into a ... |
import re
from pathlib import Path
import polib
placeholder_regexp = re.compile(r"\{[^\}]*?\}")
for path in Path(__file__).parent.resolve().parent.rglob("LC_MESSAGES/*.po"):
po = polib.pofile(path)
for entry in po:
if not entry.msgstr:
continue # ignore untranslated strings
expe... |
"""
Surface plotting functions.
"""
# Author: Oualid Benkarim <oualid.benkarim@mcgill.ca>
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
import vtk
from .base import Plotter
from .colormaps import colormaps
from ..vtk_interface import wrap_vtk
from ..vtk_interface.decorators import wra... |
# Generated by Django 3.1 on 2020-08-14 14:22
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('progress', '0006_auto_20200814_0226'),
]
operations = [
migrations.AlterField(
model_name='haor... |
#!/usr/bin/env python3
# pip3 install python-bitcoinlib
import sys
import kmdrpc
import pprint
import bitcoin
import ast
from conf import CoinParams
from bitcoin.wallet import P2PKHBitcoinAddress
from bitcoin.core import x
CHAIN = sys.argv[1]
USERNAME = sys.argv[2]
PASSWORD = sys.argv[3]
pubkey = kmdrpc.getpubkey_rpc... |
"""
========
Boxplots
========
Visualizing boxplots with matplotlib.
The following examples show off how to visualize boxplots with
Matplotlib. There are many options to control their appearance and
the statistics that they use to summarize the data.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplo... |
"""
Created on 23/11/2015
@author: gioia
This script runs a simple ChatClient built with sockets.
The code is organized as follows:
- the ChatClient class defines the behaviour of the client;
- the main module function simply executes the server.
The programming language used is Python 2.7 and it is assumed you hav... |
import re
import setuptools
module_file = open("src/dzip/dzip.py").read()
metadata = dict(re.findall(r"__([a-z_]+)__\s*=\s*\"([^\"]+)\"", module_file))
setuptools.setup(
name="dzip",
version=metadata["version"],
description=metadata["doc"],
long_description=open("README.md").read(),
long_descrip... |
"""This module contains various metrics used across synthesized."""
import warnings
from typing import List, Optional, Sequence, Union, cast
import dcor as dcor
import numpy as np
import pandas as pd
from scipy.spatial.distance import jensenshannon
from scipy.stats import entropy, wasserstein_distance
from sklearn.lin... |
import dgl
import backend as F
import numpy as np
import unittest
from test_utils import parametrize_dtype
from dgl.utils import Filter
def test_graph_filter():
g = dgl.DGLGraph().to(F.ctx())
g.add_nodes(4)
g.add_edges([0,1,2,3], [1,2,3,0])
n_repr = np.zeros((4, 5))
e_repr = np.zeros((4, 5))
n... |
import trimesh
import numpy as np
from data_processing.libmesh.inside_mesh import check_mesh_contains
import math
import os
import glob
from multiprocessing import Pool
def to_rotation_matrix(euler_angles):
R_x = np.array([[1, 0, 0],
[0, math.cos(euler_angles[0]), -math.sin(euler_angles[0])],
... |
# Copyright 2012, Dag Wieers <dag@wieers.com>
#
# 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 versi... |
from Crypto.Hash import SHA256
from time import gmtime, strftime
def _parseFile(name):
cfg = open(name, 'r')
paramList = [x.replace(' ','') for x in cfg.read().split('\n') if len(x) > 0]
prmMap = {}
for prm in paramList:
key, value = prm.split('=')
prmMap[key] = value
return prmMap
... |
# Copyright 2020 NREL
# 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... |
from typing import Dict, Optional
import pandas as pd
import pygeos as geos
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.exceptions import InvalidExpectationConfigurationError
from great_expectations.execution_engine import (
ExecutionEngine,
P... |
###########################################################################
#
# Copyright 2019 Google 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
#
# https://www.apache.org... |
from types import SimpleNamespace
from django.test import SimpleTestCase
from .. import utils
from .testcase import EmailSignalTestCase
class TestConvertToPrimitive(SimpleTestCase):
"""Unittests for the `convert_to_primitive` utility function."""
def test_convert_to_true(self):
"""Test the `convert_t... |
#!/usr/bin/env python3
import socket
import threading
def client_handler(conn,addr):
msg = "you are {}:{}\n".format(addr[0],addr[1])
conn.send(msg.encode("UTF-8"))
while True:
try:
data = conn.recv(1024)
conn.sendall(data)
except socket.error:
conn.close(... |
from __future__ import division
import numpy as np
from scipy import stats
def get_summation_error(errors):
sum_error = np.sqrt(np.sum([err**2 for err in errors]))
return sum_error
def get_difference_error(errors):
diff_error = np.sqrt(np.sum([err**2 for err in errors]))
return diff_error
def get... |
from distutils.core import setup
version = 'DEPRECATED'
setup(
name='BoxOfficeMojo',
version=version,
install_requires=['BeautifulSoup4', 'vcrpy'],
author='Justin Cano',
author_email='jcano001@ucr.edu',
packages=['bom', 'tests'],
test_suite='tests',
url='https://github.com/hyperbit/BoxOfficeMojoAPI',
license... |
# coding: utf-8
from __future__ import unicode_literals
from .. import Provider as DateTimeProvider
class Provider(DateTimeProvider):
def day_of_week(self):
day = self.date('%w')
DAY_NAMES = {
"0": "Nedjelja",
"1": "Ponedjeljak",
"2": "Utorak",
"3"... |
# -*- coding: utf-8 -*- vim:fileencoding=utf-8:
__version__ = '2.3.7'
__all__ = ['Cling', 'Error', 'Reactor']
class Error(Exception):
"""The module's generic exception"""
from cli import Cling
from reactor import Reactor
|
"""This module contains the DimmableLight base type."""
import threading
from raspy.object_disposed_exception import ObjectDisposedException
from raspy.components.lights import light
class DimmableLight(light.Light):
"""Base class for dimmable light component abstractions."""
def __init__(self):
""... |
from scoreboard import Scoreboard
from food import Food
import turtle
from snake import Snake
from scoreboard import Scoreboard
from white import White
import time
#Screen setup
#-------------------------------------------#
turtle_screen=turtle.Screen()
turtle_screen.setup(width=600,height=600)
turtle_screen.bgcolor("... |
from keras.optimizers import Adam
class GANBase(object):
def __init__(self, optimizer=Adam(0.0002, 0.5), verbose=True):
self.optimizer = optimizer
self.verbose = verbose
def get_optimizer(self):
return self.optimizer
def build_generator(self, *args, **kwargs):
raise NotI... |
""""
Challenge 4 - Random Walk
"""
import turtle as t
import random
turtle1 = t.Turtle()
# our colours
"""
colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue",
"LightSeaGreen", "wheat", "SlateGray", "SeaGreen"]
"""
t.colormode(255)
# this function is to choose a random color with RGB
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.