repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
maferelo/saleor | saleor/account/migrations/0035_staffnotificationrecipient.py | # Generated by Django 2.2.6 on 2019-11-22 10:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("account", "0034_service_account_token")]
operations = [
migrations.CreateModel(
... |
mozilla/relman-auto-nag | auto_nag/scripts/has_str_no_range.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from libmozdata.bugzilla import Bugzilla
from auto_nag.bzcleaner import BzCleaner
from auto_nag.people import People
... |
sunlightlabs/tcamp | tcamp/sked/models.py | import hashlib
import re
import datetime
from django.conf import settings
from django.core.urlresolvers import reverse, Resolver404
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.template.defaultfi... |
lokik/sfepy | examples/multi_physics/biot_parallel_interactive.py | #!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, ... |
wlonk/hexes | hexes/hexes.py | """
This module contains the core concepts of Hexes:
* :py:class:`.Style`
* :py:class:`.Box`
* :py:class:`.Application`
"""
import asyncio
import curses
import logging
from collections import defaultdict
from math import floor
from .aiotextpad import AsyncTextbox
from .utils import (
Point,
flatten,
wrap_... |
dimagi/commcare-hq | corehq/apps/smsbillables/migrations/0006_remove_smsbillable_api_response.py | from django.db import migrations
def confirm_no_data_loss(apps, schema_editor):
if apps.get_model('smsbillables', 'SmsBillable').objects.filter(api_response__isnull=False).exists():
raise Exception(
'There exists an SmsBillable with api_response != None.'
' Preventing this migratio... |
zfrenchee/pandas | asv_bench/benchmarks/groupby.py | from string import ascii_letters, digits
from itertools import product
from functools import partial
import numpy as np
from pandas import (DataFrame, Series, MultiIndex, date_range, period_range,
TimeGrouper, Categorical)
import pandas.util.testing as tm
from .pandas_vb_common import setup # noq... |
aattaran/Machine-Learning-with-Python | CTCI/Chapter 9/Question9_03/magic_index.py | #! /usr/bin/env python
# Author: Victor Terron (c) 2014
# Email: `echo vt2rron1iaa32s | tr 132 @.e`
# License: GNU GPLv3
# 9.3. A magic index in an array A[0...n-1] is defined to be an index such that
# A[i] = i. Given a sorted array of distinct integers, write a method to find a
# magic index, if one exists, in arra... |
dimagi/commcare-hq | corehq/apps/app_manager/tests/test_extension_case.py | from django.test import SimpleTestCase
from couchdbkit import BadValueError
from unittest.mock import patch
from corehq.apps.app_manager.exceptions import CaseError
from corehq.apps.app_manager.models import (
AdvancedModule,
AdvancedOpenCaseAction,
Application,
CaseIndex,
FormActionCondition,
... |
automl/auto-sklearn | autosklearn/pipeline/components/data_preprocessing/categorical_encoding/no_encoding.py | from typing import Dict, Optional, Tuple, Union
import numpy as np
from ConfigSpace.configuration_space import ConfigurationSpace
from autosklearn.pipeline.base import DATASET_PROPERTIES_TYPE, PIPELINE_DATA_DTYPE
from autosklearn.pipeline.components.base import \
AutoSklearnPreprocessingAlgorithm
from autosklearn... |
diefenbach/lfs-paypal | lfs_paypal/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ipn', '__first__'),
('order', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PayPalOrde... |
MrHarcombe/python-gpiozero | gpiozero/__init__.py | from __future__ import (
unicode_literals,
print_function,
absolute_import,
division,
)
from .pins import (
Factory,
Pin,
SPI,
)
from .pins.data import (
PiBoardInfo,
HeaderInfo,
PinInfo,
pi_info,
)
# Yes, import * is naughty, but exc imports nothing else so there's no cross... |
almarklein/bokeh | bokeh/tests/test_properties.py | import unittest
import numpy as np
from bokeh.properties import (
HasProps, Int, Array, String, Enum, Float, DataSpec, ColorSpec, DashPattern
)
class Basictest(unittest.TestCase):
def test_simple_class(self):
class Foo(HasProps):
x = Int(12)
y = String("hello")
z =... |
vlegoff/tsunami | src/primaires/joueur/masques/nv_groupe/__init__.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
... |
cvsuser-chromium/native_client | pnacl/scripts/llvm-test.py | #!/usr/bin/python
# Copyright (c) 2013 The Native Client 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 script runs the LLVM regression tests and the LLVM testsuite.
These tests are tightly coupled to the LLVM build, and re... |
chen0040/pyalgs | tests/data_structures/commons/priority_queue_unit_test.py | import unittest
from pyalgs.data_structures.commons.priority_queue import MinPQ, MaxPQ
class MinPQUnitTest(unittest.TestCase):
def test_min(self):
pq = MinPQ.create()
pq.enqueue(10)
pq.enqueue(5)
pq.enqueue(12)
pq.enqueue(14)
pq.enqueue(2)
self.assertFalse... |
VitoJanko/LVR_VEK1 | sat_solver.py | # -*- coding: cp1250 -*-
from bool import *
#===============================================================================
#SAT solver
#===============================================================================
def SAT(cnf,spr,cs,pureLiteral="True"):
#SAT(cnf, spr, cs) je funkcija, ki resi SAT za podan sl... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSupertranslation225613631WordpressCom.py |
def extractSupertranslation225613631WordpressCom(item):
'''
Parser for 'supertranslation225613631.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', ... |
mindflayer/python-mocket | tests/main/test_mode.py | import pytest
import requests
from mocket import Mocketizer, mocketize
from mocket.exceptions import StrictMocketException
@mocketize(strict_mode=True)
def test_strict_mode_fails():
url = "https://httpbin.org/ip"
with pytest.raises(StrictMocketException):
requests.get(url)
@pytest.mark.skipif('os.... |
Transkribus/TranskribusDU | TranskribusDU/graph/pkg_GraphBinaryConjugateSegmenter/MultiSinglePageXml_Separator.py | # -*- coding: utf-8 -*-
"""
Multi single PageXml graph in conjugate mode, exploting SeparatorRegion
as additional edge features
Copyright NAVER(C) 2019
2019-08-20 JL. Meunier
"""
from .PageXmlSeparatorRegion import PageXmlSeparatorRegion
from .MultiSinglePageXml import MultiSingleP... |
qedsoftware/commcare-hq | corehq/apps/receiverwrapper/tests/test_app_id.py | from django.core.cache import cache
from django.test import TestCase
from corehq.apps.app_manager.models import Application
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.receiverwrapper.util import get_version_from_build_id, get_submit_url
from corehq.form_processor.interfaces.dbaccessors impo... |
mwort/modelmanager | modelmanager/plugins/browser/api/views.py | import traceback
import os
import os.path as osp
import sys
from django.conf import settings
from django.http import HttpResponse
from django.contrib.admin.utils import unquote
from .models import Function
from browser.models import Run
# strange behaviour with unquote under PY3
if sys.version_info >= (3, 0):
de... |
mitodl/micromasters | financialaid/api.py | """
API helper functions for financialaid
"""
import logging
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from financialaid.constants import DEFAULT_INCOME_THRESHOLD, FinancialAidStatus
from financialaid.exceptions import NotSupportedException
from financialaid.models impor... |
sunlightlabs/mptindicators | mptindicators/scorecard/models.py | from __future__ import unicode_literals
import random
from collections import defaultdict
from django.db import models
import re
class Region(models.Model):
name = models.CharField(max_length=255)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
class Country(mod... |
ifduyue/sentry | src/sentry/integrations/issues.py | from __future__ import absolute_import
import logging
import six
from sentry import features
from sentry.models import Activity, Event, Group, GroupStatus, Organization
from sentry.utils.http import absolute_uri
from sentry.utils.safe import safe_execute
logger = logging.getLogger('sentry.integrations.issues')
cla... |
ericmjl/bokeh | tests/integration/widgets/test_toggle.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... |
idrmhyprbls/PyroChess | tests/test_basic.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
import unittest
# import nose
# import nose.tools
import pyrochess
class TestModule(unittest.TestCase):
"""Nose test class."""
# @classmethod
# def setUpClass(self):
# p... |
rgerkin/python-neo | neo/io/tools.py | # -*- coding: utf-8 -*-
"""
Tools for IO coder:
* Creating RecordingChannel and making links with AnalogSignals and
SPikeTrains
"""
try:
from collections.abc import MutableSequence
except ImportError:
from collections import MutableSequence
import numpy as np
from neo.core import (AnalogSignal, Block,
... |
zat1gi/stochastic | auxiliary/cubature/gen_ordered_cubature.py | #!/usr/bin/env python
# I create cubature using Gauss-Legendre or Gauss-Hermite quadrature.
# The first input chooses which.
# The second input is the number of dimensions over which to integrate.
# The next inputs are for GL the bounds of the UQ space supports,
# for GH they are the average and standard deviation of t... |
jorisvandenbossche/numpy | numpy/core/tests/test_function_base.py | from __future__ import division, absolute_import, print_function
from numpy import (
logspace, linspace, geomspace, dtype, array, sctypes, arange, isnan,
ndarray, sqrt, nextafter, stack
)
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_array_equal, assert_allclose,
suppress... |
justinabrahms/permachart | permachart/charter/forms.py | from collections import defaultdict
from django.http import QueryDict
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from charter.models import Chart, ChartDataSet, DataRow
from charter.form_utils import BaseFormSet
class ChartForm(djangoforms.ModelForm):
class Meta:
mo... |
bokeh/bokeh | tests/unit/bokeh/model/test___init___model.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.
#-------------------------------------------------------------------... |
samuelmaudo/yepes | yepes/contrib/standards/model_mixins.py | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
import re
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import six
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from yepes import fields
from ... |
alset333/NetworkedLearningChatbot | PeterMaar-NetLrnChatBot/Server/Chatbot.py | #!/usr/bin/env python3
# Chatbot.py
import time
import pickle
import random
import os
import sys
__author__ = 'Peter Maar'
__version__ = '0.2.0'
thingsToSayOld = []
smartSayDict = {}
debugTestMode = False # Inital value on import or when running as main. This can be changed after import in another class/file
def ... |
HwisooSo/gemV-update | src/mem/cache/Cache.py | # Copyright (c) 2012-2013, 2015 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the fun... |
mverleg/svsite | source/tweaks/templatetags/currency.py |
from django.template import Library
class WrongFormatException(Exception):
""" Special exception because ValueError tends to get swallowed """
register = Library()
@register.filter
def euro(value):
if not value:
value = 0.
try:
value = float(value)
except ValueError:
raise WrongFormatException('|euro g... |
endlessm/chromium-browser | third_party/chromite/scripts/cros_sysroot_utils.py | # -*- coding: utf-8 -*-
# Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Collection of tools to create sysroots."""
from __future__ import print_function
import os
import sys
from chromite.lib impo... |
perseas/Pyrseas | pyrseas/augment/column.py | # -*- coding: utf-8 -*-
"""
pyrseas.augment.column
~~~~~~~~~~~~~~~~~~~~~~
This module defines two classes: CfgColumn derived from
DbAugment and CfgColumnDict derived from DbAugmentDict.
"""
from pyrseas.augment import DbAugmentDict, DbAugment
from pyrseas.dbobject.column import Column
class CfgColumn... |
bsipocz/glue | glue/core/data_factories.py | """ Factory methods to build Data objects from files"""
"""
Implementation notes:
Each factory method conforms to the folowing structure, which
helps the GUI Frontend easily load data:
1) The first argument is a file name to open
2) The return value is a Data object
3) The function has a .label attribute that desc... |
praekelt/jmbo-superhero | superhero/tools.py | from django import template
from django.contrib import messages
from django.contrib.admin import helpers
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _
import object_tools
from superhero.forms import ImportForm
from superhero.models import Superhero
class Superher... |
ESGF/esgf-drslib | drslib/thredds.py | """
Check metadata in a THREDDS catalog is consistent with the DRS.
Things to check:
1. All DRS components set as properties and validate with drslib
2. drs_id is consistent with properties
3. version is a date
4. dataset urlPath is consistent with the DRS directory structure.
5. Checksums are present and the right f... |
rwgdrummer/maskgen | plugins/ConvertToColor/__init__.py | import numpy as np
import os
from maskgen.image_wrap import openImageFile,ImageWrapper
import cv2
"""
Convert a gray image into a single color channel.
"""
def transform(img, source, target, **kwargs):
channel_map = {
"red":0,
"green":1,
"blue":2
}
donor = kwargs['mask'] if 'mask' ... |
qedsoftware/commcare-hq | corehq/apps/ota/tests/test_search_claim_endpoints.py | import re
from uuid import uuid4
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.util import post_case_blocks
from casexml.apps.case.tests.util import delete_all_cases
from corehq.apps.case_search.models import C... |
timsnyder/bokeh | bokeh/core/property/dataspec.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
eriknw/benchtoolz | benchtoolz/benchutils.py | from __future__ import print_function
import glob
import imp
import inspect
import os.path
import pyclbr
import sys
import textwrap
import timeit
from .printutils import ProgressPrinter, BenchPrinter, nsorted
# We can introduce better configuration handling later.
# We should, however, think about and clean up the *va... |
luciansmith/sedml-test-suite | contributions/HARMONY 2021/create_sedml_surface_fill_ls.py | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 10 14:58:01 2021
@author: Lucian
"""
import tellurium as te
import phrasedml
import libsedml
import sys
import os
r = te.loada ('''
$S1 -> S2; k1*S1/(0.1 + S4^n)
S2 -> S3; k2*S2
S3 -> S4; k3*S3;
S4 ->; k4*S4
k1 = 0.1; k2 = 0.4;
... |
tbabej/astropy | astropy/vo/client/tests/test_conesearch.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for `astropy.vo.client.conesearch` and `astropy.vo.client.async`."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# STDLIB
import os
import time
# THIRD-PARTY
import numpy as np
# ... |
kastman/lyman | lyman/frontend.py | """Forward facing lyman tools with information about ecosystem."""
import os
import os.path as op
import re
import sys
import imp
import shutil
import yaml
import numpy as np
from moss import Bunch # TODO get from nipype
# TODO maybe defer workflow imports?
from .workflows.template import define_template_workflow
f... |
whyflyru/django-seo | tests/userapp/tests.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import hashlib
import django
try:
from django.utils import six
except ImportError:
import six
from django.test import TestCase, override_settings
from django.http import Http404
try:
from django.test import TransactionTestCase
except ImportErr... |
britco/django-oscar-stripe | oscar_stripe/facade.py | from django.conf import settings
from oscar.apps.payment.exceptions import UnableToTakePayment, InvalidGatewayRequestError
from django.utils import timezone
import stripe
from django.db.models import get_model
import logging
logger = logging.getLogger(__name__)
Source = get_model('payment', 'Source')
Order = get_mod... |
portnov/assethub | assethub/assets/forms.py |
from django import forms
from django.forms import ModelForm
from django.db import models
from django.core.files.images import get_image_dimensions
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordResetForm
from django.utils.translation import ugettext as _, ugettext_lazy as _l
... |
bmaupin/pytoutv-plus | pytoutv_plus/app.py | #!/usr/bin/env python
# Some of this is from here:
# https://github.com/bvanheu/pytoutv/blob/master/toutvcli/app.py
# Copyright (c) 2012, Benjamin Vanheuverzwijn <bvanheu@gmail.com>
# Copyright (c) 2014, Philippe Proulx <eepp.ca>
# All rights reserved.
#
# Thanks to Marc-Etienne M. Leveille
#
# Redistribution and use... |
jmeyers314/mcgalsim | mcgalsim.py | from copy import deepcopy
from argparse import ArgumentParser
import time
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import galsim
import emcee
import triangle
from astropy.utils.console import ProgressBar
def walker_ball(alpha, spread, nwalkers):
return [alpha+np.r... |
kevinkepp/look-at-this | sft/agent/DeepQAgentReplayCloning.py | from __future__ import division
import random
import copy
import numpy as np
from sft.agent.DeepQAgentReplay import DeepQAgentReplay
class DeepQAgentReplayCloning(DeepQAgentReplay):
# actions: possible actions
# gamma: discount factor
# epsilon: epsilon-greedy strategy
# epsilon: discount function for epsilon
... |
ifding/ifding.github.io | gans/modular_gan_test.py | # coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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 ... |
mKeRix/home-assistant | homeassistant/components/plex/__init__.py | """Support to embed Plex."""
import asyncio
import functools
import json
import logging
import plexapi.exceptions
from plexwebsocket import PlexWebsocket
import requests.exceptions
import voluptuous as vol
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.media_player... |
msincenselee/vnpy | vnpy/app/algo_trading/algos/twap_algo.py | from vnpy.trader.constant import Offset, Direction
from vnpy.trader.object import TradeData
from vnpy.trader.engine import BaseEngine
from vnpy.app.algo_trading import AlgoTemplate
class TwapAlgo(AlgoTemplate):
""""""
display_name = "TWAP 时间加权平均"
default_setting = {
"vt_symbol": "",
"di... |
allanburleson/python-adventure-game | pag/classes.py | """
Contains most classes used in the game.
"""
### This file deserves a better name
import random
import os
import shelve
import sys
from pag import cwd
from pag import sf_name
from pag import utils
### Why do we need lists like this again?
Creatures = []
Items = []
class GameObject:
__ui = None
def __in... |
tgbugs/heatmaps | stats.py | """
File for computing statistics of heatmaps.
May eventually be merged into the explore interface.
"""
import requests
import numpy as np
import pylab as plt
from IPython import embed
from heatmaps.visualization import sCollapseToSrcName, applyCollapse
from heatmaps.services import LITERATURE_ID, TOTAL_TERM_ID... |
kuboschek/jay | settings/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='VotingSystem',
fields=[
('id', models.AutoField... |
cuttlefishh/papers | vibrio-fischeri-transcriptomics/code/python/GOcollapser.py | #!/usr/bin/env python
import sys
filecount=0
#Usage GOcollapser.py Final_AGbaseresults.txt ParsedBlastx2Uniprot.txt GOTable.txt
INFILE = open(sys.argv[1], 'r') #opens an input file with concatenated AGBaseoutput
contignames = sys.argv[2] #an input file with the gene names and uniprot ID's
OUT=open(sys.argv[3],'w') #... |
jptomo/rpython-lang-scheme | rpython/rtyper/tool/rfficache.py |
# XXX This is completely outdated file, kept here only for bootstrapping
# reasons. If you touch it, try removing it
import py
import os
from rpython.translator.tool.cbuild import ExternalCompilationInfo
from rpython.tool.udir import udir
from rpython.rlib import rarithmetic
from rpython.rtyper.lltypesystem impor... |
oxnz/NZChat | cast/x.py | #!/usr/bin/env python
import socket
def tcpClient():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.0.101', 8889))
s.listen(10)
while True:
c, a = s.accept()
print 'got connection from', a
c.send('hello, this is server')
r = c.recv(400)
print 'read to server', r
c.send('hello ag... |
birsoyo/conan | conans/test/util/files_extract_wildcard_test.py | import os
import tarfile
import zipfile
from unittest import TestCase
from conans.test.utils.test_files import temp_folder
from conans.tools import unzip
from conans.util.files import save_files
def create_archive(archive, root, relative_file_paths):
""" Create an archive with given file paths relative to given... |
joegomes/deepchem | examples/hopv/hopv_graph_conv.py | """
Script that trains graph-conv models on HOPV dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from hopv_datasets import load_hopv
#... |
thegreenrobot/littlechef-rackspace | test/test_deploy.py | import unittest2 as unittest
import mock
from littlechef_rackspace.lib import Host
from littlechef_rackspace.deploy import ChefDeployer
class ChefDeployerTest(unittest.TestCase):
def setUp(self):
self.host = Host(name="test.example.com",
ip_address="50.56.57.58")
self.oha... |
mabotech/mabolab | mabolab/common/singleton.py |
import threading
class Singleton(object):
objs = {}
objs_locker = threading.Lock()
def __new__(cls, *args, **kv):
#print cls
if cls in cls.objs:
return cls.objs[cls]['obj']
cls.objs_locker.acquire()
try:
if cls in cls.objs: ## double check l... |
showa-yojyo/notebook | source/_sample/pyopengl/transform.py | #!/usr/bin/env python
"""transform.py: Provide some of deprecated transform features of OpenGL 3.0.
Reference:
* rndblnch / opengl-programmable
<http://bitbucket.org/rndblnch/opengl-programmable>
* OpenGLBook.com
<http://openglbook.com/chapter-4-entering-the-third-dimension.html>
* Tutorials for modern O... |
oblique-labs/pyVM | rpython/rtyper/rbool.py | from rpython.annotator import model as annmodel
from rpython.rtyper.error import TyperError
from rpython.rtyper.lltypesystem.lltype import Signed, Unsigned, Bool, Float
from rpython.rtyper.rmodel import log
from rpython.rtyper.rint import IntegerRepr
from rpython.rtyper.rfloat import FloatRepr
from rpython.tool.pairtyp... |
damianpv/sfotipy | artists/migrations/0004_initial.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):
# Adding model 'Artist'
db.create_table(u'artists_artist', (
... |
ahmedbodi/terracoin | qa/rpc-tests/test_framework/script.py | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# script.py
#
# This file is modified from python-bitcoinlib.
#
"""Scripts
Functionality to build scr... |
akhilaananthram/inception | src/inception/image/operation/statadjust.py | """
Statistics-based image adjustment operations
"""
from ..image import Image
from ..statadjust import adjust
from .base import Operation
class StatAdjustOperation(Operation):
"""
Performs a statistical image match of the foreground to the background,
using an adapted version of "Understanding and Impro... |
glemaitre/UnbalancedDataset | imblearn/under_sampling/prototype_generation/tests/test_cluster_centroids.py | """Test the module cluster centroids."""
from __future__ import print_function
from collections import Counter
import numpy as np
from scipy import sparse
from pytest import raises
from sklearn.utils.testing import assert_allclose
from sklearn.utils.testing import assert_array_equal
from sklearn.cluster import KMean... |
relic7/prodimages | python/queryImgStat.py | def sqlQuery_ReturnImgStatus(style):
import sqlalchemy
orcl_engine = sqlalchemy.create_engine('oracle+cx_oracle://prod_team_ro:9thfl00r@borac101-vip.l3.bluefly.com:1521/bfyprd11')
#orcl_engine = sqlalchemy.create_engine('oracle+cx_oracle://jbragato:Blu3f!y@192.168.30.66:1531/dssprd1')
connection = orcl_... |
gwu-libraries/sfm-ui | sfm/message_consumer/management/commands/startconsumer.py | from django.conf import settings
from django.core.management.base import BaseCommand
from message_consumer.sfm_ui_consumer import SfmUiConsumer
from sfmutils.consumer import MqConfig, EXCHANGE
QUEUE = "sfm_ui"
ROUTING_KEYS = ["harvest.status.*", "harvest.status.*.*", "harvest.status.*.*.*", "warc_created",
... |
jamesmawm/Mastering-Python-for-Finance-source-codes | B03898_10_codes/TrinomialLattice.py | """
README
======
This file contains Python codes.
======
"""
""" Price an option by the trinomial lattice """
from TrinomialTreeOption import TrinomialTreeOption
import numpy as np
class TrinomialLattice(TrinomialTreeOption):
def _setup_parameters_(self):
super(TrinomialLattice, self)._setup_parameters... |
lordmos/blink | Tools/Scripts/webkitpy/layout_tests/print_layout_test_times_unittest.py | # Copyright (C) 2013 Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
kprestel/PyInvestment | pytech/utils/exceptions.py | """
Hold exceptions used throughout the package
"""
from arctic.exceptions import NoDataFoundException
from pandas_datareader._utils import RemoteDataError
class PyInvestmentError(Exception):
"""Base exception class for all PyInvestment exceptions"""
msg = None
def __init__(self, *args, **kwargs):
... |
scandio/s3stat | s3stat.py | #!/usr/bin/env python
"""
S3 Stat
=======
This python module uses the really nice `goaccess <http://goaccess.io/>`_ utility
to provide you with an amazing Amazon log file analyser tool that is relatively easy to install, and is extremely
easy to extend.
GOACCESS version needed: 0.8.5
Installation
-------------
::
... |
MADindustries/WhatManager2 | qiller/tidal_api.py | import logging
import requests
logger = logging.getLogger(__name__)
class TidalAPI(object):
def __init__(self, session_id):
self.session_id = session_id
def call(self, *args):
url = 'https://listen.tidalhifi.com/v1/' + '/'.join(args)
params = {
'sessionId': self.session... |
theosysbio/means | src/means/approximation/mea/closure_normal.py | """
Normal moment closure
------
This part of the package provides the original the Normal (Gaussian) closure.
"""
import sympy as sp
from sympy.utilities.iterables import multiset_partitions
import operator
from means.util.sympyhelpers import product
from closure_scalar import ClosureBase
class NormalClosure(Closu... |
tnotstar/pycalcstats | src/statistics.py | ## Module statistics.py
##
## Copyright (c) 2013 Steven D'Aprano <steve+python@pearwood.info>.
##
## 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/L... |
demisto/content | Packs/SymantecMSS/Integrations/SymantecMSS/SymantecMSS.py | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import xml
import tempfile
import contextlib
import OpenSSL.crypto
from xml.sax.saxutils import escape
import re
''' GLOBALS/PARAMS '''
FETCH_MAX_INCIDENTS = 500
SECURITY_INCIDENT_NODE_XPATH = ".//Sec... |
schulmar/apitrace | specs/cglapi.py | ##########################################################################
#
# Copyright 2008-2009 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software withou... |
chronossc/openpyxl | openpyxl/reader/__init__.py | # file openpyxl/reader/__init__.py
# Copyright (c) 2010 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy... |
lucasb-eyer/DeepFried2 | examples/utils.py | import sys as _sys
def printnow(fmt, *a, **kw):
_sys.stdout.write(fmt.format(*a, **kw))
_sys.stdout.flush()
# Progressbar
##############
try:
import progressbar as _pb
def make_progressbar(prefix, data_size):
widgets = [prefix, ', processed ', _pb.Counter(), ' of ', str(data_size),
... |
michelangelo/Cumae | external/avr-libc-2.0.0/devtools/cr_check.py | #! /usr/bin/env python
#
# Copyright (c) 2004 Theodore A. Roth
# 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, thi... |
damienstanton/nanodegree | selfdriving_vehicle/openpilot/selfdrive/car/honda/carstate.py | import numpy as np
import selfdrive.messaging as messaging
from selfdrive.boardd.boardd import can_capnp_to_can_list
from selfdrive.config import VehicleParams
from common.realtime import sec_since_boot
from selfdrive.car.fingerprints import fingerprints
from selfdrive.car.honda.can_parser import CANParser
def get_c... |
cmput404wi16/metablog-project | app/models.py | #!/usr/bin/env python
import os
from app import app, db
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_utils import ScalarListType
from datetime import datetime
from flask import Flask
import hashlib
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpire... |
hishnash/inspyred | examples/advanced/logging_example.py | from random import Random
from time import time
import inspyred
import math
# Define an additional "necessary" function for the evaluator
# to see how it must be handled when using pp.
def my_squaring_function(x):
return x**2
def generate_rastrigin(random, args):
size = args.get('num_inputs', 10)
return [... |
fuzeman/trakt.py | trakt/interfaces/movies/__init__.py | from __future__ import absolute_import, division, print_function
from trakt.core.helpers import dictfilter
from trakt.core.pagination import PaginationIterator
from trakt.interfaces.base import Interface
from trakt.mapper.summary import SummaryMapper
import requests
class MoviesInterface(Interface):
path = 'mov... |
lmazuel/azure-sdk-for-python | azure-mgmt-eventhub/azure/mgmt/eventhub/models/operation_display.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
sheeprine/khal | khal/khalendar/__init__.py | # vim: set ts=4 sw=4 expandtab sts=4 fileencoding=utf-8:
# Copyright (c) 2013-2015 Christian Geier et al.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# wi... |
ebressert/ScipyNumpy_book_examples | python_examples/numpy_243_ex1.py | import numpy as np
def temp_and_rain(lat ,min_temp=10, max_temp=10, points=1000):
# Extremely over simplified temperature dependence
# latitude.
lat = np.abs(lat)
temp = np.random.normal(scale=5, size=lat.shape) + lat / 2
temp = np.abs(temp)
# Randomizer, we'll never know if the rain is
#... |
sserrot/champion_relationships | venv/Lib/site-packages/PIL/McIdasImagePlugin.py | #
# The Python Imaging Library.
# $Id$
#
# Basic McIdas support for PIL
#
# History:
# 1997-05-05 fl Created (8-bit images only)
# 2009-03-08 fl Added 16/32-bit support.
#
# Thanks to Richard Jones and Craig Swank for specs and samples.
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# Se... |
Southpaw-TACTIC/TACTIC | src/tactic/protocol/api_test.py | #
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
import tacticenv
from pyasm.common import Cont... |
ylatuya/Flumotion | flumotion/manager/worker.py | # -*- Mode: Python; test-case-name: flumotion.test.test_manager_worker -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General ... |
bobmyhill/burnman | burnman/optimize/nonlinear_solvers.py | import numpy as np
from scipy.linalg import lu_factor, lu_solve
from collections import namedtuple
def solve_constraint_lagrangian(x, jac_x, c_x, c_prime):
"""
Function which solves the problem
minimize || J.dot(x_mod - x) ||
subject to C(x_mod) = 0
via the method of Lagrange multipliers.
Par... |
bbusemeyer/busempyer | drivers/run_bands.py | import cryfiles_io as cio
import sys
import subprocess as sub
# I'm not sure how general these are, but they're for FeSe.
cryinp = open(sys.argv[1],'r')
natoms = [4,4]
kpath = [
[0,0,0],
[1,0,0],
[1,1,0],
[1,1,1],
[1,0,1],
[0,0,1]
]
denom = 2
projs = []
with open("band.inp",'w') as bandf:
b... |
Dave667/service | plugin.video.sovok.tv/resources/lib/addon.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2011 XBMC-Russia, HD-lab Team, E-mail: dev@hd-lab.ru
# Writer (c) 2011, Kostynoy S.A., E-mail: seppius2@gmail.com
import sys, xbmc, xbmcgui, xbmcplugin, xbmcaddon, re
import os, urllib, urllib2
__addon__ = xbmcaddon.Addon( id = 'plugin.video.sovok.tv' )
__lang... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.