repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
deepmind/sonnet | sonnet/src/conformance/tensorflow1_test.py | # Copyright 2019 The Sonnet Authors. 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 l... |
quattor/aquilon | tests/broker/test_add_sandbox.py | #!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2010-2017,2019 Contributor
#
# 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... |
kubevirt/client-python | kubevirt/models/v1_i6300_esb_watchdog.py | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1I6300E... |
bigfatpanda-training/pandas-practical-python-primer | training/level-4-creating-web-services/bfp-reference/exercise_07/friends_api/datastore.py | friends = [
{
"id": "BFP",
"firstName": "Big Fat",
"lastName": "Panda",
"telephone": "574-213-0726",
"email": "mike@eikonomega.com",
"notes": "My bestest friend in all the world."
},
{
"id": "VinDi",
"firstName": "Vin",
"lastName": "Die... |
angr/angr | angr/storage/memory_mixins/paged_memory/stack_allocation_mixin.py | import logging
from .paged_memory_mixin import PagedMemoryMixin
from ....errors import SimSegfaultException, SimMemoryError
l = logging.getLogger(__name__)
class StackAllocationMixin(PagedMemoryMixin):
"""
This mixin adds automatic allocation for a stack region based on the stack_end and stack_size parameter... |
congpc/DjangoExample | mysite/mysite/urls.py | """mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
mmetak/streamlink | tests/test_streamlink_api.py | import os.path
import unittest
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from streamlink import Streamlink
from streamlink.api import streams
PluginPath = os.path.join(os.path.dirname(__file__), "plugins")
def get_session():
s = Streamlink()
s.load_plugins(Plugi... |
uArm-Developer/UArmForROS | visualization/visual_display.py | #!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import Header
import sys
import math
import time
from std_msgs.msg import String
from std_msgs.msg import Int32
PI = math.pi
def main_fcn():
pub = rospy.Publisher('joint_states',JointState,queue_size = 10)
pub2 = rospy.Publ... |
ciju/perf-hier | fork_join_queue.py | #!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# 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 o... |
nikcub/Sketch | project-template/app/admin.py |
import sketch
import app.models
#---------------------------------------------------------------------------
# admin controllers
#---------------------------------------------------------------------------
class UsersIndex(sketch.AdminController):
def get(self):
return self.render('admin.users', {
"us... |
pyinvoke/invoke | tests/_support/contextualized.py | from invoke import task
@task
def go(c):
return c
@task
def check_warn(c):
# default: False
assert c.config.run.warn is True
@task
def check_pty(c):
# default: False
assert c.config.run.pty is True
@task
def check_hide(c):
# default: None
assert c.config.run.hide == "both"
@task
de... |
NikitaKarnauhov/xbmc-desktop-launcher-generator | script.desktop.launcher.generator/addon.py | import xbmc
import subprocess
import glob
import xdg.DesktopEntry
import os
import string
import shutil
import shlex
import errno
import codecs
import PIL.Image
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr
addon_prefix = "script.desktop.launcher."
addon_name = addon_prefix + "generator"
v... |
PaulMcMillan/sherry | sherry/power.py | """
Drivers for OBM power on/off handling
"""
import logging
import subprocess
# FIXME (PaulM): I'm not entirely happy with this
from sherry import app
log = app.logger
class PowerDriver(object):
"""Abstraction for powering on/off nodes"""
def __init__(self, address, user, password):
self.address =... |
richardroyal/wp-plugin-generator | wp_plugin_generator/write_wp_plugin.py | """
Import data from config file and generate WordPress plugin bootstrap.
"""
import os, sys, argparse, yaml, write_wp_readme, write_config_file, write_wp_manifest, write_wp_widgets
def parse_and_run_command():
"""
A one-shot function that parses the args, and then runs the command
that the user specifies on t... |
bjodah/aqchem | chempy/util/_expr.py | # -*- coding: utf-8 -*-
"""
This module provides a class :class:`Expr` to subclass from in order to
describe expressions. The hope was that this class would allow straightforward
interoperability between python packages handling symbolics (SymPy) and units
(quantities) as well as working without either of those. The pr... |
rogueleaderr/definitive_guide_to_django_deployment_2 | fabfile.py | import os, json
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, execute
from fabric.colors import green as _green, yellow as _yellow
from fabric.context_managers import hide, show, lcd
import ... |
SEMAFORInformatik/femagtools | femagtools/isa7.py | # -*- coding: utf-8 -*-
"""
femagtools.isa7
~~~~~~~~~~~~~~~
Read FEMAG I7/ISA7 model files
"""
import logging
import struct
import sys
import pdb
import re
import numpy as np
from collections import Counter
logger = logging.getLogger('femagtools.isa7')
class Reader(object):
"""
Open and Read I7/... |
AlexShukhman/alexshukhman.github.io | src/python/skillsBuilder.py | '''
Builder for Skills HTML
'''
# ----- Local Imports -----
import importlib
common = importlib.import_module('src.python.common')
# ----- Local Helpers -----
# Build HTML from JSON
def build(fType, fName, j):
t = "skills"
html = f"<script>i.{t} = {str(len(j))};</script><p class='iconHeader'>"+t.capitalize()... |
gcavalcante8808/flask-wiki | flask_wiki/backend/custom_fields.py | from sqlalchemy.types import TypeDecorator, CHAR
import uuid
class GUIDField(TypeDecorator):
# Platform independent GUID Implementation that uses little endianess.
impl = CHAR
def load_dialect_impl(self, dialect):
return dialect.type_descriptor(CHAR(32))
def process_bind_param(self, value, d... |
mpi4py/mpi4py | test/test_util_pkl5.py | from mpi4py import MPI
from mpi4py.util import pkl5
import unittest
_basic = [
None,
True, False,
-7, 0, 7,
-2**63+1, 2**63-1,
-2.17, 0.0, 3.14,
1+2j, 2-3j,
'mpi4py',
]
messages = list(_basic)
messages += [
list(_basic),
tuple(_basic),
set(_basic),
frozenset(_basic),
dic... |
Puppet-Finland/trac | files/spam-filter/tracspamfilter/captcha/rand.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Edgewall Software
# Copyright (C) 2006 Alec Thomas <alec@swapoff.org>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewal... |
puttarajubr/commcare-hq | custom/openlmis/tests/test_facility_sync.py | import os
from django.test import TestCase
from casexml.apps.case.tests import delete_all_cases
from corehq.apps.commtrack.tests import bootstrap_domain
from corehq.apps.locations.models import Location, LocationType
from custom.openlmis.api import get_facilities
from custom.openlmis.commtrack import sync_facility_to_s... |
urinieto/SegmenterMIREX2014 | eval.py | #!/usr/bin/env python
"""Evaluates the segmenter using mir_eval
"""
import argparse
import glob
import logging
import os
import sys
import time
import pandas as pd
from joblib import Parallel, delayed
import mir_eval
def eval_track(ref_file, est_file, i=-1, N=-1):
"""Evaluates a single file."""
# Progress b... |
RoyalTS/econ-python-environment | .mywaflib/waflib/Node.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2010 (ita)
"""
Node: filesystem structure, contains lists of nodes
#. Each file/folder is represented by exactly one node.
#. Some potential class properties are stored on :py:class:`waflib.Build.BuildContext` : nodes to depend on, etc.
Unused class memb... |
npe9/noahevans-go9 | lib/codereview/codereview.py | # coding=utf-8
# (The line above is necessary so that I can use 世界 in the
# *comment* below without Python getting all bent out of shape.)
# Copyright 2007-2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may o... |
emulbreh/djff | setup.py | from setuptools import setup, find_packages
setup(
name = 'djff',
version = '0.1',
author = 'Johannes Dollinger',
author_email = 'emulbreh@googlemail.com',
description = "A django app to highlighting diffs",
url = 'http://github.com/emulbreh/djff/',
packages = find_packages(),
package_d... |
ZeitOnline/zeit.campus | src/zeit/campus/browser/tests/test_article.py | import zeit.campus.testing
import zeit.cms.testing
import zeit.content.article.testing
class StudyCourseTest(zeit.cms.testing.BrowserTestCase):
layer = zeit.campus.testing.LAYER
def test_study_course_can_be_edited(self):
self.repository['campus']['article'] = (
zeit.content.article.testi... |
darinf/ports | apply_to_chromium.py | # Copyright 2016 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.
import filecmp
import os
import os.path
import shutil
import sys
# Applies the ports EDK overlay to a local chromium checkout.
# These are copied non-rec... |
reychil/project-alpha-1 | code/utils/functions/glm.py | import numpy as np
import numpy.linalg as npl
def glm(data_4d, conv):
"""
Return a tuple of the estimated coefficients in 4 dimensions and
the design matrix.
Parameters
----------
data_4d: numpy array of 4 dimensions
The image data of one subject
conv: numpy array of 1 dimen... |
oisinmulvihill/nozama-cloudsearch | nozama/cloudsearch/data/db.py | # -*- coding: utf-8 -*-
"""
"""
import logging
from urllib.parse import urljoin
from pymongo import MongoClient
from elasticsearch import Elasticsearch
class DB(object):
"""An lightwrapper around a mongodb connection.
The init is given the configuration dict::
dict(
db_name='<name>', #... |
johannfaouzi/pyts | examples/metrics/plot_itakura.py | """
=====================
Itakura parallelogram
=====================
This example explains how to set the `max_slope` parameter of the itakura
parallelogram when computing the Dynamic Time Warping (DTW) with
``method == "itakura"``. The Itakura parallelogram is defined through a
``max_slope`` parameter which determin... |
idooley/AnalogCrossover | calculator/parallel_resistors.py | #!/opt/local/bin/python3.4
# Loads some common resistor values and then exhaustively searches the space of possible combinations to find a good combination.
import re,sys,math,blist
from blist import sortedset
def convertToValue(x) :
y = x.strip()
if y.endswith("pF") :
return float(y.replace("pF","")) * ... |
IjonTichy/TichyBot | src/objects/listeners/partlistener.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from . import baselistener
from .. import ircresponse
from functions import ansicodes
SB = ansicodes.BOLDON
EB = ansicodes.BOLDOFF
class PartListener(baselistener.BaseListener):
def processLine(self, line):
leaveMsg = ("{}", " [", "{}", "]", " has left " ... |
desihub/fiberassign | py/fiberassign/gfa.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
fiberassign.gfa
===============
Functions for computing coverage of GFAs
"""
import numpy as np
import fitsio
from astropy.table import Table
import desimodel.focalplane.gfa
from desitarget.gaiamatch import gaia_psflike
from ... |
DemocracyClub/UK-Polling-Stations | polling_stations/apps/data_importers/management/commands/import_barnet.py | from data_importers.management.commands import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "BNE"
addresses_name = "2021-03-25T11:42:15.781785/Democracy Club_Polling Districts.csv"
stations_name = "2021-03-25T11:42:15.781785/Democracy Club_Polling Stations.csv... |
glenc/sp.py | src/sp/stsadm.py | # Interface for STSADM.EXE
#
# Allows users to execute STSADM operations by calling the
# run method. The run method takes an operation argument
# and a list of name-value pairs for the operation arguments
#
# import references
import clr
clr.AddReference("System")
from System import Environment
from Syste... |
vmalloc/pact | pact/pact.py | from .utils import EdgeTriggered
from .base import PactBase
from .group import PactGroup
class Pact(PactBase):
def __init__(self, msg, timeout_seconds=None, lazy=True):
self.msg = msg
super(Pact, self).__init__(timeout_seconds)
self._until = []
self._is_lazy = lazy
def until(... |
BrianHicks/probe | tests/test_probe.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_probe
----------------------------------
Tests for `probe` module.
"""
import unittest
from probe import probe
class TestProbe(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
... |
nacl-webkit/chrome_deps | tools/telemetry/telemetry/page_runner_unittest.py | # Copyright (c) 2012 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.
import os
import tempfile
import unittest
from telemetry import browser_finder
from telemetry import page as page_module
from telemetry import page_set
f... |
xkmato/casepro | casepro/profiles/migrations/0006_notification.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.conf import settings
INDEX_SQL = """
-- for displaying a user's latest notifications in a given org
CREATE INDEX profiles_notification_org_user_created_on ON profiles_noti... |
lukesneeringer/django-jinja | setup.py | #!/usr/bin/env python
from distutils.core import setup
from os.path import dirname, realpath
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
import sys
pip_requirements = 'requirements.txt'
class Tox(TestCommand):
"""The test command should install and then run tox.
... |
andresgz/cookiecutter-django | {{cookiecutter.project_slug}}/config/settings/common.py | # -*- coding: utf-8 -*-
"""
Django settings for {{cookiecutter.project_name}} project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolu... |
mozilla/FlightDeck | utils/os_utils.py | import os
import commonware
log = commonware.log.getLogger('f.utils')
# from http://jimmyg.org/blog/2009/working-with-python-subprocess.html
def whereis(program):
for path in os.environ.get('PATH', '').split(':'):
if os.path.exists(os.path.join(path, program)) and \
not os.path.isdir(os.path.j... |
SaltwaterC/sploit-tools | hextobin.py | #!/usr/bin/env python
import binascii, sys, re
import sploit
pattern = re.compile(r"\s+")
def show_help():
print sys.argv[0] + " input.hex output.bin"
print "\tinput.hex - file containing the hex representation of the bytes. Specify \"-\" for reading the hex string from STDIN."
print "\toutput.bin - the binary fi... |
yograterol/flask-bundle-system | docs/conf.py | # -*- coding: utf-8 -*-
#
# System Bundle documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 25 15:03:55 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... |
llvmpy/llvmpy | llvm_cbuilder/shortnames.py | from llvm.core import Type
void = Type.void()
char = Type.int(8)
short = Type.int(16)
int = Type.int(32)
int16 = short
int32 = int
int64 = Type.int(64)
float = Type.float()
double = Type.double()
# platform dependent
def _determine_sizes():
import ctypes
# Makes following assumption:
# sizeof(py_ssize_t... |
joinourtalents/django-popup-forms | popup_forms/templatetags/popup_form.py | import re
from copy import copy
from django import template
from django.template.context import RequestContext
register = template.Library()
class TokenVarExtractor(object):
"""Extracts variables from split content of the token.
Used to extract both positional and keyword arguments.
:param token: The ... |
dimagi/commcare-hq | corehq/apps/translations/generators.py | import datetime
import os
import re
import tempfile
from collections import OrderedDict, defaultdict, namedtuple
from itertools import chain
from django.utils.functional import cached_property
import polib
from memoized import memoized
from corehq.apps.app_manager.dbaccessors import (
get_current_app,
get_ve... |
hakril/PythonForWindows | samples/security/security_descriptor.py | import windows.security
SDDL = "O:BAG:AND:(A;OI;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)(D;CIIO;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)"
sd = windows.security.SecurityDescriptor.from_string(SDDL)
print("Security descriptor is: {0}".format(sd))
print("Owner: {0}".format(sd.owner))
print(" - lookup: {0}".format(windows.utils.lookup_s... |
AunShiLord/sympy | sympy/core/logic.py | """Logic expressions handling
NOTE
----
at present this is mainly needed for facts.py , feel free however to improve
this stuff for general purpose.
"""
from __future__ import print_function, division
def _fuzzy_group(args, quick_exit=False):
"""Return True if all args are True, None if there is any None else F... |
gipi/OHR | ohr/contrib/sites/migrations/0002_set_site_domain_and_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID... |
gmr/tredis | tests/connect_tests.py | import logging
import os
import re
import mock
import uuid
from tornado import testing
from tornado import gen
import tredis
from tredis import exceptions
from . import base
ADDR_PATTERN = re.compile(r'(addr=([\.\d:]+))')
class BadConnectTestCase(base.AsyncTestCase):
AUTO_CONNECT = False
@property
de... |
bokeh/bokeh | bokeh/server/util.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
serge-sans-paille/pythran | pythran/passmanager.py | """
This module provides classes and functions for pass management.
There are two kinds of passes: transformations and analysis.
* ModuleAnalysis, FunctionAnalysis and NodeAnalysis are to be
subclassed by any pass that collects information about the AST.
* gather is used to gather (!) the result of an an... |
niwinz/pyssh-ctypes | pyssh/result.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import ctypes
import sys
from . import api
from . import compat
class LazyResult(object):
"""
Lazy command execution result wrapper.
This wrapper implements a iterator interface.
"""
_return_code = None
_consumed = False
... |
Gustavo6046/ChatterBot | chatterbot/storage/json_queue.py | import json
import logging
import queue
import threading
import time
import traceback
from chatterbot.storage import StorageAdapter
from chatterbot.conversation import Response
from datetime import datetime
comptime = '%m %d %Y %H %M %S'
class SafeDatabase(object):
def __init__(self, filename, auto_start=True, ... |
gugu/django-social-auth-1 | social_auth/backends/contrib/evernote.py | """
EverNote OAuth support
No extra configurations are needed to make this work.
"""
from urllib2 import HTTPError
try:
from urlparse import parse_qs
parse_qs # placate pyflakes
except ImportError:
# fall back for Python 2.5
from cgi import parse_qs
from oauth2 import Token
from social_auth.utils imp... |
taoteg/restful-python-tutorials | polyglot-ninja/jwt-expiry-example.py | import jwt
import datetime
import time
payload = {
"uid": 23,
"name":"mungbean",
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=2)
}
SECRET_KEY = "SUPERSECRET"
token = jwt.encode(payload=payload, key=SECRET_KEY)
print("Generated Token: {}".format(token.decode()))
time.sleep(10) # Wait ... |
jorisvandenbossche/numpy | numpy/core/shape_base.py | from __future__ import division, absolute_import, print_function
__all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'block', 'hstack',
'stack', 'vstack']
import functools
import operator
import warnings
from . import numeric as _nx
from . import overrides
from ._asarray import array, asanyarray
from .mu... |
imankulov/sentry | src/sentry/digests/backends/redis.py | from __future__ import absolute_import
import functools
import itertools
import logging
import random
import time
from contextlib import contextmanager
from django.conf import settings
from rb import Cluster
from redis.client import Script
from redis.exceptions import (
ResponseError,
WatchError,
)
from sent... |
sramana/bottle-debugtoolbar | bottle_debugtoolbar/panels/profiler.py | import sys
try:
import cProfile as profile
except ImportError:
import profile
import functools
import os.path
import pstats
from bottle_debugtoolbar.panels import DebugPanel
from bottle_debugtoolbar.utils import format_fname
class ProfilerDebugPanel(DebugPanel):
"""
Panel that displays the time a res... |
nikdoof/posmaster | posmaster/poscore/management/commands/import_map.py | from __future__ import division
import sqlite3
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from poscore.models import Region, Constellation, System, Planet, Moon
class Command(BaseCommand):
args = '<map csv>'
help = 'Imports the EVE Map from a CSV dump o... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractFlamingdeityBlogspotCom.py |
def extractFlamingdeityBlogspotCom(item):
'''
Parser for 'flamingdeity.blogspot.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'),
('L... |
jjhelmus/pyfive | tests/test_file_like.py | """ Unit tests for pyfive using the filelike objects """
import io
import os
import numpy as np
from numpy.testing import assert_array_equal, assert_almost_equal
import pyfive
DIRNAME = os.path.dirname(__file__)
LATEST_HDF5_FILE = os.path.join(DIRNAME, 'latest.hdf5')
# Polygot string type for representing unicode... |
cgohlke/imagecodecs | tests/conftest.py | # imagecodecs/tests/conftest.py
import os
import sys
if os.environ.get('VSCODE_CWD'):
# work around pytest not using PYTHONPATH in VSCode
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
)
def pytest_report_header(config):
try:
pyversion = f'Python ... |
BillyR512/Cookiecutter-Django-Ansible | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/wsgi.py | """
WSGI config for {{ project_name }} project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... |
hakril/PythonForWindows | ctypes_generation/extended_structs/_MEMORY_BASIC_INFORMATION64.py | INITIAL_MEMORY_BASIC_INFORMATION64 = _MEMORY_BASIC_INFORMATION64
class _MEMORY_BASIC_INFORMATION64(INITIAL_MEMORY_BASIC_INFORMATION64):
STATE_MAPPER = FlagMapper(MEM_COMMIT, MEM_FREE, MEM_RESERVE)
TYPE_MAPPER = FlagMapper(MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE)
PROTECT_MAPPER = FlagMapper(PAGE_NOACCESS, PAGE_R... |
Sumith1896/sympy | sympy/galgebra/stringarrays.py | # sympy/galgebra/stringarrays.py
"""
stringarrays.py are a group of helper functions to convert string
input to vector and multivector class function to arrays of SymPy
symbols.
"""
import operator
from sympy.core.compatibility import reduce
from itertools import combinations
from sympy import S, Symbol, Function
f... |
pagea/bridgedb | lib/bridgedb/test/test_smtp.py | """integration tests for BridgeDB ."""
from __future__ import print_function
import smtplib
import asyncore
import threading
import Queue
import random
import os
from smtpd import SMTPServer
from twisted.trial import unittest
from twisted.trial.unittest import SkipTest
from bridgedb.test.util import processExists
... |
alexsavio/aizkolari | aizkolari_svmperf_old.py | #!/usr/bin/python
#-------------------------------------------------------------------------------
#License GPL v3.0
#Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
#Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
#Universidad del Pais Vasco UPV/EHU
#Use this at your own risk!
#2012-01-15
#-----------... |
dcramer/jinja1-djangosupport | jdebug.py | # -*- coding: utf-8 -*-
"""
jdebug
~~~~~~
Helper module to simplify jinja debugging. Use
:copyright: 2006 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import gc
from jinja import Environment
from jinja.parser import Parser
from jinja.lexer import Lexer
f... |
ZeitOnline/zeit.cms | src/zeit/cms/locking/browser/tests/test_lock.py | from datetime import datetime
import mock
import pytz
import time
import urllib2
import zeit.cms.checkout.interfaces
import zeit.cms.testing
import zope.app.locking.lockinfo
class TimeFreezeLockInfo(zope.app.locking.lockinfo.LockInfo):
def __init__(self, *args, **kw):
super(TimeFreezeLockInfo, self).__in... |
matthew-brett/draft-statsmodels | scikits/statsmodels/sandbox/tools/tools_pca.py | # -*- coding: utf-8 -*-
"""Principal Component Analysis
Created on Tue Sep 29 20:11:23 2009
Author: josef-pktd
TODO : add class for better reuse of results
"""
import numpy as np
def pca(data, keepdim=0, normalize=0, demean=True):
'''principal components with eigenvector decomposition
similar to princomp ... |
kurkop/django-api-rest-example | restExample/settings.py | # Django settings for restExample project.
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
... |
robclark/chromium | media/tools/constrained_network_server/cns.py | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Constrained Network Server. Serves files with supplied network constraints.
The CNS exposes a web based API allowing network co... |
savioabuga/phoenix | phoenix/health/forms.py | from datetime import date
from django import forms
from bootstrap3_datetime.widgets import DateTimePicker
from django_select2.widgets import AutoHeavySelect2Widget
from phoenix.animals.fields import MultipleAnimalsField
from .models import Treatment
class TreatmentForm(forms.ModelForm):
date = forms.DateField(ini... |
matthew-brett/draft-statsmodels | scikits/statsmodels/datasets/scotland/scotvote.py | # Autogenerated by .data_utils.convert on Sat, 27 Jun 2009, 17:33 EDT
names = ['COUNCILDIST', 'YES', 'COUTAX', 'UNEMPF', 'MOR', 'ACT', 'GDP', 'AGE', 'COUTAX_FEMALEUNEMP']
COUNCILDIST = ['"Aberdeen_City"', '"Aberdeenshire"', '"Angus"', '"Argyll_and_Bute"', '"Clackmannanshire"', '"Dumfries_and_Galloway"', '"Dundee_City... |
zstuartp/AstroReduce | astroreduce/arimage.py | import datetime
from enum import Enum
import glob
import os
from typing import List
from astropy.io import fits
from . import log
CURRENT_DATE_TIME = datetime.datetime.now().strftime("%y-%m-%dT%H:%M:%S")
logger = log.get_logger()
#
# ARImage
# This class provides an easy way to interact with astronomy fits images
... |
iddqd1/django-cms | cms/forms/wizards.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.contrib.sites.models import Site
from django.core.exceptions import PermissionDenied
from django.utils.encoding import smart_text
from django.utils.translation import (
ugettext,
ugettext_lazy as _,
get_la... |
codexns/golang-build | dev/tests.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import sys
import threading
import unittest
from os import path
import time
import re
import shutil
import os
import sublime
import shellenv
import package_events
if sys.version_info < (3,):
from Queue import Queu... |
devilry/devilry-django | devilry/devilry_qualifiesforexam/tests/test_list_statuses_view.py | # -*- coding: utf-8 -*-
# 3rd party imports
import mock
from django.utils import timezone
from model_bakery import baker
# Django imports
from django import test
# CrAdmin imports
from cradmin_legacy import cradmin_testhelpers
# Devilry imports
from devilry.devilry_qualifiesforexam.views import list_statuses_view
... |
agiliq/Dinette | dinette/search_indexes.py | from haystack import indexes
from haystack import site
from dinette.models import Ftopics, Reply, DinetteUserProfile
class TopicIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
subject = indexes.CharField(model_attr="subject")
message = indexes.CharField(model_attr="_... |
uwescience/raco | raco/backends/logical.py | import raco.rules as rules
from raco.backends import Algebra
class OptLogicalAlgebra(Algebra):
@staticmethod
def opt_rules(**kwargs):
return [rules.RemoveTrivialSequences(),
rules.SimpleGroupBy(),
rules.SplitSelects(),
rules.PushSelects(),
... |
ogreen/medianfilter | python/mf.py |
import Image
from PIL import ImageFilter
import numpy
import time
import math
def psnr(img1, img2):
mse = numpy.mean( (img1 - img2) ** 2 )
if mse == 0:
return 100
PIXEL_MAX = 255.0
# return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
return -10 * math.log10(mse/(PIXEL_MAX*PIXEL_MAX))
def... |
webeng/DeepLearningTutorials | code/fetex_image_256x256.py | from PIL import Image
from os import listdir
from os.path import isfile, join
import sys
import numpy as np
import random
from sklearn import preprocessing
import cPickle
import theano
#import scipy
#from scipy.misc import pilutil
class FetexImage(object):
verbose = None
"""docstring for FetexImage"""
def __init__(... |
aquavitae/mongokit-py3 | tests/test_custom_types.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2011, Nicolas Clairon
# 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 abov... |
wybosys/wybosys | tools/dump-git-projects-tree.py | #!/usr/bin/env python3
import os, git, sys, json, re
BLACKS = [re.compile('_.*'), re.compile('\..*')]
base=sys.argv[1]
to=sys.argv[2]
def process(dir, relv, result):
for d in os.listdir(dir):
black = False
for b in BLACKS:
if b.match(d):
black = True
... |
kylef/refract.py | refract/refraction.py | from refract.elements import (Element, String, Number, Boolean, Null, Array,
Object, Member)
__all__ = ('refract',)
def refract(structure) -> Element:
"""
Refracts the given value.
>>> refract('string')
String(content='string')
>>> refract(1)
Number(content=1)... |
rimbalinux/LMD3 | attachment/models.py | from django.db import models
from djangotoolbox import fields
from counter.tools import BaseModel
#from google.appengine.ext import db
"""
class Attachment(db.Model):
containers = db.ListProperty(db.Key,default=[])
doctype = db.StringProperty(default='photo')
filename = db.StringProperty()
file... |
jokey2k/MoritzServer | moritzprotocol/messages.py | # -*- coding: utf-8 -*-
"""
moritzprotocol.messages
~~~~~~~~~~~~~~~~~~~~~~~
Definition of known messages, based on IDs from FHEM plugin
:copyright: (c) 2014 by Markus Ullmann.
:license: BSD, see LICENSE for more details.
"""
# environment constants
# python imports
from datetime import datetime
... |
cancerregulome/inspectra | python/splitfm.py | #!/usr/bin/env python
# Copyright (c) 2013, Ryan Bressler and the Inspectra Contributors
# 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 abov... |
lojaintegrada/pyboleto | pyboleto/html.py | # -*- coding: utf-8 -*-
"""
pyboleto.html
~~~~~~~~~~~~
Classe Responsável por fazer o output do boleto em html.
:copyright: © 2012 by Artur Felipe de Sousa
:license: BSD, see LICENSE for more details.
"""
import os
import string
import sys
import codecs
import base64
from itertools import chain
... |
remarkablerocket/django-vend | django_vend/stores/views.py | from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django_vend.core.views import (VendAuthSingleObjectSyncMixin,
VendAuthCollectionSyncMixin)
from .models import VendOutlet, VendRegister
class RegisterList(VendAuthCollectionSyncMixin, L... |
dimagi/commcare-hq | corehq/apps/linked_domain/tests/test_release_manager.py | from unittest.mock import patch
from corehq.apps.app_manager.models import Application, LinkedApplication
from corehq.apps.app_manager.tests.util import patch_validate_xform
from corehq.apps.linked_domain.const import (
LINKED_MODELS_MAP,
MODEL_APP,
MODEL_CASE_SEARCH,
MODEL_DATA_DICTIONARY,
MODEL_D... |
lovehhf/django-social-auth | social_auth/db/base.py | """Models mixins for Social Auth"""
import base64
import time
import re
from datetime import datetime, timedelta
from openid.association import Association as OIDAssociation
from social_auth.utils import setting, utc
# django.contrib.auth and mongoengine.django.auth regex to validate usernames
# '^[\w@.+-_]+$', we u... |
timopulkkinen/BubbleFish | chrome/common/extensions/docs/server2/preview.py | #!/usr/bin/env python
# Copyright (c) 2012 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.
# This helps you preview the apps and extensions docs.
#
# ./preview.py --help
#
# There are two modes: server- and render- mode... |
rendon/omegaup | stuff/update_i18n.py | #!/usr/bin/python
import glob
import os
import re
REGEX = re.compile(r'^\s*(.*?)\s*=\s*(.*)\s*$')
for lang in glob.glob('frontend/templates/*.lang'):
name = os.path.basename(lang)
name = os.path.splitext(name)[0]
target = 'frontend/www/js/lang.%s.js' % name
with open(target, 'w') as dst:
dst.... |
HBCompass/temp | facet/contrib/sites/migrations/0002_set_site_domain_and_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID... |
dedaluz/django-flexslider | flexslider/templatetags/slider.py | from django import template
from django.core.cache import cache
from flexslider.models import Slider
register = template.Library()
@register.simple_tag
def slider(pk):
ckey = Slider.get_cache_key_for(pk)
result = cache.get(ckey)
if result is None:
# get slider
try:
slider = S... |
calmseas/kindle-goodreads-sync | phantomjs/test_page.py | from .phantom import Phantom
from .driver import Driver
import pytest
@pytest.fixture()
def page(request):
driver = Driver(engine='phantomjs', port=3000)
driver.start()
driver.wait_for_ready()
phantom = Phantom(driver=driver)
page = phantom.create_page()
request.addfinalizer(driver.kill)
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.