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 |
|---|---|---|---|---|---|---|---|---|
prasanna08/oppia | core/domain/user_domain_test.py | Python | apache-2.0 | 27,932 | 0.000895 | # coding: utf-8
#
# Copyright 2018 The Oppia 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 requi... | MUTED_PREFERENCE,
'mute_suggestion_notifications':
feconf.DEFAULT_SUGGESTION_NOTIFICATIONS_MUTED_PREFERENCE
}
)
class ExpUserLastPlaythroughTests(test_utils.GenericTestBase):
"""Testing | domain object for an exploration last playthrough model."""
def test_initialization(self):
"""Testing init method."""
exp_last_playthrough = (user_domain.ExpUserLastPlaythrough(
'user_id0', 'exp_id0', 0, 'last_updated', 'state0'))
self.assertEqual(
exp_last_playthro... |
tensorflow/model-optimization | tensorflow_model_optimization/python/core/api/quantization/keras/default_8bit/default_8bit_transforms/__init__.py | Python | apache-2.0 | 2,949 | 0.005426 | # Copyright 2020 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... | l_optimization.python.core.quantization.keras.default_8bit.default_8bit_transforms import Conv2DReshapeBatchNormQuantize
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit.default_8bit_transforms import Conv2DReshapeBatchNormReLUQuantize
from tensorflow_model_optimization.python.core.qu | antization.keras.default_8bit.default_8bit_transforms import InputLayerQuantize
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit.default_8bit_transforms import LayerReluActivationQuantize
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit.default_8bit_transforms... |
khornberg/nvpy-gtk | nvpy/simplenote.py | Python | bsd-3-clause | 9,573 | 0.001462 | # -*- coding: utf-8 -*-
"""
simplenote.py
~~~~~~~~~~~~~~
Python library for accessing the Simplenote API
:copyright: (c) 2011 by Daniel Schauenberg
:license: MIT, see LICENSE for more details.
"""
import urllib
import urllib2
from urllib2 import HTTPError
import base64
try:
import json
except... | ple-note.appspot.com/api/login'
DATA_URL = 'https://simple-note.a | ppspot.com/api2/data'
INDX_URL = 'https://simple-note.appspot.com/api2/index?'
NOTE_FETCH_LENGTH = 20
class Simplenote(object):
""" Class for interacting with the simplenote web service """
def __init__(self, username, password):
""" object constructor """
self.username = urllib2.quote(userna... |
mamchecker/mamchecker | mamchecker/test/hlp.py | Python | gpl-3.0 | 2,817 | 0.00071 | # -*- coding: utf-8 -*-
#from mamchecker.conftest import *
import os
import os.path
import webapp2
import datetime
from mamchecker.app import app
from mamchecker.model import (Assignment, Index, Problem, Student, Class,
Teacher, Period, School, set_student, delete_all)
from mamchecker.c... | se in a pytest test_xxx function
>>> check_test_answers(__file__,test_format)
'''
if m is None:
m = Struct()
m.update(globals())
elif isinstance(m, str):
#m = __file__
thisdir = os.path.dirname(os.path.abspath(m))
sp = thisdir.split(os.sep)
beyondmam = sp... | _module(mn)
d = from_py(m)
g = d.given()
norm_results = d.norm(d.calc(g))
if test_format:
for t in test_format:
d.norm(t)
def problems_for(
student,
skip=2,
startdir=os.path.dirname(
os.path.dirname(__file__))):
skipc = 0
for f in os.listdir(os.path.join... |
hryamzik/ansible | lib/ansible/modules/cloud/digital_ocean/digital_ocean_account_facts.py | Python | gpl-3.0 | 2,100 | 0.002857 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.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__ = ty... | DigitalOcean User account
description:
- This module can be used to gather facts about User account.
author: "Abhijeet Kasurde (@Akasurde)"
version_added: "2.6"
requirements:
- "python >= 2.6"
extends_documentation_fragment: digi | tal_ocean.documentation
'''
EXAMPLES = '''
- name: Gather facts about user account
digital_ocean_account_facts:
oauth_token: "{{ oauth_token }}"
'''
RETURN = '''
data:
description: DigitalOcean account facts
returned: success
type: dictionary
sample: {
"droplet_limit": 10,
"ema... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/system/systemglobal_authenticationpolicy_binding.py | Python | apache-2.0 | 6,831 | 0.036012 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | e.priority
return updateresource.update_resource(client)
else :
if resource and len(resource) > 0 :
updateresources = [systemglobal_authenticationpolicy_binding() for _ in range(len(resource))]
for i in range(len(resource)) :
updateresources[i].policyname = resource[i].policyname
update... | uest(client, updateresources)
except Exception as e :
raise e
@classmethod
def delete(cls, client, resource) :
try :
if resource and type(resource) is not list :
deleteresource = systemglobal_authenticationpolicy_binding()
deleteresource.policyname = resource.policyname
return deleteresource.de... |
gusibi/Metis | apis/models/model.py | Python | apache-2.0 | 4,308 | 0.004178 | #! -*- coding: utf-8 -*-
import copy
from six import with_metaclass
from bson.objectid import ObjectId
from pymongo import MongoClient
from pymongo import ReturnDocument
from apis.settings import Config
pyclient = MongoClient(Config.MONGO_MASTER_URL)
class ObjectModel(object):
def __init__(self, *args, **kwar... | ip(skip).limit(limit).sort(sorts)
else:
docs = cls.collection.find(filter=filter,
projection=projection,
**kwargs).skip(skip).limit(limit)
r | esults = []
for doc in docs:
if doc.get('_id', None):
doc['id'] = str(doc['_id'])
results.append(doc)
return results
@classmethod
def insert(cls, **kwargs):
params = getattr(cls, '__default_fields__', {})
params.update(kwargs)
... |
minlexx/xnovacmd | tests/test_requesocks.py | Python | gpl-2.0 | 1,339 | 0.00224 | #!/usr/bin/python3
# requires:
# - pysocks for socks5 proxy socket, required by requesocks
# - certifi for HTTPS certificate validation, also used in depths of requesocks
# - requesocks
import requesocks
import certifi
#SOCKS5_PROXY = '127.0.0.1:9050'
SOCKS5_PROXY = '192.168.20.1:9050'
USER_AGENT = 'Mozilla/5.0 (W... | t is None:
if type(r.content) == bytes:
text = r.content.decode('UTF-8')
if text:
print(text)
with open('res.html', 'wt', encoding=r.encoding) as f:
f.write(text)
else:
print('status code: {0}'.format(r.status_code))
if __name__ =... |
main()
|
childsish/sofia | templates/genomics/steps/molecular_weights.py | Python | gpl-2.0 | 742 | 0.002695 | from sofia.step import Step
class MolecularWeights(S | tep):
"""
Reads in a set of molecular weights. The file of molecular weights can be obtained from
http://emboss.sourceforge.net/.
"""
IN = ['molecular_weight_file']
OUT = ['molecular_weight_set']
def run(self, molecular_weight_file):
infile = open(molecular_weight_file[0], encoding... | infile.close()
interface = {}
for line in data.split('\n'):
if line.strip() == '' or line[0] == '#' or line.startswith('Mol'):
continue
parts = line.split()
interface[parts[0]] = {'avg': float(parts[1]), 'mono': float(parts[2])}
yield i... |
rihardsk/LatvianStemmer | setup.py | Python | apache-2.0 | 1,010 | 0 | from setuptools import setup
with open("README.md", "r") as f:
readme = f.read()
setup(
name='LatvianStemmer',
version='1.0.2',
description='Light stemmer for Latvian.',
py_modules=['LatvianStemmer'],
author='Rihards Krišlauks',
author_email='rihizs@gmail.com',
url='https://github.com/... | Version 2.0',
long_description=readme,
long_ | description_content_type="text/markdown",
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Development Status :: 4 - Beta',
'Intended Aud... |
getting-things-gnome/gtg | GTG/gtk/backends/configurepanel.py | Python | gpl-3.0 | 8,882 | 0.000113 | # -----------------------------------------------------------------------------
# Getting Things GNOME! - a personal organizer for the GNOME desktop
# Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Gene... | se, data=False):
"""Signal callback function, called when a backend state
(enabled/disabled) changes. Refreshes this view.
@param sender: not used, here only for signal callback compatibility
@param data: not used, here only for signal callback compatibility
"""
self.ref... | end is enabled/disabled via the UI button
@param sender: not used, here only for signal callback compatibility
"""
self.parameters_ui.commit_changes()
self.req.set_backend_enabled(self.backend.get_id(),
not self.backend.is_enabled())
def on_sync... |
jolyonb/edx-platform | openedx/features/course_experience/views/course_home_messages.py | Python | agpl-3.0 | 9,580 | 0.00261 | """
View logic for handling course messages.
"""
from __future__ import absolute_import
from datetime import datetime
from babel.dates import format_date, format_timedelta
from django.contrib import auth
from django.template.loader import render_to_string
from django.utils.http import urlquote_plus
from django.utils... | se, False otherwise
}
"""
def render_to_fragment(self, request, course_id, user_access, **kwargs):
"""
Renders a course message fragment for the specified course.
"""
course_key = CourseKey.from_string(course_id)
course = get_course_with_access(request.user, 'load', c... | already_started = course.start and now > course.start
days_until_start_string = "started" if already_started else format_timedelta(
course.start - now, locale=to_locale(get_language())
)
course_start_data = {
'course_start_date': format_date(course.start, locale=to_local... |
anna-effeindzourou/trunk | examples/timeStepperUsage.py | Python | gpl-2.0 | 6,248 | 0.024332 | # coding: utf-8
# 2012 © Bruno Chareyre <bruno.chareyre_A_hmg.inpg.fr>
"Test and demonstrate the use of timestepper and density scaling."
from yade import pack,qt,timing
O.periodic=True
O.cell.hSize=Matrix3(0.1, 0, 0,
0 ,0.1, 0,
0, 0, 0.1)
n=1000
sp=pack.SpherePack()
num=sp.makeCloud(Vector3().Zero,O.c... | GlobalStiffness timesteper + density scaling:"
print "--------------------------------------------------------------------"
timing.stats()
#_____ TYPICAL RESULTS (n=1000)____
#------------------ | --------------
#Fixed dt = 0.8 * PWave timestep:
#--------------------------------
#Name Count Time Rel. time
#-------------------------------------------------------------------------------------------------------
#ForceResetter ... |
jlinn/pylastica | pylastica/bulk/response.py | Python | apache-2.0 | 926 | 0.00324 | __author__ = 'Joe Linn'
#import pylastica
import pylastica.response
class Response(pylastica.response.Response):
def __init__(self, response_data, action, op_type):
"""
@param response_data:
@type | response_data: dict or str
@param action:
@type action: pylastica.bulk.action.Action
@param op_type: bulk operation type
@type op_type: str
"""
assert isinstance(action, pylastica.bulk.action.Action), "action must be an instance of Action: %r" % action
super(Respo... | """
@return:
@rtype: pylastica.bulk.action.Action
"""
return self._action
@property
def op_type(self):
"""
@return:
@rtype: str
"""
return self._op_type
|
jean/hamster | wafadmin/Runner.py | Python | gpl-3.0 | 3,894 | 0.066769 | #!/usr/bin/env python2
# encoding: utf-8
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
import os,sys,random,time,threading,traceback
try:from Queue import Queue
except ImportError:from queue import Queue
import Build,Utils,Logs,Options
from Logs import debug,error
from Constants import*
GAP=15
... | self.manager.add_finished(ret)
if not self.stop and getattr(ret,'more_tasks',None):
self.outstanding+=ret.more_tasks
self.total+=len(ret.more_tasks)
self.count-=1
def error_handler(self,tsk):
if not Options.options.keep:
self.stop=True
self.error=True
def start(self):
if TaskConsumer.consumers:
... | er.consumers.append(TaskConsumer())
while not self.stop:
self.refill_task_list()
tsk=self.get_next()
if not tsk:
if self.count:
continue
else:
break
if tsk.hasrun:
self.processed+=1
self.manager.add_finished(tsk)
continue
try:
st=tsk.runnable_status()
except Excepti... |
DCSaunders/tensorflow | tensorflow/python/debug/cli/curses_ui_test.py | Python | apache-2.0 | 39,416 | 0.002283 | # 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... | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ====== | ========================================================================
"""Tests of the curses-based CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import curses
import numpy as np
from tensorflow.python.debug.cli import curses_ui... |
davidsandberg/facenet | contributed/predict.py | Python | mit | 6,182 | 0.011 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#----------------------------------------------------
# MIT License
#
# Copyright (c) 2017 Rishi Rai
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and ass... | oading parameters')
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
| sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)
nrof_samples = len(image_paths)
img_list = []
count_per_image = []
for i in xrange(nrof_samples... |
kontais/EFI-MIPS | ToolKit/cmds/python/Lib/distutils/debug.py | Python | bsd-3-clause | 272 | 0 | import os
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: debug.py,v 1.1.1.1 2006/05/30 06:04:31 hhzhou Exp $"
# If DISTUTILS_DEBUG is anything other than the empty string, | we run in
# debug mo | de.
DEBUG = os.environ.get('DISTUTILS_DEBUG')
|
automl/paramsklearn | tests/components/data_preprocessing/test_one_hot_encoding.py | Python | bsd-3-clause | 4,887 | 0.001637 | import os
import unittest
import numpy as np
from scipy import sparse
from ParamSklearn.components.data_preprocessing.one_hot_encoding import OneHotEncoder
from ParamSklearn.util import _test_preprocessing
class OneHotEncoderTest(unittest.TestCase):
def setUp(self):
self.categorical = [True,
... | True,
True,
True,
True,
True,
| True,
True,
True,
True,
True,
True,
True,
True,
True,
True... |
tos-kamiya/agec | src/_version_data.py | Python | mit | 31 | 0.064516 | #codin | g: utf-8
VERSI | ON = "2.0" |
maljac/odoo-addons | account_voucher_withholding/models/account_voucher_withholding.py | Python | agpl-3.0 | 2,439 | 0.00041 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api, _
import ... | ates={'draft': [('readonly', False)]},
)
date = fields.Date(
'Date',
required=True,
readonly=True,
states={'draft': [('readonly', False)]},
default=fields.Date.context_today,
)
state = fields.Selection([
('draft', 'Draft'),
('availa... | True,
track_visibility='onchange',
)
tax_withholding_id = fields.Many2one(
'account.tax.withholding',
string='Withholding',
readonly=True,
states={'draft': [('readonly', False)]},
)
comment = fields.Text(
'Additional Information',
)
amo... |
thomasrstorey/recipesfordisaster | actions/dice.py | Python | mit | 9,680 | 0.016529 | '''
chop.py
Takes a list of input ingredient names. Chops each ingredient, and adds the
resulting model to the current blend or a new blend
Thomas Storey
2016
'''
import sys
import argparse
import bpy
import numpy as np
import os
import bmesh
from math import *
from mathutils import *
import random
def createMesh(... | (mod)
if len(dup.data.vertices) <= 0:
# if after modifier, duplicate has zero verts, delete it
deleteObject(dup)
else:
dups.appen | d(dup)
set_uvs(dup.data)
# delete cells
deleteObject(cell)
return dups
def addGroundPlane(obj):
faces = ((0,3,2,1),(0,1,5,4),(1,2,6,5),
(3,7,6,2),(0,4,7,3),(4,5,6,7))
(l, w, h) = (obj.dimensions.x, obj.dimensions.y, obj.dimensions.z)
po = (obj.bound_box[0][0]+(l*0... |
sveetch/crispy-forms-foundation | tests/conftest.py | Python | mit | 957 | 0 | """
Some fixture methods
"""
import os
import pytest
from crispy_forms.helper import FormHelper
from tests.utils import get_rendered_template, render_attempted_output
@pytest.fixture(scope='session')
def output_test_path(pytestconfig):
"""Return absolute path to test outputs directory"""
return os.path.join... | ms=[
"foundation-6"
])
def helper(request):
"""
Parametrized fixture to return helper configured for a template pack
"""
helper = Fo | rmHelper()
helper.template_pack = request.param
return helper
|
ares/robottelo | tests/foreman/cli/test_repository.py | Python | gpl-3.0 | 79,190 | 0.000051 | # -*- encoding: utf-8 -*-
"""Test class for Repository CLI
:Requirement: Repository
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: CLI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_alphanumeric, gen_string
from robottelo import ssh
from robottelo.cl... | """
url = FAKE_5_YUM_REPO
for creds in valid_http_credentials(url_encoded=True):
url_encoded = url.format(creds['login'], creds['pass'])
with self.subTest(url):
new_repo = self._make_repository({
u'content-type': u'yum',
u... | rtEqual(new_repo['content-type'], u'yum')
@tier1
def test_positive_create_with_download_policy(self):
"""Create YUM repositories with available download policies
:id: ffb386e6-c360-4d4b-a324-ccc21768b4f8
:expectedresults: YUM repository with a download policy is created
:Case... |
mhl/yournextmp-popit | mysite/urls.py | Python | agpl-3.0 | 673 | 0.002972 | import sy | s
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('candidates.ur... | BUG or ('test' in sys.argv):
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
enixdark/im-r-e-d-i-s | flask-cook/migrations/versions/399106d8a6ad_.py | Python | mit | 1,071 | 0.014006 | """empty message
Revision ID: 399106d8a6ad
Revises: None
Create Date: 2015-03-06 03:55:19.157958
"""
# revision identifiers, used by Alembic.
revision = '399106d8a6ad'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... | eyConstraint('id')
)
op.create_table('product',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=255), nullable=True),
sa.Column('price', sa.Float(), nullable=True),
sa.Column('category_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['category_id'... |
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('product')
op.drop_table('category')
### end Alembic commands ###
|
barak/autograd | autograd/util.py | Python | mit | 4,829 | 0.005384 | from __future__ import absolute_import
from __future__ import print_function
import autograd.numpy as np
import itertools as it
from autograd.core import grad, safe_type
from copy import copy
from autograd.numpy.use_gpu_numpy import use_gpu_numpy
from autograd.container_types import ListNode, TupleNode
from builtins im... | {A}.\nnumeric is:\n{B}.".format(A - B, A=A, B=B)
def check_grads(fun, *args):
if not args:
raise Exception("No args given")
exact = tuple([grad(fun, i)(*args) for i in range(len(args))])
numeric = nd(fun, *args)
check_equivalent(exact, numeric)
def to_scalar(x):
| if isinstance(x, list) or isinstance(x, ListNode) or \
isinstance(x, tuple) or isinstance(x, TupleNode):
return sum([to_scalar(item) for item in x])
return np.sum(np.real(np.sin(x)))
def quick_grad_check(fun, arg0, extra_args=(), kwargs={}, verbose=True,
eps=EPS, rtol=RTOL, at... |
jurihock/lilyfrog | LilyFrog.py | Python | gpl-3.0 | 249 | 0 | from PyQt4 import QtCore
from PyQt4.QtGui i | mport QApplication
import sys
from GUI import MainWindow
if __name__ == '__main__':
application = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(application. | exec_())
|
akrause2014/registry | test/__init__.py | Python | apache-2.0 | 636 | 0.001572 | # Co | pyright (c) The University of Edinburgh 2014
#
# 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 ... | either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
The core packages for Dispel4Py.
'''
|
SINGROUP/pycp2k | pycp2k/classes/_restart13.py | Python | lgpl-3.0 | 733 | 0.002729 | from pycp2k.inputsection import InputSection
from ._each396 import _each396
class _restart13(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
s... | s | elf._subsections = {'EACH': 'EACH'}
self._attributes = ['Section_parameters']
|
cheynepierce/PythonSfdcCanvasQuickStart | runserver.py | Python | mit | 244 | 0.012295 | imp | ort os
from canvas import app
if __name__ == '__main__':
#if we're running on Heroku, Heroku will set an environment variable containing the correct port
port = int(os.environ.get('PO | RT', 5000))
app.run(host='0.0.0.0', port=port) |
adamrehn/docker-script | test.py | Python | mit | 268 | 0.007463 | #!/usr/bin/env docker-script
#!python:latest python
import os, sys
details = os.uname()
print('Uname: ', details.sysname, details.release, details.machine)
print('Guest CWD:', os.getcwd())
print('Host CWD: ', os.environ['HOST_CWD'])
print('argv: | ', sys | .argv)
|
usig/normalizador-amba | tests/NormalizadorDireccionesAMBACalleYCalleTestCase.py | Python | mit | 3,432 | 0.004975 | # cod | ing: UTF-8
import unittest
from usig_normalizador_amba.NormalizadorDireccionesAMBA import NormalizadorDireccionesAMBA
from usig_normalizador_amba.Direccion import Direccion
from usig_normalizador_amba.Errors import ErrorCruceInexistente, ErrorCalleInexistente
from usig_normalizador | _amba.settings import CALLE_Y_CALLE
from tests.test_commons import cargarCallejeroEstatico
class NormalizadorDireccionesAMBACalleYCalleTestCase(unittest.TestCase):
partidos = ['hurlingham', 'ituzaingo', 'jose_c_paz', 'la_matanza', 'san_isidro', 'san_miguel']
nd = NormalizadorDireccionesAMBA(include_list=part... |
samrushing/irken-compiler | util/run_tests_py.py | Python | bsd-2-clause | 4,100 | 0.013415 | #
# run all the regression tests
#
# [or, you can request specific ones by giving their names on the command line]
#
import sys
import compile
import os
import subprocess
import context
def run_test (cmd, *args):
cmd = PJ ('tests', cmd)
p = subprocess.Popen ([cmd] + list(args), stdout=subprocess.PIPE)
out... | t
run_test ('t_dump_image')
# load the image and run it
exp0 = run_test ('t_dump_image','-l')
exp1 = open ('tests/t_dump_image.exp').read()
assert (exp0 == exp1)
def test_t2 | 1():
out = run_test ('t21')
exp = open ('gc.c').read()
# make sure the first part matches the contents of gc.c
assert (out[:len(exp)] == exp)
# the chars are too hard to tests for, and unlikely to be wrong.
# should really make a separate char test.
def test_t22():
out = run_test ('t22')
... |
GadgetSteve/metrics | metrics/mccabe.py | Python | mit | 1,278 | 0.001565 | """Compute McCabe's Cyclomatic Metric.
This routine computes McCabe's Cyclomatic metric for the whole file.
"""
from metricbase import MetricBase
mccabe_keywords = [
'assert',
'break',
'continue',
'elif',
'else',
'for',
'if',
'while']
class McCabeMetric(MetricBase):
"""Comp... | self.reset()
def reset(self):
"""Reset metric counter."""
self.metrics = {'mccabe': 0}
def process_token(self, tok):
"""Increment number of decision points in function."""
#if tok and tok.te | xt in mccabe_keywords:
if (tok[0][0] == 'Keyword') and tok[1] in mccabe_keywords:
self.metrics['mccabe'] += 1
def display_header(self):
"""Display header for McCabe Cyclomatic Complexity """
print 'McCabe',
def display_separator(self):
"""Display separator for McCab... |
e-gun/HipparchiaBuilder | builder/lexica/repairperseuscitations.py | Python | gpl-3.0 | 22,053 | 0.02998 | # -*- coding: utf-8 -*-
"""
HipparchiaBuilder: compile a database of Greek and Latin texts
Copyright: E Gunderson 2016-21
License: GNU GENERAL PUBLIC LICENSE 3
(see LICENSE in the top level directory of the distribution)
"""
import re
from string import punctuation
try:
from builder.dbinteraction.connection imp... | 'phi,0134': 'Terence'}
citationfinder = re.compile(r'(<cit>.*?</cit>)')
punct = re.compile('[{s}]'.format(s=re.escape(punctuation)))
locusfinder = re.compile(r'</author>\s(.*?)\s(.*?)</bibl></cit>')
quotefinder = re.compile(r'<quote lang="la">(.*?)</quote>')
querytempl | ate = """
SELECT level_00_value FROM {t}
WHERE wkuniversalid = %s and stripped_line ~* %s
"""
citations = re.findall(citationfinder, entrytext)
for au in authorstofix:
adb = re.sub(r'phi,', 'lt', au)
targetcitation = re.compile(r'<bibl n="Perseus:abo:{a},(.. |
kincl/oncall | manage.py | Python | gpl-3.0 | 1,127 | 0.004437 | from flask import url_for
from flask_script import Manager
from main import create_app
from database import db
from api.models import User
app = create_app()
manager = Manager(app)
@manager.command
def init_db():
''' Initialize the database '''
with app.test_request_context():
db.create_all()
@manag... | rule.endpoint, **options)
line = urllib.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, url))
output.append(line)
for lin | e in sorted(output):
print line
if __name__ == "__main__":
manager.run()
|
Spe3do/benchmark | src/server/speedtest_cli.py | Python | apache-2.0 | 16,640 | 0.000661 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2013 Matt Martz
# 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/lic... | 'client': getAttributesByTagName(root, 'client'),
'times': getAttributesByTagName(root, 'times'),
'download': getAttributesByTagName(root, 'download'),
'upload': getAttributesByTagName(root, 'upload')}
del root
return config
def closestServers(client, all=False):
"""Determine th... | en('http://www.speedtest.net/speedtest-servers.php')
serversxml = uh.read()
if int(uh.code) != |
brclark-usgs/flopy | flopy/mt3d/mtadv.py | Python | bsd-3-clause | 16,549 | 0.000242 | import sys
from ..pakbase import Package
class Mt3dAdv(Package):
"""
MT3DMS Advection Package Class.
Parameters
----------
model : model object
The model object (of type :class:`flopy.mt3d.mt.Mt3dms`) to which
this package will be added.
mixelm : int
MIXELM... | even if PERCEL > 1,
advection may not be more than one cell's length at most model
locat | ions.
For the explicit finite-difference or the third-order TVD scheme,
PERCEL is also a stability constraint which must not exceed one and
will be automatically reset to one if a value greater than one is
specified.
mxpart : int
MXPART is the maximum total number of mo... |
acamposruiz/quecoins | test/example_thirdparty/forms.py | Python | bsd-2-clause | 148 | 0.006757 | from a | ccount.forms import SignupForm
from captcha. | fields import CaptchaField
class SignupFormWithCaptcha(SignupForm):
captcha = CaptchaField() |
zasdfgbnm/qutip | qutip/about.py | Python | bsd-3-clause | 3,318 | 0.000904 | # This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
... | ibutions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors... | THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIREC... |
skosukhin/spack | var/spack/repos/builtin/packages/libemos/package.py | Python | lgpl-2.1 | 2,991 | 0.000669 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is pa | rt of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our | notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY ... |
STLInspector/STLInspector | STLInspector/frontend/ProjectList.py | Python | apache-2.0 | 4,110 | 0.001703 | import re
import os
import json
from os.path import join, realpath, dirname
from .Project import Project
# maintains the project list and all open projects
class ProjectList:
# datadir should point to the dir
# where files are saved and loaded
def __init__(self, datadir):
self.openProjec... | self.datadir = datadir
# readonly path for projects, used to show example projects
self.readonlydatadir = join(realpath(dirname(__file__)), 'data')
self.suffix = '.stlinspector'
# returns a list containing dicts with
# id, title, and coverage of available projects
def list... | d: [(f, os.path.join(d, f)) for f in os.listdir(d)]
files = getfiles(self.datadir) + getfiles(self.readonlydatadir)
# list of already listed ids
listedids = []
for f, file in files:
if not os.path.isfile(file):
continue
... |
etalab/udata | udata/harvest/notifications.py | Python | agpl-3.0 | 774 | 0 | from udata.features.notifications.actions import notifier
from .models import HarvestSource, VALIDATION_PENDING
import logging
log = logging.getLogger(__name__)
@notifier('validate_harvester')
def validate_harvester_notifications(user):
| '''Notify admins about pending harvester validation'''
if not user.sysadmin:
return []
notifications = []
# Only fetc | h required fields for notification serialization
# Greatly improve performances and memory usage
qs = HarvestSource.objects(validation__state=VALIDATION_PENDING)
qs = qs.only('id', 'created_at', 'name')
for source in qs:
notifications.append((source.created_at, {
'id': source.id,
... |
lukius/algo2-fiuba-tp1-2q13 | judge/exception.py | Python | mit | 1,901 | 0.008966 | # -*- coding: utf-8 -*-
class GameException(Exception):
def get_army_name(self):
return self.army_name
def set_army_name(self, army_name):
self.army_name = army_name
class ValidationException(GameException):
def __init__(self, rule):
self.rule = rule
se... | ameException):
def __init__(self, text):
self.text = text
def __str__(self):
army_name = self.get_army_name()
return '%s: formato de salida incorrecto (%s)' % (army_name,
self.text.strip())
class Missi | ngFileException(GameException):
def __init__(self, army_name, program, input_filename):
self.army_name = army_name
self.program = program
self.input_filename = input_filename
def __str__(self):
string = 'archivo de salida inexistente al ejecutar ' +\
'%s -i... |
julianjon/Cellule | appli/scripts/Actions.py | Python | gpl-2.0 | 7,632 | 0.037998 | import Cellule
import FileBrowser
from PyQt4 import Qt
class Action( Qt.QAction ):
def __init__( self, text, keySequence, description, iconName, parent ):
Qt.QAction.__init__( self, parent )
self.setText( text )
if keySequence: self.setShortcut( Qt.QKeySequenc... | lSampler" ] = NodeAction( 'cellSampler', None, 'Output basic cell geometry informations', None, mainWindowSIP )
mainWindow.nodes[ "surfaceShader" ] = NodeAction( 's | urfaceShader', None, 'Output shading informations to the assigned surface', None, mainWindowSIP )
mainWindow.nodes[ "colorGradient" ] = NodeAction( 'colorGradient', 'G', 'Ouput interpolation between input colors', None, mainWindowSIP )
mainWindow.nodes[ "decomposeC... |
GreenleafLab/NucleoATAC | nucleoatac/cli.py | Python | mit | 15,857 | 0.027685 | ###-----------Import modules---------------####
import argparse
import nucleoatac.Magic
from nucleoatac import __version__
def nucleoatac_main(args):
"""The Main function for calling nucleoatac
"""
#Parse options...
call = args.call
parser = nucleoatac_parser()
if call == "occ":
from ... | '--out',args.out])
nfr_args = parser.parse_args(['nfr','--bed', args.bed, '--occ_track', args.out + ' | .occ.bedgraph.gz', '--calls',
args.out + '.nucmap_combined.bed.gz','--out',args.out, '--fasta', args.fasta,
'--pwm', args.pwm , '--bam', args.bam])
from nucleoatac.run_occ import run_occ
from nucleoatac.run_vprocess import... |
twerkmeister/iLID | preprocessing/audio/melfilterbank.py | Python | mit | 1,553 | 0.01159 | import os, sys
dirname = os.path.dirname(__file__)
lib_path = os.path.join(dirname, "python_speech_features")
sys.path.append(lib_path)
import features as speechfeatures
import numpy as np
def filter(samplerate, signal, winlen=0.02, winstep=0.01,
nfilt=40, nfft=512, lowfreq=100, highfreq=5000, preemph=0.9... | terbank energies
"""
feat, energy = speechfeatures.fbank(np.array(signal), samplerate, winlen=winlen,winstep=winstep,
nfilt=nfilt, nfft=nfft, lowfreq=lowfreq, highfreq=highfreq, preemph=preemph)
return np.swapaxes(feat,0,1)
def logfilter(samplerate, | signal, *args, **kwargs):
"""extracts log mel filterbank energies from a given signal
Args:
samplerate (int): samples taken per second
signal(1d numpy array): sample values
*args: piped through to filter
**kwargs: piped thought to filter
Returns:
feat(2d numpy array): logarithm of filterban... |
tensorflow/federated | tensorflow_federated/python/simulation/baselines/task_data_test.py | Python | apache-2.0 | 18,038 | 0.005488 | # Copyright 2021, The TensorFlow Federated Authors.
#
# 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... | _list, all_client_datasets_as_lists)
def test_sample_train_clients_returns_preprocessed_train_datasets(self):
preprocess_fn = lambda x: x.map(lambda y: 2 * y)
train_data = create_client_data(10)
test_task_data = task_data.BaselineTaskDatasets(
train_data=train_data,
train_preprocess_fn=pr... | cess_train_data.create_tf_dataset_for_client(x)
for x in preprocess_train_data.client_ids
]
all_client_datasets_as_lists = [
list(ds.as_numpy_iterator()) for ds in all_client_datasets
]
sampled_client_datasets = test_task_data.sample_train_clients(num_clients=5)
for ds in sampled_cli... |
trondhindenes/ansible | test/units/modules/network/f5/test_bigip_trunk.py | Python | gpl-3.0 | 4,616 | 0.00065 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# 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
import os
import json
import pytest
import sys
from nose.plugins.skip i... |
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pas | s
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
name='foo',
interfaces=[
'1.3', '1.1'
],
link_selection_policy='auto',
frame_distribution_has... |
jmtyszka/mrgaze | mrgaze/calibrate.py | Python | mit | 16,369 | 0.005132 | #!/usr/bin/env python
#
# Gaze tracking calibration
# - use calibration video heatmap and priors
#
# AUTHOR : Mike Tyszka
# PLACE : Caltech
# DATES : 2014-05-15 JMT From scratch
#
# This file is part of mrgaze.
#
# mrgaze is free software: you can redistribute it and/or modify
# it under the terms of the GNU Ge... | published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mrgaze is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even t | he 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 mrgaze. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2014 California Institute... |
Openeight/enigma2 | lib/python/Components/SystemInfo.py | Python | gpl-2.0 | 11,520 | 0.006337 | from os import path
import re
from enigma import Misc_Options, eDVBCIInterfaces, eDVBResourceManager, eGetEnigmaDebugLvl
from Components.Console import Console
from Tools.Directories import SCOPE_PLUGINS, fileCheck, fileExists, fileHas, pathExists, resolveFilename
from Tools.HardwareInfo import HardwareInfo
from boxb... | = model in ("vusolo4k", "et8500")
SystemInfo["Has24hz"] = fileCheck("/proc/stb/video/videomode_24hz")
SystemInfo["Has2160p"] = fileHas("/proc/stb/video/videomode_preferred", "2160p50")
SystemInfo["HasHDMIpreemphasis"] = fileCheck("/proc/stb/hdmi/preemphasis")
SystemInfo["HasColorimetry"] = fileCheck("/proc/stb/video/h... | Info["HasHdrType"] = fileCheck("/proc/stb/video/hdmi_hdrtype")
SystemInfo["HasHDMI-CEC"] = HardwareInfo().has_hdmi() and fileExists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/HdmiCEC/plugin.pyo")) and (fileExists("/dev/cec0") or fileExists("/dev/hdmi_cec") or fileExists("/dev/ |
mozilla/verbatim | vendor/lib/python/raven/transport/threaded.py | Python | gpl-2.0 | 3,097 | 0.000323 | """
raven.transport.threaded
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import atexit
import logging
import time
import threading
import os
from Queue import Queue
from raven.transport.base import HTTPTransport... | %s pend | ing error messages" % size
print "Waiting up to %s seconds" % timeout
if os.name == 'nt':
print "Press Ctrl-Break to quit"
else:
print "Press Ctrl-C to quit"
self.stop(timeout=timeout)
def start(self):
"""
Starts the ta... |
eriser/marsyas | scripts/chord-detection/scripts/AccumulateChroma.py | Python | gpl-2.0 | 3,906 | 0.00768 | #!/usr/bin/env python
from math import sqrt
import argparse
from marsyas import *
from os import path, mkdir, makedirs
majTriad = [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0]
augTriad = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]
minTriad = [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0]
dimTriad = [1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0]
noChord... | a = [correlate(chroma, majTriad), correlate(chroma, augTriad),
# correlate(chroma, minTriad), correlate(chroma, dimTriad)]
a = [correlate(chroma, majTriad), correlate(chroma, minTriad), co | rrelate(chroma, dimTriad)]
if max(a) > maxCor:
maxCor = max(a)
if a.index(maxCor) == 0:
maxChord = chordInd[i] + ":maj"
elif a.index(maxCor) == 1:
maxChord = chordInd[i] + ":min"
elif a.index(maxCor) == 2:
maxChord =... |
egabancho/invenio | invenio/modules/workflows/testsuite/test_utils.py | Python | gpl-2.0 | 2,691 | 0.004831 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2014 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... | for utility functions."""
from __future__ import absolute_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite
class HoldingPenUtilsTest(InvenioTestCase):
"""Test basic utility functions for Holding Pen."""
def test_get_previous_next_objects_empty(self):
"""Test th... | of prev, next object ids from the list."""
from invenio.modules.workflows.utils import get_previous_next_objects
objects = []
self.assertEqual(get_previous_next_objects(objects, 1), (None, None))
def test_get_previous_next_objects_not_there(self):
"""Test the getting of prev, next ... |
LosFuzzys/CTFd | CTFd/forms/pages.py | Python | apache-2.0 | 983 | 0.002035 | from wtforms import (
BooleanField,
HiddenField,
MultipleFileField,
StringField,
TextAreaField,
)
from wtforms.validators import InputRequired
from CTFd.forms import BaseForm
class PageEditForm(BaseForm):
title = StringField(
"Title", description="This is the title shown on the naviga... | ringField(
"Route",
description="This is the URL route that your page will be at (e.g. /page). You can also enter links to link to that page.",
)
draft = BooleanField("Draft")
hidden = BooleanField("Hidden")
auth_required = BooleanField("Authenti | cation Required")
content = TextAreaField("Content")
class PageFilesUploadForm(BaseForm):
file = MultipleFileField(
"Upload Files",
description="Attach multiple files using Control+Click or Cmd+Click.",
validators=[InputRequired()],
)
type = HiddenField("Page Type", default="pa... |
pablodanielrey/scripts | docker/src/libs/wamp_utils/WampComponent.py | Python | gpl-3.0 | 694 | 0.002882 | from autobahn.wamp.types import CallOptions, RegisterOptions
from autobahn.a | syncio.wamp import ApplicationSession, ApplicationRunner
class WampComponent(ApplicationSession):
def getLogger(self):
return logging.getLogger('{}.{}'.format(self.__module__, self.__class__.__name__))
def getRegisterOptions(self):
return RegisterOptions(details_arg='details')
"""
de... | ApplicationSession.__init__(self, config)
"""
async def onJoin(self, details):
logging.info('Registrando procesos')
results = await self.register(self, options=self.getRegisterOptions())
results = await self.subscribe(self)
|
korrelate/genie | genie-web/src/test/python/utils/eureka.py | Python | apache-2.0 | 4,342 | 0.005988 | ##
#
# Copyright 2013 Netflix, 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 l... | estUrl = self._eurekaUrl + '/' + appName
req = urllib2.Request(url=restUrl)
| req.add_header('Accept', 'application/json')
assert req.get_method() == 'GET'
response = urllib2.urlopen(req)
# parse the json response
json_str = response.read()
json_obj = json.loads(json_str)
# get a list of all instances
instances = json_obj['appli... |
chirpradio/chirpradio-machine | chirp/common/id3_header.py | Python | apache-2.0 | 3,994 | 0.000751 | """
Code related to ID3 frames.
Note that this code does let you parse ID3 frames; if you need to do
that you should use mutagen, not this code. This code is strictly
designed to create simple ID3 text frames and locate ID3 frames (which
are treated as opaque binary blobs) inside a data stream.
"""
import struct
imp... | .
size_str = mutagen.id3.BitPaddedInt.to_str(len(value_encoded)+2, width=4)
return "".join([frame_tag,
size_str,
"\0\0", # Flags are all 0
"\x03", # 3 = utf-8 encoding
value_encoded,
"\0", # The utf-8 string m... | f text frames.
Args:
tag_list: A sequence of (tag_name, tag_value) pairs. tag_name should
be a 4-character string starting with "T". tag_value should be
a unicode string.
Returns:
A string containing an ID3v2.4 tag that encoded the passed-in tags.
"""
assert len(tag_list)... |
mfouesneau/faststats | faststats/interpolate/bary.py | Python | mit | 7,536 | 0.001725 | """
Rbf - Radial basis functions for interpolation/smoothing scattered Nd data. A
radial basis function (RBF) is a real-valued function whose value depends only
on the distance from the origin.
Rbf are typically used to build up function approximations of the form:
$ y(x) = \sum_{i=1}^N w_i \, \phi(||x - x_i||) ... | each
point in x2.
"""
if len(x1.shape) == 1:
x1 = x1[np.newaxis, :]
if len(x2.shape) == 1:
x2 = x2[np.newaxis, :]
x1 = x1[..., :, np.newaxis]
x2 = x2[..., np. | newaxis, :]
return self.norm(x1, x2)
def __call__(self, *args):
args = [np.asarray(x) for x in args]
if any([x.shape != y.shape for x in args for y in args]):
raise ValueError("Array lengths must be equal")
shp = args[0].shape
self.xa = np.asarray([a.flatten()... |
Distrotech/reportlab | tests/test_platypus_preformatted.py | Python | bsd-3-clause | 8,797 | 0.006934 | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
"""Tests for context-dependent indentation
"""
__version__='''$Id: test_platypus_indents.py 3660 2010-02-08 18:17:33Z damian $'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation
setOutDir(__name_... | ize)
kind = 0
L=f.text.split('\\n')
for l in L:
currentWidth = stringWidth(l,fontName,fontSize | )
requiredWidth = max(currentWidth,requiredWidth)
extraSpace = maxWidth-currentWidth
lines.append((extraSpace,l.split(' '),currentWidth))
lineno = lineno+1
maxWidth = lineno<len(maxWidths) and maxWidths[lineno] or max... |
paplorinc/intellij-community | python/testData/inspections/PyUnresolvedReferencesInspection/MockPatchObject/a.py | Python | apache-2.0 | 82 | 0.02439 | fro | m mock import patch
print(patch.object)
import mock
print(mock.patch.obj | ect) |
davidhwyllie/bugMat | python_comparator_code.py | Python | lgpl-3.0 | 2,568 | 0.065421 | ## Script that takes in a list of fastas and generates summaries of their differences
# this is python implementation to which bugMat was compared in our publication.
# code by Drs Madeleine Cule and David Eyre, Oxford University
import sys, re, os, gzip
from Bio impo | rt SeqIO
from itertools import izip
bases = "ACGT"
def get_distance( seq1, seq2 ):
'''Function to calculate the [Hamming] distance between two sequences'''
return sum(True for c1, c2 in izip( seq1, seq2 ) if c1!=c2 and c1 in bases and c2 in bases )
if __name__=="__main__":
## | Parse command line arguments
listoffasta, outname_prefix = sys.argv[1:]
outname = outname_prefix
## Read in all the sequences, and replace the id with the required nicename
seqlist = []
with open( listoffasta ) as fp:
for line in fp:
nicename, fapath = line.strip().split()
if (os.path.exists(... |
karlinjf/ChromiumXRefs | third_party/codesearch/__main__.py | Python | apache-2.0 | 7,908 | 0.002529 | # Copyright 2017 The Chromium Authors.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd.
"""Command line interface to Chromium Code Search.
Currently emits JSON formatted responses from the Chromium Cod... |
file_info_command.add_argument(
'--outline',
'-o',
help='Get outlining metadata.',
default=False,
action='store_true')
file_info_command.add_argument(
'--html', '-H', help='Get HTML.', default=False, action='store_true')
file_info_command.add_argument(
'--folding',
'-f',
help='Get f... | ,
default=False,
action='store_true')
file_info_command.set_defaults(
func=lambda cs, a: cs.SendRequestToServer(
CompoundRequest(
file_info_request=[
FileInfoRequest(
file_spec=cs.GetFileSpec(a.path),
fetch_html_content=a.html,
... |
karthikeyan5/hexa | hexa-beta/messageScreen.py | Python | mit | 383 | 0.044386 | #screen = 0 vendor,screen | = 1 customer.
import GLCD as g
fontWidth = 6
lineLength = 21
def msg(m = 'Error!!!',linenum = 7):
#vendor Screen
g.clearDisplay(0)
string = ("{:^%d}" % lineLength).format(m)
g.displayText(string,linenum,0,0)
#User Screen
g.clearDisplay(1)
string = ("{:^%d}" % li | neLength).format(m)
g.displayText(string,linenum,0,1)
|
opixido/palabre | setup.py | Python | gpl-2.0 | 879 | 0.047836 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from distutils.core import setup
setup(name = "palabre",
version = "0.6b",
description = "XML Socket Python Server",
long_description = "Flash XML Multiuser Socket Server",
author = "Célio Conort",
author_email = "palabre-dev@lists... | xt"]),
("./",["AUTHORS","COPYING","MANIFEST","MANIFEST.in","PKG-INFO"]),
("/usr/local/share/doc/palabre", ["doc/README.txt | "])
]
)
|
cuemacro/chartpy | chartpy/twitter.py | Python | apache-2.0 | 1,894 | 0.009504 | from __future__ import division
__author__ = 'saeedamen' # Saeed Amen
#
# Copyright 2016 Cuemacro
#
# 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
#
... | R CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and limitations under the License.
#
"""
Twitter
Tweet from Python using Twython library
"""
from twython import Twython
f | rom chartpy.chartconstants import ChartConstants
cc = ChartConstants()
class Twitter:
def __init__(self, *args, **kwargs):
pass
def set_key(self, TWITTER_APP_KEY, TWITTER_APP_SECRET, TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_TOKEN_SECRET):
self.twitter = Twython(TWITTER_APP_KEY, TWITTER_APP_SECRET,... |
letouriste001/SmartForest_2.0 | python3.4Smartforest/lib/python3.4/site-packages/setuptools/py31compat.py | Python | mit | 1,639 | 0.002441 | import sys
import unittest
__all__ = ['get_config_vars', 'get_path']
try:
# Python 2.7 or >=3.2
from sysconfig import get_config_vars, get_path
except ImportError:
| from distutils.sysconfig import get_config_vars, get_python_lib
def get_path(name):
if name not in ('platlib', 'purelib'):
raise ValueError("Name must be purelib or platlib")
re | turn get_python_lib(name=='platlib')
try:
# Python >=3.2
from tempfile import TemporaryDirectory
except ImportError:
import shutil
import tempfile
class TemporaryDirectory(object):
"""
Very simple temporary directory context manager.
Will try to delete afterward, but will a... |
sora7/listparse | OLD/CertainProg2/src/listparse/parsers/wa.py | Python | gpl-2.0 | 167 | 0.017964 | '''
Created on 24.05.2014
@author: | alex
'''
class Person(object):
'''
classdocs |
'''
def __init__(self):
'''
Constructor
''' |
encode/starlette | starlette/formparsers.py | Python | bsd-3-clause | 8,747 | 0.000915 | import typing
from enum import Enum
from urllib.parse import unquote_plus
from starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart import parse_options_header
except ImportError: # pragma: nocover
parse_options_header = None
multipart = None
... | ultiPartMessage.HEADERS_FINISHED:
disposition, options = parse_options_header(content_disposition)
field_name = _user_safe_decode(options[b"name"], charset)
if b"filename" in options:
filename = _user_safe_decode(options[b"filename"], c... | headers=Headers(raw=item_headers),
)
else:
file = None
elif message_type |
mdn/browsercompat | mdn/tests/__init__.py | Python | mpl-2.0 | 25 | 0 | """Te | sts for mdn a | pp."""
|
xunkai55/lifenote | lifenote.py | Python | gpl-2.0 | 14,796 | 0.006404 | # -*- coding: UTF-8 -*-
from __future__ import with_statement
from __future__ import division
import pyejdb
import os.path
from datetime import datetime
from datetime import timedelta
from datetime import date as pydate
import json
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
# ==================== basic ... | )
box = QMessageBox(self)
box.setText(u"成功添加模板")
box.exec_()
self.done(1)
return
else:
| box = QMessageBox(self)
box.setText(u"模板书写错误")
box.setDetailedText(content["_ERROR"])
box.exec_()
# ------------------------ Main GUI --------------------------
class MyGui(QtWidgets.QWidget):
def __init__(self, parent = None):
QtW... |
paulsmith/geodjango | django/contrib/localflavor/jp/forms.py | Python | bsd-3-clause | 1,252 | 0.002396 | """
JP-specific Form helpers
"""
from django.core import validators
from django.newforms import ValidationError
from django.utils.translat | ion import ugettext_lazy as _
from django.newforms.fi | elds import RegexField, Select
class JPPostalCodeField(RegexField):
"""
A form field that validates its input is a Japanese postcode.
Accepts 7 digits, with or without a hyphen.
"""
default_error_messages = {
'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'),
}
... |
dynelight/kaos-scripts | build_script_templates/monster_room_linker/monsters_room.py | Python | unlicense | 846 | 0.007092 | # Room-Monster linker
import csv
import os
import sys
import fileinput
csv_file = str(sys.argv[1])
rooms_folder = str(sys.argv[2])
with open(csv_file, 'r') as f:
reader = csv.reader(f)
# Iteration of each row in csv
line_num = 0
for row in reader:
# Ignores header
if line_num != 0... | for count, line in enumerate(fileinput.input(filename, inplace=True)):
if count >= 83 and count <= 100 | : # Python counts from 0
line = '"' + row[row_inside] + '"' + "\r\n"
row_inside += 1
sys.stdout.write(line)
line_num += 1 |
JJGO/ProjectEuler | euler/primes.py | Python | gpl-3.0 | 5,689 | 0.006855 | import time
import numpy as np
"""
Module for prime related computations
Includes:
Infinite prime iterator
Thresholded prime iterator
Primality test
Prime Factorization
Divisor Computation
Divisor Cardinality
"""
| class EratosthenesSieve(object):
"""
Dynamic Sieve of Eratosthenes for prime related computations
Attributes:
threshold: current size of the sieve
primes: list with known prime numbers
table: sieve table. 0:Composite 1:Prime
rate: rate of expansion of the sie... | 00,rate=10,sqrt_thr=False):
"""
Dynamic Eratosthenes Sieve for prime generation and factorization
Args:
init_thr: initial size of the sieve table
rate: rate of expansion of the sieve table
sqrt_thr: if True square root of init_thr is used instead
... |
CTPUG/wafer | wafer/registration/urls.py | Python | isc | 392 | 0 | from django.conf. | urls import include, url
from wafer.registration.views import (
github_login, gitlab_login, redirect_profile)
urlpatterns = [
url(r'^profile/$', redirect_profile),
url(r'^github-login/$', github_login),
url(r'^gitlab | -login/$', gitlab_login),
url(r'', include('registration.backends.default.urls')),
url(r'', include('registration.auth_urls')),
]
|
thiagof/treeio | treeio/news/south_migrations/0001_initial.py | Python | mit | 413 | 0 | # enc | oding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
# encoding: 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):
pass
def ... | |
AsgerPetersen/QGIS | python/plugins/processing/algs/lidar/lastools/lasvalidatePro.py | Python | gpl-2.0 | 2,511 | 0.001195 | # -*- coding: utf-8 -*-
"""
***************************************************************************
lasvalidatePro.py
---------------------
Date : October 2014
Copyright : (C) 2014 by Martin Isenburg
Email : martin near rapidlasso point com
************... | oup = self.trAlgorithm('LAStools Production')
self.addParametersPointInputFolderGUI()
self.addParameter(ParameterBoolean(lasvalidatePro.ONE_REPORT_PER_FILE,
self.tr("generate one '*_LVS.xml' report per file"), False))
self.addOutput(OutputFile(lasvalida... | UI()
def processAlgorithm(self, progress):
commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "lasvalidate")]
self.addParametersPointInputFolderCommands(commands)
if self.getParameterValue(lasvalidatePro.ONE_REPORT_PER_FILE):
commands.append("-oxml")
else:
... |
lyudmill/python_training | data/groups.py | Python | apache-2.0 | 944 | 0.009534 | #Keeping data in .py file example
from model.group import Group
import ra | ndom
import string
|
testdata = [
Group(name="name1",header="header1", footer="footer1"),
Group(name="name2",header="header2", footer="footer2"),
Group(name="name3",header="header3", footer="footer3")
]
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + string.punctuation + " "*10
retu... |
raf-programmer/django-biblioteka | biblio/settings.py | Python | mit | 4,959 | 0.010891 | """
Django settings for biblio project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
from configurations import Configuration
# Build paths inside the project li... | key_file.write(key)
return key
path = os.path.join(base_dir, '.secret.key')
try:
secret_key = open(path).read()
assert secret_key, "Wrong secret key"
except (IOError, AssertionError):
secret_key = gen_key(path)
return secret_key
BASE_DIR = os.path.dirnam... | t development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_secret_key(BASE_DIR)
# SECURITY WARNING: don't run with debug turned on in production!
... |
QCaudron/iterated-inference-pipeline | model_builder/test_Cmodel.py | Python | gpl-3.0 | 8,782 | 0.012412 | from Cmodel import Cmodel
import unittest
import copy
class TestCmodel(unittest.TestCase):
def setUp(self):
m = {
'state': [{'id':'S'}, {'id':'I', 'tag': ['remainder', 'infectious']}, {'id': 'R'}],
'parameter': [{'id':'r0'}, {'id':'v'}, {'id':'l'}, {'id':'e'}, {'id':'d'}, {'id':'st... | c = {
'data': {},
'metadata': [{'id': 'mu_b'}, {'id': 'mu_d'}, {'id': 'N'}, {'id': 'prop'}]
}
##link elements needed for Cmodel
l = {
'observed': [
{'id': 'Prev', 'definition': ['I'], 'model_id': 'common'},
| {'id': 'SI', 'definition': ['S', 'I'], 'model_id': 'common'},
##we have to specify a rate to the incidence E->U as we only observed a subpart of this reaction
{'id': 'Inc_out', 'definition': [{'from':'I', 'to':'R'}, {'from':'E', 'to':'U', 'rate': 'mu_d'}], 'model_id': 'common'},
... |
TheAlgorithms/Python | web_programming/giphy.py | Python | mit | 562 | 0.001779 | #!/usr/bin/env python3
import requests
giphy_api_ | key = "YOUR API KEY"
# Can be fetched from https://developers.giphy.com/dashboard/
def get_gifs(query: str, api_key: str = giphy_api_key) -> list:
"""
Get a list of URLs of GIFs based on a given query..
"""
formatted_query = "+".join(query.split())
url = f"http://api.giphy.com/v1/gifs/search?q={fo... | = "__main__":
print("\n".join(get_gifs("space ship")))
|
githubutilities/gas | gas/interface.py | Python | apache-2.0 | 106 | 0.04717 | def run(*args, **kwargs):
_run(*args, **kwargs)
def | _run(task=None):
if task | is None:
return
task()
|
apache/bloodhound | trac/trac/db_default.py | Python | apache-2.0 | 14,109 | 0.003756 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2005 Daniel Lundin <daniel@edgewall.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http... | 'repos', 'rev', 'path', 'change_type'))[
Column('repos', type='int'),
Column('rev', key_size=20),
Column('path', key_size=255),
Column('node_type', size=1),
Column('change_type', size=1, key_size=2),
Column('base_path'),
| Column('base_rev'),
Index(['repos', 'rev'])],
# Ticket system
Table('ticket', key='id')[
Column('id', auto_increment=True),
Column('type'),
Column('time', type='int64'),
Column('changetime', type='int64'),
Column('component'),
Column('severity'),
... |
trunglq7/horizon | horizon/test/test_dashboards/dogs/puppies/panel.py | Python | apache-2.0 | 241 | 0 | from django.utils.translation import ugettext_lazy as _
import horizon
from horizon.test.test_dashboards.dogs import dashboard
class Puppies(horizon.Panel):
name = _("Puppies")
slug = "p | uppies"
dashboard.Dog | s.register(Puppies)
|
was4444/chromium.src | third_party/WebKit/Source/build/scripts/make_style_shorthands.py | Python | bsd-3-clause | 3,202 | 0.001562 | #!/usr/bin/env python
# Copyright (C) 2013 Intel Corporation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, thi... | thand.h.tmpl')
def generat | e_style_property_shorthand_h(self):
return {
'properties': self._properties,
}
if __name__ == '__main__':
in_generator.Maker(StylePropertyShorthandWriter).main(sys.argv)
|
tedlaz/pyted | tests/dbapi/logger.py | Python | gpl-3.0 | 684 | 0 | # -*- coding: utf-8 -*-
"""
author Ted Lazaros <tedlaz@gmail.com>
"""
import logging
# Log Levels
# ------------
# CRITICAL 50
# ERROR 40
# WARNING 30
# INFO 20
# DEBUG 10
# NOTSET 0
frm = "%(asctime)s %(module)s : %(levelname)s %(message)s"
# Initialize logging module, give basic formats and... | filename=' | koinoxrista.log')
# logging.basicConfig(filename='koinoxrista.log',level=logging.DEBUG)
# Get OpenShot logger and set log level
log = logging.getLogger('Koinoxrista')
log.setLevel(logging.DEBUG)
|
camradal/ansible | lib/ansible/modules/network/nxos/nxos_ip_interface.py | Python | gpl-3.0 | 23,930 | 0.000669 | #!/usr/bin/python
#
# 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 later version.
#
# Ansible is distribut... | Manages Layer 3 attributes for IPv4 and IPv6 interfaces.
extends_documentation_fragment: nxos
author:
- Jason Edelman (@jedelman8)
- Gabriele Gerbino (@GGabriele)
notes:
- Interface must already be a L3 port when using this module.
- Logical interfaces (po, loop, svi) must be created first.
- C(mas... | d.
options:
interface:
description:
- Full name of interface, i.e. Ethernet1/1, vlan10.
required: true
addr:
description:
- IPv4 or IPv6 Address.
required: false
default: null
mask:
description:
- Subnet mask for IPv4 or IPv... |
bretttegart/treadmill | lib/python/treadmill/cli/admin/diag.py | Python | apache-2.0 | 4,331 | 0 | """Reports memory utilization details for given container."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import click
from treadmill import psmem
from treadmill import cgutils
from treadmill import met... | smem processes."""
@staticmethod
def format(item):
"""Return pretty-formatted item."""
schema = [
('memory-type', None, None),
('value', None, None),
]
format_list = cli.make_list_to_table(schema, Fal | se)
return format_list(item)
def init():
"""Top level command handler.
"""
@click.group()
def diag():
"""Local node and container diagnostics.
"""
pass
@diag.command(name='psmem')
@click.option('--fast', is_flag=True, help='Disable statm/pss analysis.')
@... |
aissehust/sesame-paste-noodle | mlbase/gradient_optimizer.py | Python | bsd-3-clause | 3,630 | 0.008815 | import numpy as np
import theano
import theano.tensor as T
class GradientOptimizer:
def __init__(self, lr):
self.lr = lr
def __call__(self, cost, params):
pass
@property
def learningRate(self):
return self.lr
@learningRate.setter
def learningRate(self, i):
se... | self.epsilon = epsilon
def __call__(self, cost, params):
grads = T.grad(cost=cost ,wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = acc + g**2
updates.append((acc, acc_new))
| updates.append((p, p - self.lr * g / T.sqrt(acc_new + self.epsilon)))
return updates
|
noironetworks/neutron | neutron/agent/l3/ha_router.py | Python | apache-2.0 | 19,533 | 0 | # Copyright (c) 2015 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 ... | self.keepalived_manager.disable()
conf_dir = self.keepalived_manager.get_conf_dir()
shutil.rmtree(conf_dir)
def _get_keepalived_instance(self):
return self.keepalived_manager.config.get_instance(self.ha_vr_id)
def _get_primary_vip(self):
return self._get_keepalived_insta... | turn (HA_DEV_PREFIX + self.ha_port['id'])[:self.driver.DEV_NAME_LEN]
def ha_network_added(self):
interface_name = self.get_ha_device_name()
self.driver.plug(self.ha_port['network_id'],
self.ha_port['id'],
interface_name,
se... |
npettiaux/hyde | repos/dvcs.py | Python | mit | 952 | 0.016807 | import sys
class DVCS(object):
def __init__(self, path, repo):
self.path = path
self.url = repo['url']
self.type = repo['type']
self.draft_branch = | repo['draft_branch']
self.prod_branch = repo['production_branch']
self.switch(self.draft_branch)
def save_draft(self, message=None): abstrac | t
def publish(self): abstract
def pull(self): abstract
def push(self, branch): abstract
def commit(self, message): abstract
def switch(self, branch): abstract
def add_file(self, path, message=None): abstract
def merge(self, branch): abstract
@staticmethod
def lo... |
oarriaga/single_shot_multibox_detector | src/pytorch2keras.py | Python | mit | 1,252 | 0 | import torch
import numpy as np
from models | import SSD300
# weights_path = '../trained_models/vgg16_reducedfc.pth'
weights_path = '../trained_models/ssd_300_VOC0712.pth'
vgg_weights = torch.load(weights_path)
biases = []
weights = []
for name, torch_weights in vgg_weights.items():
print(name)
if 'bias' in name:
biases.append(torch_weights.nump... | onv_weights = torch_weights.numpy()
conv_weights = np.rollaxis(conv_weights, 0, 4)
conv_weights = np.rollaxis(conv_weights, 0, 3)
weights.append(conv_weights)
vgg_weights = list(zip(weights, biases))
base_model = SSD300(return_base=True)
pytorch_layer_arg = 0
for layer in base_model.layers[1:]:... |
AsymmetricVentures/asym-logging | asymmetricbase/logging/audit.py | Python | gpl-2.0 | 4,522 | 0.041132 | # -*- coding: utf-8 -*-
# Asymmetric Base Framework - A collection of utilities for django frameworks
# Copyright (C) 2013 Asymmetric Ventures Inc.
#
# 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 S... | pe = self.record.log_type
except AttributeError:
from .models import LogEntryType
self.log_type = LogEntryType.OTHER
def _get_model(self):
try:
self.model = self.record.model
self.model_str = u"{model.__class__.__name__}.{model.id}".format(model = self.model)
except AttributeError:
self.model = ... | f):
try:
self.view_name = self.record.view_name
except AttributeError:
self.view_name = None
def _get_success(self):
try:
self.success = self.record.success
except AttributeError:
self.success = None
def _do_ignore_log(self):
from django.conf import settings
from .models import LogEntryTyp... |
ratt-ru/CubiCal | cubical/machines/ifr_gain_machine.py | Python | gpl-2.0 | 8,532 | 0.006798 | # CubiCal: a radio interferometric calibration suite
# (c) 2017 Rhodes University & Jonathan S. Kenyon
# http://github.com/ratt-ru/CubiCal
# This code is distributed under the terms of GPLv2, see LICENSE.md for details
from __future__ import print_function
import numpy as np
from numpy.ma import masked_array
from cubi... | e valid IFR gains to apply"""
return self._ifrgain is not None
def is_computing(self):
"""Returns True if we're computing output IFR gains"""
return self._ifrgains_grid is not None
def apply(self, obser_arr, freq_slice):
"""
Applies IFR-based gains (if any) to input dat... | r)
freq_slice: frequency slice in data array
"""
# IFR gains are freq,ant,ant,corr,corr, so broadcast the time axes, and slice the freq axis
if self._ifrgain is not None:
obser_arr *= self._ifrgain[np.newaxis, freq_slice, ...]
def update(self, obser_arr, corrupt_mode... |
mnieber/shared-goal | django/main/settings_prod.py | Python | apache-2.0 | 429 | 0 | from .settings import *
DATABASES = {
'default': {
| 'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sharedgoals',
'USER': 'admin',
'PASSWORD': 'blah',
'HOST': 'localhost',
'PORT': '',
}
}
# SECURITY WARNIN | G: keep the secret key used in production secret!
SECRET_KEY = '8fbc%#p8369y4%9wqky9a9d7+4m7183@)vz4#)9y#h8p)r7d(t'
ALLOWED_HOSTS += ['52.36.175.255', ]
|
Chasego/cod | leetcode/418-Sentence-Screen-Fitting/SentenceScreenFitting_001.py | Python | mit | 921 | 0.002172 | class Solution(object):
def wordsTyping(self, sentence, rows, cols):
"""
:type sentence: List[str]
:type rows: int
:type cols: int
:rtype: int
"""
cnt = 0
start = 0
row_circ = len(''.join(sentence)) + len(sentence)
nrc = (cols + 1) / ro... | ce[start])
while j < cols:
tmp = (start + 1) % len(sentence)
if not tmp:
cnt += 1
start = tmp
j += 1 + len(sentence[start])
circle.append(cnt)
if not start:
break
ncircle = len... | cnt = nrc * rows
cnt += rows/ncircle * circle[-1]
cnt += circle[rows%ncircle - 1] if rows%ncircle > 0 else 0
return cnt
|
xbmc/atv2 | xbmc/lib/libPython/Python/Demo/metaclasses/Enum.py | Python | gpl-2.0 | 4,419 | 0.000905 | """Enumeration metaclass.
XXX This is very much a work in progress.
"""
import string
class EnumMetaClass:
"""Metaclass for enumeration.
To define your own enumeration, do something like
class Color(Enum):
red = 1
green = 2
blue = 3
Now, Color.red, Color.green and Color.bl... | = EnumInstance(name, key, value)
def __getattr__(self, name):
"""Return an enumeration value.
For example, Color.red returns the value corresponding to red.
XXX Perhaps the values should be created in the constructor?
This looks in the class dictionary and if it is not found
... | special attribute __members__ returns the list of names
defined in this class (it does not merge in the names defined
in base classes).
"""
if name == '__members__':
return self.__dict.keys()
try:
return self.__dict[name]
except KeyError:
... |
Nolski/airmozilla | airmozilla/manage/views/url_transforms.py | Python | bsd-3-clause | 3,948 | 0 | from django.conf import settings
from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from django.db import transaction
from django.db.models import Max
from jsonview.decorators import json_view
from airmozilla.main.... | transform.replace_with,
'order': transform.order,
}
return {'transform': transform_as_dict}
@staff_required
@permission_required('main.change_urlmatch')
@transaction.commit_on_success
@require_ | POST
@json_view
def url_transform_remove(request, id, transform_id):
match = get_object_or_404(URLMatch, id=id)
transform = get_object_or_404(URLTransform, id=transform_id, match=match)
transform.delete()
return True
@staff_required
@permission_required('main.change_urlmatch')
@transaction.commit_on_s... |
solackerman/sqlalchemy-redshift | sqlalchemy_redshift/commands.py | Python | mit | 25,418 | 0.000039 | import collections
import numbers
import re
import sqlalchemy as sa
from sqlalchemy.ext import compiler as sa_compiler
from sqlalchemy.sql import expression as sa_expression
# At the time of this implementation, no specification for a session token was
# found. After looking at a few session tokens they appear to be... | anifest else '',
delimiter=(
'DELIMITER AS :delimiter' if el.delimiter is | not None else ''
),
encrypted='ENCRYPTED' if el.encrypted else '',
fixed_width='FIXEDWIDTH AS :fixed_width' if el.fixed_wi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.