code stringlengths 1 199k |
|---|
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mirrors.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""this module contains a set of functions to create astng trees from scratch
(build_* functions) or from living object (object_build_* functions)
:author: Sylvain Thenault
:copyright: 2003-2007 LOGILAB S.A. (Paris, FRANCE)
:contact: http://www.logilab.fr/ -- mailto:python-projects@logilab.org
:copyright: 2003-200... |
import _plotly_utils.basevalidators
class PackingValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="packing", parent_name="treemap.tiling", **kwargs):
super(PackingValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
St = []
for c in s:
if St and St[-1][0] == c:
St[-1][1] += 1
if St[-1][1] == k:
St.pop()
else:
St.append([c, 1])
return ''.join(c * n... |
"""Support for Awair sensors."""
from __future__ import annotations
from python_awair.air_data import AirData
from python_awair.devices import AwairDevice
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntr... |
__author__ = 'magus0219'
from config import DEBUG as _DEBUG, SERVER_CONFIG as _SERVER_CFG
from utils.decorator import retry
from utils.string_util import remove_quota_pair
import subprocess
import traceback
import uuid
import re
import os
import shutil
import logging
import datetime
import time
from collections import ... |
import requests
from bs4 import BeautifulSoup as BS
from pymongo import MongoClient
def check_presence(name,mainlist):
for elem in mainlist:
if(name==elem):
return True
return False
client = MongoClient()
db = client.temp2
mainbuslist=[]
mainbusstoplist=[]
file1=open("busstop_coord.txt","r")
file2=open("final_bu... |
from django.db import models
event_types = [
('view', 'View homepage'),
('cc', 'Enter credit card'),
('demo', 'Use demo'),
('email', 'Enter email address')
]
class Event(models.Model):
# we can forgo making these foreign keys and have separate models for them
# as it's somewhat orthogonal to the... |
class Item(object):
"""
Items have a serial number, a one word string describing it, and a quality
score from 1 to 100
"""
DEFAULT_ITEM_NAME = ""
def __init__(self,item_name=None):
"""
Create an Item
"""
if(name and itemID):
self.item_name = item_name
... |
import time
import english
import german
import portuguese
import czech
import french
import spanish
import danish
for item in dir(english):
langs = english, german, portuguese, czech, french, spanish, danish
for lang in langs:
if item not in dir(lang):
print(lang.__name__ + ".py", "misses",... |
import fnmatch, ftplib, optparse, os, stat, string, sys, time
class FtpWalker:
def __init__( self, site, user, passwd ):
self.ftp = ftplib.FTP( site, user, passwd )
def cd( self, path ):
try:
self.ftp.cwd( path )
except:
return False
else:
retu... |
import tensorflow as tf
import glob as glob
import getopt
import sys
import cPickle as pkl
import numpy as np
import time
import os
opts, _ = getopt.getopt(sys.argv[1:],"",["chunk_file_path=", "comp_file_path=", "means_file_path=", "stddevs_file_path=", "output_dir=", "input_dir="])
chunk_file_path = "../video_level_fe... |
from ccxt.async_support.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.error... |
<<<<<<< HEAD
<<<<<<< HEAD
import github.GithubObject
class InputFileContent(object):
"""
"""
def __init__(self, content, new_name=github.GithubObject.NotSet):
"""
:param content: string
:param new_name: string
"""
assert isinstance(content, str), content
asser... |
from pyccel.decorators import types
from pyccel.decorators import external
@external
@types('int', 'int', 'real [:,:]')
def f6(m1, m2, x):
x[:,:] = 0.
for i in range(0, m1):
for j in range(0, m2):
x[i,j] = (2*i+j) * 1.
@types('real [:]')
def h(x):
x[2] = 8. |
from django.shortcuts import render, render_to_response, RequestContext
from django.contrib import messages
from .forms import SignUpForm
def home(request):
form = SignUpForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
messages.success(reque... |
from django.db import models
from django_countries.fields import CountryField
from django.contrib.auth.models import User
from time import time
import os
import ast
choices = (
('A', 'Apprentice'),
('Me', 'Mentor'),
('Ma', 'Master'),
('G', 'Guru'),
)
class ListField(models.TextField):
__metaclass__ ... |
import tornado.web
from models.topic import NodeManager
class HotNodes(tornado.web.UIModule):
def render(self, count=20):
nodes = NodeManager().all(limit=count)
return self.render_string("module-hotnodes.html", nodes=nodes) |
from InstagramAPI.src.http.Response.Objects.Inbox import Inbox
from .Response import Response
class V2InboxResponse(Response):
def __init__(self, response):
self.pending_requests_total = None
self.seq_id = None
self.pending_requests_users = None
self.inbox = None
self.subscri... |
DEBUG = False
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
TIME_ZONE = ''
S... |
from django.core.management.base import BaseCommand
from django.conf import settings
from django.contrib.auth.models import User
from apps.statistics.models import MStatistics
from apps.rss_feeds.models import Feed
from optparse import make_option
from utils import feed_fetcher
from utils.management_functions import da... |
import requests
Favorite_Artists = input("What is your favorite artist or band on Spotify? ")
response = requests.get("https://api.spotify.com/v1/search?query=" + Favorite_Artists + "&type=artist&limit=50&market=US")
Favorite_Artists = response.json()
Favorite_Artists_List = Favorite_Artists['artists']['items']
artist_... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.core.urlresolvers import NoReverseMatch
from django.test import TestCase
class WipeUrlTests(TestCase):
def test_wipe_no_params(self):
with self.assertRaises(NoReverseMatch):
reverse('wipe_version')
... |
"""
@author: ouwj, donald
@position: ouwj-win10
@file: model.py
@time: 2017/4/19 17:07
"""
import tensorflow as tf
import numpy as np
from PIL import Image
import os
from utils import *
from params_config import *
from load_data import *
class Gan:
def __init__(self, conf):
self.dataset = conf.dataset
... |
from selenium import selenium
__version__ = "2.38.4" |
from contextlib import contextmanager
import os
import sys
import pwd
import shutil
import grp
import codecs
import urllib.request
import time
import imp
protocol = imp.load_source('protocol', '../protocol.py')
nxDSCLog = imp.load_source('nxDSCLog', '../nxDSCLog.py')
LG = nxDSCLog.DSCLog
try:
import hashlib
md5... |
import yaml
tbg1 = yaml.load(file('../../../test/john/env/tbg/tbg1.yml'), Loader=yaml.FullLoader)
print("tbg1 = %s" % str(tbg1))
print("\n")
tbg2 = yaml.load(file('../../../test/john/env/tbg/tbg2.yml'), Loader=yaml.FullLoader)
print("tbg2 = %s" % str(tbg2))
print("\n")
t1 = {}
for k1 in list(tbg1.keys()):
t1[k1] = ... |
import sys
class Stack(object):
def __init__(self):
self.memory = []
def push(self, val):
self.memory += (val,)
def pop(self):
if len(self.memory) > 0:
ret = self.memory[-1]
del self.memory[-1]
return ret
else:
Exception("Stack ... |
import shutil
import os
import os.path
from galleryitemfactory import is_jpeg_file, is_css_file, is_js_file
def copy_css(from_directory, to_directory):
"""
Scans from_directory and finds all the CSS files in it and its subdirectories.
Copies those CSS files to to_directory. Note that to_directory will have a flat... |
import os
import time
import threading
import unittest
from collections import namedtuple
import selfdrive.loggerd.deleter as deleter
from common.timeout import Timeout, TimeoutException
from selfdrive.loggerd.tests.loggerd_tests_common import UploaderTestCase
Stats = namedtuple("Stats", ['f_bavail', 'f_blocks', 'f_frs... |
class Stuff:
def __init__(self):
self.modes = {
'wee': self.things
}
self.modes['wee']()
def things(self):
print "OK"
Stuff() |
from copy import deepcopy
from typing import Any, Optional, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from msrest import Deserializer, Serializer
from . import models
from ._configuration import IotHubClientConfiguration
from .operations import Cer... |
import csv
import sys
import numpy
files = sys.argv[1:]
data = {}
for f in files:
with open(f) as file:
name = f.split(".")[0]
d = {
"times": [],
"cycles": []
}
data[name] = d
times = d["times"]
cycles = d["cycles"]
lines = csv.read... |
"""
:Author Patrik Valkovic
:Created 23.12.2017 16:04
:Licence MIT
Part of grammpy
"""
from .splitted_rules import splitted_rules |
from .misc import *
from .encodings import *
from .wrappers import * |
from __future__ import unicode_literals
import re
from abc import ABCMeta, abstractmethod
from datetime import datetime
from decimal import Decimal
from six import with_metaclass
class Field(with_metaclass(ABCMeta, object)):
def __init__(self, position, length, value=None, tag=None):
self.position = positio... |
__author__ = 'madcore' |
from ._confidential_ledger import ConfidentialLedger
from ._version import VERSION
__version__ = VERSION
__all__ = ['ConfidentialLedger']
try:
from ._patch import patch_sdk # type: ignore
patch_sdk()
except ImportError:
pass |
from copy import deepcopy
from typing import Any, Awaitable, TYPE_CHECKING
from azure.core import AsyncPipelineClient
from azure.core.rest import AsyncHttpResponse, HttpRequest
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import FormRecognizerClientConfiguration
from .operation... |
from django.contrib import admin
from registration.models import Profile, ChatMessage
from registration.forms import AdminChatMessageForm
class ProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'date_of_birth', 'photo',)
@admin.register(ChatMessage)
class ChatMessageAdmin(admin.ModelAdmin):
form = AdminCh... |
from flask import request
from eve import Eve
from . import validation
class RegistryServer(Eve):
def __init__(self, cfg, domains, logger, *args, **kwargs):
"""Create a registry server instance.
:param ice.registry.server.config.CfgRegistryServer cfg: The
cfguration object of the server.... |
import pcmd
import threading
import ConfigParser
import sys
class pcmd_thread(threading.Thread):
def __init__(self,method,ip,user,password,args):
threading.Thread.__init__(self)
self.method=method
self.ip=ip
self.user=user
self.password=password
self.args=args
def... |
"""
vermin.utils
~~~~~~~~~~~~
This module implements some miscellanious utilities
used in Vermin. Most of them are used in the wrappers.
"""
import sys
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long) |
"""DNNRegressor with custom input_fn for Housing dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import argparse
import pandas as pd
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
# "dis", "tax", "ptr... |
import numpy
import os
import pdb
import constants
import plot
import preprocess_GCAM, preprocess_IMAGE
import pygeoutil.util as util
def plot_GCAM_annual_diffs(nc_file, tme='', var='', legend='', ylabel=''):
"""
:return:
"""
arr_diff = util.max_diff_netcdf(nc_file, var = var)
arr_diff.insert(0,0.0)... |
from __future__ import print_function
from random import randint, shuffle
from rapidtest import Test, Case, randints, unordered
from solutions.find_all_duplicates_in_an_array import Solution
with Test(Solution, post_proc=unordered) as test:
Case([], result=[])
Case([1], result=[])
Case([1, 2], result=[])
... |
import numpy as np
I_aufsteigend = np.linspace(0, 5, 11)
I_abfallend = np.linspace(5, 0, 11)
B_aufsteigend = np.array([7.7, 142, 272, 420, 556, 700, 840, 975, 1077, 1158, 1220])
B_abfallend = np.array([1220, 1169, 1095, 977, 845, 703, 563, 422, 279, 138, 8.3])
Zink = np.array([2.603, 4.406, 0.043])
Kupfer = np.array([2... |
import unittest
import numpy as np
import scipy.stats as st
from os import path, getcwd
import pandas as pd
from ..graphs import GraphScatter
from ..data import Vector
from ..analysis.exc import NoDataError
from ..data import UnequalVectorLengthError
class MyTestCase(unittest.TestCase):
@property
def save_path(... |
import os
from cmc.settings import BASE_DIR
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} |
import os
import unittest
from git import Repo
from six import text_type
VERBOSE = True
if os.path.exists('vigra_cmake'):
if not os.path.isdir('vigra_cmake'):
raise RuntimeError('"vigra_cmake" is not a directory')
print("The vigra_cmake repository already exists.")
else:
print("Cloning the vigra_cma... |
from factory.alchemy import SQLAlchemyModelFactory as Factory
from factory import Faker, LazyAttribute, Sequence, SubFactory
from factory.fuzzy import FuzzyChoice, FuzzyInteger, FuzzyDecimal, FuzzyText
from sipa.model.wu.database_utils import STATUS, ACTIVE_STATUS
from sipa.model.wu.schema import (db, Nutzer, Wheim, Co... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', mo... |
"""
Utility to get trend data based on a list of watched places.
Gets enabled records from PlaceJob table and use the WOEID of each place to
access trend data for that place from Twitter API and store in the database.
"""
import os
import sys
import time
sys.path.insert(
0,
os.path.abspath(
os.path.join... |
"""
Created on 2017-8-24
@author: cheng.li
"""
import bisect
import datetime as dt
from typing import Iterable
from typing import Union
import numpy as np
import pandas as pd
from simpleutils.asserts import require
from PyFin.DateUtilities import Period
from PyFin.api import BizDayConventions
from PyFin.api import Date... |
"dbapi2 interface to pgmock"
import functools, contextlib, collections
from . import pgmock, sqparse2, pg
apilevel = '2.0'
threadsafety = 1 # 1 means module-level. I think pgmock with transaction locking as-is is fully threadsafe, so write tests and bump this to 3.
paramstyle = 'format'
DATABASES = {}
NEXT_DB_ID = 0
de... |
N = int(input())
print('GO' if N % 4 == 0 else 'SEN')
"""
import sys
sys.setrecursionlimit(10**5)
def dfs(s):
if s >= N:
return False
if memo[s] != -1:
return memo[s]
ret = False
for i in range(3):
if not dfs(s+i+1):
ret = True
memo[s] = ret
return memo[s]
mem... |
from django.urls import include, path
from rest_framework import routers
from fiubar.api import views
router = routers.DefaultRouter()
router.register(r'alumnos/plancarreras', views.AlumnoViewSet)
router.register(r'alumnos/materias', views.AlumnoMateriaViewSet)
router.register(r'facultad/carreras', views.CarreraViewSet... |
import logging
from craftbuildtools.operations import OperationPlugin
logger = logging.getLogger("craft-buildtools")
class CopyOperation(OperationPlugin):
def __init__(self):
super(CopyOperation, self).__init__()
self.name = "copy_operation"
self.description = "Copy all your brand new, brill... |
import datetime
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views import View
from apps.profile.models import Profile, RNewUserQueue
class Users(View):
def get(self, request):
last_month = datetime.datetime.utcnow() - datetime.timedelta(days=30)
last_d... |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('infokala', '0002_auto_20150602_2047'),
]
operations = [
migrations.AddField(
model_name='workflow',
name='slug',
field=models.CharField(max_length=64, verbos... |
import time
from test_framework.test_framework import DankcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
import binascii
class AddressIndexTest(DankcoinTestFramework):
def setup_chain(self):
print("Initializing test directory "+s... |
import os
THIS_DIR = os.path.dirname(__file__)
CHIEF_API_DEBUG = False
CHIEF_API_OPTS = {'use_reloader': False}
CHIEF_API_PORT = 7182
CHIEF_API_SCRIPTS_PATH = THIS_DIR + "/../scripts"
CHIEF_API_THREADS_PATH = THIS_DIR + "/../threads" |
import logging
import time
import requests
import Adafruit_VCNL40xx
import influxdb
log = logging.getLogger("ledmatrix")
DELAY_SECS = 60 # Delay between measurements
class Ambient_Light_Sensor(object):
def __init__(self, dbhost="localhost", dbport=8086, dbname=None):
self.dbclient = influxdb.InfluxDBClient(dbhos... |
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
sample = []
self.result = 0
self.validposition(n, 0, sample)
return self.result
def validposition(self, n, nalready, sample):
if nalready == n:
... |
"""
Created on 08/feb/2015
@author: gioia
The script provides my solution to the challenge about implementing a basic spreadsheet calculator.
Input:
* The first line should contain two integers: n, m - where n is width of the spreadsheet while m is its height.
* The next n*m lines should contain the content of the rela... |
"""Refine player actions into inputs."""
from mgz.fast import Action as ActionEnum
from mgz.model.definitions import Input
ACTION_TRANSLATE = {
ActionEnum.DE_QUEUE: 'Queue',
ActionEnum.DE_ATTACK_MOVE: 'Attack Move'
}
class Inputs:
"""Normalize player inputs."""
def __init__(self, gaia):
"""Initi... |
from __future__ import absolute_import
import inspect
import os
import six
def load_module_at(absolute_path):
'''Loads Python module at specified absolute path. If path points to a
package, this will load the `__init__.py` (if it exists) for that package.
:param str absolute_path: Absolute path to the desir... |
from __future__ import absolute_import
from __future__ import unicode_literals
__program__ = 'docker-stack'
__name__ = 'Docker Stack'
__maintainer__ = 'Kaliop Canada Inc.'
__version__ = '0.7' |
from PIL import Image
def resize(layer, num):
"""
Very simple function that opens an individual visualization and resizes it
:param layer: layer we are interested in
:type layer: string
:param num: number of visualizations in the layer
:type num: int
:return: nothing
"""
for i in ran... |
from .test_KappaAgent import TestKappaAgent
from .test_KappaComplex import TestKappaComplex
from .test_KappaCounter import TestKappaCounter
from .test_KappaPort import TestKappaPort
from .test_KappaRule import TestKappaRule
from .test_KappaSnapshot import TestKappaSnapshot
from .test_KappaToken import TestKappaToken |
from cart import Cart, ItemAlreadyExists, ItemDoesNotExist |
from __future__ import division
from __future__ import print_function
import argparse
from datetime import datetime
import json
import os
import librosa
import numpy as np
import tensorflow as tf
from wavenet import WaveNetModel, mu_law_decode, mu_law_encode, audio_reader
SAMPLES = 16000
TEMPERATURE = 1.0
LOGDIR = './l... |
"""
Settings for 'django_photo_contest' app
"""
DPC_SECONDS_BETWEEN_VOTATION = 604800 # 604800 seconds = 7 days
DPC_ADD_WINNER_POINTS = True # indica se al vincitore devono essere assegnati i punti
DPC_WRITE_WINNER_NOTIFY = True # indica se scrivere la notifica al vincitore
DPC_PHOTO_CONTEST_LIST = [
'bianco-e-nero... |
import re
class GoogleTimeString:
def __init__(self,time):
# regular expression that separates all "words"
time_list = re.findall(r"[\w']+", time)
self.year = str(time_list[0])
self.month = str(time_list[1])
self.day = str(time_list[2])
def __repr__(self):
return self.year+"-"+self.month+"-"+self.day |
from __future__ import print_function
import os
import sys
import time
import subprocess
sys.path.append('.')
from setup import (
setup_dict, get_project_files, print_success_message,
print_failure_message, _lint, _test, _test_all,
CODE_DIRECTORY, DOCS_DIRECTORY, TESTS_DIRECTORY, PYTEST_FLAGS)
from paver.ea... |
import idml
import ePub
definitions = {}
definitions["mypath"] = "/Volumes/Datos002/WESTPARK/iPray/june/deployment/orig/Stories/"
definitions["outPath"] = "/Volumes/Datos002/WESTPARK/iPray/june/deployment/dest/Stories/"
definitions["TEXTS_NUM"] = 37
definitions["TEXT_GENERAL_DIR"] = "/Users/chus/Dropbox/3plus2/3plus2_t... |
import urllib2 as url
import urllib
import httplib as http
import json
import time
from pprint import pprint
class OmegleHandler:
def __init(self):
""" creates an OmegleHandler """
self.omegle = None
def on_wait(self):
""" called when a 'waiting' message is received """
pass
def on_interests(self, interests)... |
from setuptools import setup, Extension
def readme():
with open("README.rst", 'r') as rf:
return rf.read()
setup(
name='btef',
author='Yi Tang',
author_email='ssnailtang@gmail.com',
version='0.1',
description='c extension for file object',
long_description=readme(),
url='https://... |
import _plotly_utils.basevalidators
class ArrayminusValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="arrayminus", parent_name="histogram.error_x", **kwargs
):
super(ArrayminusValidator, self).__init__(
plotly_name=plotly_name,
p... |
from models.corpus import Sentence
from DatabaseCorpusIterator import DatabaseCorpusIterator
class Iterator(DatabaseCorpusIterator):
## Reads a set of sentences from a database
# @author Adriano Zanette
# @version 0.1
# @return peewee.QueryResultWrapper
def getRowSet(self):
sentences = Sentence.select().w... |
import sublime_plugin
class NewFileAtCommand(sublime_plugin.WindowCommand):
def is_visible(self):
return False
def is_enabled(self):
return False
class DeleteFileCommand(sublime_plugin.WindowCommand):
def is_visible(self):
return False
def is_enabled(self):
return False
class NewFolderCommand(sublime_plugin... |
from .seal_parser import *
import os
SEPARATOR = "// -----------------------------\n"
def formatCondition(condition):
return "conditionStatus[{0}]".format(abs(condition) - 1)
def formatConditions(conditions):
result = ""
# all except last one
for c in conditions[:-1]:
if c < 0:
resul... |
from __future__ import unicode_literals
import datetime
import pickle
from operator import attrgetter
import django
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db import DEFAULT_DB_ALIAS, connections, router, trans... |
# coding: utf-8
import unittest
import pytest
import azure.mgmt.communication
from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer
from azure.mgmt.communication.models import CommunicationServiceResource
from azure.mgmt.communication.models import KeyType
from azure.mgmt.communication.models import ... |
from __future__ import division
from builtins import zip
from builtins import range
from builtins import object
import numpy as np
import abc, os
from nose.plugins.attrib import attr
import pybasicbayes
from pybasicbayes.util import testing
from future.utils import with_metaclass
class DistributionTester(with_metaclass... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
def main():
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE)
glutInitWindowSize(300, 300)
glutInitWindowPosition(100, 100)
glutCreateWindow("プリミティブの描画")
glutDisplayFunc(display)
init()
glu... |
import json, re
import random
import sys
try:
from urllib.request import build_opener
except:
from urllib2 import build_opener
SATOSHIS = 100000000
def get_provider_by_name(name):
if name == 'blockchaininfo':
return BlockchainInfoProvider()
if name == 'blockr':
return BlockrProvider()
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from model.config import cfg
from model.bbox_transform import bbox_transform_inv, clip_boxes
from model.nms_wrapper import nms
def proposal_layer(rpn_cls_prob, rpn_bbox_pred, im_info, cfg_key,... |
__author__ = "helgrind"
__version__ = "0.0.1" |
from __future__ import unicode_literals
from builtins import object
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.urls import reverse
from i... |
import sys
import os
import math
try:
# SOMENTE MUDE AQUI! - Coloque quantos pacotes quiser importar
import argparse
import matplotlib
except ImportError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename,
... |
"""PuppetDBClientTestCaseV3.py: The core of this module"""
__author__ = "monkee"
__version__ = "1.0.1"
__maintainer__ = "monk-ee"
__email__ = "magic.monkee.magic@gmail.com"
__status__ = "Development"
import utils
import v2
import v3
import v4
class ClientException(BaseException):
pass
class AuthException(BaseExcept... |
"""
homeassistant.components.device_sun_light_trigger
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to turn on lights based on
the state of the sun and devices.
"""
import logging
from datetime import datetime, timedelta
import homeassistant.components as components
from . import light, sun, ... |
def dm(st) :
"""dm(string) -> (string, string or None)
returns the double metaphone codes for given string - always a tuple
there are no checks done on the input string, but it should be a single word or name."""
vowels = ['A', 'E', 'I', 'O', 'U', 'Y']
st = st.decode('utf-8', 'ignore')
st = st.upper() # st is sho... |
from .models import Contract, Contractor, SupportContract, ContractorContact
from .tables_ajax import ContractTableJson, ContractorTableJson, \
SupportContractTableJson, ContractorContactTableJson
from ..main.views import TableView
class ContractorTable(TableView):
json_view = ContractorTableJson
model = Co... |
"""
Irmak Sirer, 2013
Python Wrapper around the Google API for search
It returns results for a google search.
A result is a dictionary (json) with the following fields:
cacheUrl
content
title
titleNoFormatting
unescapedUrl
url
visibleUrl
"""
import googlesearch.settings as settings
from googlesearch.exceptions import G... |
import argparse
from datetime import datetime, timedelta
import itertools
import logging
import requests
import conf
import locator
import notifier
BASE_URL = "http://realtime.grofsoft.com/tripview/realtime?routes=%s&type=dtva"
DEFAULT_LATENESS_THRESHOLD_MINS = 5
SEND_NOTIFICATION_ALWAYS = "always"
SEND_NOTIFICATION_AU... |
im = ImageObject()
with im:
# set a size for the image
size(200, 200)
# draw something
fill(1, 0, 0)
rect(0, 0, width(), height())
fill(1)
fontSize(30)
text("Hello World", (10, 10))
image(im, (10, 50))
im.gaussianBlur(5)
x, y = im.offset()
image(im, (300+x, 50+y)) |
import window
import os
class RunmapWindow(window.Window):
"""
Gui application interface.
"""
GLADE_FILE = os.path.splitext(__file__)[0] + '.glade'
WINDOW_NORMAL = 'window_normal'
WINDOW_EXPERT = 'window_expert'
ROOT_WINDOW = WINDOW_NORMAL
def __init__(self):
super(RunmapWind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.