content string |
|---|
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
def get_celebrity_info(info_node_dict):
celebrity_info = {}
if '性别' in info_node_dict:
celebrity_info['sex'] = \
info_node_dict['性别'].span.next_sibling.string.strip(': \n')
if '星座' in info_node_dict:
celebrity_info['cons... |
import PIL
import numpy as np
from maskgen import exif
from maskgen.image_wrap import openImageFile, ImageWrapper
from maskgen.tool_set import getExifDimensions
"""
Save te image as PNG. If the image has a orientation and 'Image Rotated', rotate the image according to the EXIF.
"""
def transform(img,source,target, **k... |
# -*- coding: utf-8 -*-
'''
Logstash Logging Handler
========================
.. versionadded:: 0.17.0
This module provides some `Logstash`_ logging handlers.
UDP Logging Handler
-------------------
For versions of `Logstash`_ before 1.2.0:
In the salt configuration file:
.. c... |
from urllib import parse
import json
from tornado.testing import AsyncHTTPTestCase
from pylm.registry.application import make_app
from datetime import datetime
from pylm.registry.messages.registry_pb2 import LogMessages
cluster = """
[Valuation Master]
Script = valuation_standalone_master.py
--pull = _1
--pub = _2
--w... |
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2013 Task Coach developers <<EMAIL>>
Task Coach 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) ... |
import discord
import requests
import subprocess
import sys
import os
import asyncio
import random
logFile = open("logs.txt", "a")
tLog = True
def commandLog(message):
msgData = message.author.name + " - " + message.author.id + " - " + message.content + "\n"
msgData = msgData.replace("\n", "\n ")
if tLog =... |
import os
from zope.interface.advice import addClassAdvisor
from lift import Runtime
_layout_engines = {}
class View(object):
"""
Base class for use by views within lift. Provides hook actions during
init, so if you override __init__, make sure it gets called.
"""
controller = None
def __in... |
import os
from tempfile import mkdtemp
from contextlib import contextmanager
from fabric.operations import put
from fabric.api import env, local, sudo, run, cd, prefix, task, settings
env.roledefs = {
'staging_prep': ['<EMAIL>']
}
STAGING_HOST = 'staging.centralfitestoque.com'
CHEF_VERSION = '10.20.0'
env.roo... |
from __future__ import unicode_literals
import boto3
import json
from botocore.exceptions import ClientError
from six.moves.email_mime_multipart import MIMEMultipart
from six.moves.email_mime_text import MIMEText
import sure # noqa
from moto import mock_ses, mock_sns, mock_sqs
from moto.ses.models import SESFeedback... |
#!/usr/bin/env python2.5
import sys
from rosettautil.rosetta import rosettaScore
from rosettautil.protein import util
from rosettautil.util import fileutil
from Bio.PDB import *
from optparse import OptionParser
usage = "%prog input.pdb output.pdb"
parser= OptionParser(usage)
parser.add_option("-n",dest="start",help="... |
import config, forms, time, lib, userdb
import subprocess
from valuespec import *
import cmk.store as store
def get_gui_messages(user_id = None):
if user_id is None:
user_id = config.user.id
path = config.config_dir + "/" + user_id.encode("utf-8") + '/messages.mk'
messages = store.load_data_from_fi... |
from nose import SkipTest
from celery.tests.utils import unittest
class MockWindow(object):
def getmaxyx(self):
return self.y, self.x
class TestCursesDisplay(unittest.TestCase):
def setUp(self):
try:
import curses # noqa
except ImportError:
raise SkipTest(... |
# -*- coding: utf-8 -*-
import nose.tools as ns
from relshell.type import Type
from relshell.timestamp import Timestamp
def test_type_usage():
ns.eq_(str(Type('STRING')), 'STRING')
ns.eq_(Type.equivalent_relshell_type(-123), Type('INT'))
def test_types():
ns.eq_(Type.equivalent_relshell_type(-123) ... |
import itertools as it
import sys
import traceback
from prettytable import PrettyTable
from operator import itemgetter
from dag.digraph import *
from dag.edge import *
import connection_factory
from geo import geo_locate as geo
from urlparse import urlparse
geolocate_cache = dict()
def geolocate(urls):
"""Caches... |
import logging
import requests
import rmock
from rmock import call
from rmock.runners.http.proxy.choosers import HeaderBasedChooser
from testtools import http_call
from nose.tools import assert_equals
class TestHttpProxy(object):
def test_http_proxy_simple(self):
first = rmock.run(port="random", k... |
import pygame
import random
pygame.display.set_caption("Multi Bingo")
screen = pygame.display.set_mode((0,0))
screen.fill([0,0,0])
pygame.mouse.set_visible(False)
meter = pygame.image.load('graphics/assets/register_cover.png').convert()
eb = pygame.image.load('spot_lite/assets/arrow.png').convert_alpha()
exb = pygame... |
"""Test fields.
$Id: test_fields.py 29570 2005-03-18 22:53:37Z rogerineichen $
"""
import unittest
from zope.testing.doctestunit import DocTestSuite
from zope.app.testing import placelesssetup
def test_suite():
return unittest.TestSuite((
DocTestSuite('zope.app.publisher.browser.fields',
... |
# In the event of a migration that applies to multiple TLOs, you can put
# functions here so you don't have to duplicate code across several migration
# files.
# For migrating analysis results to their own collection.
# mgoffin
# 2014-09-24
def migrate_analysis_results(self):
from crits.services.analysis_result im... |
from binascii import hexlify
from aiohttp import web
from aiohttp_apispec import docs, json_schema
from marshmallow.fields import Boolean, Dict, List, Nested, String
from .base_endpoint import BaseEndpoint, HTTP_BAD_REQUEST, HTTP_PRECONDITION_FAILED, Response
from .schema import DefaultResponseSchema, OverlaySchema... |
__author__ = 'colinwren'
import unittest
from dependency_graph.dependency_graph import DependencyGraph
from dependency_graph.json_formatter import JsonFormatter
from mock import Mock
from treelib import Tree
class TestJsonFormatter(unittest.TestCase):
def test_01_raises_error_if_non_dependency_graph_object_passed... |
from .line import LineChart
class ScatterplotChart(LineChart):
def _renderChart(self, cx):
"""Renders a scatterplot"""
def drawSymbol(point, size=2):
ox = point.x * self.area.w + self.area.x
oy = point.y * self.area.h + self.area.y
cx.move_to(ox-size, oy)
... |
from __future__ import absolute_import, division, print_function
import tube
from tube_calib_fit_params import TubeCalibFitParams
import mantid.simpleapi as mantid
# == Set parameters for calibration ==
filename = 'MAP14919.raw' # Calibration run ( found in \\isis\inst$\NDXMAPS\Instrument\data\cycle_09_5 )
# Set wh... |
"""
The :mod:`~openlp.core.theme` module contains all the themeing functions used by
OpenLP when displaying a song or a scripture.
"""
from openlp.core.theme.theme import Theme
__all__ = ['Theme'] |
from rally.benchmark.scenarios import base
class ZaqarScenario(base.Scenario):
"""Base class for Zaqar scenarios with basic atomic actions."""
@base.atomic_action_timer("zaqar.create_queue")
def _queue_create(self, name_length=10, **kwargs):
"""Create a Zaqar queue with random name.
:par... |
from django.contrib.gis.db import models
from django.conf import settings
class BioregionManager(models.GeoManager):
def which_bioregion(self,geom):
"""Given a geometry, this method will return the name of the bioregion that contains that geometry's centroid."""
pnt = geom.centroid
qs = sup... |
#!/usr/bin/env python3
#Title : NoTrack Input Validation
#Description : Regex Strings to match various forms of user input
#Usage : N/A this module is loaded as part of other NoTrack modules
FILTER_IP = r'^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA... |
r"""Command-line tool to validate and pretty-print JSON
Usage::
$ echo '{"json":"obj"}' | python -m simplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m simplejson.tool
Expecting property name: line 1 column 2 (char 2)
"""
import sys
import simplejson as json
... |
# Super-flaky script using ImageMagick's convert to, well, convert
# truetype fonts to Lecturer's preferred format.
# Creates 8859-1 codepoints on an UTF-8 system, for some reason.
import os
import struct
import sys
import time
minchar = 32
maxchar = 256
try: os.mkdir('Lecturer/fonts')
except: pass
for k in [8, 10,... |
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.shortcuts import redirect
from django.shortcuts import render
from pykeg.web.kbregistration.forms import KegbotRegistrationForm
from pykeg.backend import get_kegbot_backend
from pykeg.core import models
"""Kegbot-aware reg... |
#! /usr/bin/env python
#################################################################################################
#
# Script Name: bip.py
# Script Usage: This script is the menu system and runs everything else. Do not use other
# files unless you are comfortable with the code.
#
# ... |
"""Common options for the BigMLer parser
"""
import datetime
def get_common_options(defaults=None, constants=None):
"""Common options used in all subcommands
"""
if defaults is None:
defaults = {}
if constants is None:
constants = {}
now = constants.get('NOW',
... |
import sys
from airflow.models import BaseOperator
# ------------------------------------------------------------------------
#
# #TODO #FIXME Airflow 2.0
#
# Old import machinary below.
#
# This is deprecated but should be kept until Airflow 2.0
# for compatibility.
#
# ----------------------------------------------... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class TollFreeTestCase(Integrat... |
from func.minion import sub_process
from func.minion import codes
# our modules
import func_module
# =================================
class ProcessModule(func_module.FuncModule):
version = "0.0.1"
api_version = "0.0.1"
description = "Process related reporting and control."
def info(self, flags="-a... |
import functools as _f
from warnings import warn
from ...common import requires as _requires
__all__ = ["to_wkb", "to_wkt", "area", "distance", "length", "boundary", "bounds", "centroid", "representative_point", "convex_hull", "envelope", "buffer", "simplify", "difference", "intersection", "symmetric_difference", "uni... |
import binascii
import os
import sys
import pygame
from specialfunctions import *
# Useful RGB Values
WHITE = pygame.Color(0xff, 0xff, 0xff, 0xff)
BLACK = pygame.Color(0x00, 0x00, 0x00, 0xff)
HOTPINK = pygame.Color(0xff, 0x69, 0xb4, 0xff)
RED = pygame.Color(0xff, 0x00, 0x00, 0xff)
YELLOW = pygame.Color(0xff... |
#Made by Kerb
import sys
from com.l2scoria import Config
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "603_DaimontheWhiteEyedPart1"
#Npcs
EYE = 31683
TABLE1,TABLE2,TA... |
__author__ = "Emanuele Pucciarelli"
__organization__ = "C.O.R.P. s.n.c"
__copyright__ = "Copyright 2007-2012, C.O.R.P. s.n.c"
__license__ = "GNU Affero GPL v. 3.0"
__contact__ = "<EMAIL>"
# Django settings for Faxcelerate.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAG... |
from IPy import IP
from cloudify import exceptions as cfy_exc
import collections
from pyvcloud.schema.vcd.v1_5.schemas.vcloud import taskType
from vcloud_plugin_common import (wait_for_task, get_vcloud_config,
is_subscription, error_response)
VCLOUD_VAPP_NAME = 'vcloud_vapp_name'
PUB... |
#!/usr/bin/env python
from __future__ import absolute_import
import os
import os.path
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
NAME = "future"
PACKAGES = ["... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
from math import log
TABLE_PADDING = ' ' * 3
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[32m'
WARNING = '\033[93m'
FAIL = '\033[31m'
ENDC = '\033[0m'
def disable(self):
... |
"""Tests for the tasks endpoint."""
from datetime import date, timedelta
import pytest
from django.urls import reverse
from rest_framework import status
def test_task_list_not_archived(auth_client, task_factory):
task = task_factory(archived=False)
task_factory(archived=True)
url = reverse("task-list")
... |
"""Various generic utility classes and functions.
Provided utilities are generally stable, but absolute backwards compatibility
between major versions is not guaranteed.
"""
from .argumentparser import ArgumentParser
from .application import Application
from .compress import compress_text
from .connectioncache import... |
"""
This is the implementation of Copy-NET
We start from the basic Seq2seq framework for a auto-encoder.
"""
import logging
import time
import numpy as np
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from experiments.config import setup_syn
from emolga.utils.generic_utils import *
from emolga.... |
import tensorflow.compat.v1 as tf
from tensorflow_gan.examples.stargan import layers
class LayersTest(tf.test.TestCase):
def test_residual_block(self):
n = 2
h = 32
w = h
c = 256
input_tensor = tf.random.uniform((n, h, w, c))
output_tensor = layers._residual_block(
input_net=inpu... |
import re
from django.conf import settings
from django.core import urlresolvers
import localeurl.settings
SUPPORTED_LOCALES = dict(settings.LANGUAGES)
LOCALES_RE = '|'.join(SUPPORTED_LOCALES)
PATH_RE = re.compile(r'^/(?P<locale>%s)(?=/)(?P<path>.*)$' % LOCALES_RE)
DOMAIN_RE = re.compile(r'^(?P<locale>%s)(?=/)\.(?P<dom... |
"""
Local node REST api.
"""
from __future__ import absolute_import
import os
import httplib
# pylint: disable=E0611,F0401
import flask
import flask.ext.restplus as restplus
from flask import request
from treadmill import webutils
def _archive_type():
"""Get archive type from query string."""
archive_type ... |
import MaKaC.webinterface.pages.category as category
import MaKaC.webinterface.wcomponents as wcomponents
import MaKaC.webinterface.urlHandlers as urlHandlers
import MaKaC.conference as conference
from indico.core.config import Config
import MaKaC.common.info as info
from MaKaC.i18n import _
from MaKaC.common.timezoneU... |
"""
Variable Markov Oracle algorithm
"""
from msaf.algorithms.interface import SegmenterInterface
import librosa
from . import main
class Segmenter(SegmenterInterface):
"""
This script identifies the structure of a given track using the Variable
Markov Oracle technique described here:
Wang, C., Mysor... |
"""
Custom Authenticator to use GitHub OAuth with JupyterHub
Most of the code c/o Kyle Kelley (@rgbkrk)
"""
import json
import os
import urllib
from tornado.auth import OAuth2Mixin
from tornado.escape import url_escape
from tornado import gen, web
from tornado.httputil import url_concat
from tornado.httpclient imp... |
from unittest import TestCase
from net.wyun.mer.ink.sample import Sample
import numpy as np
import MySQLdb
import _mysql
'''
test mysql db
'''
class TestEquation(TestCase):
def setUp(self):
# Open database connection
self.db = MySQLdb.connect("host6", 3308, "uxb", "uxb123", "uxb", charset = 'ut... |
import time
from urllib.parse import urlencode
import requests
import requests.auth
from flask import Flask, abort, request
from .config import Config
from .utils import get_file
cfg_cls = Config()
app = Flask(__name__)
@app.route('/')
def homepage():
try:
with open(get_file('furikura/ui/login/login.ht... |
from pygame import sprite, Rect
import pygame.font
import enum
from enum import Enum
class ButtonType(Enum):
Quit = 1
PlayAgain = 2
Castle = 3
class Button(sprite.Sprite):
def __init__(self, screen, message, bType, color, textColor, textFont, buttonCount):
sprite.Sprite.__init__(self)
... |
import requests
import simplejson as json
from simplejson.scanner import JSONDecodeError
from time import sleep
from datetime import datetime
from parse import search_landsat_tiles, search_modis_tiles
from conf import API_HOST_URL, API_VERSION, HEADERS
from Exceptions import *
from Downloaders import BaseDownloader
c... |
"""
Record data at different readout powers at regular intervals.
"""
from __future__ import division
import time
import numpy as np
from kid_readout.roach import r2baseband, analog
from kid_readout.measurement import acquire, core, basic
from kid_readout.equipment import hardware
from kid_readout.settings import ROA... |
import os
# we need to select a txaio subsystem because we're importing the base
# protocol classes here for testing purposes. "normally" yo'd import
# from autobahn.twisted.wamp or autobahn.asyncio.wamp explicitly.
import txaio
if os.environ.get('USE_TWISTED', False):
txaio.use_twisted()
else:
txaio.use_async... |
'''
Module of MacOS API for plyer.bluetooth.
'''
from subprocess import Popen, PIPE
from plyer.facades import Bluetooth
from plyer.utils import whereis_exe
from os import environ
class OSXBluetooth(Bluetooth):
'''
Implementation of MacOS bluetooth API.
'''
def _get_info(self):
old_lang = en... |
import os
import string
import httplib2
import json
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.django_orm import Storage
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import Co... |
from pysollib.game import Game
from pysollib.gamedb import GI, GameInfo, registerGame
from pysollib.hint import CautiousDefaultHint
from pysollib.layout import Layout
from pysollib.stack import \
DealRowTalonStack, \
InitialDealTalonStack, \
RedealTalonStack, \
SS_FoundationStack, \
... |
import os, sys
import myfun
import numpy as np
import lagrangian_stats
import scipy.interpolate as interpolate
import csv
import matplotlib.pyplot as plt
import advect_functions
import fio
from intergrid import Intergrid
## READ archive (too many points... somehow)
# args: name, dayi, dayf, days
#label = 'm_25_2_512'... |
import pytest
import numpy as np
import dask.array as da
from pyxem.signals.diffraction2d import Diffraction2D
import pyxem.utils.pixelated_stem_tools as pst
from hyperspy.signals import Signal2D
class TestRadialIntegrationDaskArray:
def test_simple(self):
dask_array = da.zeros((10, 10, 15, 15), chunks=(5... |
"""StarStruct fixedpoint element class."""
# pylint: disable=line-too-long
import re
import struct
import decimal
from decimal import Decimal
from starstruct.element import register, Element
from starstruct.modes import Mode
# TODO: I think we could probably just do most of this with struct.calcsize
BITS_FORMAT = ... |
import data_pipeline.constants.const as const
from .base_message import BaseMessage
class OracleMessage(BaseMessage):
def __init__(self):
"""Constructer OracleMessage()
Attributes:
operation_code (str): operation code
statement_id (str): statement id
commit_tim... |
"""
The hierarchy of Doxhooks exceptions.
All Doxhooks exceptions derive from `DoxhooksError`, which derives from
`Exception`. Exceptional conditions can arise when Doxhooks is handling
input data (`DoxhooksDataError`) or files (`DoxhooksFileError`).
Doxhooks exception hierarchy
****************************
* `Excep... |
import common.core
import data_loader.loader_util
from chart.chart_data import chart_data
import arc_mon.arc_view
def arc_dashboard(*cluster_list):
ret = []
for cluster in cluster_list:
cluster_map = arc_mon.arc_view.arc_cluster_map
if cluster not in cluster_map:
ret.append(data_loader.loader_util.title_lo... |
'''
Copyright (C) 2015 Saeed Gholami Shahbandi. All rights reserved.
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Th... |
# -*- coding: utf-8 -*-
"""
Date: 2/2/2017
Team: Satoshi Nakamoto
@Authors: Alex Levering and Hector Muro
Non-standard dependencies:
* Twython
* NLTK
* Folium
* Geocoder
* psycopg2
TO DO BEFOREHAND:
The following steps are non-automatable and have to be performed manually.
* Have the NLTK vader lexicon locally (nltk... |
#!/usr/bin/env python
# TODO(cs): inject deterministic.js into the HTML? May change behavior enough
# to cause the replay to miss some resources, but then again, if the replay is
# going to miss some resources, it's probably acutely non-deterministic in the
# first place, so deterministic.js injection shouldn't make i... |
#!/usr/bin/python3.4
import requests
import xml.etree.ElementTree as ET
import json
import sys, os
from optparse import OptionParser
def searchLastFM(user, api_key, tracks, currPage):
payload = {
"user": user,
"api_key": api_key,
"limit": 50, # 50 elem on each page
"method": "user.getrecenttracks",
"page"... |
from django import template
from django.utils.safestring import mark_safe
from django.template.base import Node
register = template.Library()
from tag_parser import template_tag
from tag_parser.basetags import BaseNode
@template_tag(register, 'asset')
class JsCssAssetNode(BaseNode):
"""
Implement asset filte... |
# coding: utf-8
# In[1]:
import numpy as np
import tensorflow as tf
from __future__ import print_function
# # XOR Network
# ### Data generation
# In[2]:
def create_examples(N, batch_size):
A = np.random.binomial(n=1, p=0.5, size=(batch_size, N))
B = np.random.binomial(n=1, p=0.5, size=(batch_size, N,))
... |
"""
.. currentmodule:: pygmin.optimize
Optimizers (`pygmin.optimize`)
================================
This module contains all of the optimizers available in pygmin. There are so
many available for testing purposes and because sometimes different optimizers are
more appropriate in different circumstances. These o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" calisphere new production index QA script """
import os
import sys
import argparse
import xlsxwriter
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from pprint i... |
from tools import *
global buffer
buffer=None
global bufferstring
bufferstring=" "
try:
#import infodock
pass
except:
sayexc()
def saySomething(stuff):
'''
event server
'''
#say("---------------------------------------------------------------------------------------")
global buffer
global bufferstring
d... |
import sys, os
from datetime import datetime
import django
import traceback
os.environ['DJANGO_SETTINGS_MODULE']="mwd_proj.settings"
django.setup()
from mwd_proj.utils.utils2 import *
import traceback
from django.db.models import Sum
import operator
import math
from django.db.models.functions import Lower
from mwd_proj... |
# Youtube scraper
from extensions.scrapers import base
import itertools
import requests
import validators
from urllib import parse
from lxml import etree
class Scraper(base.Scraper):
def __init__(self):
super().__init__()
def can_be_scraped(self, song):
if not self.is_url(song):
return True
return self... |
from . import pathinformation
class SecondaryInformation(object):
__slots__ = 'paths', 'externalReferences'
def __init__(self, paths, externalReferences):
self.paths = paths
self.externalReferences = externalReferences
def merge(self, other):
paths, pathsChanged = self.paths.inplaceMerge(other.paths)
if pa... |
#!/usr/bin/python
# coding: utf8
import geocoder
location = 'Ottawa, Ontario'
city = 'Ottawa'
ottawa = (45.4215296, -75.6971930)
winnetka = 'Winnetka'
winnetka_bbox = [-118.604794,34.172684,-118.500938,34.236144]
def test_mapbox():
g = geocoder.mapbox(location)
assert g.ok
osm_count, fields_count = g.d... |
# -*- coding: utf-8 -*-
import os
import scrapy
import re
import urlparse
import logging
from functions import *
from pypinyin import lazy_pinyin
from scrapy.selector import Selector
from taobaomm.settings import LOG_FILE
from taobaomm.items import MMItem
logger=logging.getLogger('taobaomm')
formatter=log... |
'''
Created on Feb 25, 2015
@author: James Culbertson
'''
from ConfigParser import ConfigParser
import constants as c
import os.path
class Config(object):
'''
Loads and saves the configurations files.
User config is read and written on demand.
'''
def __init__(self):
self.user_config = {}... |
class KodeDriveError(Exception):
application = 'KodeDrive'
class FileNotInConfig(KodeDriveError):
def __init__(self, f_path):
super(Exception, self).__init__(
"%s could not find %s. Is it being synchronized?" % (self.application, f_path)
)
class DeviceNotFound(KodeDriveError):
def __init__(s... |
from Errors import CommandExecutionError
class CommandSequence:
"""A CommandSequence wraps a series of commands to be performed
on a visit to one top-level site into one logical
"site visit," keyed by a visit id. An example of a CommandSequence
that visits a page and dumps cookies modified on that visi... |
PYMCA_IMPORTED = False
try:
from PyMca5.PyMca import QPeriodicTable
PYMCA_IMPORTED = 5
except BaseException:
try:
from PyMca import QPeriodicTable
PYMCA_IMPORTED = 4
except BaseException:
pass
from mxcubeqt.utils import qt_import
__credits__ = ["MXCuBE collaboration"]
__licens... |
from lifxlan import *
from random import randint, betavariate
from time import sleep
def main():
lan = LifxLAN()
tilechain_lights = lan.get_tilechain_lights()
if len(tilechain_lights) != 0:
t = lan.get_tilechain_lights()[0] #grab the first tilechain
print("Selected TileChain light: {}".form... |
# A flat-bottom harmonic potential on the center of mass
# that keeps the system within a cylinder
# with principal axis along the direction (1,0,0).
from MMTK.ForceFields.ForceField import ForceField
from MMTK_cylinder import CylinderTerm
import numpy as N
# Exactly the same as the pure Python version
class Cylinde... |
"""This test contains necessary smoke tests for the Control."""
import pytest
from cfme import control
from cfme import test_requirements
from cfme.utils.appliance.implementations.ui import navigate_to
pytestmark = [
test_requirements.control,
pytest.mark.smoke,
pytest.mark.tier(2)
]
destinations = [
... |
#!/usr/bin/python
from subprocess import *
from email.mime.text import MIMEText
import pickle
from os import path
from datetime import datetime
from datetime import timedelta
#######################################
## BEGIN configurable options
#######################################
vsql = '/opt/vertica/bin/vsql'
ve... |
"""
Django settings for ptaAPP project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... |
import sys
import pytest
import pprint
import pylibefp
from systems import *
from qcelemental.testing import compare_recursive
def test_opts_libefp():
asdf = system_1()
ref1 = {
'ai_elec': False,
'elec_damp': 'screen',
'ai_disp': False,
'chtr': False,
'swf_cutoff': 0.... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SSL_DISABLE = False
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_RECORD_QUERIES = True
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAI... |
import os
import platform
from contextlib import contextmanager
from subprocess import Popen, PIPE, STDOUT
PLATFORM_NAME = platform.system()
def get_maven_name():
return 'mvn.cmd' if PLATFORM_NAME == 'Windows' else 'mvn'
def which(file_name):
if PLATFORM_NAME == 'Linux':
exit_code, file_path = run... |
from django.conf import settings
from django.db import models
class AbstractUserScore(models.Model):
class Meta(object):
abstract = True
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=False,
related_name='scores',
db_index=True,
on_delete=models.CASC... |
import pandas as pd
import datetime as dt
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import os
#set 'working directory' to help windows task scheduler. This is where the script is saved
os.chdir('C:/Users/Operator/Desktop')
#Prepare file, asertain todays date and... |
from __future__ import unicode_literals
"""
Sends email via outgoing server specified in "Control Panel"
Allows easy adding of Attachments of "File" objects
"""
import webnotes
import conf
from webnotes import msgprint
from webnotes.utils import cint
def get_email(recipients, sender='', msg='', subject='[No Subject]... |
import os
import cv2
import glob
import numpy as np
import logging
from sklearn.utils import shuffle
from main.dataset import DataSet
def load_image(image_path, image_size, file_index=0, num_files=1,
images=None, ids=None, labels=None, cls=None, category=None):
if images is None:
images = ... |
#!/usr/bin/env python3
import datetime
import json
import pydgraph
# Create a client stub.
def create_client_stub():
return pydgraph.DgraphClientStub('localhost:9080')
# Create a client.
def create_client(client_stub):
return pydgraph.DgraphClient(client_stub)
# Drop All - discard all data and start from... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# tvalacarta - XBMC Plugin
# Canal para Canal 22 (México)
# http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/
#------------------------------------------------------------
import urlparse,re
import urllib
import os
from core import... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='django-handlers',
version=__import__('django_handlers').__version__,
url='https://github.com/antonev/django-handlers',
license='MIT',
description='Simple library for creation '
... |
""" Copyright (C) 2018 Travis DeWolf
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 program is distributed in the hope t... |
import json
import arrow
import random
import discord
import aiohttp
import datetime
def time_to_seconds(time):
hrs, mins, secs = time.split(':')
output = (int(hrs) * 3600) + (int(mins) * 60) + int(secs)
return output
def get_usercaps(username, trials):
output = username
for trial in trials:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.