code stringlengths 1 199k |
|---|
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
words = s.split(' ')
occurences = []
for word in words:
occurences.append((word, words.count(word)))
words = filter(lambda a: a != word, words)
... |
'''
Copyright (c) 2019-2021, Arm Limited and Contributors
SPDX-License-Identifier: Apache-2.0
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 req... |
import time
import datetime
import traceback
try:
import httplib as httplibs
except ImportError:
import http.client as httplibs
import shlex
import subprocess
import sys
from common import CommonVariables
from subprocess import *
from Utils.WAAgentUtil import waagent
import sys
class HttpUtil(object):
"""de... |
from PySide import QtGui
from .simple import Simple
class Boolean(Simple):
'''Boolean control.'''
def _construct(self):
'''Construct widget.'''
super(Boolean, self)._construct()
self.layout().setStretchFactor(self._control, 0)
self.layout().addStretch(1)
def _constructControl... |
from wsgi_basic.common import wsgi
from wsgi_basic.user import controllers
class Router(wsgi.ComposableRouter):
def add_routes(self, mapper):
user_controller = controllers.User()
mapper.connect('/users',
controller=user_controller,
action='create_user',
... |
from oslo_config import cfg
from st2common.constants.auth import VALID_MODES
from st2auth.backends import get_backend_instance as get_auth_backend_instance
from st2auth.backends.constants import AuthBackendCapability
__all__ = [
'validate_auth_backend_is_correctly_configured'
]
def validate_auth_backend_is_correctl... |
import weakref
class ExpensiveObject:
def __del__(self):
print('(Deleting {})'.format(self))
def on_finalize(*args):
print('on_finalize({!r})'.format(args))
obj = ExpensiveObject()
weakref.finalize(obj, on_finalize, 'extra argument')
del obj |
import time
from givabit.ui_tests import ui_test_utils
from givabit.ui_tests.page_objects.confirmation_page import ConfirmationPage
from givabit.ui_tests.page_objects.front_page import FrontPage
from givabit.ui_tests.page_objects.login_page import LoginPage, TestUser
from givabit.ui_tests.page_objects.signup_page impor... |
from collections import OrderedDict
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_cor... |
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2012-2013 by the SaltStack Team, see AUTHORS for more details
:license: Apache 2.0, see LICENSE for more details.
tests.integration.states.match
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''
import os
from salttesting import skipIf
from... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
import tempfile
import time
import unittest
from apache_beam import coders
from apache_beam.io import filesystems
from apache_beam.runners.interactive import cache_manager as cache
class ... |
import fixtures
import lxml.etree
from oslo_log import log as logging
from datahub.news_detector.rule import article
from datahub.news_detector.rule import config
from datahub.news_detector.rule.extractor import Extractor
from datahub.tests import base
DOMAIN_PATH = "./data/targets"
LOG = logging.getLogger(__name__)
cl... |
"""
Django settings for api project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
from urlpars... |
import datetime
import collections
from sqlalchemy import and_
from sqlalchemy import not_
from sqlalchemy import or_
from ggrc.models.custom_attribute_value import CustomAttributeValue
from ggrc.models.reflection import AttributeInfo
from ggrc.models.relationship_helper import RelationshipHelper
from ggrc.converters i... |
from boole.core.expr import *
import sage
from sage.symbolic.expression_conversions import Converter
from sage.symbolic.ring import the_SymbolicRing
from sage.symbolic.function_factory import function_factory
import operator as _operator
_built_in_sage_funs = {
equals.name: (lambda args: args[0] == args[1]),
no... |
from __future__ import absolute_import, division, print_function
import six
from cryptography import utils
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.backends.interfaces import RSABackend
def generate_private_key(public_exponent, key_size, backend):
if not isinstance... |
import sys
import heapq
from itertools import takewhile
zero = 0
def clone(obj):
return 0 #obj.copy();
def add(acc, key, val):
return acc + float(val)
def process_results(result):
values = sorted(result, reverse=True)
return values
topN = [(0, "")] * 10
def print_result(result):
for (val, key) in pr... |
from __future__ import print_function, unicode_literals, absolute_import
set_lcd_filter = """
Apply color filtering to LCD decimated bitmaps.
Works when called `Glyph.render` with `RENDER_MODE.LCD` or `RENDER_MODE.LCD_V`.
Parameters
----------
filter : `LCD_FILTER` constant
Notes
-----
This feature is always disabled b... |
import pytest
import trafaret as t
from trafaret.keys import (
KeysSubset,
subdict,
xor_key,
confirm_key,
)
from trafaret import catch_error, extract_error, DataError
class TestKey:
def test_key(self):
default = lambda: 1
res = next(t.Key(name='test', default=default)({}))
as... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Slider'
db.create_table('mezzanine_slides_slide', (
('id', self.gf('django.db.models.fields.AutoField')(pri... |
from . import Cache
import requests
from . import NotFoundError
class HttpCache(Cache):
"""Cache that uses HTTP protocol. Similar to a read-only version of the S3 cache, except that the
list() method requires that a special file, meta/_list.json be put to the source"""
def __init__(self, url, **kwargs):
... |
from __future__ import print_function
import os, sys, inspect
import h5py
import numpy as np
import matplotlib
import random
import math, copy
import six
from Crypto.Random.random import randint
from functools import partial
from collections import OrderedDict, Counter
import caffe
from caffe import layers as L, params... |
from __future__ import print_function
import imp
import os
import re
import select
import signal
import socket
import sys
import time
from contextlib import closing
from ctypes.util import find_library
import pytest
import requests
from process_tests import TestProcess
from process_tests import TestSocket
from process_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import err
from .plotting_abstract import PlottingBase
def factory(lib_name, plots, *args):
# Matplotlib
if lib_name == 'mp':
from . import plotMP
plotting = plotMP.Plotting(plots, *arg... |
class BaseCommand():
def begin(self, cmdobj):
self.cmdobj = cmdobj
self.process()
def process(self):
pass
def usage():
return "this is an example command" |
from . import commands
class RRPproxy(object):
"""
RRPproxy The Metaregistry domain services
"""
commands = {
'AddDomain': True,
'AddContact': True,
'CheckDomain': True,
'StatusDomain': True,
'QueryDomainList': True,
'DeleteDomain': True,
'RenewDom... |
import os
from setuptools import setup, find_packages
from elvis import __version__ as version
setup(
version=version,
) |
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='pandas-fin',
version='0.0.1',
description='Sample package for Python-Guide.org',
long_description=readme,
author='Kenneth Reitz',
author_... |
from __future__ import print_function
import unittest
import imp
import operator
import sys
is_pypy = '__pypy__' in sys.builtin_module_names
import wrapt
from compat import PY2, PY3, exec_
OBJECTS_CODE = """
class TargetBaseClass(object):
"documentation"
class Target(TargetBaseClass):
"documentation"
def target... |
"""
This program is a part of The Commotion Client
Copyright (C) 2014 Seamus Tuohy s2e@opentechinstitute.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or... |
from datetime import datetime
from django.test import TestCase
from surveyor_manager.models import Surveyor
from onadata.apps.logger.factory import XFormManagerFactory
from onadata.apps.logger.models import XForm
xform_factory = XFormManagerFactory()
class TestSurveyorRegistration(TestCase):
def setUp(self):
... |
from __future__ import unicode_literals
from future.builtins import int, str, zip
from django import forms
from django.contrib.comments.forms import CommentSecurityForm, CommentForm
from django.contrib.comments.signals import comment_was_posted
from django.utils.safestring import mark_safe
from django.utils.translation... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Integration'] , ['Lag1Trend'] , ['BestCycle'] , ['NoAR'] ); |
from soppa.contrib import *
class Carbon(Soppa):
path = '/opt/graphite/'
def setup(self):
self.sudo('mkdir -p {path}')
self.sudo('chown -R {user} {path}')
with self.cd('{path}conf/'):
self.up('carbon.conf', '{path}conf/carbon.conf')
self.up('storage-schemas.conf',... |
"""
Tests for docutils odtwriter.
Instructions for adding a new test:
1. Add a new method to class DocutilsOdtTestCase (below) named
test_odt_xxxx, where xxxx describes your new feature. See
test_odt_basic for an example.
2. Add a new input reST (.txt) file in test/functional/input. This
file should contain t... |
from __future__ import print_function, division
from collections import defaultdict
from sympy import SYMPY_DEBUG
from sympy.core import (Basic, S, C, Add, Mul, Pow,
Derivative, Wild, Symbol, sympify, expand, expand_mul, expand_func,
Function, Dummy, Expr, factor_terms,
FunctionClass, expand_power_base, sym... |
import unittest
import numpy.testing as nptest
from concorde.tsp import TSPSolver
from concorde.tests.data_utils import get_dataset_path, get_solution_data
class TestTSPSolver(unittest.TestCase):
def test_from_data(self):
# Given
xs = [1, 2, 3]
ys = [4, 5, 6]
name = "testdataset"
... |
from __future__ import absolute_import
import json
import datetime
import pytz
import logging
from django.core.mail import send_mail
from django.contrib.auth import authenticate, login as auth_login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group, User
from django.... |
"""
A couple useful CommandFactory implementations.
GenericPrefixFactory is likely to be the base of most actual command
factory implementations, since it deals with the relatively common case
of a family of simple arguments, all sharing a common prefix.
ArbitraryPostfixFactory can be used as the ba... |
def extractPanxueyoWordpressCom(item):
'''
Parser for 'panxueyo.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous'... |
import unittest
import matplotlib.pyplot as plt
import numpy as np
from numpy.testing import assert_array_almost_equal
from control.sisotool import sisotool
from control.rlocus import _RLClickDispatcher
from control.xferfcn import TransferFunction
class TestSisotool(unittest.TestCase):
"""These are tests for the si... |
from __future__ import unicode_literals
from optparse import make_option
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand
from django.db.models import get_models, get_app, get_model
from ...models import Index
from ...registry i... |
from pyface.wizard.simple_wizard import * |
from __future__ import absolute_import
import logging
logger = logging.getLogger(__name__)
import numpy as np
from centrosome.mode import mode
import unittest
class TestMode(unittest.TestCase):
def test_00_00_empty(self):
self.assertEqual(len(mode(np.zeros(0))), 0)
def test_01_01_single_mode(self):
... |
from selenium.webdriver.phantomjs.webdriver import WebDriver
success = True
wd = WebDriver()
wd.implicitly_wait(6)
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
try:
wd.get("https://accounts.qa.crowdcompass.com/users/sign_in")
# wd.find... |
"""
Web handlers for the FractalServer.
"""
import json
import tornado.web
from pydantic import ValidationError
from qcelemental.util import deserialize, serialize
from .interface.models.rest_models import rest_model
from .storage_sockets.storage_utils import add_metadata_template
_valid_encodings = {
"application/... |
from __future__ import absolute_import
import six
from sentry.models import (
Environment,
OrganizationMember,
OrganizationMemberTeam,
Project,
EnvironmentProject,
ProjectOwnership,
ProjectTeam,
Release,
ReleaseProject,
ReleaseProjectEnvironment,
Rule,
)
from sentry.testutils... |
'''
Perceived Usefulness and Ease of Use questionnaire
@author: Peter Parente <parente@cs.unc.edu>
@copyright: Copyright (c) 2008 Peter Parente
@license: BSD License
All rights reserved. This program and the accompanying materials are made
available under the terms of The BSD License which accompanies this
distribution... |
from . import storage |
import threading
class caselessDict(object):
"""
Case-insensitive dictionary. Adapted from
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315
"""
def __init__(self, inDict=None):
"""Constructor: takes conventional dictionary as input (or nothing)
"""
self.dict = {... |
import os
import argparse
def parse_param_file(filepath):
with open(filepath, 'r') as f:
kw_exprs = [x.strip() for x in f.readlines() if x.strip()]
return eval('dict({})'.format(','.join(kw_exprs)))
def parse_args():
parser = argparse.ArgumentParser(
description='Simple Demo of Image Segment... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SnippetFlag'
db.create_table('cab_snippetflag', (
('id', self.gf('django.db.models.fields.AutoField')(prima... |
"""
Low-dependency indexing utilities.
"""
import warnings
import numpy as np
from pandas._typing import Any, AnyArrayLike
from pandas.core.dtypes.common import (
is_array_like,
is_bool_dtype,
is_extension_array_dtype,
is_integer,
is_integer_dtype,
is_list_like,
)
from pandas.core.dtypes.generic... |
__author__ = 'Omar Al-Hinai'
__email__ = 'ohinai@gmail.com'
__version__ = '0.1.0'
__all__ = ["buckley_leverett"] |
'''
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
'''
class MinStack:
def ... |
"""Useful module for solving Python 2 and 3 compatibility problems
.. module:: lib.compat.contentfix
:platform: Unix
:synopsis: Useful module for solving Python 2 and 3 content encoding/decoding compatibility problems
.. moduleauthor:: Petr Czaderna <pc@hydratk.org>
"""
import codecs
def slash_escape(err):
... |
from admin import admin, AdminCtrl
class Admin_TermsCtrl(AdminCtrl):
@admin
def get(self, *args):
pager = {}
pager['qnty'] = min(max(int(self.input('qnty', 10)), 1), 100)
pager['page'] = max(int(self.input('page', 1)), 1)
pager['lgth'] = 0;
terms = self.datum('terms').res... |
from south.db import db
from django.db import models
from boar.mailing_lists.models import *
class Migration:
def forwards(self, orm):
# Adding model 'MailingList'
db.create_table('mailing_lists_mailinglist', (
('id', orm['mailing_lists.MailingList:id']),
('order', orm['maili... |
"""
Created on Fri Mar 24 01:10:00 2017
@author: root
"""# -*- coding: utf-8 -*-
"""
Created on Sat Dec 20 14:03:06 2014
@author: holmes
"""
import numpy as np
import caffe
import sys
import scipy.io as io
import glob
import os
import shutil
import cv2
import pickle
from PIL import Image
def get_name(image_path):
l... |
from sets import Set
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.forms import widgets, ValidationError
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext
from snapboard.models import Cat... |
import logging
import sys
import traceback
import jsonschema
from django.core.management.base import BaseCommand
from hs_core.hydroshare import current_site_url, set_dirty_bag_flag
from hs_core.models import CoreMetaData
from hs_file_types.models import ModelInstanceLogicalFile
from hs_modflow_modelinstance.models impo... |
"""
weasyprint.tests.layout
-----------------------
Tests for layout, ie. positioning and dimensioning of boxes,
line breaks, page breaks.
:copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import division, unico... |
"""
raven.contrib.django.middleware
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.conf import settings
from raven.contrib.django.models import client
import threading
import logging
def is_... |
from typing import Dict
from .. import uwsgi
class _Request:
"""Current request information."""
__slots__ = []
@property
def env(self) -> Dict[str, str]:
"""Request environment dictionary."""
return uwsgi.env
@property
def id(self) -> int:
"""Returns current request numbe... |
from __future__ import absolute_import, unicode_literals
import os
import tempfile
import re
from collections import OrderedDict
try:
#py3
from base64 import decodebytes
except ImportError:
# py2
from base64 import decodestring as decodebytes
from pypandoc import convert as pandoc
from traitlets.config.... |
from ConfigParser import ConfigParser
class Configuration:
def __getattr__(self, option_name):
if option_name in self.register:
return eval(self.register[option_name])
else:
print ("There is no option >> " + option_name + " <<")
return False
def set(self, opti... |
"""
Filename: matching_tools.py
Author: Daisuke Oyama
Tools for matching algorithms.
"""
import numpy as np
from numba import jit
def random_prefs(m, n, allow_unmatched=True, return_caps=False):
"""
Generate random preference order lists for two groups, say, m males
and n females.
Each male has a prefer... |
import math
import re
from cwbot.modules.BaseDungeonModule import BaseDungeonModule, eventDbMatch
def killPercent(n):
return int(max(0, min(99, 100*n / 500.0)))
class AhbgModule(BaseDungeonModule):
"""
A module for tracking Ancient Hobo Burial Ground dances and observations.
This module is essentially s... |
""" support numpy compatibility across versions """
import numpy as np
from pandas.util.version import Version
_np_version = np.__version__
_nlv = Version(_np_version)
np_version_under1p19 = _nlv < Version("1.19")
np_version_under1p20 = _nlv < Version("1.20")
np_version_under1p22 = _nlv < Version("1.22")
np_version_gte... |
"""
test_find_vivo_uri.py -- return the first VIVO URI that staisfies a
match on predicate and value
Version 0.1 MC 2014-03-25
-- Initial version.
"""
__author__ = "Michael Conlon"
__copyright__ = "Copyright 2014, University of Florida"
__license__ = "BSD 3-Clause license"
__version__ = "0.1"
import vi... |
import os
import sys
import warnings
import setuptools
import versioneer
from setuptools import setup, Extension
versioneer.VCS = 'git'
versioneer.versionfile_source = 'trackpy/_version.py'
versioneer.versionfile_build = 'trackpy/_version.py'
versioneer.tag_prefix = 'v'
versioneer.parentdir_prefix = '.'
def read(fname)... |
from django.contrib import admin
from django.forms import SelectMultiple
from django.db import models
from .models import Product, Tag
from categories.models import Category
class ProductAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': SelectMultiple(attrs={'size':'20'})},... |
from django.db import models
from django.contrib.contenttypes import generic
from favorites.models import FavoriteItem
from favorites.signals import remove_favorite_items
class SimpleModel(models.Model):
text = models.CharField(max_length=30)
#favorites = generic.GenericRelation(FavoriteItem, null=True)
def... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'ContactFormContent'
db.delete_table('page_page_contactformcontent')
# Adding field 'MyContactFormContent.than... |
__author__ = 'chris'
import traceback
import sys
from wooey.version import DJANGO_VERSION, DJ110
if DJANGO_VERSION >= DJ110:
from django.utils.deprecation import MiddlewareMixin
else:
MiddlewareMixin = object
class ProcessExceptionMiddleware(MiddlewareMixin):
def process_response(self, request, response):
... |
import warnings
import IECore
import Gaffer
import GafferUI
QtGui = GafferUI._qtImport( "QtGui" )
class PlugWidget( GafferUI.Widget ) :
def __init__( self, plugOrWidget, label=None, description=None, **kw ) :
GafferUI.Widget.__init__( self, QtGui.QWidget(), **kw )
layout = QtGui.QHBoxLayout()
layout.setContentsM... |
from django.conf.urls import url, include
from rest_framework import routers
from account.api.v1 import views
router = routers.DefaultRouter()
router.register(r'user-profiles', views.UserProfileViewSet)
router.register(r'schools', views.SchoolViewSet)
urlpatterns = [
url('^cities/$', views.city_list, name='account_... |
"""Fichier contenant la fonction correspond."""
import re
from primaires.scripting.fonction import Fonction
from primaires.scripting.instruction import ErreurExecution
from primaires.format.fonctions import supprimer_accents
class ClasseFonction(Fonction):
"""Test si une chaîne correspond à une expression régulière... |
import logging
import random
import time
import zlib
from twisted.internet import defer
from twisted.web.client import getPage
from stem import Flag
from stem.descriptor.networkstatus import NetworkStatusDocumentV3
from stem.descriptor.remote import get_authorities
from oppy import data_dir
MICRO_CONSENSUS_PATH = '/tor... |
from feincms.contents import RichTextContent
from feincms.module.medialibrary.contents import MediaFileContent
from elephantblog.models import Entry
Entry.register_regions(
("main", "Main content area"),
)
Entry.register_extensions("feincms.extensions.translations")
Entry.create_content_type(RichTextContent, cleans... |
"""
Example DU task for ABP Table: doing jointly row and header/data
Copyright Naver Labs Europe(C) 2018 H. Déjean, JL Meunier
Developed for the EU project READ. The READ project has received funding
from the European Union's Horizon 2020 research and innovation programme
under grant agreement No 6... |
from abc import ABCMeta, abstractmethod
from aiovault.util import ok, task, Path
class AuthBackend(metaclass=ABCMeta):
def __init__(self, name, type, req_handler):
self.name = name
self.type = type
self.req_handler = req_handler
@property
def path(self):
return Path('/auth/%s... |
from __future__ import print_function, unicode_literals
import logging
__author__ = "danishabdullah"
LOG = logging.getLogger("bigschema")
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
LOG.addHandler(ch)
LOG.setLevel(logging.... |
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it'... |
import pints
import numpy as np
class DreamMCMC(pints.MultiChainMCMC):
"""
Uses differential evolution adaptive Metropolis (DREAM) MCMC as described
in [1]_ to perform posterior sampling from the posterior.
In each step of the algorithm N chains are evolved using the following
steps:
1. Select p... |
import cgi
import unittest
import six
from six.moves import xmlrpc_client as xmlrpclib
from six.moves.urllib.parse import urlparse
from scrapy.http import Request, FormRequest, XmlRpcRequest, Headers, HtmlResponse
from scrapy.utils.python import to_bytes, to_native_str
class RequestTest(unittest.TestCase):
request_... |
import os
import sys
from pyramid.paster import get_appsettings, setup_logging
from pyvac.helpers.sqla import create_engine, dispose_engine
from pyvac.models import (
DBSession, Base, VacationType, Countries,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print(('usage: %s <config_uri>\n'
'(ex... |
import settings
from django.utils.encoding import smart_str
from mediagenerator.generators.bundles.base import Filter
class YUICompressor(Filter):
def __init__(self, **kwargs):
super(YUICompressor, self).__init__(**kwargs)
assert self.filetype in ('css', 'js'), (
'YUICompressor only supp... |
import subprocess
import tempfile
class ConsEntry(object):
def __init__(self, key):
self.key = key
self.tmpls = {}
self.external_vars = []
self.num_internal_vars = 0
self.num_constraints = 0
self.Aij = 0
self.Bij = 0
self.Cij = 0
class SubstEntry(object):
def __init__(self):
self... |
def extractTbrithatransHomeBlog(item):
'''
Parser for 'tbrithatrans.home.blog'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
chp_prefixes = [
('JCG&SW Chapter ', 'Jiang Chao Ge and The Spirit Weapon',... |
from dogapi.common import is_p3k
__all__ = [
'SnapshotApi',
]
if is_p3k():
from urllib.parse import urlparse
else:
from urlparse import urlparse
class SnapshotApi(object):
def graph_snapshot(self, metric_query, start, end, event_query=None):
"""
Take a snapshot of a graph, returning the ... |
"""URLs for the threebot_stats app."""
from django.conf.urls import url
from threebot_stats import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<workflow_slug>[-\w]+)/$', views.detail, name='detail'),
] |
'''
Variant of node_wrapper that fetches and stores data on amazon's S3 using boto
'''
import os
from tempfile import mkdtemp
from ConfigParser import RawConfigParser
try:
from boto.s3 import Connection
import tables
from boto.s3.key import Key
except ImportError:
pass
class S3NodeWrapper(object):
'... |
import unittest
import os
import os.path
import shlex
import logging
import test.env
from pypcpe2 import comsubseq
from pypcpe2 import env
from pypcpe2 import utility
class TestEnv(unittest.TestCase):
def setUp(self):
self.test_data_folder = os.path.join(test.env.test_data_folder,
... |
from .iqr_search import IQRSearch
from .iqr_search_fusion import IQRSearchFusion |
from datetime import datetime
import unittest
from numpy.random import randn
import numpy as np
from pandas.core.api import Index, Series, DataMatrix, DataFrame, isnull
import pandas.util.testing as common
import test_frame
class TestDataMatrix(test_frame.TestDataFrame):
klass = DataMatrix
def test_more_constru... |
import logging
from coremltools.converters._profile_utils import _profile
from coremltools.converters.mil.mil.passes.pass_registry import PASS_REGISTRY
@_profile
def torch_passes(prog):
passes = [
"common::dead_code_elimination",
"common::loop_invariant_elimination",
"common::dead_code_elimi... |
from __future__ import unicode_literals
from django.contrib.auth.admin import UserAdmin
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
class CustomerAdmin(UserAdmin):
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {... |
import json
import urlparse
from django.http import QueryDict
from django.test.client import RequestFactory
from django.utils.translation import trim_whitespace
import mock
import pytest
from jingo.helpers import datetime as datetime_filter
from pyquery import PyQuery as pq
from olympia import amo
from olympia.amo.test... |
import os
import re
import smtplib
from subprocess import Popen, PIPE
import time
from genshi.builder import tag
from trac import __version__
from trac.config import BoolOption, ConfigurationError, ExtensionOption, \
IntOption, Option
from trac.core import *
from trac.util.compat import close_fd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.