repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
duynguyen/incubator-openwhisk
tests/dat/actions/malformed.py
Python
apache-2.0
124
0
"""Invalid Python comment test.""" // invalid p
ython comment # noqa -- tell linters to ignore the intentional s
yntax error
ncoevoet/ChanReg
test.py
Python
mit
1,737
0.000576
### # Copyright (c) 2013, Nicolas Coevoet # 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 conditio...
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### from supybot
.test import * class ChanRegTestCase(PluginTestCase): plugins = ('ChanReg',) # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
ging/horizon
openstack_dashboard/dashboards/idm/home/views.py
Python
apache-2.0
3,184
0.000942
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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 la...
return super(IndexView, self).dispatch(request, *args, **kwargs) def has_more_data(self, table): return False def get_organizations_data(self): organizations = [] # try: # organizations = fiware_api.keystone.project_list( # self.request,
# user=self.request.user.id) # switchable_organizations = [org.id for org # in self.request.organizations] # organizations = sorted(organizations, key=lambda x: x.name.lower()) # for org in organizations: # if org.id in...
alexadusei/ProjectEuler
q008.py
Python
mit
1,143
0.006999
#------------------------------------------------------------------------------- # Name: Largest Product in a Series # Purpose: The four adjacent digits in the 1000-digit number (provided in # textfile 'q008.txt') that have the greatest product are # 9 x 9 x 8 x 9 = 5832. Find the...
---- # H
elper function to read large number from textfile def readNums(): file = open("q008.txt") nums = [] for line in file: line = line.strip() for i in range (len(line)): nums += [int(line[i])] return nums numbers = readNums() currentSum = 0 DIGITS = 13 for i in range(len(number...
TornikeNatsvlishvili/skivri.ge
backend/backend/extensions.py
Python
mit
94
0.010638
from flask_pymongo import PyMongo from flask_cors import CORS
mongo = PyMongo() cors = CORS
()
crunchmail/munch-core
src/munch/core/celery.py
Python
agpl-3.0
4,888
0
import os import sys import logging from functools import wraps import celery from celery.signals import celeryd_after_setup from kombu import Queue from django.conf import settings from munch.core.utils import get_worker_types log = logging.getLogger('munch') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'munch....
ask: {'worker': worker_type, 'key': munch_app}}) log.debug( 'Registered route for {} on {} workers'.format( task, worker_type.upper())) def import_tasks_map(self, tasks_map, munch_app): for worker, tasks in tasks_map.items(): for task in tasks: ...
lf, task): if task in self.routes: worker = self.routes.get(task)['worker'] key = self.routes.get(task)['key'] queue = self.queues.get(worker) return { 'queue': queue['name'], 'exchange': self.exchange, 'exchange_typ...
dwang159/iris-api
src/iris/role_lookup/mailing_list.py
Python
bsd-2-clause
2,203
0.002724
# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. # See LICENSE in the project root for license information. from iris import db from iris.role_lookup import IrisRoleLookupException import logging logger = logging.getLogger(__name__) class mailing_list(object): d...
logger.warn('Invalid mailing list %s', list_name) cursor.close() connection.close() return None list_id, list_count = list_info if self.max_list_names > 0 and list_count >= self.max_list_names: logger.warn('Not returning any results for list group %s...
es) cursor.close() connection.close() raise IrisRoleLookupException('List %s contains too many members to safely expand (%s >= %s)' % (list_name, list_count, self.max_list_names)) cursor.execute('''SELECT `target`.`name` FROM `mailing_list_membershi...
teampopong/crawlers
twitter/setup.py
Python
agpl-3.0
1,997
0.002504
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from __future__ import unicode_literals import requests from requests_oauthlib import OAuth1 from urlparse import parse_qs REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token" AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token=" ACCESS_TOKE...
ests.post(url=ACCESS_TOKEN_URL, auth=oauth) credentials = parse_qs(r.content) token = credentials.get('oauth_token')[0] secret = credentials.get('oauth_token_secret')[0] return token, secret def get_oauth1(keys): if not keys['oauth_token']: keys['oauth_token'], keys['oauth_token_secret']\...
nt '\nInput the keys below to twitter/settings.py' import pprint; pprint.pprint(keys) import sys; sys.exit() oauth = OAuth1(keys['consumer_key'], client_secret=keys['consumer_secret'], resource_owner_key=keys['oauth_token'], resource_owner_secret=keys...
keegancsmith/MCP
setup.py
Python
bsd-2-clause
772
0
#!/usr/bin/env python from setuptools import setup setup( name='MCP', version='0.2', author='Keegan Carruthers-Smith', author_email='keegan.csmith@gmail.com', url='https://github.com/keegancsmith/MCP', license='BSD', py_modules=['mcp'], description='A program to orchestrate Entellect C...
allenge bot matches.', long_description=file('READM
E.rst').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Uti...
uwosh/Campus_Directory_web_service
getCurrentOrNextSemesterCX.py
Python
gpl-2.0
1,292
0.006192
# returns the current PeopleSoft semester code, as of today # if today is between semesters, returns the next semester code import cx_Oracle def getCurrentOrNextSemesterCX (self): file = open('/opt/Plone-2.5.5/zeocluster/client1/Extensions/Oracle_Database_Connection_NGUYEN_PRD.txt', 'r') for line in file.read...
code cursor.execute("""select t1.strm, t1.descr from ps_term_tbl t1 where t1.institution = 'UWOSH' and t1.acad_career = 'UGRD' and t1.term_begin_dt = (select min(term_begin_dt) from ps_term_tbl t2 where t2.institution = t1.i
nstitution and t2.acad_career = t1.acad_career and term_begin_dt > sysdate)""") for column_1 in cursor: try: return column_1[0] except: pass
yaoshengzhe/vitess
test/backup.py
Python
bsd-3-clause
5,848
0.007011
#!/usr/bin/env python import warnings # Dropping a table inexplicably produces a warning despite # the "IF EXISTS" clause. Squelch these warnings. warnings.simplefilter('ignore') import logging import unittest import environment import tablet import utils use_mysqlctld = True tablet_master = tablet.Tablet(use_mysq...
itShardMaster', 'test_keyspace/0', tablet_master.tablet_alias]) # insert data on master, wait for slave to get it tablet_master.mquery('vt_test_keyspace', self._create_vt_insert_test) self._insert_master(1) timeout = 10 while True: try: result = tablet_replica1.mq...
# ignore exceptions, we'll just timeout (the tablet creation # can take some time to replicate, and we get a 'table vt_insert_test # does not exist exception in some rare cases) logging.exception('exception waiting for data to replicate') timeout = utils.wait_step('slave tablet getting da...
kawamon/hue
desktop/core/ext-py/Django-1.11.29/tests/gis_tests/geos_tests/test_geos.py
Python
apache-2.0
54,041
0.001129
from __future__ import unicode_literals import ctypes import json import random from binascii import a2b_hex, b2a_hex from io import BytesIO from unittest import skipUnless from django.contrib.gis import gdal from django.contrib.gis.geos import ( HAS_GEOS, GeometryCollection, GEOSException, GEOSGeometry, LinearRi...
pect self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.a
ssertAlmostEqual(p.y, pnt.tuple[1], 9) # Testing the third dimension, and getting the tuple arguments if hasattr(p, 'z'): self.assertIs(pnt.hasz, True)
sasha-gitg/python-aiplatform
google/cloud/aiplatform_v1/types/dataset_service.py
Python
apache-2.0
14,664
0.00075
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
y:value equality - \`labels.key:\* or labels:key - key existence - A key including a space must be quoted. ``labels."a key"``. Some examples: - ``displayName="myDisplayName"`` - ``labels.myKey="myValue"`` page_size (int): ...
e size. page_token (str): The standard list page token. read_mask (google.protobuf.field_mask_pb2.FieldMask): Mask specifying which fields to read. order_by (str): A comma-separated list of fields to order by, sorted in ascending order. Use "desc" ...
rven/odoo
addons/website_event/models/__init__.py
Python
agpl-3.0
296
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copy
right and licensing details. from . import event_event from . import event_registration from . import event_type from . import website from . import website_event_menu
from . import website_menu from . import website_visitor
bhell/jimi
jimi/jimi/catalog/urls.py
Python
bsd-3-clause
178
0.005618
from django.conf.urls.defaults import
patterns urlpatterns = patterns("jimi.catalog.views", (r"^/?$", "all_categories"), (r"^(?P<slug>[-\w]+)/$", "node", {}, "node")
, )
factorlibre/l10n-spain
l10n_es_facturae/models/__init__.py
Python
agpl-3.0
405
0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from . import payment_mode from . import res_company from . import res_partner from . impo
rt account_tax_template from . import account_tax from . import res_currency from . import account_invoice_integration from . import account_invoice_integration_method from . import account_invoice_integration_log from . impo
rt account_invoice
windskyer/mvpn
mvpn/openstack/common/excutils.py
Python
gpl-2.0
655
0.001527
class save_and_reraise_exception(object): def __init__(self): self.reraise = True def __enter__(self): self.type_, self.value, self.tb, = sys.exc_info() return self def __exit__(self, exc_
type, exc_val, exc_tb): if exc_type is not None: logging.error(_('Original exception being dropped: %s'), traceback.format_exception(self.type_, self.value, self.tb)) ...
return False if self.reraise: six.reraise(self.type_, self.value, self.tb)
fernandolobato/balarco
clients/migrations/0003_auto_20170221_0107.py
Python
mit
804
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-02-21 01:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('clients', '0002_contact'), ] operations = [ migrations.AlterField( ...
l_name='contact', name='alternate_email', field=models.EmailField(blank=True, max_length=255), ), migrations.AlterField( model_name='contact', name='alternate_phone', field=models.CharField(blank=True, max_length=50)
, ), migrations.AlterField( model_name='contact', name='phone', field=models.CharField(blank=True, max_length=50), ), ]
TheStackBox/xuansdk
SDKLibrary/com/cloudMedia/theKuroBox/sdk/paramTypes/kbxHSBColor.py
Python
gpl-3.0
2,217
0.00406
############################################################################################## # Copyright 2014-2015 Cloud Media Sdn. Bhd. # # This file is part of Xuan Application Development SDK. # # Xuan Application Development SDK is free software: you can redistribute it and/or modify # it under the terms of...
ILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Xuan Application Development SDK. If not, see <http://www.gnu.org/licenses/>. ######################################################...
Type import KBXParamType from com.cloudMedia.theKuroBox.sdk.paramTypes.kbxParamWrapper import KBXParamWrapper from com.cloudMedia.theKuroBox.sdk.util.logger import Logger class KBXHSBColorType(KBXObjectType): TYPE_NAME = "kbxHSBColor" PROP_KBX_PARAM_OBJ_KEY_HUE = "h" PROP_KBX_PARAM_OBJ_KEY_SATUR...
calancha/DIRAC
ResourceStatusSystem/Agent/CacheFeederAgent.py
Python
gpl-3.0
6,141
0.033708
# $HeadURL: $ ''' CacheFeederAgent This agent feeds the Cache tables with the outputs of the cache commands. ''' from DIRAC import S_OK#, S_ERROR, gConfig from DIRAC.AccountingSystem.Client.ReportsClient import ReportsClient from DIRAC.Core.Base....
f.clients[ 'WMSAdministrator' ] = RPCClient( 'WorkloadManagement/WMSAdministrator' ) self.cCaller = CommandCaller return S_OK() def loadCommand( self, commandModule, commandDict ): commandName = commandDict.keys()[ 0 ] commandArgs = commandDict[ commandName ] commandTuple = ( '%s...
nd' % commandModule, '%sCommand' % commandName ) commandObject = self.cCaller.commandInvocation( commandTuple, pArgs = commandArgs, clients = self.clients ) if not commandObject[ 'OK' ]: self.log.error( 'Error initializing %s' % commandName ) ...
dataplumber/edge
src/main/python/libraries/edge/opensearch/templateresponse.py
Python
apache-2.0
1,202
0.00416
import logging from xml.dom.minidom import * from jinja2 import Environment, Template from edge.dateutility import DateUtility from edge.opensearch.response import Response class TemplateResponse(Response): def __init__(self): super(TemplateResponse, self).__init__() self.env = Environment() ...
debug("Problem generating template " + str(e)) xmlStr = self.template.render({}).encode('utf-8').replace('\n', '') document =
xml.dom.minidom.parseString(xmlStr) return document.toprettyxml() else: return self.template.render(self.variables).replace('\n', '')
jeremiah-c-leary/vhdl-style-guide
vsg/tests/generate/test_rule_015.py
Python
gpl-3.0
1,158
0.004318
import os import unittest from vsg.rules import generate from vsg import vhdlFile from vsg.tests import utils sTestDir = os.path.dirname(__file__) lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_015_test_input.vhd')) lExpected = [] lExpected.append('') utils.read_file(os.path.join(sTestDir,...
self.assertEqual(oRule.ide
ntifier, '015') lExpected = [20, 25, 30] oRule.analyze(self.oFile) self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations)) def test_fix_rule_015(self): oRule = generate.rule_015() oRule.fix(self.oFile) lActual = self.oFi...
danggrianto/big-list-of-naughty-strings
setup.py
Python
mit
458
0.002183
from setuptools import find_packages, setup setup( name='blns', versio
n='0.1.7', url='https://github.com/danggrianto/big-list-of-naughty-strings', license='MIT', author='Daniel Anggrianto', author_email='daniel@anggrianto.com', description='Big List of Naug
hty String. Forked from https://github.com/minimaxir/big-list-of-naughty-strings', keywords='Big List of Naughty String', packages=['blns'], platforms='any', )
magicmilo/MiSynth-Wavetable-Generator
main.py
Python
apache-2.0
9,015
0.003439
#coding: utf-8 #!/usr/bin/env python3 #Initial test code for MiSynth Wave Generator #Opens Wave Files And Cuts And Plays Them As The FPGA will #Synth plays back 2048 samples at frequency of note #Effective sample rate is 901,120Hz @ 440Hz #CURRENTLY A DRAWING LOOP TO BE SOLVED, THANKS WX/PYTHON FOR YOUR #COMPLETE LACK...
NU, self.OnQuitButton, id=wx.ID_EXI
T) menuBar.Append(menu, "&Actions") self.SetMenuBar(menuBar) self.wavepanel = WavePanel(self, self.getscale, self.setsector) self.wavepanel.SetBackgroundColour(wx.Colour(32,55,91)) self.scopepanel = ScopePanel(self) self.scopepanel.SetBackgroundColour(wx.Colour(20,25,20)...
lvh/txyoga
setup.py
Python
isc
528
0.017045
import setuptools setuptools.setup(name=
'txyoga', version='0', description='REST toolkit for Twisted', url='https://github.com/lvh/txyoga', author='Laurens Van Houtven', author_email='_@lvh.cc', packages = setuptools.find_packages(), requires=['twisted'], license='ISC', classifiers=[ "Developm...
"Topic :: Internet :: WWW/HTTP", ])
0shimax/DL-vision
src/net/cifar10.py
Python
mit
1,111
0
import chainer import chainer.functions as F import chainer.links as L class Cifar10(chainer.Chain): def __init__(self, n_class, in_ch): super().__init__( conv1=L.Convolution2D(in_ch, 32, 5, pad=2), conv2=L.Convolution2D(32, 32, 5, pad=2), conv3=L.Convolution2D(32, 64,...
, t): x.volatile = True h = F.max_pooling_2d(F.elu(self.conv1(x)), 3, stride=2) h = F.max_pooling_2d(F.elu(self.conv2(h)), 3, stride=2)
h = F.elu(self.conv3(h)) h.volatile = False h = F.spatial_pyramid_pooling_2d(h, 3, F.MaxPooling2D) h = F.dropout(F.elu(self.fc4(h)), ratio=0.5, train=self.train) h = self.fc5(h) self.prob = F.softmax(h) self.loss = F.softmax_cross_entropy(h, t) self.acc...
tiangolo/fastapi
docs_src/extending_openapi/tutorial003.py
Python
mit
205
0
from fastapi
import FastAPI app = FastAPI(swagger_ui_parameters={"syntaxHighlight": False}) @app.get("/users/{username}") async def read_user(username: str): retu
rn {"message": f"Hello {username}"}
nens/githubinfo
githubinfo/commits.py
Python
gpl-3.0
11,594
0.000086
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from collections import defaultdict # from pprint import pprint import argparse # Note: python 2.7+ import datetime import json import logging import os import sys impor...
ogger.debug("Loading project {}...".format
(self.name)) self.branch_SHAs = self.load_branches() self.commits = self.load_project_commits() self.load_individual_commits() def load_branches(self): """Return SHAs of commits for branches.""" url = BRANCHES_URL.format(owner=self.owner, project=self.name) branches ...
kdart/pycopia3
process/setup.py
Python
apache-2.0
1,057
0
#!
/usr/bin/python3.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab import sys from glob import glob from setuptools import setup NAME = "pycopia3-process" VERSION = "1.0" if sys.platform not in ("win32", "cli"): DATA_FILES = [ ('/etc/pycopia', glob("etc/*")), ] else: DATA_FILES = [] setup(nam...
cessTests", # install_requires=['pycopia-core>=1.0.dev-r138,==dev'], data_files=DATA_FILES, description="Modules for running, interacting with, and managing processes.", # noqa long_description=open("README.md").read(), license="LGPL", author="Keith Dart", keywords="pycopia frame...
boto/s3transfer
tests/unit/test_subscribers.py
Python
apache-2.0
3,197
0
# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the 'license' file accompa...
# constructor args. with self.assertRaises(TypeError): OverrideConstructorSubscriber() def test_not_callable_in_subclass_subscriber_method(self): with self.assertRaisesRegex( InvalidSubscriberMethodError, 'must be c
allable' ): NotCallableSubscriber() def test_no_kwargs_in_subclass_subscriber_method(self): with self.assertRaisesRegex( InvalidSubscriberMethodError, 'must accept keyword' ): NoKwargsSubscriber()
yuanagain/seniorthesis
src/intervals/newton.py
Python
mit
4,396
0.036624
from interval import interval, inf, imath, fpu from complexinterval import ComplexInterval, _one, _zero from complexpolynomial import ComplexPolynomial class Newton: def __init__(self, start, poly): self.start = start self.poly = poly self.iterates = 0 self.deriv = poly.derive() self.step = start def ite...
omial([a_5, a_6, a_3, a_1, a_0]) print(poly_3) print("============================") print("Testing Evaluation") print("----------------------------") print(poly_1(w)) print(poly_1(_one())) print(poly_1(_zero())) print("") print(poly_2(w)) print(poly_2(_one())) print(poly_2(_zero())) print("") print(...
"----------------------------") print(poly_1.derive()) print(poly_1.derive().derive()) print(poly_1.derive().derive().derive()) print("") print(poly_2.derive()) print(poly_2.derive().derive()) print("") print(poly_3.derive()) print(poly_3.derive().derive()) print("============================") print("New...
bengosney/rhgd3
gardens/migrations/0026_auto_20180308_0720.py
Python
gpl-3.0
653
0.001531
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-03-08 07:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gardens', '0025_auto_20180216_1951'), ] operations = [ migrations.AlterMode...
options={'ordering': ('position',), 'verbose_name': 'Work Type', 'verbose_name_plural': 'Work Types'}, ), migrations.AddField( model_name='worktype', name='position',
field=models.PositiveIntegerField(default=0), ), ]
mikewrock/phd_backup_full
devel/lib/python2.7/dist-packages/phd/srv/_calc_service.py
Python
apache-2.0
19,928
0.018567
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from phd/calc_serviceRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class calc_serviceRequest(genpy.Message): _md5sum = "504533770c671b8893346f8f23298fee" _t...
(length,) = _struct_I.unpack(str[start:end]) pattern = '<%si'%length start = end end += struct.calcsize(pattern) self.post_ids = struct.unpack(pattern, str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length ...
start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.location = str[start:end].decode('utf-8') else: self.location = str[start:end] return self except struct.error as e: raise genpy.Deserializatio...
ESSolutions/ESSArch_Core
ESSArch_Core/auth/migrations/0016_auto_20181221_1716.py
Python
gpl-3.0
505
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-12-21 1
6:16 from django.db import migrations, models import django.db.models.deletion import mptt.fields import picklefield.fields class Migration(migrations.Migration): dependencies = [ ('essauth', '0015_proxypermission'), ] operations = [ migrations.AddField( model_name='userprofi...
ield(default='en', max_length=10), ), ]
databricks/spark-pr-dashboard
sparkprs/controllers/prs.py
Python
apache-2.0
3,838
0.002866
import google.appengine.ext.ndb as ndb import json import logging import datetime from flask import Blueprint from flask import Response from natsort import natsorted from sparkprs import cache, app from sparkprs.models import Issue, JIRAIssue prs = Blueprint('prs', __name__) @prs.route('/search-open-prs') @cache...
ersions = set() for jira_number in jiras: jira = JIRAIssue.get_by_id("%s-%i" % (app.config['JIRA_PROJECT'], jira_number)) if jira: target_versions.update(jira.target_versions) if jira.is_closed:
d['closed_jiras'].append(jira_number) if target_versions: d['jira_target_versions'] = natsorted(target_versions) json_dicts.append(d) except: logging.error("Exception while processing PR #%i", pr.number) raise respo...
chancegrissom/qmk_firmware
lib/python/qmk/cli/list/__init__.py
Python
gpl-2.0
24
0
fr
om . import keyboards
jnewland/home-assistant
homeassistant/components/ring/binary_sensor.py
Python
apache-2.0
3,663
0
"""This component provides HA sensor support for Ring Door Bell/Chimes.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA, BinarySensorDevice) from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_ENTITY_NAMESPACE,...
lf._data.id attrs['firmware'] = self._data.firmware attrs['timezone'] = self._data.timezone if self._data.alert and self._data.alert_expires_at: attrs['expires_at'] = self._data.alert_expires_at
attrs['state'] = self._data.alert.get('state') return attrs def update(self): """Get the latest data and updates the state.""" self._data.check_alerts() if self._data.alert: if self._sensor_type == self._data.alert.get('kind') and \ self._dat...
elliotf/appenginewiki
wiki.py
Python
lgpl-2.1
9,987
0.003304
#!/usr/bin/env python # # Copyright 2008 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...
uery.DESCENDING)) page_list = [] for entity in query.Get(100): page_list.append(Page(entity['name'], entity)) self.generat
e('index.html', { 'pages': page_list, }) class PageRequestHandler(BaseRequestHandler): def get(self, page_name): # if we don't have a user, we won't know which namespace to use (for now) user = users.get_current_user() if not user: self.redirect(users.create...
pablo-the-programmer/Registration
conference/conference/wsgi.py
Python
mit
1,415
0.000707
""" WSGI config for p1 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_APPLICATION`` setti...
ltiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "p1.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conference.settings") # This application object is used by any WSGI server configur...
file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
MSeifert04/numpy
numpy/core/tests/test_deprecations.py
Python
bsd-3-clause
24,541
0.001222
""" Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. """ from __future__ import division, absolute_import, print_function import datetime import sys import operator import warnings import pytest import shutil import tempfile import n...
This first checks if the function when called gives `num` DeprecationWarnings, after that it tries to raise these DeprecationWarnings and compares them with `exceptions`. The exceptions can be different for cases where this code path is simply not anticipated and the exception i...
The function to test num : int Number of DeprecationWarnings to expect. This should normally be 1. ignore_others : bool Whether warnings of the wrong type should be ignored (note that the message is not checked) function_fails : bool If the f...
Peter-Slump/mahjong
tests/mahjong/models/test_tabel.py
Python
mit
1,613
0
import unittest from mahjong.models import Table, ALL_WINDS, WIND_EAST, WIND_NORTH, WIND_SOUTH import mahjong.services.stone class MahjongTabelModelTestCase(unittest.TestCase): def setUp(self): self.table = Table(stones=mahjong.services.stone.get_all_shuffled()) self.table.wall_wind = WIND_EAST...
elf): """ Case: we iterate throught the stones of the table Expected: we get the s
ame stones as the list we give """ stones = mahjong.services.stone.get_all_shuffled() table = Table(stones=stones) table.wall_wind = WIND_NORTH # Last wind table.wall_index = 35 # Last stone for stone in table: self.assertEqual(stone, stones.pop()) def...
savi-dev/horizon
horizon/dashboards/syspanel/projects/forms.py
Python
apache-2.0
5,991
0.001335
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
t, data['name'], data['description'], data['enabled']) messages.success(request, _('%s was successfully created.') % data['name']) except: e...
jects:index') class UpdateTenant(forms.SelfHandlingForm): id = forms.CharField(label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'})) name = forms.CharField(label=_("Name")) description = forms.CharField( widget=forms.widgets.Textarea(), label=_("Descrip...
epage/telepathy-bluewire
hand_tests/generic.py
Python
lgpl-2.1
17,072
0.034149
#!/usr/bin/env python import sys import gobject import dbus.mainloop.glib dbus.mainloop.glib.DBusGMainLoop(set_as_default = True) import telepathy DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties' def get_registry(): reg = telepathy.client.ManagerRegistry() reg.LoadManagers() return reg def get_connection...
elepathy.server.CONNECTION].Connect( reply_handler = self._on_generic_message, error_handler = self._on_error, ) def _on_done(self): super(Connect, self)._on_done() def _on_change(self, status, reason): if status == telepathy.constants.CONNECTION_STATUS_DISCONNECTED: print "Disconnected!" self._co...
one elif status == telepathy.constants.CONNECTION_STATUS_CONNECTED: print "Connected" self._on_done() elif status == telepathy.constants.CONNECTION_STATUS_CONNECTING: print "Connecting" else: print "Status: %r" % status class SimplePresenceOptions(Action): def __init__(self, connAction): super(S...
ITPS/odoo-saas-tools
saas_portal_demo/controllers/__init__.py
Python
gpl-3.0
924
0
# -*- encoding: utf-8 -*- ############################################################################## # Copyright (c) 2015 - Present All Rights Reserved # Author: Cesar Lage <kaerdsar@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gener...
Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General...
ic License is available at: # <http://www.gnu.org/licenses/gpl.html>. ############################################################################## import main
dankolbman/MarketCents
twitter_feed.py
Python
mit
920
0.018478
# authenticates with twitter, searches for microsoft, evaluates overall # sentiment for microsoft import numpy as np import twitter from textblob import TextBlob f = open('me.auth
') keys = f.readlines() # Read in keys keys = [x.strip('\n') for x in keys] # Connect api = twitter.Api(consumer_key = keys[0], consumer_secret = keys[1], access_token_key = keys[2], access_token_secret = keys[3]) print 'logged in as ', api.VerifyCred...
atus content blobs = [ TextBlob(status.text) for status in search ] sentiments = [ blob.sentiment.polarity for blob in blobs ] filtered_sentiments = filter(lambda a: a!=0.0, sentiments) overall_sentiment = sum(filtered_sentiments)/len(filtered_sentiments) print 'Overall sentiment for microsoft: {0}'.format(overall_...
wtrevino/django-listings
listings/syndication/views.py
Python
mit
619
0.001616
# -*- coding: utf-8 -*- from django.http import HttpResponse, Http404 from django.template import Context from django.contrib.si
tes.models import Site from listings.syndication.models import Feed from listings.models import POSTING_ACTIVE def display_feed(request, feed_url): site = Site.objects.get_current() try: feed = site.feed_set.get(feed_url=feed_url) except Feed.DoesNotExist: raise Http404 template = feed...
ype=feed.content_type)
CorunaDevelopers/teleTweetBot
teleTweetBot/handlers/TelegramMessageHandler.py
Python
gpl-3.0
632
0
#!/usr/bin
/env python # _*_ coding:utf-8 _* from commands import StartCommand from commands
import StopCommand from commands import TwitterCommand from handlers.ExceptionHandler import ExceptionHandler COMMANDS = { '/start': StartCommand.process_message, '/stop': StopCommand.process_message, '/tweet': TwitterCommand.process_message } def process_message(twitter_api, telegram_message): try...
boxed/CMi
web_frontend/gdata/apps/organization/client.py
Python
mit
20,094
0.003583
#!/usr/bin/python2.4 # # Copyright 2011 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 ...
customer_id) if org_unit_path_or_user_email: uri += '/' + org_unit_path_or_user_email if params: uri += '?' + urllib.urlencode(params) return uri MakeOrganizationUnitProvisioningUri = make_organization_unit_provisioning_uri def make_organization_unit_orgunit_provisioning_uri(self, cus...
org_unit_path=None, params=None): """Creates a resource feed URI for the orgunit's Provisioning API calls. Using this client's Google Apps domain, create a feed URI for organization unit orgunit's provisioning in that domai...
fierval/retina
DiabeticRetinopathy/Refactoring/kobra/imaging.py
Python
mit
6,612
0.013313
from matplotlib import pyplot as plt from matplotlib import cm from os import path import numpy as np import cv2 import pandas as pd from math import exp, pi, sqrt import mahotas as mh from numbapro import vectorize def show_images(images,titles=None, scale=1.3): """Display a list of images""" n_ims = len(im...
fig = plt.figure() n = 1 for image,title in zip(images,titles): a = fig.add_subplot(1,n_ims,n) # Make subplot if image.ndim == 2: # Is image grayscale? plt.imshow(image, cmap = c
m.Greys_r) else: plt.imshow(cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) a.set_title(title) plt.axis("off") n += 1 fig.set_size_inches(np.array(fig.get_size_inches(), dtype=np.float) * n_ims / scale) plt.show() plt.close() # Pyramid Down & blurr # Easy-peesy def p...
mrkulk/text-world
evennia/commands/default/general.py
Python
bsd-3-clause
13,667
0.001537
""" General Character commands usually availabe to all characters """ from django.conf import settings from evennia.utils import utils, prettytable from evennia.commands.default.muxcommand import MuxCommand # limit symbol import for API __all__ = ("CmdHome", "CmdLook", "CmdNick", "CmdInventory", "CmdGet", ...
ject for everyone to use, you need build privileges and to us
e the @alias command. """ key = "nick" aliases = ["nickname", "nicks", "@nick", "alias"] locks = "cmd:all()" def func(self): "Create the nickname" caller = self.caller switches = self.switches nicks = caller.nicks.get(return_obj=True) if 'list' in switches:...
kyokley/BattlePyEngine
src/battlePy/ship.py
Python
mit
1,526
0
from battlePy.utils import docprop (UP, DOWN, LEFT, RIGHT) = SHIP_ORIENTATIONS = range(4) VECTOR_DICT = {UP: (0, 1), DOWN: (0, -1), LEFT: (-1, 0), RIGHT: (1, 0)} class Ship(object): name = docprop('name', 'Name of the ship') size = docprop('size', 'Size of the ship') hits = docprop('hits', 'Set of curren...
self.locations = set() self.game = game self.symbol = self.name[0] def __repr__(self): return "<%s %s %s>" % (self.__class__.__name__, id(self), self.name) def placeShip(self, location, orientation): self.locations = set() newLocation = location self.l...
newLocation = ( newLocation[0] + VECTOR_DICT[orientation][0], newLocation[1] + VECTOR_DICT[orientation][1], ) self.locations.add(newLocation) def isPlacementValid(self): return self.game.isValidShipPlacement(self) def addHit(self, location)...
tycho/yubioath-desktop
yubioath/gui/messages.py
Python
gpl-3.0
5,696
0.000351
# Copyright (c) 2014 Yubico AB # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
ully imported %d tokens.%s" delete_title = "Confirm credential deletion" delete_desc_1 = """<span>Are you sure you want to delete the credential?</span> <br> This action cannot be undone. <br><br> <b>Delete credential: %s</b> """ free = "free" in_use = "in use" require_touch = "Require touch" require_manual_refresh = "...
verwrite it? This action cannot be undone." qr_scan = "Scan a QR code" qr_scanning = "Scanning for QR code..." qr_not_found = "QR code not found" qr_not_found_desc = "No usable QR code detected. Make sure the QR code is " \ "fully visible on your primary screen and try again." qr_invalid_type = "Invalid OTP type" q...
rgurevych/python_for_testers
tests/test_contacts_data_compliance.py
Python
apache-2.0
3,163
0.007272
import re from models.contact import Contact def test_all_contacts_on_homepage(app, db): if app.contact.count() == 0: app.contact.add(Contact(first_name="Mister", last_name="Muster", mobile_phone="123", email_1="test@test.com")) contacts_from_homepage = sorted(app.contact.get_contact_list(), key = Cont...
er", mobile_phone="123", email_1="test@test.com")) index = randrange(len(app.contact.get_contact_list())) contact_from_homepage = app.contact.get_contact_list()[index] contact_from_editpage = app.contact.get_contact_data_editpage(index) assert contact_from_home
page.first_name == contact_from_editpage.first_name assert contact_from_homepage.last_name == contact_from_editpage.last_name assert contact_from_homepage.address == contact_from_editpage.address assert contact_from_homepage.all_phones_homepage == merge_phones_homepage(contact_from_editpage) assert cont...
KSG-IT/ksg-nett
schedules/migrations/0009_auto_20190422_1627.py
Python
gpl-3.0
489
0.002045
# Generated b
y Django 2.2 on 2019-04-22 16:27 from django.db import migrations import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('schedules', '0008_auto_20180208_1946'), ] operations = [ migrations.AlterField( model_name='shiftslotdayrule', na...
(choices=[(0, 'dummy')], default='mo', max_length=2, no_check_for_status=True), ), ]
grow/pygrow
grow/extensions/base_extension_test.py
Python
mit
844
0
"""Tests for base extension.""" import unittest from grow.extensions import base_extension class BaseExtensionTestCase(unittest.TestCase): """Test the base extension.""" def test_config_disabled(self): """Uses the disabled config.""" ext = base_extension.BaseExtension(None, { 'di...
': [ 'a', ], 'enabled': [ 'a', ], }) self.assertFalse(ext.hooks.is_enabled('a')) self.assertFalse(ext.hooks.is_enabled('b')) def test_config_enabled(self): """Uses the enabled config.""" ext = base_extension...
_enabled('b'))
leeclemmer/ggeocode
ggeocode/ggeocode.py
Python
mit
3,893
0.041613
import sys import logging import urllib import urllib2 import json from lxml import etree class GGeocode(): """ Wrapper for Google Geocode API v3. https://developers.google.com/maps/documentation/geocoding/ """ def __init__(self, method='http', output='json', sensor='false', address='', ...
plit(':')[0] not in ['route', 'locality', 'administrative_area',
'postal_code', 'country']: raise ValueError("""Component is %s - must be: route, locality, administrative_area, postal_code or country""" % (component.split(':')[0],)) self.params['components'] = components # optional parameters: # client and signature # bounds # language...
chipx86/reviewboard
reviewboard/reviews/evolutions/change_descriptions.py
Python
mit
432
0
from __future__ import unicode_literals from django.d
b import models from django_evolution.mutations import AddField MUTATIONS = [ AddField('ReviewRequest', 'changedescs', models.ManyToManyField, related_model='changedescs.ChangeDescription'), AddField('ReviewRequestDraft', 'changedesc', models.ForeignKey, initial=None, null=True, ...
d_model='changedescs.ChangeDescription') ]
theo-l/django
django/db/backends/mysql/features.py
Python
bsd-3-clause
6,495
0.002002
import operator from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_pk = True related_fields_match_type = True # MySQL doesn't support sliced subq...
isn't loaded into the mysql.time_zone. with self.connection.cursor() as cursor: cursor.execute("SELECT CONVERT_TZ('2001-01-01 01:00:00', 'UTC', 'UTC')") return cursor.fetchone()[0] is not None @cached_property def is_sql_auto_is_null_enabled(self): with self.connection.c...
n result and result[0] == 1 @cached_property def supports_over_clause(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 2) supports_frame_range_fixed_distance = property(operator.attrgetter('supports_over_clause')) @cach...
CompassionCH/compassion-modules
partner_communication/wizards/pdf_wizard.py
Python
agpl-3.0
2,115
0.001891
############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
munication. """ _name = "partner.communication.pdf.wizard" _description = "Partner Communication - PDF Wizard" communication_id = fields.Many2one( "partner.communication.job", required=True, ondelete="cascade", readonly=False ) preview = fields.Binary(compute="_compute_pdf") state ...
lection(related="communication_id.state") body_html = fields.Html(compute="_compute_html") @api.multi def _compute_pdf(self): if self.state != "physical": return comm = self.communication_id report = comm.report_id.with_context( lang=comm.partner_id.lang, mus...
nvbn/python-social-auth
examples/flask_example/models/__init__.py
Python
bsd-3-clause
79
0
from flask_examp
le.models import user from social.apps.flask_app import model
s
memsharded/conan
conans/test/unittests/client/build/meson_test.py
Python
mit
9,218
0.003688
import os import shutil import unittest from parameterized.parameterized import parameterized import six from conans.client import defs_to_string from conans.client.build.meson import Meson from conans.client.conf import default_settings_yml from conans.client.tools import args_to_string from conans.errors import Con...
ath.join(self.tempdir, "my_cache_source_folder") cmd_expected = 'meson "%s" "%s" --backend=ninja %s --buildtype=release' \ % (source_expected, build_expected, defs_to_string(defs)) self._check_commands(cmd_expected, conan_file.command) args = ['--werror', '--warnlevel 3']...
defs['default_library'] = 'static' meson.configure(source_folder="source", build_folder="build", args=args, defs={'default_library': 'static'}) build_expected = os.path.join(self.tempdir, "my_cache_build_folder", "build") source_expected = os.path.join(self.tempdir, ...
hzlf/openbroadcast
website/cms/plugins/inherit/models.py
Python
gpl-3.0
681
0.005874
from django.db import models from django.utils.translation import ugettext_lazy as _ from c
ms.models import CMSPlugin, Page from django.conf import settings class InheritPagePlaceholder(CMSPlugin): """ Provides the ability to inherit plugins for a certain placeholder from an associated "parent" page instance """ from_page = models.ForeignKey(Page, null=True, blank=True, help_text=_("Choose a...
eholder, empty will choose current page")) from_language = models.CharField(_("language"), max_length=5, choices=settings.CMS_LANGUAGES, blank=True, null=True, help_text=_("Optional: the language of the plugins you want"))
lanbing510/GTDWeb
manage.py
Python
gpl-2.0
249
0
#!/usr/bin/env python import os import sys if __name__ == "__main__":
os.environ.setdefault("DJ
ANGO_SETTINGS_MODULE", "gtdweb.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
bastustrump/genimpro
rp_extract.py
Python
mit
39,383
0.013737
''' RP_extract: Rhythm Patterns Audio Feature Extractor @author: 2014-2015 Alexander Schindler, Thomas Lidy Re-implementation by Alexander Schindler of RP_extract for Matlab Matlab version originally by Thomas Lidy, based on Musik Analysis Toolbox by Elias Pampalk ( see http://ifs.tuwien.ac.at/mir/downloads.html ) ...
g [:]) and add a 0 in front (to make calculations below easier) phons = phon[:] phons.insert(0,0) phons = np.asarray(phons) # Loudness Curves eq_loudness = np.array([[55, 40, 32, 24, 19, 14, 10, 6, 4, 3, 2, 2, 0,-2,
-5,-4, 0, 5, 10, 14, 25, 35], [66, 52, 43, 37, 32, 27, 23, 21, 20, 20, 20, 20,19,16,13,13,18, 22, 25, 30, 40, 50], [76, 64, 57, 51, 47, 43, 41, 41, 40, 40, 40,39.5,38,35,33,33,35, 41, 46, 50, 60, 70], [89, 79, 74, 70, 66, 63, 61, 60, 60, 60...
chrisidefix/devide
resources/python/filename_view_module_mixin_frame.py
Python
bsd-3-clause
2,169
0.005533
#!/usr/bin/env python # -*- coding: ISO-8859-1 -*- # generated by wxGlade 0.3.5.1 on Sat Jun 04 00:11:24 2005 import wx class FilenameViewModuleMixinFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: FilenameViewModuleMixinFrame.__init__ kwds["style"] = wx.CAPTION|wx.MINIMIZE_BOX...
_5.Add(sizer_3, 1, w
x.ALL|wx.EXPAND, 7) self.viewFramePanel.SetAutoLayout(True) self.viewFramePanel.SetSizer(sizer_5) sizer_5.Fit(self.viewFramePanel) sizer_5.SetSizeHints(self.viewFramePanel) sizer_1.Add(self.viewFramePanel, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(si...
Gnomescroll/Gnomescroll
server/waflib/extras/sync_exec.py
Python
gpl-3.0
777
0.023166
#! /usr/bin/env python # encodin
g: utf-8 """ Force the execution output to be synchronized May deadlock with a lot of output (subprocess limitation) """ import sys from waflib.Build import BuildContext from waflib import Utils, Logs def exec_command(self, cmd, **kw): subprocess = Utils.subprocess kw['shell'] = isinstance(cmd, str) Logs.debug('r...
: kw['stdout'] = kw['stderr'] = subprocess.PIPE p = subprocess.Popen(cmd, **kw) (out, err) = p.communicate() if out: sys.stdout.write(out.decode(sys.stdout.encoding or 'iso8859-1')) if err: sys.stdout.write(err.decode(sys.stdout.encoding or 'iso8859-1')) return p.returncode except OSError: return -...
webcomics/dosage
dosagelib/plugins/namirdeiter.py
Python
mit
2,179
0.001377
# SPDX-License-Identifier: MIT # Copyright (C) 2019-2020 Tobias Gruetzmacher # Copyright (C) 2019-2020 Daniel Ring from .common import _ParserScraper class NamirDeiter(_ParserScraper): imageSearch = '//img[contains(@src, "comics/")]' prevSearch = ('//a[@rel="prev"]', '//a[./img[contains(@src...
f).__init__('NamirDeiter/' + name) self.url = 'https://' + baseUrl + '/' self.stripUrl = self.url + 'comics/index.php?date=%s' if first: self.firstStripUrl = self.stripUrl % first else: self.firstStripUrl = self.url + 'comics/' if last: self...
l): # Links are often absolute and keep jumping between http and https return tourl.replace('http:', 'https:').replace('/www.', '/') @classmethod def getmodules(cls): return ( cls('ApartmentForTwo', 'apartmentfor2.com'), cls('NamirDeiter', 'namirdeiter.com', last...
hkkwok/MachOTool
mach_o/headers/prebind_cksum_command.py
Python
apache-2.0
488
0.002049
from utils.header import MagicField, Field fro
m load_command import LoadCommandHeader, LoadCommandCommand class PrebindCksumCommand(LoadCommandHeader): ENDIAN = None FIELDS = ( Magic
Field('cmd', 'I', {LoadCommandCommand.COMMANDS['LC_DYSYMTAB']: 'LC_DYSYMTAB'}), Field('cmdsize', 'I'), Field('cksum', 'I'), ) def __init__(self, bytes_=None, **kwargs): self.cksum = None super(PrebindCksumCommand, self).__init__(bytes_, **kwargs)
tensorflow/tensorflow
tensorflow/python/framework/subscribe.py
Python
apache-2.0
12,914
0.006814
# Copyright 2016 The TensorFlow 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 applica...
or.op.name + '/subscription/' with ops.name_scope(name_scope): outs = [] for s in side_effects: outs += s(tensor) with ops.control_dependencies(outs): out = array_ops.identity(tensor) for consumer_op, index in update_input: consumer_op._update_inp
ut(index, out) # pylint: disable=protected-access for consumer_op in update_control_input: # If an op has more than one output and two or more of its output tensors # are subscribed at the same time, we remove the control dependency from # the original op only once and we add the dependencies to all the...
MariusLauge/dnd_tracker
dnd_tracker/settings.py
Python
gpl-3.0
3,300
0.001818
""" Django settings for dnd_tracker project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ impor...
}, ] WSGI_APPLICATION = 'dnd_tracker.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
# Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthVali...
renskiy/fabricio
examples/hello_world/fabfile.py
Python
mit
901
0.00111
""" https://github.com/renskiy/fabricio/blob/master/examples/hello_world """ from fabricio import tasks, docker from fabricio.misc import AvailableVagrantHosts app = tasks.DockerTasks( service=docker.Container( name='app', image='nginx:stable-alpine', options={ # `docker run` o...
ck` command in the list # migrate_commands=True, # show `migrate` and `migrate-back` commands in the list # backup_commands=True, # show `backup` and `restore` commands in the list # pull_command=True, # show `pull` command in the list # update_command=True, #
show `update` command in the list # revert_command=True, # show `revert` command in the list # destroy_command=True, # show `destroy` command in the list )
sdague/home-assistant
homeassistant/components/simulated/sensor.py
Python
apache-2.0
4,535
0.000441
"""Adds a simulated sensor.""" from datetime import datetime import math from random import Random import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity impor...
d sensor.""" def __init__( self, name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ): """Init the class.""" self._name = name self._unit = unit self._amp = amp self._mean = mean self._period = period self._phase = phase # phase ...
elf._seed = seed self._random = Random(seed) # A local seeded Random self._start_time = ( datetime(1970, 1, 1, tzinfo=dt_util.UTC) if relative_to_epoch else dt_util.utcnow() ) self._relative_to_epoch = relative_to_epoch self._state = None ...
zamattiac/SHARE
providers/org/biorxiv/migrations/0001_initial.py
Python
apache-2.0
658
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-08 15:45 from __future__ import unicode_litera
ls from django.db import migrations import share.robot class Migration(migrations.Migration): dependencies = [ ('share', '0001_initial'), ('djcelery', '0001_initial'), ] operations = [ migrations.RunPython( code=share.robot.RobotUserMigration('org.biorxiv'), ...
eduleMigration('org.biorxiv'), ), ]
morpheby/ist303-miye
client/__init__.py
Python
gpl-3.0
755
0.005298
""" __init__.py ist303-miye Copyright (C) 2017 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 Fre
e Software Foundation; either version 2 of the License, or (at your option) any later version. This p
rogram is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if...
informatics-isi-edu/synspy
hook-vispy.py
Python
bsd-3-clause
111
0
from PyInstaller.utils.hooks import collect_submodules, collect_data_fil
es datas = collect_data_files('vispy
')
rasikapohankar/zeroclickinfo-fathead
lib/fathead/react_native/parse.py
Python
apache-2.0
15,135
0.004361
# -*- coding: utf-8 -*- import os import csv from bs4 import BeautifulSoup INFO = {'download_path': 'download/docs', 'doc_base_url': 'https://facebook.github.io/react-native/releases/0.40/docs{}', 'out_file': 'output.txt'} HOME_LINK= 'http://facebook.github.io/react-native/docs/getting-started.ht...
""" data = [] if self.intro_text and self.title: d
ata_elements = { 'module': self.title, 'function': '', 'method_signature': '', 'first_paragraph': self.intro_text, 'url': self.create_url('') } data.append(data_elements) titleName='propTitle' for pr...
W0mpRat/WebDev03
UdacityFrameWork.py
Python
unlicense
781
0.002561
__author__ = 'canderson' import os import webapp2 import jinja2 from google.appengine.ext imp
ort db template_dir = os.path.join(os.path.dirname(__file__), 'templates') env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True) class Handler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_s...
env.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) class MainPage(Handler): def get(self): #self.write("asciichan!") self.render('form.html') app = webapp2.WSGIApplication([('/', MainPage)], debug=...
persandstrom/home-assistant
tests/components/switch/test_template.py
Python
apache-2.0
16,305
0
"""The tests for the Template switch platform.""" from homeassistant.core import callback from homeassistant import setup import homeassistant.components as core from homeassistant.const import STATE_ON, STATE_OFF from tests.common import ( get_test_home_assistant, assert_setup_component) class TestTemplateSwit...
.state == STATE_ON state = self.hass.states.set('switch.test_state', STATE_OFF) self.hass.block_till_done() state = self.hass.states.get('switch.test_template_switch') assert state.state == STATE_OFF def test_template_state_boolean_on(self): """Test the setting of the stat...
component(1, 'switch'): assert setup.setup_component(self.hass, 'switch', { 'switch': { 'platform': 'template', 'switches': { 'test_template_switch': { 'value_template': ...
fabteam1/komsukomsuhuhu
komsukomsuhuu/komsukomsuhuu/celery.py
Python
mit
655
0.003053
from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' pro
gram. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'komsukomsuhuu.settings') from django.conf import settings app = Celery('komsukomsuhuu', broker='amqp://', backend='amqp://', ) # Using a string here means the worker will not have to # pi
ckle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
Bodidze/21v-python
unit_01/15.py
Python
mit
114
0.026316
#!/usr/bin
/python # the sum of two elements defines the next a, b = 0, 1 whi
le b < 10: print b a, b = b, a + b
Arcanemagus/SickRage
sickbeard/providers/newpct.py
Python
gpl-3.0
10,924
0.00403
# coding=utf-8 # Author: CristianBB # Greetings to Mr. Pine-apple # URL: https://sick-rage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either versi...
orrent_row = row.find('a')
download_url = torrent_row.get('href', '') title = self._processTitle(torrent_row.get('title', ''), download_url) if not all([title, download_url]): continue # Provider does not provide seeder...
Aravinthu/odoo
addons/board/models/board.py
Python
agpl-3.0
1,665
0.002402
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file
for full copyright and licensing details. from odoo import api, models from odoo.tools import pycompat class Board(models.AbstractModel): _name = 'board.board' _description = "Board" _auto = False @api.model def create(self, vals): return self @api.model def fields_view_get(sel...
rides orm field_view_get. @return: Dictionary of Fields, arch and toolbar. """ res = super(Board, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) custom_view = self.env['ir.ui.view.custom'].search([('user_id', '=', self.env.uid), ('ref_id',...
rmhyman/DataScience
Lesson1/titanic_data_heuristic1.py
Python
mit
2,937
0.007831
import numpy import pandas import statsmodels.api as sm ''' In this exercise, we will perform some rudimentary practices similar to those of an actual data scientist. Part of a data scientist's job is to use her or his intuition and insight to write algorithms and heuristics. A data...
ikipedia.org/wiki/RMS_Titanic http://www.kaggle.com/c/titanic-gettingStarted In this exercise and the following ones, you are given a list of Titantic passengers and their associated information. More information about the data can
be seen at the link below: http://www.kaggle.com/c/titanic-gettingStarted/data. For this exercise, you need to write a simple heuristic that will use the passengers' gender to predict if that person survived the Titanic disaster. You prediction should be 78% accurate or higher. ...
goal/uwsgi
plugins/logcrypto/uwsgiplugin.py
Python
gpl-2.0
80
0
NAME = 'lo
gcrypto' CFLAGS = []
LDFLAGS = [] LIBS = [] GCC_LIST = ['logcrypto']
pantaray/Analytic-Tools
sde_solvers.py
Python
gpl-3.0
29,346
0.015743
# sde_solvers.py - Collection of numerical methods to solve (vector-valued) SDEs # # Author: Stefan Fuertinger [stefan.fuertinger@esi-frankfurt.de] # Created: February 19 2014 # Last modified: <2017-09-15 11:31:25> from __future__ import division import numpy as np from scipy.stats import norm def rk_1(func,x0,tstep...
-)autonomous scalar noise Parameters ---------- func : callable (X,t,**kwargs) Returns drift `A` and diffusion `B` of the SDE. See Examples for details. x0 : NumPy 1darray Initial condition tsteps : NumPy 1darray Sequence of time points for which to solve (including initi...
) **kwargs : keyword arguments Additional keyword arguments to be passed on to `func`. See `Examples` for details. Returns ------- Y : NumPy 2darray Approximate solution at timepoints given by `tsteps`. Format is `Y[:,tk]` approximate solution at time `tk` Thu...
ryfeus/lambda-packs
pytorch/source/caffe2/python/operator_test/ngram_ops_test.py
Python
mit
2,472
0.000405
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import hypothesis.strategies as st from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy a...
pected_output.append(val) expected_output = np.array(expected_output, dtype=np.int32) workspace.ResetWorkspace() workspace.FeedBlob('floats', floats) op = core.CreateOperator( "NGramFromCategorical", ['floats'], ['output'], col_ids=col_ids...
its, vals=vals, ) workspace.RunOperatorOnce(op) output = workspace.blobs['output'] np.testing.assert_array_equal(output, expected_output)
kapt/django-oscar
runtests.py
Python
bsd-3-clause
3,114
0.000321
#!/usr/bin/env python """ Custom test runner If args or options, we run the testsuite as quickly as possible. If args but no options, we default to using the spec plugin and aborting on first error/failure. If options, we ignore defaults and pass options onto Nose. Examples: Run all tests (as fast as possible) $ ....
l tests relating to shipping $ ./runtests.py --attr=shipping Re-run failing tests (needs to be run twice to first build the index) $ ./runtests.py ... --failed Drop into pdb when a test fails $ ./runtests.py ... --pdb-failures """ import sys import logging imp
ort warnings from tests.config import configure from django.utils.six.moves import map # No logging logging.disable(logging.CRITICAL) def run_tests(verbosity, *test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner(verbosity=verbosity) if not test_args: test_ar...
chrisnorman7/gmp3
application.py
Python
mpl-2.0
686
0
"""Application specific storage.""" import wx from sound_lib.output import Output from gmusicapi import Mobileclient name = 'GMP3' __version__ = '
4.3.0' db_version = 1 url = 'https://github.com/chrisnorman7/gmp3' app = wx.App(False) app.SetAppName(name) paths = wx.StandardPaths.Get() output = Output() api = Mobileclient() api.android_id = '123456789abcde' frame = None # The main window. track = None # The current track. stream = None # Th...
es. # Prevent the killer bug that makes the timer try and pop up billions of login # windows: logging_in = False
mferenca/HMS-ecommerce
ecommerce/extensions/offer/tests/test_utils.py
Python
agpl-3.0
2,446
0.004088
from decimal import Decimal import ddt from babel.numbers import format_currency from django.conf import settings from django.utils.translation import get_language, to_locale from oscar.core.loading import get_model from oscar.test.factories import * # pylint:disable=wildcard-import,unused-wildcard-import from ecom...
at('verified', False, 100, self.partner) self.stock_record = StockRecord.objects.filter(product=self.verified_seat).first() self.seat_price = self.stock_record.price_excl_tax self._range = RangeFactory(products=[self.verified_seat, ]) self.percentage_benefit = BenefitFactory(type=Benefi...
Benefit.FIXED, range=self._range, value=self.seat_price - 10) def test_format_benefit_value(self): """ format_benefit_value(benefit) should format benefit value based on benefit type """ benefit_value = format_benefit_value(self.percentage_benefit) self.assertEqual(benefit_value, '35%') ...
indrajitr/ansible
lib/ansible/modules/group.py
Python
gpl-3.0
19,765
0.001164
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Stephen Fromm <sfromm@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: group v...
[key])) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) def group_exists(self): ...
not be used to determine whether or not a group exists locally. # It returns True if the group exists locally or in the directory, so instead # look in the local GROUP file for an existing account. if self.local: if not os.path.exists(self.GROUPFILE): self.module.fail...
nschloe/voropy
tests/test_signed_area.py
Python
mit
1,654
0.002418
import pathlib import meshio import numpy as np import pytest import meshplex this_dir = pathlib.Path(__file__).resolve().parent @pytest.mark.parametrize( "points,cells,ref", [ # line ([[0.0], [0.35]], [[0, 1]], [0.35]), ([[0.0], [0.35]], [[1, 0]], [-0.3
5]), # triangle ([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], [[0, 1, 2]], [0.5]), ([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]], [[0, 1, 2]], [-0.
5]), ( [[0.0, 0.0], [1.0, 0.0], [1.1, 1.0], [0.0, 1.0]], [[0, 1, 2], [0, 3, 2]], [0.5, -0.55], ), # tetra ( [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [[0, 1, 2, 3]], [1 / 6], ), ...
bitsteller/witica
witica/metadata/extractor.py
Python
mit
7,072
0.035209
import json, codecs, re from abc import ABCMeta, abstractmethod from PIL import Image, ExifTags from witica.util import throw, sstr, suni #regular expressions regarding item ids RE_METAFILE = r'^meta\/[^\n]+$' RE_FIRST_ITEMID = r'(?!meta\/)[^\n?@.]+' RE_ITEMFILE_EXTENSION = r'[^\n?@\/]+' RE_ITEMID = r'^' + RE_FIRST_...
fTags.TAGS[k]: v for k, v in img._getexif().items() if k in ExifTags.TAGS } if ("ImageDescription" in exif or "UserComment" in exif): if "UserComment" in exif: meta["title"] = exif["UserComment"] if "ImageDescription" in exif: meta["title"] = exif["ImageDescription"] if ("Make" in ex...
"Model" in exif else "") if ("Orientation" in exif): meta["orientation"] = exif["Orientation"] if ("Artist" in exif): meta["author"] = exif["Artist"] if ("DateTimeOriginal" in exif): meta["created"] = exif["DateTimeOriginal"] #TODO: convert to unix time if ("Flash" in exif): meta["flash"] =...
gfarnadi/FairPSL
debug/compare_map/run_fpsl_cvxpy.py
Python
mit
1,367
0.010241
#!/usr/bin/env python import os, sys SCRIPTDIR = os.path.dirname(__file__) ENGINDIR = os.path.join(SCRIPTDIR, '..', '..', 'engines') sys.path.append(os.path.abspath(ENGINDIR)) from fpsl_cvxpy import map_inference PROBLEMDIR = os.path.join(SCRIPTDIR, '..', '..', 'problems', 'paper_review') sys.path.append(os.path.abs...
results = map_inference(rules, hard_rules) reviews = atoms['review'] with open(ojoin(out_path, 'POSITIVEREVIEW.txt'), 'w') as f: for (review, paper), (vid, _) in reviews.items(): print("'%s'\t'%s'\t%f"%(review, paper, res
ults[vid]), file=f) acceptable = atoms['acceptable'] with open(ojoin(out_path, 'ACCEPTABLE.txt'), 'w') as f: for paper, (vid, _) in acceptable.items(): print("'%s'\t%f"%(paper, results[vid]), file=f) presents = atoms['presents'] with open(ojoin(out_path, 'PRESENTS.txt'), 'w...
jdsolucoes/Ppostit
printy/migrations/0002_auto_20150921_2215.py
Python
apache-2.0
967
0.002068
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('printy', '0001_initial'), ] operations = [ migrations.CreateModel( name='PostItModel', fields=[ ...
toField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('width', models.FloatField()), ('height', models.FloatField()), ], ), migrations.AlterField( model_name='postit', name='print_page', field=m...
rations.AddField( model_name='printpage', name='post_it_model', field=models.ForeignKey(default=1, to='printy.PostItModel'), preserve_default=False, ), ]
siggame/discuss
discuss/discuss/production.py
Python
bsd-3-clause
642
0
from discuss.discuss.settings import * ########################################################################## # # Server settings # ############
############################################################## ALLOWED_HOSTS = ["localhost"] WSGI_APPLICATION = 'discuss.discuss.wsgi_production.application' ########################################################################## # # Database settings # ############################################################...
ds.sqlite3', 'NAME': os.path.join(VAR_DIR, 'db', 'production_db.sqlite3'), } }
paultag/hy
hy/errors.py
Python
mit
4,271
0
# -*- encoding: utf-8 -*- # # Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org> # Copyright (c) 2013 Bob Tolbert <bob@tolbert.org> # # 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 wit...
'*(start-1), colored.green('^' + '-'*length)) if len(source) > 2: # write the middle lines for line in source[1:-1]: result += ' %s\n' % colored.red("".join(line)) result += ' %s\n' % colored.green("-"*len(line)) ...
# write the last line result += ' %s\n' % colored.red("".join(source[-1])) result += ' %s\n' % colored.green('-'*(end-1) + '^') result += colored.yellow("%s: %s\n\n" % (self.__class__.__name__, self.message...
bird-house/birdhousebuilder.recipe.adagucserver
birdhousebuilder/recipe/adagucserver/tests/test_docs.py
Python
bsd-3-clause
1,620
0.003086
# -*- coding: utf-8 -*- """ Doctest runner for 'birdhousebuilder.recipe.adagucserver'. """ __docformat__ = 'restructuredtext' import os import sys import unittest import zc.buildout.tests import zc.buildout.testing from zope.testing import doctest, renormalizing optionflags = (doctest.ELLIPSIS | doc...
# If want to clean up the doctest output you
# can register additional regexp normalizers # here. The format is a two-tuple with the RE # as the first item and the replacement as the # second item, e.g. # (re.compile('my-[rR]eg[eE]ps'), 'my-regexps') ...
googleads/google-ads-python
google/ads/googleads/v10/errors/types/time_zone_error.py
Python
apache-2.0
1,124
0.00089
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
buted under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package="google....
e): r"""Container for enum describing possible time zone errors. """ class TimeZoneError(proto.Enum): r"""Enum describing possible currency code errors.""" UNSPECIFIED = 0 UNKNOWN = 1 INVALID_TIME_ZONE = 5 __all__ = tuple(sorted(__protobuf__.manifest))
seraphlnWu/django-mongoengine
django_mongoengine/admin/__init__.py
Python
bsd-3-clause
451
0.002217
from django_mongoengine.admin.options import * from django_mongoengine.admin.sites import site from django.conf import settings if getattr(settings, 'DJANGO_MONGOENGINE_OVERRIDE_ADMIN', False): import django.contrib.adm
in # copy already registered model admins # without that the already registered models # don't show up in the new admin site._registry = django.co
ntrib.admin.site._registry django.contrib.admin.site = site
slaporte/qualityvis
inputs/google.py
Python
gpl-3.0
1,054
0.004744
from base import Input from wapiti import get_json class GoogleNews(Input): prefix = 'gn' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=' + self.page_title) def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res.get('resp...
f): return get_json('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' + self.page_title) def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res['responseData']: return {} else: return super(GoogleSearch, self).process(f_res['responseDat...
Count']) stats = { 'count': lambda f: f }