repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
bjodah/pyodesys
pyodesys/native/odeint.py
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import copy from ..util import import_ from ._base import _NativeCodeBase, _NativeSysBase, _compile_kwargs pyodeint = import_('pyodeint') class NativeOdeintCode(_NativeCodeBase): wrapper_name = '_odeint_wrapper' def...
Alex-Ian-Hamilton/sunpy
sunpy/spectra/tests/test_callisto.py
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import import shutil from tempfile import mkdtemp from datetime import datetime import pytest import os import glob import numpy as np from numpy.testing import assert_array_almost_equal, assert_allclose import...
thisch/python-falafel
examples/project1/testrunner.py
#!/usr/bin/env python from __future__ import print_function import argparse import os from falafel import findout_terminal_width from falafel import test_list from falafel.runners import FalafelTestRunner from falafel.loaders import FalafelTestLoader parser = argparse.ArgumentParser(description='custom test runner ...
castelao/CoTeDe
cotede/qctests/gradient.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import logging import numpy as np from numpy import ma from cotede.qctests import QCCheckVar try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: PANDAS_AVAILABLE = Fa...
mikewolfli/django-goflow
sampleproject/urls.py
from django.conf.urls import * from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # django-flags for internationalization (r'^lang/', include('sampleproject.flags.urls')), # FOR DEBUG AND TES...
dimagi/commcare-hq
corehq/form_processor/tests/test_sql_update_strategy.py
from django.test import TestCase from freezegun import freeze_time from unittest.mock import patch from testil import eq from corehq.util.soft_assert.core import SoftAssert from casexml.apps.case.exceptions import ReconciliationError from casexml.apps.case.xml.parser import CaseUpdateAction, KNOWN_PROPERTIES from core...
GenericMappingTools/gmt-python
pygmt/src/subplot.py
""" subplot - Manage modern mode figure subplot configuration and selection. """ import contextlib from pygmt.clib import Session from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import ( build_arg_string, fmt_docstring, is_nonstr_iter, kwargs_to_strings, use_alias, ) @fmt_docstrin...
ergodicbreak/evennia
evennia/server/evennia_launcher.py
#!/usr/bin/env python """ EVENNIA SERVER LAUNCHER SCRIPT This is the start point for running Evennia. Sets the appropriate environmental variables and launches the server and portal through the evennia_runner. Run without arguments to get a menu. Run the script with the -h flag to see usage information. """ from __f...
tommy-u/enable
enable/text_field_style.py
# Enthought library imports from traits.api import HasTraits, Int, Bool from kiva.trait_defs.api import KivaFont from enable.colors import ColorTrait class TextFieldStyle(HasTraits): """ This class holds style settings for rendering an EnableTextField. fixme: See docstring on EnableBoxStyle """ #...
aledista/django-view-timer
django_view_timer/urls.py
import warnings from django.core.urlresolvers import ResolverMatch from django.core.urlresolvers import ( RegexURLPattern as DjangoRegexURLPattern, RegexURLResolver ) from django.core.exceptions import ImproperlyConfigured from django.utils import six from django.utils.deprecation import RemovedInDjango20Warni...
solarpermit/solarpermit
website/models/server.py
import datetime from django.db import models from django.conf import settings #server variables that needed to be stored in db class ServerVariable(models.Model): name = models.CharField(max_length=64, blank=True, null=True) value = models.TextField(blank=True, null=True) class Meta: app_l...
WaveBlocks/WaveBlocksND
WaveBlocksND/Plot/stemcf3d.py
"""The WaveBlocks Project Function for stem-plotting functions of the type f:IxI -> C with abs(f) as z-value and phase(f) as color code. This function makes a three dimensional stem plot. @author: R. Bourquin @copyright: Copyright (C) 2012, 2014, 2016 R. Bourquin @license: Modified BSD License """ from numpy import ...
containers-ftw/apps
tests/circle_urls.py
#!/usr/bin/env python ''' circle_urls.py will rename all url files to not have extension .html ''' import sys import os from glob import glob site_dir = os.path.abspath(sys.argv[1]) print("Using site directory %s" %(site_dir)) files = glob("%s/*.html" %(site_dir)) # For each file, we need to replace all links to h...
aldenjenkins/foobargamingwebsite
paypal/standard/ipn/south_migrations/0006_auto__chg_field_paypalipn_custom__chg_field_paypalipn_transaction_subj.py
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'PayPalIPN.custom' db.alter_column(u'paypal_ipn', 'cust...
MwanzanFelipe/rockletonfortune
zillions/urls.py
from django.conf.urls import * from . import views from . import z_queries from rockletonfortune import settings from django.contrib.auth.views import login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth import views as auth_views from django.views.static import serve from ...
datapythonista/pandas
pandas/core/ops/mask_ops.py
""" Ops for masked arrays. """ from typing import ( Optional, Union, ) import numpy as np from pandas._libs import ( lib, missing as libmissing, ) def kleene_or( left: Union[bool, np.ndarray], right: Union[bool, np.ndarray], left_mask: Optional[np.ndarray], right_mask: Optional[np.nd...
glassesfactory/Shimehari
shimehari/core/manage/commands/create.py
#!/usr/bin/env python # -*- coding: utf-8 -*- u""" =============================== Shimehari.core.manage.commands.create ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ アプリケーションを新たに作成する create コマンド 各コマンドモジュールは共通インターフェースとして Command クラスを持ちます。 =============================== """ import os import sys import e...
mbdriscoll/asp-old
tests/asp_module_tests.py
import unittest2 as unittest import asp.jit.asp_module as asp_module import asp.codegen.cpp_ast as cpp_ast from mock import Mock class TimerTest(unittest.TestCase): def test_timer(self): pass # mod = asp_module.ASPModule() # mod.add_function("void test(){;;;;}", "test") # # mod.test...
ericmjl/bokeh
bokeh/core/validation/__init__.py
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
p1c2u/openapi-core
openapi_core/validation/request/shortcuts.py
"""OpenAPI core validation request shortcuts module""" from functools import partial from openapi_core.validation.request.validators import RequestBodyValidator from openapi_core.validation.request.validators import ( RequestParametersValidator, ) from openapi_core.validation.request.validators import RequestSecur...
datavisyn/tdp_core
tdp_core/config.py
from phovea_server.ns import Namespace, abort from phovea_server.util import jsonify from phovea_server.config import get as get_config from phovea_server.plugin import list as list_plugins import logging app = Namespace(__name__) _log = logging.getLogger(__name__) @app.route('/<path:path>') def _config(path): pat...
kevin-intel/scikit-learn
sklearn/impute/_knn.py
# Authors: Ashim Bhattarai <ashimb9@gmail.com> # Thomas J Fan <thomasjpfan@gmail.com> # License: BSD 3 clause import numpy as np from ._base import _BaseImputer from ..utils.validation import FLOAT_DTYPES from ..metrics import pairwise_distances_chunked from ..metrics.pairwise import _NAN_METRICS from ..neig...
JakubBrachTieto/openthread
tests/scripts/thread-cert/Cert_5_6_01_NetworkDataRegisterBeforeAttachLeader.py
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
data-exp-lab/girder_ythub
plugin_tests/notebook_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import mock from tests import base from girder.models.model_base import ValidationException def setUpModule(): base.enabledPlugins.append('ythub') base.startServer() def tearDownModule(): base.stopServer() class FakeAsyncResult(object): def __init__(s...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractSecretchateauWordpressCom.py
def extractSecretchateauWordpressCom(item): ''' Parser for 'secretchateau.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None titlemap = [ ('GRMHCD ', 'Grim Reaper Makes His C-Debut', 'trans...
idlesign/uwsgiconf
tests/presets/test_nice.py
from os import environ from uwsgiconf.presets.nice import Section, PythonSection def test_nice_section(assert_lines): assert_lines([ 'env = LANG=en_US.UTF-8', 'workers = %k', 'die-on-term = true', 'vacuum = true', 'threads = 4', ], Section(threads=4)) assert_lin...
jeisenma/ProgrammingConcepts
11-gui/slidy.py
from slider import * def setup(): global slidy size(400,200) slidy = Slider( Rect(50,80,300,40), minVal=100, maxVal=255 ) def draw(): background(slidy.value) slidy.draw() def mousePressed(): slidy.press() def mouseDragged(): slidy.drag() def mouseReleased(): slidy.release()
pbs/django-cms
cms/test_utils/cli.py
# -*- coding: utf-8 -*- import os gettext = lambda s: s urlpatterns = [] def configure(**extra): from django.conf import settings os.environ['DJANGO_SETTINGS_MODULE'] = 'cms.test_utils.cli' defaults = dict( CACHE_BACKEND='locmem:///', DEBUG=True, DATABASE_SUPPORTS_TRANSACTIONS=T...
douban/douban-sqlstore
douban/sqlstore/genconfig.py
#!/usr/bin/env python #coding=utf8 """Utility script for generating sqlstore configs sample settings file: ################# starts ##################### default_params = { 'roles': ['m', 's', 'b', 'g', 'h'], 'rw_user': { 'user': 'rw_user', 'passwd': 'password' }, 'ro_user': { ...
saltastro/timDIMM
weather.py
#!/usr/bin/env python import sys import html5lib import urllib2 from numpy import median, array from xml_icd import parseICD from html5lib import treebuilders def salt(): wx = {} try: tcs = parseICD("http://icd.salt/xml/salt-tcs-icd.xml") time = tcs['tcs xml time info'] bms = tcs['bm...
beregond/jsonmodels
setup.py
#!/usr/bin/env python # coding: utf-8 import os import sys from setuptools.command.test import test as TestCommand from jsonmodels import __version__, __author__, __email__ from setuptools import setup PROJECT_NAME = 'jsonmodels' if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.e...
Teekuningas/mne-python
mne/preprocessing/_fine_cal.py
# -*- coding: utf-8 -*- # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np from ..utils import check_fname, _check_fname def read_fine_calibration(fname): """Read fine calibration information from a .dat file. The fine calibration typically includes improved sens...
tpltnt/SimpleCV
SimpleCV/examples/detection/MotionTracker.py
#!/usr/bin/python ''' This SimpleCV example uses a technique called frame differencing to determine if motion has occured. You take an initial image, then another, subtract the difference, what is left over is what has changed between those two images this are typically blobs on the images, so we do a blob search to c...
ksmaheshkumar/django-DefectDojo
dojo/models.py
from datetime import date, datetime import os from django.conf import settings from django.contrib import admin from django.contrib.auth.models import User from django.db import models from django.db.models import Q from django.utils.timezone import now from pytz import timezone localtz = timezone(settings.TIME_ZONE)...
dimagi/commcare-hq
corehq/apps/data_interfaces/migrations/0006_case_rule_refactor.py
# Generated by Django 1.10.6 on 2017-04-04 12:54 import django.db.models.deletion from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('data_interfaces', '0005_remove_match_type_choices'), ] operations = [ migrations....
CountZer0/PipelineConstructionSet
python/maya/site-packages/pymel-1.0.5/pymel/internal/cmdcache.py
# Built-in imports import os, re, inspect, keyword # Maya imports import maya.cmds as cmds import maya.mel as mm # PyMEL imports import pymel.util as util import pymel.versions as versions # Module imports from . import plogging from . import startup _logger = plogging.getLogger(__name__) moduleNameShortToLong = {...
LeoYReyes/GoogleSearchAutomator
Crawler.py
import google import re from bs4 import BeautifulSoup def findContactPage(url): html = google.get_page(url) soup = BeautifulSoup(html) contactStr = soup.find_all('a', href=re.compile(".*?contact", re.IGNORECASE)) return contactStr if __name__ == "__main__": url = "http://www.wrangler.com/" c...
clawpack/clawpack-4.x
doc/sphinx/conf.py
# -*- coding: utf-8 -*- # # Clawpack documentation build configuration file, created by # sphinx-quickstart on Wed Mar 25 12:07:14 2009. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickle...
qedsoftware/commcare-hq
corehq/sql_accessors/migrations/0035_add_undelete_functions.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from corehq.sql_db.operations import RawSQLMigration from corehq.form_processor.models import XFormInstanceSQL migrator = RawSQLMigration(('corehq', 'sql_accessors', 'sql_templates'), { 'FORM_STATE_DELETED': XFormInst...
WaveBlocks/WaveBlocks
src/tests/TestComplexMath.py
"""The WaveBlocks Project Test the complex math functions. @author: R. Bourquin @copyright: Copyright (C) 2010, 2011 R. Bourquin @license: Modified BSD License """ from numpy import * from matplotlib.pyplot import * from WaveBlocks.ComplexMath import * from WaveBlocks.Plot import plotcf # Continuous complex angle...
mrgloom/menpofit
menpofit/modelinstance.py
import numpy as np from menpo.base import Targetable, Vectorizable from menpo.model import MeanInstanceLinearModel from menpofit.differentiable import DP def similarity_2d_instance_model(shape): r""" A MeanInstanceLinearModel that encodes all possible 2D similarity transforms of a 2D shape (of n_points)....
desihub/desisurvey
py/desisurvey/holdingpen.py
import os import subprocess import re import glob import numpy as np from astropy.io import fits from astropy.time import Time from astropy.table import Table import desiutil.log import desisurvey.config import desisurvey.plan import desisurvey.tiles from desisurvey.utils import yesno logger = desiutil.log.get_logger(...
mitsuhiko/sentry
tests/sentry/api/endpoints/test_shared_group_details.py
from __future__ import absolute_import, print_function from sentry.testutils import APITestCase class SharedGroupDetailsTest(APITestCase): def test_simple(self): self.login_as(user=self.user) group = self.create_group() event = self.create_event(group=group) url = '/api/0/shared...
vlegoff/tsunami
src/secondaires/auberge/commandes/auberge/editer.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
wasit7/PythonDay
django/mysite2/mysite2/settings.py
""" Django settings for mysite2 project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # B...
NigelCleland/Tessen
Tessen/generate.py
""" """ import pandas as pd import numpy as np from OfferPandas import Frame, load_offerframe import sys import os import datetime import time def create_fan(energy, reserve, fName=None, return_fan=True, break_tp=False, force_plsr_only=True, verbose=False, *args, **kargs): """ A wrapper which ...
chimeno/wagtail
wagtail/wagtailsnippets/widgets.py
from __future__ import absolute_import, unicode_literals import json from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailadmin.widgets import AdminChooser class AdminSnippetChooser(AdminChooser): target_content_type = None def __i...
expfactory/expfactory
expfactory/database/relational.py
""" Copyright (c) 2017-2022, Vanessa Sochat All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the f...
cmry/ebacs
corks.py
import bottle from cork import Cork from utils import skeleton aaa = Cork('users', email_sender='c.emmery@outlook.com', smtp_url='smtp://smtp.magnet.ie') authorize = aaa.make_auth_decorator(fail_redirect='/login', role="user") def postd(): return bottle.request.forms def post_get(name, default=''):...
bitcraft/pyglet
contrib/experimental/mt_media/drivers/directsound/__init__.py
#!/usr/bin/python # $Id:$ import ctypes import math import sys import threading import time import pyglet _debug = pyglet.options['debug_media'] import mt_media from . import lib_dsound as lib from pyglet.window.win32 import user32, kernel32 class DirectSoundException(mt_media.MediaException): pass def _db...
jcfr/mystic
models/storn.py
#!/usr/bin/env python # # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) # Author: Patrick Hung (patrickh @caltech) # Copyright (c) 1997-2015 California Institute of Technology. # License: 3-clause BSD. The full license text is available at: # - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/m...
kaiix/schematics
schematics/types/base.py
import uuid import re import datetime import decimal import itertools import functools import random import string import six from six import iteritems from ..exceptions import ( StopValidation, ValidationError, ConversionError, MockCreationError ) try: from string import ascii_letters # PY3 except ImportErr...
flgiordano/netcash
+/google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_projection_spec.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
OpenACalendar/OpenACalendar-Tools-Social
example-facebook-post-weekly/facebook-post-weekly.py
#!/usr/bin/env python import logging from pdb import set_trace import requests import simplejson from time import time import os import facebook # MY_API_URL # MY_SITE_MSG # MY_GROUP_NAME # POST_TO_ID = None def run(): data = get_from_cal_json() msg = create_msg(data) post(msg) def get_from_cal_json...
docwalter/py3status
py3status/modules/whoami.py
# -*- coding: utf-8 -*- """ Display logged-in username. Configuration parameters: format: display format for whoami (default '{username}') Format placeholders: {username} display current username Inspired by i3 FAQ: https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html @author ultrabug ...
kapteyn-astro/kapteyn
doc/source/EXAMPLES/mu_minorticks.py
from kapteyn import maputils from matplotlib import pyplot as plt fitsobj = maputils.FITSimage("m101.fits") fig = plt.figure() fig.subplots_adjust(left=0.18, bottom=0.10, right=0.90, top=0.90, wspace=0.95, hspace=0.20) for i in range(4): f = fig.add_subplot(2,2,i+1) mplim = fitsobj.Annotat...
puttarajubr/commcare-hq
corehq/apps/reports/models.py
from datetime import datetime, timedelta import logging from urllib import urlencode from django.http import Http404 from django.utils import html from django.utils.safestring import mark_safe import pytz from corehq import Domain from corehq.apps import reports from corehq.apps.app_manager.models import get_app, Form,...
kennethlove/django_bookmarks
dj_bookmarks/bookmarks/migrations/0006_bookmark_collections.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-15 17:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bookmarks', '0005_auto_20170915_1015'), ] operations = [ migrations.AddFiel...
leprikon-cz/leprikon
leprikon/views/journals.py
from django.http import Http404 from django.shortcuts import get_object_or_404 from django.urls.base import reverse_lazy as reverse from django.utils.translation import ugettext_lazy as _ from ..forms.journals import JournalEntryForm, JournalForm, JournalLeaderEntryForm from ..models.journals import Journal, JournalEn...
flgiordano/netcash
+/google-cloud-sdk/lib/googlecloudsdk/api_lib/compute/firewalls_utils.py
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
westurner/pkgsetcomp
pkgsetcomp/pyrpo.py
#!/usr/bin/env python # encoding: utf-8 from __future__ import print_function """Search for code repositories and generate reports""" import datetime import errno import logging import os import pprint import re import subprocess import sys from collections import deque, namedtuple from distutils.util import convert_p...
ihmeuw/vivarium
src/vivarium/framework/resource.py
""" =================== Resource Management =================== This module provides a tool to manage dependencies on resources within a :mod:`vivarium` simulation. These resources take the form of things that can be created and utilized by components, for example columns in the :mod:`state table <vivarium.framework.p...
gustavla/self-supervision
selfsup/caffe.py
from .util import DummyDict from .util import tprint import deepdish as dd import numpy as np # CAFFE WEIGHTS: O x I x H x W # TFLOW WEIGHTS: H x W x I x O def to_caffe(tfW, name=None, shape=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()): assert conv_fc_transitionals is None or name is not No...
all-of-us/raw-data-repository
rdr_service/lib_fhir/fhirclient_4_0_0/models/binary.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Binary) on 2019-05-07. # 2019, SMART Health IT. from . import resource class Binary(resource.Resource): """ Pure binary content defined by a format other than FHIR. A resourc...
patrickm/chromium.src
content/test/gpu/gpu_tests/cloud_storage_test_base.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Base classes for a test and validator which upload results (reference images, error images) to cloud storage.""" import os import re import tempfile fro...
pansapiens/mytardis
tardis/tardis_portal/tests/test_download.py
# -*- coding: utf-8 -*- from os import makedirs from os.path import abspath, basename, dirname, join, exists, getsize from shutil import rmtree from zipfile import is_zipfile, ZipFile from tarfile import is_tarfile, TarFile from tempfile import NamedTemporaryFile from compare import expect from django.test import Te...
vlegoff/mud
menu/validate_account.py
""" This module contains the 'validate_account' menu node. """ from textwrap import dedent from menu.character import _options_choose_characters def validate_account(caller, input): """Prompt the user to enter the received validation code.""" text = "" options = ( { "key": "b", ...
katiecheng/Bombolone
env/lib/python2.7/site-packages/requests/_oauth.py
# -*- coding: utf-8 -*- """ requests._oauth ~~~~~~~~~~~~~~~ This module comtains the path hack neccesary for oauthlib to be vendored into requests while allowing upstream changes. """ import os import sys try: from oauthlib.oauth1 import rfc5849 from oauthlib.common import extract_params from oauthlib.o...
disqus/django-old
tests/regressiontests/forms/localflavor/co.py
from django.contrib.localflavor.co.forms import CODepartmentSelect from utils import LocalFlavorTestCase class COLocalFlavorTests(LocalFlavorTestCase): def test_CODepartmentSelect(self): d = CODepartmentSelect() out = u"""<select name="department"> <option value="AMA">Amazonas</option> <option val...
almarklein/scikit-image
skimage/util/shape.py
__all__ = ['view_as_blocks', 'view_as_windows'] import numpy as np from numpy.lib.stride_tricks import as_strided def view_as_blocks(arr_in, block_shape): """Block view of the input n-dimensional array (using re-striding). Blocks are non-overlapping views of the input array. Parameters ---------- ...
rustyrazorblade/machete
machete/wiki/tests/test_create_page.py
from unittest import TestCase from machete.base.tests import IntegrationTestCase from machete.wiki.models import Wiki, Page class CreatePageTest(TestCase): def test_create_page(self): wiki = Wiki.create() page = wiki.create_page("test name [Some link]", "/index.html...
pauloschilling/sentry
src/sentry/interfaces/exception.py
""" sentry.interfaces.exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Exception',) from django.conf import settings from sentry.interfaces.base impor...
haijieg/SFrame
oss_src/unity/python/sframe/data_structures/__init__.py
""" GraphLab Create offers several data structures for data analysis. Concise descriptions of the data structures and their methods are contained in the API documentation, along with a small number of simple examples. For more detailed descriptions and examples, please see the `User Guide <https://dato.com/learn/userg...
vlinhart/django-smsbrana
smsbrana/views.py
# -*- coding: utf-8 -*- from datetime import datetime from django.http import HttpResponse from smsbrana import SmsConnect from smsbrana import signals from smsbrana.const import DELIVERY_STATUS_DELIVERED, DATETIME_FORMAT from smsbrana.models import SentSms def smsconnect_notification(request): sc = SmsConnect() ...
carlohamalainen/volgenmodel-nipype
new_data_to_atlas_space.py
#!/usr/bin/env python3 import os import os.path from nipype.interfaces.utility import IdentityInterface, Function from nipype.interfaces.io import SelectFiles, DataSink, DataGrabber from nipype.pipeline.engine import Workflow, Node, MapNode from nipype.interfaces.minc import Resample, BigAverage, VolSymm import argpars...
shub0/algorithm-data-structure
python/sum_roof_to_leaf.py
#! /usr/bin/python ''' Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / \ 2 3 The root-to-leaf path 1->2 represen...
goddardl/gaffer
python/GafferSceneUI/TransformUI.py
########################################################################## # # Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
jonzobrist/Percona-Server-5.1
kewpie/lib/util/mysqlBaseTestCase.py
#! /usr/bin/env python # -*- mode: python; indent-tabs-mode: nil; -*- # vim:expandtab:shiftwidth=2:tabstop=2:smarttab: # # Copyright (C) 2011 Patrick Crews # # # 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 Softwar...
globocom/database-as-a-service
dbaas/maintenance/async_jobs/remove_instance_database.py
from maintenance.async_jobs import BaseJob from maintenance.models import RemoveInstanceDatabase __all__ = ('RemoveInstanceDatabase',) class RemoveInstanceDatabaseJob(BaseJob): step_manger_class = RemoveInstanceDatabase get_steps_method = 'remove_readonly_instance_steps' success_msg = 'Instance removed ...
seymour1/label-virusshare
test/test_hashes.py
import json import argparse import logging import glob # Logging Information logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s: %(message)s') fh = logging.FileHandler('test_hashes.log') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHand...
neiljdo/readysaster-icannhas-web
readysaster-icannhas-web/hazard/utils.py
import json import urllib import urllib2 from django.core.files import File from django.conf import settings from django.contrib.gis.geos import Point from .models import FloodMap, ReturnPeriod def get_geoserver_baseurl(): ''' Just input the layer name, height, width and boundarybox ''' url = settin...
sdss/marvin
tests/tools/test_map.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: Brian Cherinka, José Sánchez-Gallego, and Brett Andrews # @Date: 2017-07-02 # @Filename: test_map.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # # @Last modified by: andrews # @Last modified time: 2019-11-22 12:11:29 import ...
hep-cce/hpc-edge-service
argo/test_jobs/test_submit_alpgen.py
#!/usr/bin/env python import sys,logging,optparse from AlpgenArgoJob import AlpgenArgoJob sys.path.append('/users/hpcusers/balsam/argo_deploy/argo_core') from MessageInterface import MessageInterface def main(): parser = optparse.OptionParser(description='submit alpgen job to ARGO') parser.add_option('-e','--ev...
cluck/dnspython
tests/test_namedict.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
metamarcdw/PyBitmessage-I2P
src/i2p/test/test_socket.py
# -------------------------------------------------------- # test_socket.py: Unit tests for socket, select. # -------------------------------------------------------- # Make sure we can import i2p import sys; sys.path += ['../../'] import traceback, time, thread, threading, random, copy from i2p import socket, selec...
pombredanne/opc-diag
ez_setup.py
#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools...
frappe/frappe
frappe/core/doctype/prepared_report/test_prepared_report.py
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies and Contributors # License: MIT. See LICENSE import frappe import unittest import json class TestPreparedReport(unittest.TestCase): def setUp(self): self.report = frappe.get_doc({ "doctype": "Report", "name": "Permitted Documents For User" }...
xkong/baniugui
dict4ini/p3.py
# $Id: p3.py,v 1.2 2003/11/18 19:04:03 phr Exp phr $ # Simple p3 encryption "algorithm": it's just SHA used as a stream # cipher in output feedback mode. # Author: Paul Rubin, Fort GNOX Cryptography, <phr-crypto at nightsong.com>. # Algorithmic advice from David Wagner, Richard Parker, Bryan # Olson, and Paul Crowley...
mmottahedi/neuralnilm_prototype
scripts/e127.py
from __future__ import print_function, division import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer from lasagne.nonlinearities import sigmoid, rectify from lasagne.objectives import c...
g2p/xtraceback
xtraceback/lexer.py
try: from pygments.lexer import bygroups, include, using from pygments.lexers.agile import PythonLexer, PythonTracebackLexer from pygments.token import Text, Name, Number, Generic, String, Operator except ImportError: # pragma: no cover # this is for nose coverage which does a recursive import on the p...
ee08b397/LeetCode-4
070 Text Justification.py
""" Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly ...
dracarysX/flask_restapi
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys class MyTest(TestCommand): def run_tests(self): tests = unittest.TestLoader().discover('tests', pattern='test_*.py') unittes...
OpenSourcePolicyCenter/webapp-public
webapp/apps/pages/urls.py
from django.conf.urls import url from .views import (homepage, aboutpage, newspage, gallerypage, hellopage, embedpage, widgetpage, newsdetailpage, apps_landing_page, border_adjustment_plot, docspage, gettingstartedpage) urlpatterns = [ # url(r'^apps/$', apps_landing_page, n...
aaiijmrtt/JUCSE
Compilers/parser.py
_first = dict() _follow = dict() _table = dict() _endsymbol = '$' _emptysymbol = '#' # function to remove left recursion from a subgrammar def recursion(grammar): section = grammar[0][0] nonrecursivegrammar = [[item for item in rule] + [section + 'bar'] for rule in grammar if rule[0] != rule[1]] recursivegrammar = ...
kmike/DAWG-Python
tests/utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import zipfile DEV_DATA_PATH = os.path.join( os.path.dirname(__file__), '..', 'dev_data', ) def data_path(*args): """ Returns a path to dev data """ return os.path.join(DEV_DATA_PATH, *args) def words100k(): zip_...
BitcoinUnlimited/BitcoinUnlimited
qa/rpc-tests/electrum_reorg.py
#!/usr/bin/env python3 # Copyright (c) 2019 The Bitcoin Unlimited developers """ Tests to check if basic electrum server integration works """ import random from test_framework.util import waitFor, assert_equal from test_framework.test_framework import BitcoinTestFramework from test_framework.loginit import logging fro...
YaoQ/zigbee-on-pcduino
zigbee.py
#!/usr/bin/env python # -*- coding:UTF-8 -*- import urllib import urllib2 import json import serial import time import gpio import re import binascii import threading import datetime import sys # use your deviceID and apikey deviceID="xxxxxxxxxx" apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" key_pin = "gpio12" s = "" doo...
MBARIMike/biofloat
biofloat/converters.py
# -*- coding: utf-8 -*- # Module containing functions for converting biofloat DataFrames to other formats from collections import OrderedDict def to_odv(df, odv_file_name, vars=None): '''Output biofloat DataFrame in Ocean Data View spreadsheet format to file named odv_file_name. Pass in a OrderedDict named va...
VirusTotal/content
Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment.py
from CommonServerPython import * ''' STANDALONE FUNCTION ''' def get_threat_indicator_list(args: Dict[str, Any]) -> list: """ Executes cofense-threat-indicator-list command for given arguments. :type args: ``Dict[str, Any]`` :param args: The script arguments provided by the user. :return: List ...
lidingpku/open-conference-data
iswc-metadata/src/mu/lib_entity.py
""" syntax entity ::= {id(utc millisecond), type, id_from, id_to, status, data, source, note} data example1: search wikipedia { "id":1378327851001, "type":"name-name", "id-from":"MIT", "id-to":"Massachusetts Institute of Technology", "status":"auto", "date":"2013-09-04", "source":"wikipedia...