code stringlengths 1 199k |
|---|
"""Utilities to support packages."""
import os
import sys
import imp
import os.path
from types import ModuleType
from org.python.core import imp as _imp, BytecodeLoader
__all__ = [
'get_importer', 'iter_importers', 'get_loader', 'find_loader',
'walk_packages', 'iter_modules',
'ImpImporter', 'ImpLoader', 're... |
from . import foo |
from __future__ import unicode_literals
from django.apps import AppConfig
class ProfileConfig(AppConfig):
name = "profiles"
verbose_name = 'User Profiles'
def ready(self):
from . import signals # noqa |
records = [select.query.decode(r) for r in records] |
class С:
def __init__(self, x=None):
if x is None:
self.foo = {
'A': {
'x': 0,
'y': 0,
},
}
else: # init was given the previous state
assert isinstance(x, С)
self.foo = {
... |
from __future__ import absolute_import
import sys
import jinja2
from django.conf import settings
from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.utils import six
from django.utils.module_loading import import_string
from .base import BaseEngine
from .utils import csrf_input_lazy, csrf_... |
doctests = """
Test simple loop with conditional
>>> sum({i*i for i in range(100) if i&1 == 1})
166650
Test simple case
>>> {2*y + x + 1 for x in (0,) for y in (1,)}
set([3])
Test simple nesting
>>> list(sorted({(i,j) for i in range(3) for j in range(4)}))
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0)... |
def main(request, response):
headers = []
if 'Content-Type' in request.GET:
headers += [('Content-Type', request.GET['Content-Type'])]
with open('./resources/ahem/AHEM____.TTF') as f:
return 200, headers, f.read() |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
cache: memory
short_description: RAM backed, non persistent
description:
- RAM backed cache that is not persistent.
- This is the default used if no other plugin is specified.
... |
buildSettings = {
# local: use this build if you're not modifying external resources
# no external resources allowed - they're not needed any more
'local': {
'resourceUrlBase': 'http://localhost:8100',
'distUrlBase': 'http://localhost:8100',
},
# local8000: if you need to modify exte... |
from __future__ import absolute_import, unicode_literals
import os
import shutil
import sys
import dirtyjson as json
from ..decorators import linter
from ..parsers.base import ParserBase
@linter(
name="coala",
install=[
["pipx", "install", "--spec", "coala-bears", "coala"],
[sys.executable, "-m"... |
""" This file defines the RoutingTree class which can be used for constructing
routing trees for route segments from the fpga_interchange.physical_netlist
class PhysicalBelPin/PhysicalSitePin/PhysicalSitePip/PhysicalPip.
Use of the RoutingTree requires having the DeviceResources class loaded for
the relevant part for t... |
import sys, os.path, re
from distutils.core import setup
from distutils.extension import Extension
if not os.path.isfile('config.mak'):
print "please run ./configure && make first"
print "Note: setup.py is supposed to be run from Makefile"
sys.exit(1)
buf = open("configure.ac","r").read(256)
m = re.search("... |
"""
Based on :mod:`django.contrib.auth.tokens`. Supports the following settings:
:setting:`WALDO_REGISTRATION_TIMEOUT_DAYS`
The number of days a registration link will be valid before expiring. Default: 1.
:setting:`WALDO_EMAIL_TIMEOUT_DAYS`
The number of days an email change link will be valid before expiring. Defau... |
import urllib.request
import re
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("url", help="the URL whose HTML you want to extract telephone numbers from", type=str)
args = parser.parse_args()
with urllib.request.urlopen(args.url) as response:
html = response.read().decode('utf-8')
regex = re.... |
import difflib
import shutil
__author__ = 'Adam'
import unittest
import os
import useful
class TestFileContentProcedures(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_dir = "./tests/data/"
cls.text_file_name = "TextFile_UTF16_CRLF.txt"
cls.text_file_path = os.path.join(c... |
from axelrod import Player
import random
class Random(Player):
"""A player who randomly chooses between cooperating and defecting."""
name = 'Random'
def strategy(self, opponent):
return random.choice(['C','D']) |
import unittest
import copy
from scrapy.http import Headers
class HeadersTest(unittest.TestCase):
def test_basics(self):
h = Headers({'Content-Type': 'text/html', 'Content-Length': 1234})
assert h['Content-Type']
assert h['Content-Length']
self.assertRaises(KeyError, h.__getitem__, '... |
'''
mode | desc
r 또는 rt | 텍스트 모드로 읽기
w 또는 wt | 텍스트 모드로 쓰기
a 또는 at | 텍스트 모드로 파일 마지막에 추가하기
rb | 바이너리 모드로 읽기
wb | 바이너리 모드로 쓰기
ab | 바이너리 모드로 파일 마지막에 추가하기
'''
f = open("./py200_sample.txt", "w")
f.write("abcd")
f.close()
r = open("./py200_sample.txt", "r")
print("-" * 60)
print(r.... |
from otp.ai.AIBaseGlobal import *
from pandac.PandaModules import *
from DistributedNPCToonBaseAI import *
import ToonDNA
from direct.task.Task import Task
from toontown.ai import DatabaseObject
from toontown.estate import ClosetGlobals
class DistributedNPCTailorAI(DistributedNPCToonBaseAI):
freeClothes = simbase.c... |
import os
import time
import logging
import string
import requests
import unicodedata
import base64
try: import cPickle as pickle
except: import pickle
import datetime
from django.utils import timezone
import json
from pprint import pprint
from django.shortcuts import render_to_response
from django.http import HttpResp... |
"""Checks/fixes are bundled in one namespace."""
import logging
from rdflib.namespace import RDF, SKOS
from .rdftools.namespace import SKOSEXT
from .rdftools import localname, find_prop_overlap
def _hierarchy_cycles_visit(rdf, node, parent, break_cycles, status):
if status.get(node) is None:
status[node] = ... |
import unittest, sys, os
sys.path[:0] = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from saklient.cloud.enums.eserverinstancestatus import EServerInstanceStatus
class TestEnum(unittest.TestCase):
def test_should_be_defined(self):
self.assertEqual(EServerInstanceStatus.UP, "up");
self... |
__author__ = 'las3wh'
print('goodbye') |
def superstring(arr, accumulator=''):
# We now have all strings
if len(arr) == 0:
return accumulator
# Initial call
elif len(accumulator) == 0:
accumulator = arr.pop(0)
return superstring(arr, accumulator)
# Recursive call
else:
for i in range(len(arr)):
... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('attracker_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='segment',
name='additional_miles',
... |
import csv
import httplib2
import json
import os
import sys
from bs4 import BeautifulSoup
mbz_instDict = {}
h = httplib2.Http()
link = 'https://musicbrainz.org/instruments'
uri_root = 'https://musicbrainz.org'
resp, html_doc = h.request(link, "GET")
soup = BeautifulSoup(html_doc, "lxml")
for result in soup.body.select(... |
from pyspark.sql import SparkSession, Row
from pyspark.ml.feature import Word2Vec, Tokenizer, StopWordsRemover, Word2VecModel
import sys;
from string import punctuation
def strip_punctuation(arr):
return [''.join(c for c in s if c not in punctuation) for s in arr]
def main():
spark = SparkSession.builder \
... |
from django.shortcuts import render,get_object_or_404
from django.http import Http404
from django.http import HttpResponse
def home(request):
return render(request,'index.html'); |
from clickerft.cft import Cft
from time import sleep
class Suite(Cft):
def test_buy_item_4(self):
while int(self.clicksPerGeneration.text) < 2:
if int(self.clicksOwned.text) < 1:
sleep(.5)
continue
self.increaseClicksPerGeneration.click()
while... |
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def __init__(self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
protos = dict()
... |
"""Contains utility functions for working with the shell"""
from contextlib import contextmanager
import datetime
from decimal import Decimal
import json
import pprint
import sys
import time
import traceback
SHELL_CONTROL_SEQUENCES = {
'BLUE': '\033[34m',
'LTBLUE': '\033[94m',
'GREEN': '\033[32m',
'LTGR... |
"""
Django settings for school project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)))
... |
"""
A simple client to query a TensorFlow Serving instance.
Example:
$ python client.py \
--images IMG_0932_sm.jpg \
--num_results 10 \
--model_name inception \
--host localhost \
--port 9000 \
--timeout 10
Author: Grant Van Horn
"""
from __future__ import absolute_import
from __future__ import division
from __future__... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('merchants', '0006_classfy'),
]
operations = [
migrations.CreateModel(
name='RegionItem',
fields=[
('name', models... |
import json
import os
from processes.postgres import Postgres
from processes.gather_exception import GatherException
try:
DB_SERVER = os.environ['DB_SERVER']
DB_PORT = os.environ['DB_PORT']
DB_DATABASE = os.environ['DB_DATABASE']
DB_USER = os.environ['DB_USER']
DB_PASSWORD = os.environ['DB_PASSWORD'... |
import struct
import socket
import asyncore
import time
import sys
import random
from binascii import hexlify, unhexlify
from io import BytesIO
from codecs import encode
import hashlib
from threading import RLock
from threading import Thread
import logging
import copy
import sscoin_hash
BIP0031_VERSION = 60000
MY_VERSI... |
import urllib.parse
import urllib.request
import json
import logging
import requests
log = logging.getLogger('tyggbot')
class APIBase:
@staticmethod
def _get(url, headers={}):
try:
req = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(req)
exc... |
'''
Created on Dec 13, 2015
@author: Shannon Litwin
'''
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
import Lib_LCD as LCD
import Lib_Main as BBB
import sys
import signal
import time
leftForward = "P8_46"
leftBackward = "P8_45"
rightForward = "P9_14"
rightBackward = "P9_16"
def Control_C_Exit(signa... |
"""
Custom managers for Django models registered with the tagging
application.
"""
from django.contrib.contenttypes.models import ContentType
from django.db import models
class ModelTagManager(models.Manager):
"""
A manager for retrieving tags for a particular model.
"""
def __init__(self, tag_model):
... |
import parsers
import tokenizer
import context
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in unicode(text))
class Tag(object):
... |
import os
import sys
import json
from optional_django import staticfiles
from optional_django.serializers import JSONEncoder
from optional_django.safestring import mark_safe
from optional_django import six
from js_host.function import Function
from js_host.exceptions import FunctionError
from react.render import Render... |
import pytest
import math
import pickle
from ezdxf.math._vector import Vec2, Vec3
from ezdxf.acc import USE_C_EXT
all_vec_classes = [Vec2, Vec3]
vec2_only = [Vec2]
if USE_C_EXT:
from ezdxf.acc.vector import Vec2 as CVec2
all_vec_classes.append(CVec2)
vec2_only.append(CVec2)
@pytest.fixture(params=all_vec_cl... |
from django.shortcuts import render
from .models import Course, Student, StudentCourse
from .serializers import CourseSerializer, StudentSerialiser
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
class StudentViewSet(viewset... |
import time
from test_framework.test_framework import DeuscoinTestFramework
from test_framework.util import *
class TimestampIndexTest(DeuscoinTestFramework):
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 4)
def setup... |
"""
A simple example demonstrating the various ways to call cmd2.Cmd.read_input() for input history and tab completion
"""
from typing import (
List,
)
import cmd2
EXAMPLE_COMMANDS = "Example Commands"
class ReadInputApp(cmd2.Cmd):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **k... |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpRes... |
from __future__ import absolute_import
from .make_haploblocks import get_haploblocks
from .genetic_models import check_genetic_models
from .model_score import get_model_score
from .fix_variant import make_print_version
from .variant_annotator import VariantAnnotator |
import copy
import json
import re
from svtplay_dl.error import ServiceError
from svtplay_dl.fetcher.hls import hlsparse
from svtplay_dl.fetcher.http import HTTP
from svtplay_dl.service import OpenGraphThumbMixin
from svtplay_dl.service import Service
class Vimeo(Service, OpenGraphThumbMixin):
supported_domains = ["... |
from django.apps import apps
from django.contrib import admin
AccessToken = apps.get_model('oauth2', 'AccessToken')
Client = apps.get_model('oauth2', 'Client')
Grant = apps.get_model('oauth2', 'Grant')
RefreshToken = apps.get_model('oauth2', 'RefreshToken')
class AccessTokenAdmin(admin.ModelAdmin):
list_display = (... |
from rest_framework.permissions import BasePermission
class IsBuilding(BasePermission):
"""Checks if a current building (preselected by middleware)
has been assigned for this user"""
def has_permission(self, request, view):
return request.building is not None |
from importlib import import_module
def import_object(object_path):
"""
Import class or function by path
:param object_path: path to the object for import
:return: imported object
"""
module_path, class_name = object_path.rsplit('.', 1)
module = import_module(module_path)
return getattr(... |
import cgi
import cgitb
cgitb.enable()
import mjl, mhl, flt
import redis,os # Questa volta servira` anche os ?
TestoPagina="Configurazione sensori di temperatura"
ConfigFile="../conf/thermo.json"
WriteFile="/cgi-bin/writesensors.py"
RedisKey = "sensore:temperatura"
Dir1w = "/sys/bus/w1/devices/"
MyDB = flt.OpenDBFile(C... |
import json
from pprint import pprint
import time
import io
def ampmformat (hhmmss):
"""
This method converts time in 24h format to 12h format
Example: "00:32" is "12:32 AM"
"13:33" is "01:33 PM"
"""
ampm = hhmmss.split (":")
if (len(ampm) == 0) or (len(ampm) > 3):
return hhmmss
#... |
class bitarray():
def __init__(self,length,defaultValue=False):
if (length < 0):
raise Exception("Length param error")
self.array=[]
self.length=length
fillValue=defaultValue
for i in range(self.length):
self.array.append(defaultValue)
self.ve... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse
from configparser import SafeConfigParser
class Configurable(object):
"""
Configuration processing for the network
"""
def __init__(self, *args, **kwargs):
self._name = kwar... |
from pyquery import PyQuery as pq
from proxypool.schemas.proxy import Proxy
from proxypool.crawlers.base import BaseCrawler
from loguru import logger
BASE_URL = 'https://www.xicidaili.com/'
class XicidailiCrawler(BaseCrawler):
"""
xididaili crawler, https://www.xicidaili.com/
"""
urls = [BASE_URL]
i... |
from django.contrib import admin
from .models import Contact
admin.site.register(Contact) |
from interface.design.ui_screen import Ui_wnd_gifextract
from PyQt5 import QtWidgets
import sys
import listener
import config
import ffmpeg
import queue
import interface.menus.Frame_CreateGif
import interface.menus.Frame_ExtractFrames
import interface.menus.Frame_Queue
class Screen(QtWidgets.QMainWindow):
def __ini... |
from django.core.management import call_command
from django.test import TestCase
from mock import call
from mock import patch
from kolibri.core.content import models as content
class DeleteChannelTestCase(TestCase):
"""
Testcase for delete channel management command
"""
fixtures = ["content_test.json"]
... |
from wtforms import IntegerField, SelectMultipleField
from wtforms.validators import NumberRange
from dmutils.forms import DmForm
import flask_featureflags
class BriefSearchForm(DmForm):
page = IntegerField(default=1, validators=(NumberRange(min=1),))
status = SelectMultipleField("Status", choices=(
("l... |
import os
import re
import string
def isMov(filename):
# ÅжÏÊÇ·ñΪµçÓ°Îļþ
suffix = filename.split('.')[-1].lower() # ÌáÈ¡ºó׺
pattern = re.compile(r'mpg|mpeg|m2v|mkv|dat|vob|avi|wmv|rm|ram|rmvb|mov|avi|mp4|qt|viv')
if pattern.search(suffix): # Æ¥ÅäÊÇ·ñΪµçÓ°¸ñʽ
return True
else:
... |
import db_info
import db_cancel
import db_news
import hashlib
from tweeter import format_info, format_cancel, format_news
import settings
log = settings.log
def add_info_to_queue(q, *args):
try:
# 更新した数をカウント
updated = 0
for lec_info in args:
id = db_info.add_info(*lec_info)
... |
import argparse
from collections import defaultdict
def calculateJaccardIndex(x,z,neighbours):
shared = neighbours[x].intersection(neighbours[z])
combined = neighbours[x].union(neighbours[z])
return len(shared)/float(len(combined))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Calculate s... |
import scrapy
import xml.etree.ElementTree as ET
from locations.items import GeojsonPointItem
URL = 'http://hosted.where2getit.com/auntieannes/2014/ajax?&xml_request=%3Crequest%3E%3Cappkey%3E6B95F8A2-0C8A-11DF-A056-A52C2C77206B%3C%2Fappkey%3E%3Cformdata+id%3D%22locatorsearch%22%3E%3Cdataview%3Estore_default%3C%2Fdatavi... |
from .update_resource import UpdateResource
class VirtualMachineUpdate(UpdateResource):
"""Describes a Virtual Machine.
Variables are only populated by the server, and will be ignored when
sending a request.
:param tags: Resource tags
:type tags: dict[str, str]
:param plan: Specifies information... |
"""Family module for Wikitech."""
from pywikibot import family
class Family(family.WikimediaOrgFamily):
"""Family class for Wikitech."""
name = 'wikitech'
code = 'en'
def protocol(self, code) -> str:
"""Return the protocol for this family."""
return 'https' |
import os
import argparse
import datetime
from lxml import etree, html
from lxml.html.clean import Cleaner
import fnmatch # To match files by pattern
import re
import time
import pandas as pd
def timeit(method):
"""Time methods."""
def timed(*args, **kw):
ts = time.time()
result = method(*args,... |
import pygame
from pygame.locals import *
import numpy as np
grid_size = 100
n_row = 4
n_col = 12
state = np.zeros((n_row * grid_size, n_col * grid_size))
step_size = 0.5
epsilon = 0.1 # parameter for epislon-greedy
N_actions = 4 # number of actions {left,up,right,down}
N_episodes = 600 # number of episodes
goal_r = 3
... |
__author__ = 'jdaniel'
import copy
import random
import itertools
import operator
import math
import struct
import os
import sys
import json
from collections import defaultdict
class AlgorithmBase(object):
def __init__(self, objective_function):
"""
Base Algorithm class which contains utility functi... |
"""update cascading rules
Revision ID: 619fe6fe066c
Revises: 73ea6c072986
Create Date: 2017-03-15 10:51:12.494508
"""
revision = "619fe6fe066c"
down_revision = "73ea6c072986"
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic -... |
"""Freebox component constants."""
from __future__ import annotations
import socket
from homeassistant.components.sensor import SensorEntityDescription
from homeassistant.const import DATA_RATE_KILOBYTES_PER_SECOND, PERCENTAGE, Platform
DOMAIN = "freebox"
SERVICE_REBOOT = "reboot"
APP_DESC = {
"app_id": "hass",
... |
""" Functions and classes dealing with commands. """ |
import os
from slackclient import SlackClient
BOT_NAME = 'chopbot3000'
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
if __name__ == "__main__":
api_call = slack_client.api_call("users.list")
if api_call.get('ok'):
# retrieve all users so we can find our bot
users = api_call.get('... |
import re
import os
import itertools
import time
from string import upper
import ete3
import copy
import subprocess
from collections import defaultdict
from sys import platform
from scipy import stats
from ete3 import Tree
from natsort import natsorted
from Bio import AlignIO
"""
Functions:
~
Chabrielle Allen
Travis Be... |
"""Configuration for Invenio-Formatter."""
from __future__ import absolute_import, print_function
FORMATTER_BADGES_ALLOWED_TITLES = ['DOI']
"""List of allowed titles in badges."""
FORMATTER_BADGES_TITLE_MAPPING = {}
"""Mapping of titles.""" |
from __future__ import unicode_literals
test_data = [
{
"Transaction" : {
"transaction_date" : "2015-01-08",
"amount" : -1286.75,
"security_amount" : 4.0726,
"security_rate" : 413.68
},
"Account" : {
"name" : "Spar Aktie"
},... |
import logging
from marshmallow import ValidationError, post_load
from marshmallow_jsonapi import Schema, fields
from timeswitch.auth.dao import User
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
LOGGER = logging.getLogger(__name__)
cl... |
from __future__ import absolute_import, unicode_literals
from random import shuffle
class Carta():
def __init__(self, numero, naipe):
self.numero = numero
self.naipe = naipe
def __repr__(self):
return '%s de %s' % (self.numero, self.naipe)
class Baralho():
def __init__(self):
... |
__all__ = ("settings", "urls", "wsgi")
__version__ = "0.159.0" |
import sys
from os import path
current_dir = path.dirname(__file__)
sys.path.insert(0, path.join(path.dirname(current_dir), 'wdom')) |
import sys
import time
from pprint import pprint
import telepot
from telepot.namedtuple import StickerSet
TOKEN = sys.argv[1]
USER_ID = long(sys.argv[2])
STICKER_SET = sys.argv[3]
bot = telepot.Bot(TOKEN)
f = bot.uploadStickerFile(USER_ID, open('gandhi.png', 'rb'))
print 'Uploaded Gandhi'
bot.addStickerToSet(USER_ID, S... |
from __future__ import unicode_literals
import unittest
from ship.datastructures import rowdatacollection as rdc
from ship.datastructures import dataobject as do
from ship.fmp.datunits import ROW_DATA_TYPES as rdt
class RowDataCollectionTests(unittest.TestCase):
def setUp(self):
# Create some object to use ... |
"""
Django settings for busquecursos project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_K... |
class PortalMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# ... |
from snovault import upgrade_step
@upgrade_step('gene', '1', '2')
def gene_1_2(value, system):
# https://encodedcc.atlassian.net/browse/ENCD-5005
# go_annotations are replaced by a link on UI to GO
value.pop('go_annotations', None)
@upgrade_step('gene', '2', '3')
def gene_2_3(value, system):
# https://e... |
import numpy as np
import os,sys
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import argparse
ap=argparse.ArgumentParser()
ap.add_argument('-vis') # 1 plot cropped point cloud
ap.add_argument('-refine') # 1 refine mesh
ap.add_argument('-clean') # 1 remove tmp files
if ap.parse_args()... |
"""oclubs filters."""
from __future__ import absolute_import
from oclubs.filters.resfilter import ResFilter, ResFilterConverter
from oclubs.filters.clubfilter import ClubFilter, ClubFilterConverter
from oclubs.filters.roomfilter import RoomFilter, RoomFilterConverter
__all__ = ['ResFilter', 'ResFilterConverter',
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('benchmark', '0008_benchmarkdefinition_commit_keyword_updated'),
]
operations = [
migrations.AlterField(
model_name='benchmarkexecutionentry',... |
"""Creates beautiful visualizations of the publication database."""
import datetime
import sqlite3 as sql
import numpy as np
from astropy import log
from matplotlib import pyplot as plt
import matplotlib.patheffects as path_effects
import matplotlib as mpl
from matplotlib import style
import seaborn as sns
from kpub im... |
import sys, os
ON_RTD = os.environ.get('READTHEDOCS') == 'True'
if ON_RTD:
from unittest.mock import MagicMock
MOCK_MODULES = ['h5py']
sys.modules.update((mod_name, MagicMock()) for mod_name in MOCK_MODULES)
import bayespy as bp
html_theme = 'sphinx_rtd_theme'
extensions = [
'sphinx.ext.autodoc',
's... |
import logging
from office365.sharepoint.helpers.utils import to_camel
logger = logging.getLogger(__name__)
class QueryStringBuilder:
"""class to map web-querystring dictionary to sharepoint-querystring"""
date_operators = ['ge', 'gt', 'le', 'lt']
mapping_operator = {
'gte': 'ge',
'gt': 'gt'... |
import unittest
import json
import time
from celery import current_app
from django.conf import settings
from django.utils import timezone
from ep.models import DPMeasurements, DeviceParameter
from ep.tasks import send_msg
from django.test import TestCase, modify_settings, override_settings
from ep.tests.static_factorie... |
from django.http import Http404, HttpResponse
from django.template.context_processors import csrf
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.views import APIView
from .model... |
import imp
import optparse
import os
import platform
import re
import signal
import subprocess
import sys
import tempfile
import time
import threading
import utils
from os.path import join, dirname, abspath, basename, isdir, exists
from datetime import datetime
from Queue import Queue, Empty
VERBOSE = False
class Progr... |
import getopt
import json
import locale
import os
import re
import sys
from urllib import request, parse
import platform
import threading
from .version import __version__
from .util import log, sogou_proxy_server, get_filename, unescape_html
dry_run = False
force = False
player = None
sogou_proxy = None
sogou_env = Non... |
import math
import scipy.optimize as opt
log = math.log
exp = math.exp
small = 1e-20 # unitless
T0 = 1 # K
Tcrit = 650 # K
zero_C = 273.15 # K
p0 = 1 # Pa
atm = 101325 # Pa
bar = 100000 ... |
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
from DbC import pre, post
def check_pre(*args):
'P... |
import django.db.models.deletion
import django.utils.timezone
import django_fsm
from django.conf import settings
from django.db import migrations, models
import apps.core.models
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
o... |
from datetime import date
from openpyxl import load_workbook
if __name__ == '__main__':
wb = load_workbook('FixedCouponBond.xlsx')
ws = wb.active
# Take the input parameters
today = ws['C2'].value.date()
# OIS Data
ois_startdate = today
ois_maturities = []
ois_mktquotes = []
for cell... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.