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 |
|---|---|---|---|---|---|---|---|---|
Diti24/python-ivi | ivi/tektronix/tektronixOA5012.py | Python | mit | 1,438 | 0.003477 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
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... | , publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS P... | NGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .tektronixOA5000 import *
class tektroni... |
v-knyagnitskiy/EcoMap | ecomap/www/authorize_views.py | Python | gpl-3.0 | 13,028 | 0.00023 | # -*- coding: utf-8 -*-
"""Module contains routes for user authorization,
registering and logout.
"""
import json
import requests
import time
from flask import request, jsonify, Response, render_template
from flask_login import login_user, logout_user, login_required
from urlparse import parse_qsl
import ecomap.u... | ods=['POST', 'GET'])
@auto.doc()
@login_required
def logout():
"""Method for user's log out.
:rtype: JSON
:return:
- if logging out was successful:
``{result:True}``
- in case of problems:
``{result:False}``
"""
return jsonify(result=logout_user())
@app.rou... | register', methods=['POST'])
@auto.doc()
def register():
"""Method for registration new user in db.
Method checks if user is not exists and handle
registration processes.
:rtype: JSON
:request args: `{'first_name': 'Ivan',
'last_name': 'Sirko',
'nickname': '... |
gc3-uzh-ch/elasticluster-web | elasticluster_base/migrations/0012_auto__add_field_cluster_image_user.py | Python | gpl-3.0 | 8,212 | 0.008037 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Cluster.image_user'
db.add_column(u'elasticluster_base_cluster', 'image_user',
... | b.models.fields.related.Foreig | nKey', [], {'to': u"orm['auth.User']"})
}
}
comple |
Ali-aqrabawi/ezclinic | lib/djangae/tests/test_query_transform.py | Python | mit | 20,523 | 0.003265 | # LIBRARIES
from django.db import models, connections, connection as default_connection
from django.db.models.sql.datastructures import EmptyResultSet
from django.db.models.query import Q
from google.appengine.api import datastore
# DJANGAE
from djangae.db.backends.appengine.query import transform_query, Query, WhereN... | , 'SELECT')
self.assertEqual(query.tables, [ TransformTestModel._meta.db_table ])
self.assertTrue(query.where)
self.assertEqual(2, len(query.where.children)) # Two child nodes
self.assertEqual(["field1", "-field2"], query.order_by)
def test_projection(self):
query = transfor... | query = transform_query(
connections['default'],
TransformTestModel.objects.values_list("field1").query
)
self.assertEqual(set(["field1"]), query.columns)
query = transform_query(
connections['default'],
TransformTestModel.objects.defer("field1",... |
legnaleurc/tornado | tornado/test/tcpclient_test.py | Python | apache-2.0 | 16,665 | 0.00024 | #!/usr/bin/env python
#
# Copyright 2014 Facebook
#
# 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 a... | 4()
if Resolver.configured_class().__name__.endswith('TwistedResolver'):
self.skipTest('TwistedResolver does not support multiple addresses')
self.do_test_connect(socket.AF_INET6, 'localhost')
def test_connect_unspec_ipv4(self):
self.do_test_connect(socket.AF_UNSPEC, '127.0.0.1'... | socket.AF_UNSPEC, '::1')
def test_connect_unspec_dual(self):
self.do_test_connect(socket.AF_UNSPEC, 'localhost')
@gen_test
def test_refused_ipv4(self):
cleanup_func, port = refusing_port()
self.addCleanup(cleanup_func)
with self.assertRaises(IOError):
yield self... |
withanage/HEIDIEditor | controllers/plan.py | Python | gpl-3.0 | 1,068 | 0.004682 | # -*- coding: utf-8 -*-
### required - do no delete
@auth.requires_login()
def plan():
return dict()
def new():
form = SQLFORM.factory(db.contacts,db | .groups)
if form.accepts(request.vars):
_id_user = db.contacts.insert(**db.contacts._filter_fields(form.vars))
form.vars.contact = _id_user
id = db.groups.insert(**db.groups._filter_fields(form.vars))
response.flash = 'User registered successfully'
return locals()
def update... | ).select()[0]
form = SQLFORM(db.contacts, group.contact.id)
group = SQLFORM(db.group, group.id)
# Adding the group form
form.append(group)
if form.accepts(request.vars):
# Updating the contacts
db.contacts.update(**db.contacts._filter_fields(form.vars))
# Atualizando o g... |
Clinical-Genomics/scout | scout/adapter/mongo/event.py | Python | bsd-3-clause | 17,111 | 0.000935 | import logging
from datetime import datetime
import pymongo
from bson import ObjectId
from scout.constants import CASE_STATUSES, REV_ACMG_MAP
from .case_events import CaseEventHandler
from .variant_events import VariantEventHandler
COMMENT_LEVELS = ["global", "specific"]
LOG = logging.getLogger(__name__)
class E... | el,
created_at=datetime.now(),
updated_at=datetime.now(),
)
if individuals:
event["individuals"] = individuals
if hpo_term:
event["hpo_term"] = hpo_term
LOG.debug("Saving Event")
self.event_collection.insert_one(event)
LOG.... | ne,
comments=False,
panel=None,
):
"""Fetch events from the database.
Args:
institute (dict): An institute
case (dict): A case
variant_id (str, optional): global variant id
level (str, optional): restrict comments to 'specific' or 'global'
... |
davjohnst/fundamentals | tests/adv_python/iterators/test_iterator_example.py | Python | apache-2.0 | 874 | 0.002288 | #!/usr/bin/env python
from unittest import TestCase
from fundamentals.adv_python.iterators.iterator_example import IteratorExample
class TestIteratorExample(TestCase):
def test_default_iter(self):
ie = IteratorExample([1, 2, 3, 4, 5])
default_it = ie.get_default_iterator()
val = default_... | rtEqual(1, val)
sum = 0
for x in default_it:
sum += x
self.assertEqual(14, sum)
def test_backwards_iter(self):
ie = | IteratorExample([2, 4, 6, 8])
backwards_it = ie.get_backwards_iterator()
self.assertEqual(8, backwards_it.next())
self.assertEqual(6, backwards_it.next())
self.assertEqual(4, backwards_it.next())
self.assertEqual(2, backwards_it.next())
with self.assertRaises(StopIterati... |
idea4bsd/idea4bsd | python/testData/inspections/AddCallSuperTypeAnnotationsPreserved.py | Python | apache-2.0 | 261 | 0.068966 | clas | s A:
def __init__(self, a:int, b:float, *args: | tuple, c:complex, **kwargs:dict) -> None:
pass
class B(A):
def <warning descr="Call to __init__ of super class is missed">__i<caret>nit__</warning>(self, d:str, *, e:bytes) -> list:
pass |
s-monisha/LibreHatti | src/librehatti/voucher/urls.py | Python | gpl-2.0 | 283 | 0.014134 | from django.conf.urls impor | t url, patterns
from django.views.generic import TemplateView
urlpatterns = patterns('librehatti.voucher.views',
url(r'^voucher_generate/','voucher_generate'),
url(r'^voucher_show/','voucher_show'),
url(r'^v | oucher_print/','voucher_print'),
)
|
fr34k8/pythonect | pythonect/internal/parsers/test/test_p2y.py | Python | bsd-3-clause | 3,355 | 0.002683 | # Copyright (c) 2012-2013, Itzik Kotler
# 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 condit... | OF SUBSTITUTE GO | ODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
impo... |
jotes/pontoon | pontoon/actionlog/models.py | Python | bsd-3-clause | 3,117 | 0.001925 | from django.core.exceptions import ValidationError
from django.db import models
class ActionLog(models.Model):
ACTIONS_TYPES = (
# A translation has been created.
("translation:created", "Translation created"),
# A translation has been deleted.
("translation:deleted", "Translation ... | pe != "comment:added"
) and (not self.translation or self.entity or self.locale):
raise ValidationError(
'For action type "{}", only `translation` is accep | ted'.format(
self.action_type
)
)
def save(self, *args, **kwargs):
self.validate_action_type_choice()
self.validate_foreign_keys_per_action()
super(ActionLog, self).save(*args, **kwargs)
|
postfix/topics | yelp/yelp-reviews.py | Python | apache-2.0 | 988 | 0.002024 | import os
import time
import json
from pymongo import MongoClient
from settings import Settings
dataset_file = Settings.DATASET_FILE
reviews_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.REVIEWS_DATABASE][
Settings.REVIEWS_COLLECTION]
count = 0
done = 0
start = time.time()
with open(data... | count = sum(1 for line in dataset)
with open(dataset_file) as dataset:
next(dataset)
for line in dataset:
try:
data = json.loads(line)
except ValueError:
print 'Oops!'
if data["type"] == "review":
reviews_collection.insert({
"review... | e += 1
if done % 100 == 0:
end = time.time()
os.system('cls')
print 'Done ' + str(done) + ' out of ' + str(count) + ' in ' + str((end - start))
|
RaviSoji/probabilistic_LDA | tests/test_optimizer/test_optimizer_inference.py | Python | apache-2.0 | 4,213 | 0.002374 | # Copyright 2017 Ravi Sojitra. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | model/test_model_inference.p | y. """
pass
def test_optimize_maximum_likelihood_Psi():
""" Implemented in tests/test_model/test_model_inference.py. """
pass
def test_optimize_maximum_likelihood_relevant_U_dims():
""" Implemented in tests/test_model/test_model_inference.py. """
pass
def test_optimize_maximum_likelihood_inv_A():... |
openstack/zaqar | zaqar/tests/functional/wsgi/v1_1/test_claims.py | Python | apache-2.0 | 9,025 | 0 | # Copyright (c) 2014 Rackspace, 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 or agreed to in wr... | t JSO | N body will have a TTL value
outside the allowed range.Allowed ttl values is
60 <= ttl <= 43200.
"""
doc = {"ttl": ttl, "grace": 100}
result = self.client.post(data=doc)
self.assertEqual(400, result.status_code)
test_claim_invalid_ttl.tags = ['negative']
@ddt.d... |
camradal/ansible | lib/ansible/plugins/action/ios_config.py | Python | gpl-3.0 | 926 | 0.00216 | #
# Copyright 2015 Peter Sprygada <psprygada@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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... | 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action.net_config import ActionModule as _ActionModule
class ActionModule(_ActionModule):
pass
... |
obi-two/Rebelion | data/scripts/templates/object/tangible/encoded_disk/shared_encoded_disk_base.py | Python | mit | 458 | 0.045852 | #### NOTICE: THIS FILE IS AUTOG | ENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/encoded_disk/shared_encoded_disk_base.iff"
result.attribute_template_id = -1
result.stfName("item... |
#### END MODIFICATIONS ####
return result |
lexifdev/crawlers | bills/meta/html.py | Python | agpl-3.0 | 1,875 | 0.003207 | #! /usr/bin/python2.7
# -*- coding: utf-8 -*-
import os
import re
import sys
import math
import gevent
from gevent import monkey; monkey.patch_all()
import requests
import utils
from settings import BASEURL, DIR, PAGE_SIZE
def convert(assembly_id):
baseurl = '%sAGE_FROM=%d&AGE_TO=%d' % (BASEURL['list'], assembl... | ):
url, directory = convert(assembly_id)
utils.check_dir(directory)
fn = '%s/tmp.html' % directory
utils.get_webpage | (url, fn)
page = utils.read_webpage(fn)
m = re.search(u'총(.+)건', page.xpath('//span[@class="text3"]/text()')[0])
nbills = int(m.group(1))
npages = int(math.ceil(nbills/float(PAGE_SIZE)))
print 'Total %d bills, %d pages to %s' % (nbills, npages, directory)
return npages
def get_html(assembly_id,... |
diogocs1/comps | web/addons/base_report_designer/__openerp__.py | Python | apache-2.0 | 1,794 | 0.003902 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | t/Export .sxw report that you can m | odify in OpenOffice.
Once you have modified it you can upload the report using the same wizard.
""",
'author': 'OpenERP SA',
'website': 'https://www.odoo.com',
'depends': ['base'],
'data': ['wizard/base_report_design_view.xml' , 'base_report_designer_installer.xml'],
'demo': [],
'installable': ... |
PierrotLC/pykalman | pykalman/utils.py | Python | bsd-3-clause | 5,836 | 0.000685 | # New BSD License
#
# Copyright (c) 2007 - 2012 The scikit-learn developers.
# All rights reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# a. Redistributions of source code must retain the above copyrig... | The model is most probabily stuck in a component with too
# few observations, we need to reini | tialize this components
cv_chol = linalg.cholesky(cv + min_covar * np.eye(n_dim),
lower=True)
cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol)))
cv_sol = solve_triangular(cv_chol, (X - mu).T, lower=True).T
log_prob[:, c] = - .5 * (np.sum(cv_so... |
jaimejimbo/kmp-downloader | kmpd.py | Python | gpl-3.0 | 8,901 | 0.037636 | #!/usr/bin/python
# Downloads kernel from http://kernel.ubuntu.com/~kernel-ppa/mainline/
# Requires: python-bs4
# Copyright (c) 2012 Savvas Radevic <vicedar@gmail.com>
#
# 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 ... | n tuple("yYnN"):
continue
else:
if sel1 in tuple("yY"):
selkh = True
else:
selkh = False
break
sel2 = -1
while True:
sel2 = raw_input("Would you like to download kernel image [Y/n]: ")
if sel2 == "":
selki = True
break
if not sel2 in tuple("yYnN"):
continue
else:
... | in tuple("yY"):
selki = True
else:
selki = False
break
sel3 = -1
while True:
sel3 = raw_input("Would you like to download kernel extras [Y/n]: ")
if sel3 == "":
selke = True
break
if not sel3 in tuple("yYnN"):
continue
else:
if sel3 in tuple("yY"):
selke = True
el... |
jpopelka/fabric8-analytics-worker | alembic/versions/750621a9cd89_drop_server_tables.py | Python | gpl-3.0 | 4,138 | 0.005075 | """Removed tables: roles_users, permissions_roles, user, role, and permission.
Revision ID: 750621a9cd89
Revises: 6e7ff4c3177e
Create Date: 2017-03-21 21:26:29.795993
"""
# revision identifiers, used by Alembic.
revision = '750621a9cd89'
down_revision = '6e7ff4c3177e'
branch_labels = None
depends_on = None
from ale... | les_users')
op.drop_table('permissions_roles')
op.drop_table('user')
op.drop_table('role')
op.drop_table('permission')
# ### end Alembic commands ###
def downgrade():
"""Downgrade the database to an older revision."""
# ### commands auto generated by Alembic - please adjust! ###
op.cre... | sa.INTEGER(),
server_default=sa.text("nextval('role_id_seq'::regclass)"),
nullable=False),
sa.Column('name', sa.VARCHAR(length=80), autoincrement=False, nullable=True),
sa.Column('description', sa.VARCHAR(length=255), au... |
colobas/gerador-horarios | bs4/dammit.py | Python | mit | 24,978 | 0.055122 | # -*- coding: utf-8 -*-
"""Beautiful Soup bonus library: Unicode, Dammit
This class forces XML data into a standard format (usually to UTF-8 or
Unicode). It is heavily based on code from Mark Pilgrim's Universal
Feed Parser. It does not rewrite the XML or HTML to reflect a new
encoding; that's the tree builder's job.... | de characte | rs with named HTML entities.
This differs from data.encode(encoding, 'xmlcharrefreplace')
in that the goal is to make the result more readable (to those
with ASCII displays) rather than to recover from
errors. There's absolutely nothing wrong with a UTF-8 string
containg a LATIN SMALL LETTER E WITH ACUTE, bu... |
trendels/rhino | test/examples/test_build_url.py | Python | mit | 339 | 0.00295 | from rhino.test import TestClient
from examples.build_url import app
client = TestCl | ient(app.wsgi)
def test_index():
res = client.get('/')
assert res.code == 302
assert res.headers['Location'] == 'http://localhost/u:1/p:1'
def test_url():
res = client.get | ('/u:1/p:1')
assert 'http://localhost/u:1/p:1' in res.body
|
wujuguang/scrapyd | setup.py | Python | bsd-3-clause | 1,705 | 0 | import sys
try:
from setuptools import setup
using_setuptools = True
except ImportError:
from distutils.core import setup
using_setuptools = False
from os.path import join, dirname
with open(join(dirname(__file__), 'scrapyd/VERSION')) as f:
version = f.read().strip()
setup_args = {
'name': '... | g Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 | .4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: No Input... |
ucoin-io/cutecoin | src/sakia/gui/navigation/network/controller.py | Python | mit | 2,750 | 0.001455 | from .model import NetworkModel
from .view import NetworkView
from PyQt5.QtWidgets import QAction, QMenu
from PyQt5.QtGui import QCursor, QDesktopServices
from PyQt5.QtCore import pyqtSlot, QUrl, QObject
from duniterpy.api import bma
from duniterpy.documents import BMAEndpoint
class NetworkController(QObject):
""... | tworkView: the view
:param sakia.gui.network.model.NetworkModel model: the model
"""
super().__init__(parent)
self.view = view
self.model = model
table_model = self.model.init_network_table_model()
self.view.set_network_table_model(table_model)
self.view.m... | manually)
self.view.table_network.customContextMenuRequested.connect(self.node_context_menu)
@classmethod
def create(cls, parent, app, network_service):
"""
:param PyQt5.QObject parent:
:param sakia.app.Application app:
:param sakia.services.NetworkService network_servi... |
chubbymaggie/amoco | amoco/ui/render.py | Python | gpl-2.0 | 9,193 | 0.016969 | # -*- coding: utf-8 -*-
from cStringIO import StringIO
from amoco.logger import Log
logger = Log(__name__)
import re
try:
from pygments.token import Token
from pygments.style import Style
from pygments.lexer import RegexLexer
from pygments.formatters import *
except ImportError:
logger.info("pyg... | c in cols:
r.append(''.join([t[1] for t in c]))
return r
def show(self,raw=False,**params):
formatter = params.get('formatter',None)
outfile = params.get('outfile',None)
align = params.get('align',self.align)
fill = params.get('fill',self.fill)
| sep = params.get('sep',self.separator)
width = params.get('maxwidth',self.maxwidth)
colsz = params.get('colsize')
hidden_c = params.get('hidden_c',set())
squash_c = params.get('squash_c',True)
head = params.get('head','')
tail = params.get('t... |
medspx/QGIS | python/plugins/processing/algs/grass7/ext/r_mask.py | Python | gpl-2.0 | 1,535 | 0 | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_mask.py
---------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
****************************************... | processCommand(alg, parameters, context):
# Remove input
alg.removeParameter('input')
alg.processCommand(parameters, context, True)
def processOutputs(alg, parameters, context):
# We need to add the initial input raster lay | er to output
fileName = alg.parameterAsOutputLayer(parameters, 'output', context)
grassName = '{}{}'.format('input', alg.uniqueSuffix)
alg.exportRasterLayer(grassName, fileNam)
|
cherry-wb/SideTools | examples/mainwindows/application/application_rc.py | Python | apache-2.0 | 37,127 | 0.015757 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Tue Aug 3 15:36:52 2010
# by: The Resource Compiler for PySide (Qt v4.6.2)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = "\
\x00\x00\x03\x54\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x... | x90\xd2\x53\x6a\
\x02\x88\x46\xa3\xdc\x3c\x14\x0a\xa1\xb8\xb4\x02\xd7\x06\x05\xdc\
\x66\x87\xe4\xa0\x01\x1c\x64\xc4\x04\x28\x3b\x64\x06\x48\x3d\x9c\
\x73\x12\x99\xd3\xb9\x40\x20\xc5\x65\x55\xb8\xd8\x2d\xa0\x7f\x3a\
\x63\xae\x7d\x90\x69\xe0\xa3\x76\x99\x00\xfe\x5d\x3d\xa5\x26\xad\
\xae\xae\x72\x88\xb7\x4a\x2a\x70\x... | df\
\x74\x09\x50\x4f\x00\xbf\xcc\x65\x1a\xb8\x32\x06\x34\xec\xa7\x01\
\xc9\x58\xda\xeb\x64\x4e\x69\x29\x39\x1d\x44\x04\x40\xf5\xd3\xcf\
\xde\x7c\x5b\x81\x96\xeb\x02\x4f\x7e\x75\x1c\xb8\x71\x0f\xf8\x71\
\x2c\x9e\x7e\xbd\x4e\x6d\xa6\x37\xaa\xac\x00\x9e\x64\x2c\x6d\x37\
\x32\x25\x00\xd1\x23\xf2\xe4\x12\xcc\x1b\x27\x1... |
wrouesnel/docker | hack/infrastructure/docker-ci/report/deployment.py | Python | apache-2.0 | 4,268 | 0.00492 | #!/usr/bin/env python
'''Deploy docker-ci report container on Digital Ocean.
Usage:
export CONFIG_JSON='
{ "DROPLET_NAME": "Digital_Ocean_dropplet_name",
"DO_CLIENT_ID": "Digital_Ocean_client_id",
"DO_API_KEY": "Digital_Ocean_api_key",
"DOCKER_KEY_ID": ... | EMAIL_RCP}"}}'.format(**env))
run('mkdir -p /data/report')
put('./', '/data/report')
with cd('/data/report'):
run('chmod 700 report.py')
run('echo "{}" > credentials.json'.format(CONFIG_JSON))
| run('docker build -t report .')
run('rm credentials.json')
run("echo -e '30 09 * * * /usr/bin/docker run report\n' |"
" /usr/bin/crontab -")
|
lcdb/lcdblib | tests/test_pandas_utils.py | Python | mit | 1,376 | 0.005087 | import pytest
import pandas as pd
from lcdblib.pandas import utils
@pytest.fixture(scope='session')
def sample_table():
metadata = {
'sample': ['one', 'two'],
'tissue': ['ovary', 'testis']
}
return pd.DataFrame(metadata)
def test_cartesian_df(sample_table):
df2 = pd.DataFrame({'num... | utils.cartesian_product(sample_table, sf2)
# Compare a slice
sf = result.iloc[0, :].sort_index()
sf.name = ''
test_sf = pd.Series({'sample': 'one', 'tissue': 'ovary', 'num': 100}, name='').sort_index()
assert sf.equals(test_sf)
assert result.shape == (4, 3)
def test_cartesian_dict(sample_table... | df2)
# Compare a slice
sf = result.iloc[0, :].sort_index()
sf.name = ''
test_sf = pd.Series({'sample': 'one', 'tissue': 'ovary', 'num': 100}, name='').sort_index()
assert sf.equals(test_sf)
assert result.shape == (4, 3)
|
HearthSim/pyreplib | tests/test_replay.py | Python | mit | 7,090 | 0.003244 | import unittest
import datetime
import struct
from pyreplib import replay
# Need to put in the useless bytes, so we replace 'x' (pad byte) with 'B'.
PLAYER_PACK_FORMAT = replay.PLAYER_STRUCT_FORMAT.replace('x', 'B')
HEADER_PACK_FORMAT = replay.HEADER_STRUCT_FORMAT.replace('x', 'B')
class TestHelperFunctions(unittest... | K_FORMAT, 2, 0, 2, 1, 0, 'Terran')
p4 = struct.pack(PLAYER_PACK_FORMAT, 3, 1, 2, 2, 0, 'Protoss')
player = self.rep._decode_player(p1)
self.assertEquals(player.name, '')
self.assertEquals(player.race, 0)
self.assertEquals(player.race_name, 'Zerg')
self.assertEquals(pla... | player.human, False)
player = self.rep._decode_player(p2)
self.assertEquals(player.name, 'Zerg')
self.assertEquals(player.race, 0)
self.assertEquals(player.race_name, 'Zerg')
self.assertEquals(player.type, 1)
self.assertEquals(player.slot, -1)
self.assertEquals(p... |
matt-gardner/deep_qa | deep_qa/data/instances/sequence_tagging/verb_semantics_instance.py | Python | apache-2.0 | 9,078 | 0.003415 | from typing import Dict, List, Tuple
import numpy
from overrides import overrides
from ..instance import TextInstance, IndexedInstance
from ...data_indexer import DataIndexer
class VerbSemanticsInstance(TextInstance):
"""
A VerbSemanticsInstance is a :class:`TextInstance` that is a single sentence of text,... | def __init__(self,
sentence: List[int],
verb: List[int],
entity: List[int],
label: Tuple[List[int], List[List[int]]],
index: int=None):
super(IndexedVerbSemanticsInstance, self).__init__(label, index)
self.sentence = s... | self.verb = verb
self.entity = entity
self.label = label
@classmethod
@overrides
def empty_instance(cls):
return IndexedVerbSemanticsInstance([], [], [], label=([], [[]]), index=None)
@overrides
def get_padding_lengths(self) -> Dict[str, int]:
"""
This si... |
kashifpk/droneos | droneos_ui/setup.py | Python | gpl-2.0 | 1,304 | 0 | import os
import sys
from setuptools import set | up, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'PyCK',
'pyramid',
'SQLAlchemy',
'transaction',
'pyramid_tm',
'pyramid_debugtoolbar',
'pyramid_ha... | roneos_ui',
version='0.0',
description='droneos_ui',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: PyCK",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author... |
LordDamionDevil/Lony | lib/discord/ext/commands/errors.py | Python | gpl-3.0 | 4,513 | 0.004653 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2016 Rapptz
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 us... | r: float
The amoun | t of seconds to wait before you can retry again.
"""
def __init__(self, cooldown, retry_after):
self.cooldown = cooldown
self.retry_after = retry_after
super().__init__('You are on cooldown. Try again in {:.2f}s'.format(retry_after))
|
leppa/home-assistant | homeassistant/components/lupusec/switch.py | Python | apache-2.0 | 1,109 | 0 | """Support for Lupusec Security System switches."""
from datetime import timedelta
import logging
import lupupy.constants as CONST
from homeassistant.components.switch import SwitchDevice
from . import DOMAIN as LUPUSEC_DOMAIN, LupusecDevice
SCAN_INTERVAL = timedelta(seconds=2)
_LOGGER = logging.getLogger(__name__... | s, config, add_entities, discovery_info=None):
"""Set up Lupusec switch devices."""
if discovery_info is None:
return
data = hass.data[LUPUSEC_DOMAIN]
devices = []
for device in data.lupusec.get_devices(generic_type=CONST.TYPE_SWITCH):
devices.append(LupusecSwitch(data, device))
... | ce, SwitchDevice):
"""Representation of a Lupusec switch."""
def turn_on(self, **kwargs):
"""Turn on the device."""
self._device.switch_on()
def turn_off(self, **kwargs):
"""Turn off the device."""
self._device.switch_off()
@property
def is_on(self):
"""Ret... |
dejay313/dojostreams | script.module.urlresolver/lib/urlresolver/plugins/facebook.py | Python | gpl-2.0 | 2,383 | 0.007973 | '''
facebook urlresolver plugin
Copyright (C) 2013 icharania
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 is d... | a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
import urllib
from urlresolver import common
from urlresolver.resolver import UrlResolver, ResolverError
class FacebookResolver(UrlResolver):
name = "facebook"
domains = ["facebook.com"]... | def __init__(self):
self.net = common.Net()
def get_media_url(self, host, media_id):
web_url = self.get_url(host, media_id)
link = self.net.http_GET(web_url).content
if link.find('Video Unavailable') >= 0:
err_message = 'The requested video was not found.'
... |
tragiclifestories/django | tests/migrations/test_migrations_backwards_deps_1/0002_second.py | Python | bsd-3-clause | 211 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django | .db import migrations
class Migration(migrations.Mig | ration):
dependencies = [('migrations', '0001_initial')]
operations = []
|
gtaylor/django-eve-db | eve_db/migrations/0017_auto__del_field_maplandmark_importance__del_field_maplandmark_radius.py | Python | bsd-3-clause | 72,063 | 0.007702 | # -*- 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):
# Deleting field 'MapLandmark.importance'
db.delete_column(u'eve_db_mapla... | db.models.fields.TextField', [], {'blank': 'True'}),
'short_female_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'short_male_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'starter_ship_type': ('django.db.models.fields.relate... | line_starter_ship_set'", 'null': 'True', 'to': "orm['eve_db.InvType']"}),
'starting_charisma': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'starting_intelligence': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'starting_memory': ('django.db.model... |
tkaitchuck/nupic | external/linux64/lib/python2.6/site-packages/matplotlib/backends/backend_qt.py | Python | gpl-3.0 | 16,846 | 0.019649 | from __future__ import division
import math
import os
import sys
import matplotlib
from matplotlib import verbose
from matplotlib.cbook import is_string_like, onetrue
from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \
FigureManagerBase, FigureCanvasBase, NavigationToolbar2, cursors
from mat... | """
for manager in Gcf.get_all_fig_managers():
manager.window.show()
if DEBUG: print 'Inside show'
figManager = Gcf.get_active()
if figMana | ger != None:
figManager.canvas.draw()
if _create_qApp.qAppCreatedHere:
qt.qApp.exec_loop()
def new_figure_manager( num, *args, **kwargs ):
"""
Create a new figure manager instance
"""
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass( *args, **kwargs )
... |
modoboa/modoboa | modoboa/core/api/v1/tests.py | Python | isc | 699 | 0 | from django.urls import reverse_lazy
from modoboa.lib.tests import ModoTestCase
class OpenAPITestCase(ModoTestCase):
openapi_schema_url = reverse_lazy('schema-v1-legacy')
def test_unauthorized(self):
self.client.logout()
response = self.client.get(self.openapi_schema_url)
self.asser... | )
response = self.client.get(self.openapi_schema_url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['info'], {
'title': "Modoboa API",
'version': "v1",
})
| |
mastizada/kuma | vendor/packages/ipython/IPython/frontend/process/winprocess.py | Python | mpl-2.0 | 9,831 | 0.003255 | # A module to expose various thread/process/job related structures and
# methods from kernel32
#
# The MIT License
#
# Copyright (c) 2006 the Mozilla Foundation <http://www.mozilla.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentati... | o = WINFUNCTYPE(BOOL, # Return type
HANDLE, # hJob
HANDLE # hPro | cess
)
AssignProcessToJobObjectFlags = ((1, "hJob"),
(1, "hProcess"))
AssignProcessToJobObject = AssignProcessToJobObjectProto(
("AssignProcessToJobObject", windll.kernel32),
AssignProcessToJobObjectFlags)
AssignProcessToJobObje... |
ktan2020/legacy-automation | win/Lib/site-packages/selenium/webdriver/remote/errorhandler.py | Python | mit | 6,980 | 0.001003 | # Cop | yright 2010 WebDriver committe | rs
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
whummer/moto | moto/backends.py | Python | apache-2.0 | 4,058 | 0 | from __future__ import unicode_literals
from moto.acm import acm_backends
from moto.apigateway import apigateway_backends
from moto.autoscaling import autoscaling_backends
from moto.awslambda import lambda_backends
from moto.cloudformation import cloudformation_backends
from moto.cloudwatch import cloudwatch_backends
... | idp import cognitoidp_backends
from moto.core import moto_api_backends
from moto.datapipeline import datapipeline_backends
from moto.dynamodb import dynamodb_backends
from moto.dynamodb2 import dynamodb_backends2
from moto.dynamodbstreams import dynamodbstrea | ms_backends
from moto.ec2 import ec2_backends
from moto.ecr import ecr_backends
from moto.ecs import ecs_backends
from moto.elb import elb_backends
from moto.elbv2 import elbv2_backends
from moto.emr import emr_backends
from moto.events import events_backends
from moto.glacier import glacier_backends
from moto.glue imp... |
philanthropy-u/edx-platform | common/djangoapps/philu_commands/management/commands/notify_non_active_users.py | Python | agpl-3.0 | 3,635 | 0.004127 | """
A command to notify non active users
"""
from datetime import datetime, timedelta
from logging import getLogger
from django.core.management.base import BaseCommand
from pytz import utc
from common.lib.mandrill_client.client import MandrillClient
from courseware.models import StudentModule
from lms.djangoapps.bran... | (utc).date()
log.info('Today date %s', today)
course_start_date = get_course_open_date(course).date()
log.info('Course start date %s', course_start_date)
delta_date = today - course_start_date
log.info('Days passed since course started %s', delta_date.days)
... | D_EMAIL:
log.info('Getting all enrollments for %s course', course.display_name)
all_enrollments = CourseEnrollment.objects.filter(course_id=course.id)
active_users = []
enrolled_users = []
for enrollment in all_enrollments:
... |
jasonyaw/SFrame | oss_src/unity/python/sframe/connect/server.py | Python | bsd-3-clause | 11,681 | 0.004109 | """
This module contains the interface for graphlab server, and the
implementation of a local graphlab server.
"""
'''
Copyright (C) 2015 Dato, Inc.
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
'''
from ..cython.cy_ipc import... | either encryption keys must be set.
assert(bool(public_key) == bool(secret_key))
if not self.server_addr:
# by default we use '/tmp/graphlab_server-$pid'
# where the pid is the server process id
self.server_addr = 'default'
if not self.server_bin:
| if not default_local_conf.server_bin:
raise RuntimeError("Unable to start local server. Please set the GRAPHLAB_UNITY environment variable.")
else:
self.server_bin = default_local_conf.server_bin
if not self.unity_log:
self.unity_log = default_loca... |
pprett/statsmodels | statsmodels/graphics/tests/test_tsaplots.py | Python | bsd-3-clause | 516 | 0.003876 | import numpy as np
from numpy.testing import dec
im | port statsmodels.api as sm
from statsmodels.graphics.gofplots import qqplot
try:
import matplotlib.pyplot as plt
have_matplotlib = True
except:
have_matplotl | ib = False
@dec.skipif(not have_matplotlib)
def test_qqplot():
#just test that it runs
data = sm.datasets.longley.load()
data.exog = sm.add_constant(data.exog)
mod_fit = sm.OLS(data.endog, data.exog).fit()
res = mod_fit.resid
fig = sm.qqplot(res)
plt.close(fig)
|
ishay2b/tensorflow | tensorflow/python/kernel_tests/cwise_ops_test.py | Python | apache-2.0 | 79,720 | 0.007514 | # Copyright 2015 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... | ps.rsqrt)
self._compareBoth(x, np.exp, math_o | ps.exp)
self._compareBoth(x, np.expm1, math_ops.expm1)
self._compareBoth(z, np.log, math_ops.log)
self._compareBoth(z, np.log1p, math_ops.log1p)
self._compareBoth(x, np.sinh, math_ops.sinh)
self._compareBoth(x, np.cosh, math_ops.cosh)
self._compareBoth(x, np.tanh, math_ops.tanh)
self._compar... |
Ebag333/Pyfa | eos/effects/elitebonuscommanddestroyermwdsigradius3.py | Python | gpl-3.0 | 312 | 0.00641 | # Not used by any item
type = "passive"
def handler(fit, src, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("High Speed Maneuvering"), " | signatureRadiusBonus",
src.getModifiedItemAttr("eliteBonusCommand | Destroyer3"), skill="Command Destroyers")
|
Jvlythical/KoDrive | tests/test_syncthing_factory.py | Python | mit | 14,384 | 0.019049 | import pytest
import json
import os
from kodrive import syncthing_factory as factory
from kodrive.utils import config_rollbacker as rb
from mock import adapters as mock
Cache = {}
# Generate roll back objects
c_app_rb = rb.AppRollbacker(mock.client)
s_app_rb = rb.AppRollbacker(mock.server)
c_st_rb = rb.SyncthingRoll... | test_add():
''' Ensure that kodrive add meets specs '''
mock.client.wait_start(0.5, 10)
client_sync_dir = mock.client_conf['sync_dir']
mock.client.add(
path=client_sync_dir,
tag='my-sync'
)
mock.client.wait_start(0.5, 10)
folder = mock.client.find_folder({
'path': client_sync_dir
})
... | into config['folders']" % client_sync_dir
assert False
# Also test if folder was added into json file
assert True
def test_key():
''' Ensure that kodrive key meets specs '''
mock.client.wait_start(0.5, 10)
output = mock.client.encode_key(mock.client_conf['sync_dir'], False, False)
assert len(outpu... |
indictranstech/focal-erpnext | stock/doctype/batch/test_batch.py | Python | agpl-3.0 | 421 | 0.019002 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contri | butors
# License: GNU General Public License v3. See license.txt
import frappe
from frappe.exceptions import ValidationError
import unittest
class TestBatch(unittest.TestCase):
def test_item_has_batch_en | abled(self):
self.assertRaises(ValidationError, frappe.get_doc({
"doctype": "Batch",
"name": "_test Batch",
"item": "_Test Item"
}).save) |
eayunstack/neutron | neutron/tests/unit/api/rpc/agentnotifiers/test_dhcp_rpc_agent_api.py | Python | apache-2.0 | 12,113 | 0.000083 | # Copyright (c) 2013 Red Hat, 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 or agreed to in writ... | eat_timestamp = timeutils.utcnow()
agent2 = agent_model.Agent()
agent2.admin_state_up = False
agent2.heartbeat_timestamp = timeutils.utcnow()
network = {'id': 'foo_network_id'}
self._test__get_enabled_agents(network, agents=[agent1])
def test__get_enabled_agents_with_inacti | ve_ones(self):
agent1 = agent_model.Agent()
agent1.admin_state_up = True
agent1.heartbeat_timestamp = timeutils.utcnow()
agent2 = agent_model.Agent()
agent2.admin_state_up = True
# This is effectively an inactive agent
agent2.heartbeat_timestamp = datetime.datetim... |
hsuaz/ferrox | ferrox/lib/bbcode_for_fa.py | Python | mit | 2,694 | 0.007053 | from ferrox.lib.bbcode import *
import ferrox.lib.helpers as h
import ferrox.model
#from base import h
#from ferrox import model
class User(TagBase):
no_close = True
def __init__(self):
self.last_error = None
pass
def start(self, name, params):
if not params:
self.last... | ser.tag_handlers['u'] = Underline()
parser.tag_handlers['s'] = Strike()
parser.tag_handlers['quote'] = Quote()
parser.tag_handlers['url'] = URL(h.html_escape)
parser.tag_handlers['code'] = Code()
parser.tag_handlers['user'] = User()
parser. | tag_handlers['icon'] = parser.tag_handlers['user']
parser_long = BBcodeParser(sanitizer=h.html_escape) # for use with [cut] tags
parser_long.tag_handlers.update(parser.tag_handlers)
parser_long.tag_handlers['cut'] = Cut()
parser_short = BBcodeParser(sanitizer=h.html_escape) # for use with [cut] tags
parser_short.tag_... |
brunyuriy/adasim | resources/scripts/merge-csv.py | Python | mit | 529 | 0.049149 | #!/usr/bin/pyth | on
#
# Script:
# Purpose:
# Author: Jochen Wuttke, wuttkej@gmail.com
# Date:
import sys, os
def merge(out, file):
f = open(file)
f.readline() #skip header
for line in f.readlines():
out.write(line)
def main():
files = os.listdir( "." )
output = open("data.log", "w")
output.write("Nodes, Cars, Car, Hops, Time... | in()
|
hangtwenty/yobot | yobot/slack_logic.py | Python | bsd-3-clause | 12,877 | 0.004428 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Business logic - gets request in from Slack, does stuff, sends requests back to Slack.
Notes for developers who want to add or change functionality: You're in the right module.
* If you were to run this behind a server (Flask would work well) instead of behind AWS ... | me = user_to_introduce.get(FIELDNAME_USER_NAME, No | ne)
introduce_readable_name = _get_readable_name(user_to_introduce)
if not introduce_readable_name:
raise ValueError("Somehow the user I chose has NO real_name, username, or email. "
"This should never happen but it did.")
msg = generate_random_introduction_text(
in... |
morgan-county/site | morgan/apps/cms/migrations/0001_initial.py | Python | mit | 2,452 | 0.004486 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0004_make_focal_point_key_not_nullable'),
('wagtailcore', '0008_populate_latest_revision_created_at'),
]
op... | rtrait', models.ForeignKey(verbose_name='Portrait', to='wagtailimages.Image', null=True)),
],
options={
'abstract': False,
},
| bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='OfficePage',
fields=[
('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('body', models.TextF... |
EthereumWebhooks/blockhooks | lib/ethereum/abi.py | Python | apache-2.0 | 27,296 | 0.000733 | # -*- coding: utf8 -*-
from __future__ import print_function
import ast
import re
import warnings
import yaml # use yaml instead of json to get non unicode (works with ascii only data)
from rlp.utils import decode_hex, encode_hex
from ethereum import utils
from ethereum.utils import (
big_endian_to_int, ceil32,... | return 'uint256'
if name == 'fixed':
return 'fixed128x128'
if name == 'ufixed':
return 'ufixed128x128'
if name.startswith('int['):
return 'int256' + name[3:]
if name.startswith('uint['): |
return 'uint256' + name[4:]
if name.startswith('fixed['):
return 'fixed128x128' + name[5:]
if name.startswith('ufixed['):
return 'ufixed128x128' + name[6:]
return name
def normalize_name(name):
""" Return normalized event/function name. """
if '(' in name:
retur... |
sander76/home-assistant | homeassistant/components/hyperion/__init__.py | Python | apache-2.0 | 11,527 | 0.001909 | """The Hype | rion component."""
from __future__ import annotations
import asyncio
from contextlib import suppress
import logging
from typing import | Any, Callable, cast
from awesomeversion import AwesomeVersion
from hyperion import client, const as hyperion_const
from homeassistant.components.camera.const import DOMAIN as CAMERA_DOMAIN
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DO... |
marnnie/Cable-buenaventura | plugin.video.genesis/modules/resolvers/played.py | Python | gpl-2.0 | 1,169 | 0.002566 | # -*- coding: utf-8 -*-
'''
Genesis Add-on
Copyright (C) 2015 lambda
This program is free software: you can r | edistribute 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 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without e | ven 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 not, see <http://www.gnu.org/licenses/>.
'''
import re
from modules.lib... |
ebursztein/SiteFab | plugins/site/rendering/js_post/js_posts.py | Python | gpl-3.0 | 2,312 | 0.007353 | import os
import json
from SiteFab.SiteFab import SiteFab
from SiteFab import files
from SiteFab.Plugins import SiteRendering
class JSPosts(SiteRendering):
#@profile
def process(self, unused, site, config):
plugin_name = "js_posts"
js_filename = "js_posts.js"
# configuration
... | ript:%s not found or too small." % js_file)
js_posts = {}
for post in site.posts:
js_post = {}
js_post['id'] = post.id
for field in meta_fields_to_output:
if field in post.meta:
js_post[field] = post.meta[field]
... | utput and 'responsive_images' in site.plugin_data:
if post.meta.banner in site.plugin_data['responsive_images']:
js_post['banner_srcsets'] = site.plugin_data['responsive_images'][post.meta.banner]['srcsets']
if 'thumbnail_banner' in plugin_data_to_output and 'thumbnails' ... |
guillochon/FriendlyFit | mosfit/modules/transforms/diffusion_csm.py | Python | mit | 2,712 | 0 | """Definitions for the `DiffusionCSM` class."""
from collections import OrderedDict
import numexpr as ne
import numpy as np
from mosfit.constants import C_CGS, DAY_CGS, M_SUN_CGS, AU_CGS
from mosfit.modules.transforms.transform import Transform
# Important: Only define one ``Module`` class per file.
class Diffusio... | .process(s | elf, **kwargs)
self._kappa = kwargs[self.key('kappa')]
self._mass = kwargs[self.key('mcsm')] * M_SUN_CGS
self._R0 = kwargs[self.key('r0')] * AU_CGS # AU to cm
self._s = kwargs[self.key('s')]
self._rho = kwargs[self.key('rho')]
# scaling constant for CSM density profile
... |
simonmonk/hacking2 | pi/ch07_relay_click.py | Python | mit | 433 | 0.020785 | import RPi.GPIO as GPIO
import time
# Configure the Pi to use the BCM (Broadcom) pin names, rather than the pin positions
GPIO.setmode(GPIO.BCM)
relay_pin = 18
GPIO.setup(relay_pin, GPIO.OUT)
try:
while True:
GPIO.output(relay_pin, True)
time.sleep(2)
GPIO.output(re... |
finally:
print("Cleaning u | p")
GPIO.cleanup() |
quantumlib/OpenFermion-Cirq | openfermioncirq/experiments/hfvqe/gradient_hf_test.py | Python | apache-2.0 | 942 | 0.001062 | import numpy as np
from openfermioncirq.experiments.hfvqe.gradient_hf import (rhf_func_generator,
rhf_minimization)
from openfermioncirq.experiments.hfvqe.molecular_example import make_h6_1_3
def test_rhf_func_gen():
rhf_objective, molecule, parameters, _, _ = make_h6_1_3()
ansa... | generator(rhf_objective)
assert np.isclose(molecule.hf_energy, energy(parameters))
ansatz, energy, _, opdm_func = rhf_func_generator(
rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True)
assert np.isclose(molecule.hf_energy, energy(parameters))
test_opdm = opdm_func(parameters)... | = ansatz(parameters)
initial_opdm = np.diag([1] * 3 + [0] * 3)
final_odpm = u @ initial_opdm @ u.T
assert np.allclose(test_opdm, final_odpm)
result = rhf_minimization(rhf_objective, initial_guess=parameters)
assert np.allclose(result.x, parameters)
|
funkyfuture/deck-chores | deck_chores/main.py | Python | isc | 9,972 | 0.001705 | import json
import logging
import os
import sys
from datetime import datetime, timedelta, timezone
from signal import signal, SIGINT, SIGTERM, SIGUSR1
from typing import Optional
from apscheduler.schedulers import SchedulerNotRunningError
from dateutil.parser import isoparse as parse_iso_timestamp
from docker.models.c... | sed=container.status == 'paused'
)
log.debug('Finished inspection of running containers.')
|
# the timezone info is removed here, because the object will be fed to docker-py
# (version 4.4.4 at the time of writing) which cannot process timezone aware
# datetime objects
return last_event_time.replace(tzinfo=None)
def reassign_jobs(container_id: str, consider_paused: bool) -> Optional[str]:
... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/armor/shared_armor_segment_ubese_advanced.py | Python | mit | 463 | 0.047516 | #### NOTICE: THIS FILE IS | AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/armor/shared_armor_segment_ubese_advanced.iff"
result.attribute_template_id = -1
r... | MODIFICATIONS ####
return result |
FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/sqlite3/test/userfunctions.py | Python | gpl-2.0 | 15,125 | 0.003041 | #-*- coding: iso-8859-1 -*-
# pysqlite2/test/userfunctions.py: tests for user-defined functions and
# aggregates.
#
# Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de>
#
# This file is part of pysqlite.
#
# This software is provided 'as-is', without any express or implied
# warran... | e))
self.assertEqual(val, None)
def CheckFuncReturnBlob(self):
cur = self.co | n.cursor()
cur.execute("select returnblob()")
val = cur.fetchone()[0]
self.assertEqual(type(val), bytes)
self.assertEqual(val, b"blob")
def CheckFuncReturnLongLong(self):
cur = self.con.cursor()
cur.execute("select returnlonglong()")
val = cur.fetchone()[0]
... |
MSusik/invenio | invenio/testsuite/test_utils_hash.py | Python | gpl-2.0 | 1,644 | 0.008516 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2013 CERN.
##
## Invenio 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 2 of the
## License, or (at your option) a... | thout 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suit... | st_suite, InvenioTestCase
class TestHashUtils(InvenioTestCase):
"""
hashutils TestSuite.
"""
def test_md5(self):
self.assertEqual(md5('').hexdigest(),
'd41d8cd98f00b204e9800998ecf8427e')
self.assertEqual(md5('test').hexdigest(),
'098f6b... |
robalford/reConstruct | userprofiles/apps.py | Python | bsd-3-clause | 99 | 0 | from django.apps import AppConfig
class UserprofilesConfig(AppConfig):
name = | 'userprof | iles'
|
Winterflower/cachey | cachey/tests/test_cache.py | Python | bsd-3-clause | 1,608 | 0.002488 | import sys
from time import sleep
fro | m cachey import Cache, Scorer, nbytes
def test_cache():
c = Cache(available_bytes=nbytes(1) * 3)
c.put('x', 1, 10)
assert c.get('x') == 1
assert 'x' in c
c.put('a', 1, 10)
c.put('b', 1, 10)
c.put('c', 1, 10 | )
assert set(c.data) == set('xbc')
c.put('d', 1, 10)
assert set(c.data) == set('xcd')
c.clear()
assert 'x' not in c
assert not c.data
assert not c.heap
def test_cache_scores_update():
c = Cache(available_bytes=nbytes(1) * 2)
c.put('x', 1, 1)
c.put('y', 1, 1)
c.get('x')
... |
Juniper/nova | nova/api/openstack/compute/rescue.py | Python | apache-2.0 | 4,187 | 0 | # Copyright 2011 OpenStack Foundation
#
# 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 a... | 'rescue', id)
except exception.InvalidVolume as | volume_error:
raise exc.HTTPConflict(explanation=volume_error.format_message())
except exception.InstanceNotRescuable as non_rescuable:
raise exc.HTTPBadRequest(
explanation=non_rescuable.format_message())
if CONF.api.enable_instance_password:
return... |
django-json-api/rest_framework_ember | example/tests/test_performance.py | Python | bsd-2-clause | 4,273 | 0.001404 | from datetime import date, timedelta
from random import randint
from django.utils import timezone
from rest_framework.test import APITestCase
from example.factories import CommentFactory, EntryFactory
from example.models import Author, Blog, Comment, Entry, LabResults, ResearchProject
class PerformanceTestCase(APIT... | prefetched
"""
with self.assertNumQueries(5):
response = self.client.get("/comments?include=author&page[size]=25")
self.assertEqual(len(response.data["results"]), 25)
def test_query_select_related_entry(self):
"""We expect a list view with an include have two queries... | response = self.client.get("/comments?include=writer&page[size]=25")
self.assertEqual(len(response.data["results"]), 25)
def test_query_prefetch_uses_included_resources(self):
"""We expect a list view with `included_resources` to have three queries:
1. Primary resource COUNT qu... |
andrewsomething/libcloud | libcloud/compute/drivers/vcloud.py | Python | apache-2.0 | 94,722 | 0.000095 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | fixxpath(lease_element, 'StorageLeaseExpiration')
)
def apply_if_elem_not_none(elem, function):
return function(elem.text) if elem is not None else None
return cls(
lease_id=lease_id,
deployment_lease=apply_if_elem_not_none(deployment_lease, int),
... | deployment_lease_expiration=apply_if_elem_not_none(
deployment_lease_expiration,
parse_date
),
storage_lease_expiration=apply_if_elem_not_none(
storage_lease_expiration,
parse_date
)
)
def get_deployment_tim... |
nopbyte/popularIoTy-test-scripts | create-data-from-graph/graph/node.py | Python | apache-2.0 | 207 | 0.028986 | class Node():
|
def __init__(self, node,graph):
self.vertex = node
self.ids = graph.vertex_properties["id"]
self.graph = graph
def getId(self):
return self.ids[se | lf.vertex]
|
suizokukan/anceps | dchars/languages/lat/symbols.py | Python | gpl-3.0 | 4,869 | 0.03277 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
################################################################################
# DChars Copyright (C) 2012 Suizokukan
# Contact: suizokukan _A.T._ orange dot fr
#
# This file is part of DChars.
# DChars is free software: you can redistribute it and/or modify
# ... | .gnu.org/licenses/>.
################################################################################
"""
❏DChars❏ : dchars/languages/lat/symbols.py
"""
# problem with Pylint :
# pylint: disable=E0611
# many errors like "No name 'extensions' in module 'dchars'"
from dchars.utilities.name2symbols import Name2Symbols... | ! If you modify these dictionaries, don't forget to modify the
# corresponding transliteration's dictionaries !
#
#...............................................................................
SYMB_UPPER_CASE = Name2Symbols(
{
'a' : ('A',),
'b' : ('B',),
'c' : ('C',... |
keikenuro/kaiju-libnow | kaiju_libnow/kaiju/core/config/structures/application/web/OnErrorConfig.py | Python | gpl-3.0 | 1,090 | 0.005505 | from kaiju.core.config.structures.application.web.ErrorConfig import ErrorConfig
class OnErrorConfig(obje | ct):
@staticmethod
def | parse_xml(web_xml):
"""
:param web_xml:
:param variables:
:return:
"""
handler = web_xml.get('handler')
if not handler:
raise ValueError("The <onerror> tag must have an 'handler' attribute declared.")
errors = []
for error in web_xml.fi... |
kennethcc2005/yahoo_finance_stocks | td_sequence.py | Python | mit | 3,188 | 0.006901 | '''
TD_Sequence in class.
'''
import numpy as np
import pandas as pd
import json
import pandas.io.data as web
from datetime import date, datetime, timedelta
from collections import defaultdict
class TDSequence(object):
def __init__(self, data):
self.data = data
def sequence(self):
setup = s... | a.iloc[-1]['Low'] <= self.data.ilo | c[-4]['Low'])) or \
((self.data.iloc[-2]['Low'] <= self.data.iloc[-3]['Low']) and (self.data.iloc[-2]['Low'] <= self.data.iloc[-4]['Low'])):
buy_counter = 10
return buy_counter
else:
r... |
mrkm4ntr/incubator-airflow | airflow/providers/jenkins/hooks/jenkins.py | Python | apache-2.0 | 1,903 | 0.001051 | #
# Licensed to the Ap | ache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional informa | tion
# regarding copyright ownership. The ASF licenses this file
# to you 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 applicab... |
nonNoise/akilib | pypi/akilib/edison/AKI_SPI_AQM1248A.py | Python | mit | 3,569 | 0.017372 |
############################################################
#The MIT License (MIT)
#Copyright (c) 2015 Yuta KItagami
#Project: https://github.com/nonNoise/akilib
############################################################
import mraa
import time
from struct import *
class AKI_SPI_AQM1248A:
def __init__(sel... | (line & 0x0F))
def Clear(self):
for i in range(8+1):
self.Page(i)
self.Column(0)
for j in range(128):
self.Write_Data(0)
| def Test(self):
for i in range(6):
self.Page(i)
self.Column(0)
for j in range(128):
self.Write_Data(0x80)
def Pixel_Check(self,x,y):
if(self.buffer.getpixel((x,y)) > 127):
return 1
else :
return 0
def Uplode(... |
Mrs-X/Darknet | test/functional/wallet_listsinceblock.py | Python | mit | 9,552 | 0.002198 | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the listsincelast RPC."""
from test_framework.test_framework import PivxTestFramework
from test_framew... | of a reorg. The former will vanish and the
latter will appear as the true transaction (with confirmations dropping
as a result).
ab0
/ \
aa1 [tx1] bb1
| |
aa2 | bb2
| |
aa3 bb3 [tx1]
|
bb4
Asserted:
1. tx1 is listed in listsinceblock.
2. It is included in 'removed' as it was removed, even though it is now
present in a different block.
3. It is listed ... |
queria/my-tempest | tempest/services/compute/xml/hosts_client.py | Python | apache-2.0 | 2,919 | 0 | # Copyright 2013 IBM Corp.
#
# 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 agreed t... | children()]
return resp, body
def reboot_host(self, hostname):
"""Reboot a host."""
resp, body = self.get("os-hosts/%s/reboot" % str(hostname))
node = etree.fromstring(body)
body = [xml_utils.xml_to_json(x) for x in node.getchildren()] |
return resp, body
|
shaftoe/home-assistant | homeassistant/components/media_player/openhome.py | Python | apache-2.0 | 6,679 | 0 | """
Support for Openhome Devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.openhome/
"""
import logging
from homeassistant.components.media_player import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_ON... | self._device.Uuid()
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def source_list(self):
"""List of available input sources."""
return self._source_names
@property
def media_image_url(se | lf):
"""Image url of current playing media."""
return self._track_information["albumArt"]
@property
def media_artist(self):
"""Artist of current playing media, music track only."""
return self._track_information["artist"]
@property
def media_album_name(self):
""... |
badrihippo/sirius | media/models.py | Python | gpl-2.0 | 1,378 | 0.007257 | from django.db import models
class Picture(models.Model):
disp_title = models.CharField(max_length=256, blank=True)
caption = models.CharField(max_length=300,blank=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='smedia', blank=True, null=True)
credit = models.T... | LField(blank=True)
illustrators = models.ManyToManyField('people.Person', blank=True)
sources = models.ManyToManyField('Source', blank=True)
def __unicode__(self):
if self.disp_title:
return self.disp_title
elif self.caption:
return self.caption
else:
... | lute_url(self):
if self.image: return self.image.url
else: return self.url
class Source(models.Model):
name = models.CharField(max_length=300, blank=True)
url = models.URLField(blank=True)
detail = models.TextField(blank=True)
copyrights = models.ManyToManyField('Copyright', blank=True)
... |
mikeireland/pynrm | fake_companion.py | Python | mit | 4,240 | 0.018868 | from __future__ import division
import numpy as np,opticstools,matplotlib.pyplot as plt,math,scipy.ndimage,copy
from skimage.measure import block_reduce
import astropy.io.fits as pyfits
import os,sys,contratio as crat
nameList = sys.argv[5:len(sys.argv)]
if len(sys.argv)<4:
print('Useage: crat_from_object.py raw_di... | [ii-2])+'.fits') or ii in lineNums:
ii-=1
if len(cal_els)==numCals:
break
if jj<len(all_elements) and os.path.isfile(cubeDir+'/cube'+str(all_elements[jj-2])+'.fits') and jj not in lineN | ums:
cal_els.append(all_elements[jj-2])
jj+=1
elif jj>=len(all_elements) or not os.path.isfile(cubeDir+'/cube'+str(all_elements[jj-2])+'.fits') or jj in lineNums:
jj+=1
if len(cal_els)==numCals:
break
if len(cal_els)==numCals:
break
tgt_cubes ... |
ski7777/ftcommunity-TXT | board/fischertechnik/TXT/rootfs/opt/ftc/ftduino_direct.py | Python | gpl-3.0 | 4,063 | 0.014275 | #
# Kommandos fuer ftduino.comm :
#
# void led_set <0|1>
#
# string ftduino_direct_get_version
# char[16] ftduino_id_set <string maxlen=16>
# char[16] ftduino_id_get
#
#
# void input_set_mode <I1..I8> <switch|resistance|voltage>
# uint16_t input_get <I1..I8>
#
# void output_set <O1..O8> <... | r erste gefundene ftduino angesprochen
try:
if device==None:
liste=ftduino_scan()
port=liste[0][0]
if liste!=None:
self.ftduino = serial.Serial(port, 115200, timeout=0.1, writeTimeout = 0.1)
time.sleep(0... |
else:
self.ftduino = serial.Serial(device, 115200, timeout=0.1, writeTimeout = 0.1)
except:
pass
def getDevice(self):
return self.ftduino
def comm(self, command):
try:
command=command+"\n"
self.ftduino.flushInput()
... |
fizyk/pyramid_fullauth | src/pyramid_fullauth/routing/__init__.py | Python | mit | 240 | 0.004167 | # Copyright (c) 2013 - 2016 by pyramid_fullauth authors and | contributors <see AUTHORS file>
#
# This module is part of pyramid_fullauth and is relea | sed under
# the MIT License (MIT): http://opensource.org/licenses/MIT
"""Routing module."""
|
ivano666/tensorflow | tensorflow/python/kernel_tests/scalar_strict_test.py | Python | apache-2.0 | 5,013 | 0.006782 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | a vector')
def testReshape(self):
self.check(tf.reshape, (7, 1), 'sizes input must be 1-D', [7])
def testSh | ardedFilename(self):
self.check(gen_io_ops._sharded_filename, ('foo', 4, [100]),
'must be a scalar', b'foo-00004-of-00100')
def testShardedFilespec(self):
self.check(gen_io_ops._sharded_filespec, ('foo', [100]),
'must be a scalar', b'foo-?????-of-00100')
def testUnsortedSegme... |
kampfschlaefer/jenkins_api_simulator | jenkins_api_simulator/passthrough.py | Python | gpl-3.0 | 3,301 | 0 |
from flask import Flask, request, make_response
import requests
import logging
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.debug = True
jenkins_url = 'http://localhost:8000'
def prepare_response(response):
_headers = {}
for h in ['content-type', 'x-jenkins-session', 'x-jenkins', 'server... | eplace(jenkins_url, request.url_root.strip('/'))
return make_response((_content, response.status_code, _headers))
@app.route('/api/python', methods=['GET'])
def handle_api_python():
log | ger.info('Request for /api/python')
logger.info(
'path %s, method %s, data "%s"',
request.path, request.method, request.data
)
if request.method == 'GET':
r = requests.get('%s%s' % (jenkins_url, request.path))
# print(' Will return %s' % r.text)
return prepare_respons... |
tvotyakov/codeeval | easy/road-trip/code.py | Python | gpl-2.0 | 2,270 | 0.009251 | #!python3
def calc_distances(road_points):
'''(list of tuples) -> list of integers
>>> calc_distances([('Rkbs', 5453), ('Wdqiz', 1245), ('Rwds', 3890), ('Ujma', 5589), ('Tbzmo', 1303)])
[1245, 58, 2587, 1563, 136]
>>> calc_distances([('Vgdfz', 70), ('Mgknxpi', 3958), ('Nsptghk', 2626), ('Wuzp',... | 3), ('Voclqmb', 5236)]
'''
def parse_element(el):
t = el.strip().split(',')
return t[0], int(t[1])
g = map(parse_element, in_str.strip(';').split(';'))
return list(g)
if __name__ == '__main__':
import sys
if (len(sys.argv) <= 1):
import doctest
... | 'r')
for test in test_cases:
test = test.rstrip('\n')
if not test: continue # ignore an empty line
print(','.join(map(str, calc_distances(parse_string(test)))))
test_cases.close()
|
rpelizzi/websheets | app/xls2csv.py | Python | gpl-3.0 | 7,056 | 0.002834 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import csv
import xlrd
from optparse import OptionParser
def xls2csv(infilepath, outfile, sheetid=1, delimiter=",", sheetdelimiter="--------", encoding="cp1251"):
writer = csv.writer(outfile, dialect='excel', quoting=csv.QUOTE_ALL, delimiter=delimiter)
... | cval = "%s:%s" % (e1.__name__, e2)
else: # XL_CELL_EMPTY, XL_CELL_ERROR, XL_CELL_BLANK
cval = ""
row[j] = cval
writer.writerow(row)
#xlrd format excel number
#http://uucode.com/blog/2013/10/22/using-xlrd-and-formatting-excel-numbers/
import re
re_maybe_numfm... | the format "Standard/GENERAL" mean.
# As far as I understand, the presentation can differ depending
# on the locale and user settings. Here is a my proposal.
if None == s_fmt or 'GENERAL' == s_fmt:
return (None, '#', '#')
# Find the number-part
m = re_maybe_numfmt.search(s_fmt)
if m i... |
mkomitee/pstatus | doc/conf.py | Python | bsd-2-clause | 8,175 | 0.007462 | # -*- coding: utf-8 -*-
#
# pstatus documentation build configuration file, created by
# sphinx-quickstart on Sat Apr 13 22:16:16 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | relative to this directory.
templates_path = ['_templates']
# The suffix of source f | ilenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pstatus'
copyright = u'2013, Michael Komitee'
# The version info for the project you're documenting, acts as replac... |
RIPE-NCC/ripe-atlas-cousteau | ripe/atlas/cousteau/request.py | Python | gpl-3.0 | 10,865 | 0.000184 | # Copyright (c) 2016 RIPE NCC
#
# 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 is distributed in the h... | l import parser
from datetime import datetime
from .version import __version__
class AtlasRequest(object):
"""
Base class for doing Atlas requests. Contains functions that can be used by
most Atlas requests.
"""
http_methods = {
"GET": requests.get,
"POST": requests.post,
... | }
def __init__(self, **kwargs):
self.url = ""
self.key = kwargs.get("key")
self.url_path = kwargs.get("url_path", "")
self.server = kwargs.get("server") or "atlas.ripe.net"
self.verify = kwargs.get("verify", True)
self.proxies = kwargs.get("proxies", {})
sel... |
Vaayne/vaayne.com | app/views/error.py | Python | mit | 318 | 0.006289 | # -*- coding:utf-8 -*-
# Created by Vaayne at 201 | 6/07/27 12:59
from . import view
from flask import render_template
@view.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@view.app_errorhandler(500)
def internet_server_error(e):
return | render_template('500.html'), 500 |
gmatteo/pymatgen | pymatgen/command_line/critic2_caller.py | Python | mit | 33,962 | 0.001414 | """
This module implements an interface to the critic2 Bader analysis code.
For most Bader analysis purposes, users are referred to
pymatgen.command_line.bader_caller instead, this module is for advanced
usage requiring identification of critical points in the charge density.
This module depends on a compiled critic2... | rystals), minimum distance between
critical points for them to be equivalent
* NUCEPS, same as CPEPS but specifically for nucleus critical
points (critic2 default is depedent on grid dimensions)
* NUCEPSH, same as NUCEPS but specifically for hydrogen nuclei
since associated... | t (field units), discard critical point if any
element of the diagonal of the Hessian is below this value,
useful for discarding points in vacuum regions
* DISCARD, float (field units), discard critical points with field
value below this value, useful for discarding points in vacuu... |
pombredanne/invenio-old | modules/bibharvest/lib/bibharvest_templates.py | Python | gpl-2.0 | 23,444 | 0.00546 | ## This file is part of CDS Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
##
## CDS Invenio 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 2 of the
## License, or (... | "" [<a title="%s" href="%s/%s">?</a>]</small>""" % (guidetitle, CFG_SITE_URL, guideurl)
return titlebar
d | ef tmpl_output_numbersources(self, ln, numbersources):
"""Get the navigation trail
- 'number of sources' *int* - The number of sources in the database"""
_ = gettext_set_language(ln)
present = _("OAI sources currently present in the database")
notpresent = _("No OAI sources cur... |
chebee7i/dit | dit/multivariate/entropy.py | Python | bsd-3-clause | 2,340 | 0.000427 | """
A version of the entropy with signature common to the other multivariate
measures.
"""
from ..helpers import normalize_rvs
from ..shannon import conditional_entropy, entropy as shannon_entropy
from ..utils import flatten
def entropy(dist, rvs=None, crvs=None, rv_mode=None):
"""
Compute the conditional joi... | indices. If equal
to 'names', the the elements are interpreted as random variable names.
If `None`, then the value of `dist._rv_mode` is consulted, which
def | aults to 'indices'.
Returns
-------
H : float
The entropy.
Raises
------
ditException
Raised if `rvs` or `crvs` contain non-existant random variables.
Examples
--------
Let's construct a 3-variable distribution for the XOR logic gate and name
the random variabl... |
Silmathoron/NNGT | doc/examples/multi_groups_network.py | Python | gpl-3.0 | 1,906 | 0.000525 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
#
# This file is part of the NNGT project to generate and analyze
# neuronal networks and their activity.
# Copyright (C) 2015-2019 Tanguy Fardet
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | t.plot.chord_diagram(pop_graph, names="name", u | se_gradient=True,
show=True)
|
soylentme/shipwire-python | shipwire/responses.py | Python | mit | 2,748 | 0.000364 | """
The following class names are paired with the methods listed
at the top of the api module. If you add a method to the api
module you must also add a corresponding Response class below.
"""
import requests
HTTP_SUCCESS = 200
SHIPWIRE_GET_ALL_LIMIT = 200
class ShipwireResponse(object):
def __init__(self, resp... | pass
class QuoteResponse(Sh | ipwireResponse):
pass
class Split_ordersResponse(ListResponse):
pass
|
AlexOugh/horizon | openstack_dashboard/nikola_auth/backend.py | Python | apache-2.0 | 9,701 | 0.000825 | # 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 agreed to in writing, software
# distributed under the... | tion,
| keystone_exceptions.AuthorizationFailure) as exc:
msg = _('Unable to retrieve authorized projects.')
raise exceptions.AuthException(msg)
# Abort if there are no projects for this user
if not projects:
msg = _('You are not authorized for any pr... |
wangjun/pyload | module/plugins/crypter/DailymotionBatch.py | Python | gpl-3.0 | 3,865 | 0.00207 | # -*- coding: utf-8 -*-
"""
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 is distributed in... | laylistInfo(se | lf, id):
ref = "playlist/" + id
req = {"fields": "name,owner.screenname"}
playlist = self.api_response(ref, req)
if "error" in playlist:
return
name = playlist["name"]
owner = playlist["owner.screenname"]
return name, owner
def _getPlaylists(sel... |
tsdmgz/ansible | test/units/mock/path.py | Python | gpl-3.0 | 191 | 0.005236 | from ansible.compat.tests.mock import MagicMock
from ansible.utils.path import unfrackpath
mock_unfrackpath_noop = | MagicMock(spec_set=unfrackpath, | side_effect=lambda x, *args, **kwargs: x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.