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 |
|---|---|---|---|---|---|---|---|---|
chrsrds/scikit-learn | examples/linear_model/plot_sgd_early_stopping.py | Python | bsd-3-clause | 5,659 | 0 | """
=============================================
Early stopping of Stochastic Gradient Descent
=============================================
Stochastic Gradient Descent is an optimization technique which minimizes a loss
function in a stochastic fashion, performing a gradient descent step sample by
sample. In particu... | e-3, n_iter_no_change=3),
'Training loss':
linear_model.SGDClassifier(early_stopping=False, n_iter_no_change=3,
to | l=0.1),
'Validation score':
linear_model.SGDClassifier(early_stopping=True, n_iter_no_change=3,
tol=0.0001, validation_fraction=0.2)
}
# Load the dataset
X, y = load_mnist(n_samples=10000)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5,
... |
mtholder/peyotl | ez_setup.py | Python | bsd-2-clause | 10,592 | 0.000189 | #!/usr/bin/env python
"""Bootstrap setuptools installation
To use setuptools in your package's setup.py, include this
file in the same directory and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
To require a specific version of setuptools, set a download
mirror, ... |
Return True if the command succeede | d.
"""
args = (sys.executable,) + args
return subprocess.call(args) == 0
def _install(archive_filename, install_args=()):
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
... |
arenadata/ambari | ambari-server/src/main/resources/common-services/HAWQ/2.0.0/package/scripts/common.py | Python | apache-2.0 | 14,813 | 0.012624 | """
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 this ... | configurations=params.hdfs_client,
configuration_attributes=params.config_attrs['h | dfs-client'])
params.XmlConfig("yarn-client.xml",
configurations=params.yarn_client,
configuration_attributes=params.config_attrs['yarn-client'])
params.XmlConfig("hawq-site.xml",
configurations=params.hawq_site,
configuration_attributes=... |
ndsc-mimic/MimicNOS | experiments/ExprTopo/multiple.py | Python | apache-2.0 | 1,693 | 0.007679 | from mininet.net import Mininet
from mininet.topo import Topo
from mininet.log import lg, setLogLevel
from mininet.cli import CLI
from mininet.node import RemoteController
FANOUT = 2
SWITCH_NUM = 2
CORES = {}
for i in range(1, SWITCH_NUM + 1):
CORES['s%d' % i] = {}
if i < 10:
CORES['s%d' % i]['dpid'] =... | id']))
# Add hosts and connect them to their core switch
for switch in CORES:
for count in xrange(1, FANOUT + 1):
# Add hosts
host = 'h_%s_%s' % (switch, count)
ip = '10.0.0.%s' % count
mac = CORES[switch]['dpid'][4 | :-1] + str(count)
h = self.addHost(host, ip=ip, mac=mac)
# Connect hosts to core switches
self.addLink(h, self.cores[switch])
if __name__ == '__main__':
topo = MultipleTopo()
net = Mininet(topo, autoSetMacs=True, xterms=False, controller=RemoteController)
net... |
FrodeSolheim/fs-uae-launcher | amitools/vamos/cfg/trace.py | Python | gpl-2.0 | 1,515 | 0.00264 | from amitools.vamos.cfgcore import *
class TraceParser(Parser):
def __init__(self, ini_prefix=None):
def_cfg = {
"trace": {
"instr": False,
"memory": False,
"vamos_ram": False,
"reg_dump": False,
"labels": False
}
}
arg_cfg = {
... | ini_trafo = {
"trace": {
"instr": "instr_trace",
"memory": "memory_trace",
"vamos_ram": "internal_memory_trace",
"reg_dump": "reg_dump",
"labels": "labels"
}
}
Parser.__in | it__(self, "trace", def_cfg, arg_cfg,
"trace", "control low-level machine tracing",
ini_trafo, ini_prefix)
|
ABaldwinHunter/django-clone-classic | django/urls/base.py | Python | bsd-3-clause | 5,754 | 0.001043 | from __future__ import unicode_literals
from threading import local
from django.utils import six
from django.utils.encoding import force_text, iri_to_uri
from django.utils.functional import lazy
from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
from django.utils.translation import override
from .e... | pass
def set_urlconf(urlconf_name):
"""
Set the URLconf for the current thread (overriding the default one in
settings). If urlconf_name is None, revert back to the default.
"""
if urlconf_name:
_urlconfs.value = urlconf_name
else:
if hasattr(_urlconfs, "value"):
... | fault one.
"""
return getattr(_urlconfs, "value", default)
def is_valid_path(path, urlconf=None):
"""
Return True if the given path resolves against the default URL resolver,
False otherwise. This is a convenience method to make working with "is
this a match?" cases easier, avoiding try...exce... |
dyzajash/fansubs_cms | fansubs_cms/settings.py | Python | bsd-3-clause | 1,999 | 0 | # -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
ENV = 'dev' # Default ENV
SECRET_KEY = os.environ.get('FANSUBS_CMS_SECRET', 'secret-key')
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.pa... | = 13
ASSETS_DEBUG = False
DEBUG_TB_ENABLED = False # Disable Debug toolbar
DEBUG_TB_INTERCEPT_REDIRECTS = False
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
SQLALCHEMY_TRACK_MODIFICATIONS = False
FLASK_LOG_LEVEL = 'INFO'
UPLOADS_DIR = os.path.abspath(os.path.join(PROJECT_ROOT... | uploads/'
RESIZE_ROOT = UPLOADS_DIR
RESIZE_CACHE_DIR = 'resize'
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.environ.get(
'FANSUBS_CMS_DB',
'postgresql://USER:PASS@localhost:5432/DB_NAME'
)
DEBUG_TB_E... |
Tejal011089/trufil-erpnext | erpnext/stock/doctype/item/test_item.py | Python | agpl-3.0 | 2,870 | 0.027178 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from frappe.test_runner import make_test_records
from erpnext.stock.doctype.item.item import WarehouseNotSet, ItemTemplat... | e_cannot_have_stock(self):
item = self.get_item(10)
make_stock_entry(item | _code=item.name, target="Stores - _TC", qty=1, incoming_rate=1)
item.has_variants = 1
self.assertRaises(ItemTemplateCannotHaveStock, item.save)
def test_default_warehouse(self):
item = frappe.copy_doc(test_records[0])
item.is_stock_item = 1
item.default_warehouse = None
self.assertRaises(WarehouseNotSet... |
toralf/torutils | key-expires.py | Python | gpl-3.0 | 610 | 0.006557 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# put out the time ( | in seconds) before the medium-term signing Tor certs expires
# appropriate cron job:
# @daily let n="$(key-expires.py /var/lib/tor/data/keys/ed25519_signing_cert) / 86400"; [[ $n -lt 35 ]] && echo "Tor cert expires in less than $n day(s)"
import codecs
import sys
import time
with open(sys.argv[1], 'rb') as f:
... | current timestamp in seconds
print(3600*expire-now)
|
GeorgiaTechDHLab/TOME | news/migrations/0011_auto_20170531_1426.py | Python | bsd-3-clause | 658 | 0.00152 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-31 14:26
from __future__ import unicode_literals
fr | om django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0010_auto_20170530_1509'),
]
operations = [
migrations.AddField(
| model_name='corpus',
name='date_ended',
field=models.DateField(blank=True, null=True, verbose_name='date ended'),
),
migrations.AlterField(
model_name='corpus',
name='date_started',
field=models.DateField(verbose_name='date started'),
... |
georgenicolaou/nfi | AndroidApps/com_google_android_feedback.py | Python | gpl-3.0 | 1,587 | 0.007561 | '''
NFI -- Silensec's Nyuki Forensics Investigator
Copyright (C) 2014 George Nicolaou (george[at]silensec[dot]com)
Silensec Ltd.
Juma Fredrick (j.fredrick[at]silensec[dot]com)
Silensec Ltd.
This file is part of Nyuki Forensics Investigator (NFI).
NFI is fr... | e, or
(at your option) any later version.
NFI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General ... | pp, KnownTable, DataTypes
import ConvertUtils
class com_google_android_feedback(IApp):
name = "com.google.android.feedback"
cname = "Google Android Feedback"
databases = {
"webviewCookiesChromium.db": [
KnownTable("cookies", None,
{"creation_utc":ConvertUtils.WebkitToUni... |
sauloal/cufflinksviewer | venvlin/lib/python2.7/site-packages/simplejson/__init__.py | Python | mit | 20,581 | 0.001846 | r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`simplejson` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of ... | ...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
>>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
'[2.0, 1.0]'
Using | simplejson.tool from the shell to validate and pretty-print::
$ echo '{"json":"obj"}' | python -m simplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m simplejson.tool
Expecting property name: line 1 column 2 (char 2)
"""
__version__ = '2.5.2'
__all__ = [
'dump', 'dumps', 'l... |
muepsilon/Stocks-Monitering-Tool | stocks/urls.py | Python | gpl-3.0 | 85 | 0.023529 | from | django.conf.urls import include, url
from . import views
urlpatterns = [
|
] |
tctimmeh/django-testing-base | testsite/testapp/views.py | Python | mit | 449 | 0.008909 | from d | jango.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'context_var': 'expected'})
def withUrlFields(request, value):
return HttpResponse(value)
@login_required
def requiresLogin(req... | atus))
|
steventimberman/masterDebater | debateIt/wsgi.py | Python | mit | 399 | 0 | """
WSGI config for maste | rDebater project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_ | wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "debateIt.settings")
application = get_wsgi_application()
|
jameshensman/GPy | GPy/models/sparse_gp_minibatch.py | Python | bsd-3-clause | 15,338 | 0.004759 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from __future__ import print_function
import numpy as np
from ..core.parameterization.param import Param
from ..core.sparse_gp import SparseGP
from ..core.gp import GP
from ..inference.latent_function_infer... | or, log_marginal_likelihood, grad_dict = self.inference_method.inference(kern, X, Z, likelihood, Y, Y_metadata, Lm=Lm,
dL_dKmm=dL_dKmm, psi0=psi0, psi1=psi1, psi2=psi2_sum_n, **kwargs)
return posterior, log_marginal_likeliho... | matic updates of values in the inner loop of missing
data handling. Both arguments are dictionaries and the values in
full_values will be updated by the current_gradients.
If a key from current_values does not exist in full_values, it will be
initialized to the value in current_values.
... |
skwashd/python-acquia-cloud | acapi/resources/database.py | Python | mit | 2,082 | 0.000961 | """Database resource."""
import re
from acapi.resources.acquiaresource import AcquiaResource
from acapi.resources.backup import Backup
from acapi.resources.backuplist import BackupList
class Database(AcquiaResource):
"""Environment database."""
#: Valid keys for environment object.
valid_keys = ["db_cl... | e database backup to fetch.
Returns
-------
Backup
The backup object.
"""
uri = "{uri}/backups/{backup_id}".format(uri=self.uri | , backup_id=backup_id)
return Backup(uri, self.auth)
def backups(self):
"""Fetch a list of database backups."""
backups = BackupList(self.uri, self.auth)
return backups
def copy(self, target, wait=True):
"""Copy a database to another environment.
Parameters
... |
skyoo/jumpserver | apps/perms/migrations/0013_rebuildusertreetask_usergrantedmappingnode.py | Python | gpl-2.0 | 2,942 | 0.005438 | # Generated by Django 2.2.13 on 2020-09-07 08:40
import assets.models.node
from django.conf import settings
from django.db import migrations, models
import django.db.models.de | letion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('assets', '0057_fill_node_value_assets_amount_and_parent_key'),
('perms', '0012_k8sapppermission'),
]
operations = [
migrations.CreateModel(
... | se_name='ID')),
('created_by', models.CharField(blank=True, max_length=32, null=True, verbose_name='Created by')),
('updated_by', models.CharField(blank=True, max_length=32, null=True, verbose_name='Updated by')),
('date_created', models.DateTimeField(auto_now_add=True, n... |
luiscape/hdxscraper-noaa | app/hdx_register/create.py | Python | mit | 10,196 | 0.017948 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import requests
import yajl as json
import progressbar as pb
dir = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
sys.path.append(dir)
from termcolor import colored as color
from utilities.prompt_format import item as I
def CreateDatase... | .
#
req = requests.get(package_show_url + resource["package_id"], headers=headers, auth=('dataproject', 'humdata'))
existing_resource | s = req.json()
names_array = []
if req.status_code != 200:
continue
for existing_resource in existing_resources['result']['resources']:
names_array.append(existing_resource.get('name'))
#
# Comparing existing resources
# with to-be-created ones.
# If it exist... |
glennyonemitsu/MarkupHiveServer | src/pyjade/convert.py | Python | mit | 2,157 | 0.00649 | import logging
import codecs
from optparse import OptionParser
from pyjade.utils import process
import os
def convert_file():
support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado']
available_compilers = {}
for i in support_compilers_list:
try:
compiler_... | parser.add_option("-e", "--ext", dest="extension",
help="Set import/extends default file extension", metavar="FILE")
options, args = parser.parse_args()
if len(args) < 1:
print "Specify the input file as the first argument."
exit()
file_output = options.output ... | else None)
compiler = options.compiler
if options.extension:
extension = '.%s'%options.extension
elif options.output:
extension = os.path.splitext(options.output)[1]
else:
extension = None
if compiler in available_compilers:
template = codecs.open(args[0... |
PMBio/mtSet | mtSet/pycore/covariance/test.py | Python | apache-2.0 | 1,304 | 0.014571 | """LMM testing code"""
import unittest
import scipy as SP
import sys
from freeform import freeform
from lowrank import lowrank
class covariance_test(object):
"""abstract test class for covars"""
def test_grad(self):
"""test analytical gradient"""
ss = 0
for i in range(self.n_params):
... | ittest.TestCase,covariance_test):
"""test class for CLowRankCF"""
def setUp(self):
SP.random.seed(1)
self.n=4
self.rank=2
self.C = lowrank(self.n,self.rank)
self.name = 'lowrank'
self.n_ | params=self.C.getNumberParams()
params=SP.exp(SP.randn(self.n_params))
self.C.setParams(params)
if __name__ == '__main__':
unittest.main()
|
Aalto-LeTech/a-plus | selenium_test/test/edit_exercise_page_test.py | Python | gpl-3.0 | 1,406 | 0.000711 | import unittest
from test_initializer import TestInitializer
from page_objects import LoginPage, EditExercisePage, CourseName
class EditExercisePageTest(unittest.TestCase):
def setUp(self):
self.driver = TestInitializer().getDefaultDriver()
TestInitializer().recreateDatabase()
LoginPag | e(self.driver).loginAsTeacher()
def testShouldSaveExercise(self):
exerciseName = "Testiharjoitus"
maxSubmissions = "5"
maxPoints = "99"
pointToPass = "50"
exerciseNumber = 1
editExercisePage = EditExercisePage(self.driver, exerciseNumber)
editExercisePage.s... | oPass(pointToPass)
editExercisePage.submit()
self.assertTrue(editExercisePage.isSuccessfulSave())
editExercisePage = EditExercisePage(self.driver, exerciseNumber)
self.assertEqual(editExercisePage.getExerciseName(), exerciseName)
self.assertEqual(editExercisePage.getMaxSubmissi... |
ewheeler/rapidpro | temba/flows/migrations/0054_flowstep_broadcasts.py | Python | agpl-3.0 | 555 | 0.001802 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('msgs', '0057_update_triggers'),
('flows', '0053_auto_20160414_0642'),
]
operations = [
migrations.AddField(
mo | del_name='flowstep',
name='broadcasts',
field=models.ManyToManyField(help_text='Any broadcasts that are associated with this step (only sent)', related_name='steps', to='msgs.Broadcast'),
),
]
|
saurabh6790/test-med-app | patches/june_2013/p05_remove_search_criteria_reports.py | Python | agpl-3.0 | 334 | 0.020958 | # | Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import webnotes
def execute():
try:
webnotes.conn.sql("""delete from `tabSearch Criteria` where ifnull(standard, 'No') = 'Yes'""")
except Excepti... | s |
IndonesiaX/edx-platform | cms/djangoapps/contentstore/views/tests/test_certificates.py | Python | agpl-3.0 | 28,836 | 0.001491 | #-*- coding: utf-8 -*-
"""
Group Configuration Tests.
"""
import json
import mock
import ddt
from django.conf import settings
from django.test.utils import override_settings
from opaque_keys.edx.keys import AssetKey
from opaque_keys.edx.locations import AssetLocation
from contentstore.utils import reverse_course_ur... | asset_key, "Fake asset", "image/png", "data",
)
contentstore().save(content)
def _add_course_certificates(self, count=1, signatory_count=0, is_active=False):
"""
Create certificate for the course.
"""
signatories = [
{
'name': 'N... | image_path': '/c4x/test/CSS101/asset/Signature{}.png'.format(i),
'id': i
} for i in xrange(0, signatory_count)
]
# create images for signatory signatures except the last signatory
for idx, signatory in enumerate(signatories):
if len(signatories) > 2 and ... |
MorcoFreeCode/2014__MorcoWrapper2D | full_project/2D/6. Cocos2D [Python2]/ProjectExample/ExampleManager.py | Python | mit | 2,691 | 0.029729 | from MorcoWrapper2D.mw2_Script import *
from MorcoWrapper2D.mw2_Input import *
from MorcoWrapper2D.mw2_Application import *
from MorcoWrapper2D.mw2_Text import *
class ExampleManager (mw2_Script):
def __init__(self):
mw2_Script.__init__(self)
self.mCamera = None
self.mBall = None
self.mCameraSpeed = 150
se... | .E):
rotCamera = self.mCameraRotationSpeed * deltaTime
if mw2_Input.GetKey(mw2_Input.Key.Q):
rotCamera = - self.mCameraRotationSpeed * deltaTime
self.mCamera.RotateWorld(rotCamera)
# move and rotate mBall
moveBall = mw2_Vector2()
r | otBall = 0
if mw2_Input.GetKey(mw2_Input.Key.ARROW_RIGHT):
moveBall.x = self.mBallSpeed * deltaTime
rotBall = self.mBallRotationSpeed * deltaTime
if mw2_Input.GetKey(mw2_Input.Key.ARROW_LEFT):
moveBall.x = - self.mBallSpeed * deltaTime
rotBall = - self.mBallRotationSpeed * deltaTime
self.mBall.Transl... |
Arvedui/i3pystatus | setup.py | Python | mit | 1,051 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(name="i3pystatus",
version="3.35",
description="A complete replacement for i3status",
url="http://github.com/enkore/i3pystatus",
license="MIT",
classifiers=[
"Development Status :: 4 - Beta",
"Env... | "License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic ... | ges(include=['i3pystatus', 'i3pystatus.*']),
entry_points={
"console_scripts": [
"i3pystatus = i3pystatus:main",
"i3pystatus-setting-util = i3pystatus.tools.setting_util:main"
]
},
zip_safe=True,
)
|
prashnts/dj-elasticsearch-flex | setup.py | Python | mit | 2,493 | 0.000401 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_version(*file_paths):
"""Retrieves the version from elasticsearch_flex/__init__.py"""
filename = os.path.join(os.path.dirname(__f... | :: 1.9',
'Framework :: Django :: 1.10',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'P | rogramming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
TheDuckCow/MCprep | MCprep_addon/addon_updater.py | Python | gpl-3.0 | 52,611 | 0.028359 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | self._current_version = None
return
elif type(tuple_values) is not tuple:
try:
tupl | e(tuple_values)
except:
raise ValueError(
"current_version must be a tuple of integers")
for i in tuple_values:
if type(i) is not int:
raise ValueError(
"current_version must be a tuple of integers")
self._current_version = tuple(tuple_values)
@property
def engine(self):
return self._en... |
AtlasDev/TICT-V1PROG-15 | les-5/practice/5_6.py | Python | mit | 863 | 0.011587 | studentencijfers = [
[95, 92, 86],
[66, 75, 54],
[89, 72, 100],
[34, 0, 0]
];
"""
Calculate the average in a two dimentional list
@param {List(List(Int))} studenten - Two dimentional list of | Ints
@return {list(Float)} One dimentional list of the average of the input
"""
def gemiddelde_per_student(studenten):
gemiddelde = [];
for student in studenten:
gemiddelde.append(float(sum(student)) / max(len(student), 1));
return gemiddelde;
"""
Calculate the average of a list
@param {List(Floa... | n(studenten):
gemiddelde = gemiddelde_per_student(studenten);
return float(sum(gemiddelde)) / max(len(gemiddelde), 1);
print(gemiddelde_per_student(studentencijfers))
print(gemiddelde_van_alle_studenten(studentencijfers))
|
onelab-eu/sfa | clientbin/sfiListNodes.py | Python | mit | 812 | 0.007389 | #! /usr/bin/env python
import sys
from sfa.client.sfi_commands import Commands
from sfa.rspecs.rspec import RSpec
from sfa.planetlab.plxrn import xrn_to_hostname
command = Commands(usage="%prog [options]",
description="List all nodes in the RSpec. " +
"Use this to display th... | le:
rspec = RSpec(command.opts.infile)
nodes = rspec.version.g | et_nodes()
if command.opts.outfile:
sys.stdout = open(command.opts.outfile, 'w')
for node in nodes:
hostname = None
if node.get('component_id'):
hostname = xrn_to_hostname(node['component_id'])
if hostname:
print hostname
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/pylint/test/functional/abstract_abc_methods.py | Python | agpl-3.0 | 463 | 0.006479 | """ This should not warn about `prop` being abstract | in Child """
# pylint: disable=too-few-public-methods,abstract-class-little-u | sed,no-absolute-import,metaclass-assignment
import abc
class Parent(object, metaclass=abc.ABCMeta):
"""Abstract Base Class """
@property
@abc.abstractmethod
def prop(self):
""" Abstract """
class Child(Parent):
""" No warning for the following. """
prop = property(lambd... |
blakearchive/archive | setup.py | Python | gpl-2.0 | 480 | 0.004167 | import os
from setuptools import setup
def read(fname):
return | open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="blake-archive",
version="0.1",
description="Blake archive web app",
license="Closed source",
packages=['blake', 'test'],
| long_description=read('README'),
classifiers=["Development Status :: 3 - Alpha"],
install_requires=["flask", "sqlalchemy", "flask-sqlalchemy", 'lxml', 'xmltodict', "nose", 'tablib']
) |
renatofb/weblate | weblate/sitemaps.py | Python | gpl-3.0 | 3,132 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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, eithe... | port Profile
PROJECT_DICT = | {
'queryset': Project.objects.all_acl(None),
'date_field': 'last_change',
}
SUBPROJECT_DICT = {
'queryset': SubProject.objects.filter(
project__in=Project.objects.all_acl(None)
),
'date_field': 'last_change',
}
TRANSLATION_DICT = {
'queryset': Translation.objects.filter(
subpr... |
zamazaljiri/django-chamber | chamber/utils/decorators.py | Python | lgpl-3.0 | 442 | 0 | class classproperty(object):
d | ef __init__(self, fget):
self.fget = fge | t
def __get__(self, owner_self, owner_cls):
return self.fget(owner_cls)
def singleton(klass):
"""
Create singleton from class
"""
instances = {}
def getinstance(*args, **kwargs):
if klass not in instances:
instances[klass] = klass(*args, **kwargs)
return i... |
rdoh/pixelated-user-agent | service/pixelated/adapter/mailstore/leap_mailstore.py | Python | agpl-3.0 | 16,152 | 0.002229 | #
# Copyright (c) 2015 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated is distrib... | ts copy
self._attachments = attachments
@property
def headers(self):
| cpy = dict(self._headers)
for name in set(self._headers.keys()).intersection(['To', 'Cc', 'Bcc']):
cpy[name] = self._headers[name].split(',') if self._headers[name] else []
return cpy
@property
def ident(self):
return self._mail_id
@property
def mail_id(self):
... |
xianjunzhengbackup/code | data science/machine_learning_for_the_web/chapter_8/movie_reviews_analizer_app/scrapy_spider/spiders/recursive_link_results.py | Python | mit | 2,856 | 0.017157 | '''
| usage: scrapy runspider recursive_link_results.py (or from root folder: scrapy crawl scrapy_spyder_recursive)
'''
#from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.http import Request
... | t used for spider crawling
name = 'scrapy_spider_recursive'
def __init__(self,url_list,search_id):#specified by -a
#REMARK is allowed_domains is not set then ALL are allowed
self.start_urls = url_list.split(',')
self.search_id = int(search_id)
#allow any link b... |
feist/pcs | pcs_test/tier0/lib/cib/rule/test_parsed_to_cib.py | Python | gpl-2.0 | 13,990 | 0.000357 | from unittest import TestCase
from lxml import etree
from pcs_test.tools.assertions import assert_xml_equal
from pcs_test.tools.xml import etree_to_str
from pcs.common.tools import Version
from pcs.lib.cib import rule
from pcs.lib.cib.rule.expression_part import (
BOOL_AND,
BOOL_OR,
DATE_OP_GT,
DATE_... | self.assert_cib(
| NodeAttrExpr(
NODE_ATTR_OP_EQ, "#uname", "node1", NODE_ATTR_TYPE_STRING
),
"""
<expression attribute="#uname" id="X-expr" operation="eq"
type="string" value="node1"
/>
""",
)
def test_type_ve... |
seanlinmt/DelimitationToolbox | packages/pykml/helpers.py | Python | gpl-2.0 | 6,052 | 0.003305 | """pyKML Helpers Module
The pykml.helpers module contains 'helper' functions that operate on pyKML
document objects for accomplishing common tasks.
"""
from packages.pykml.factory import KML_ElementMaker as K
def separate_namespace(qname):
"Separates the namespace from the element"
import re
try:
... | ip())
el.getparent().replace(el, | el_new)
# modify <gx:coords> elements
for el in doc.findall(".//{http://www.google.com/kml/ext/2.2}coord"):
el._setText(
replace_delimited_string_member(
delimited_str=el.text,
separator=' ',
index_no=index_no,
... |
jwkozel/demobx | test/integration/test_retry_and_refresh.py | Python | apache-2.0 | 1,045 | 0 | # coding: utf-8
from __future__ import unicode_literals
from mock import ANY, call
from boxsdk.config import API
def test_automatic_refresh(
box_client,
mock_box_network,
generic_successful_response,
successful_token_response,
unauthorized_response,
):
mock_box_network.ses... | ,
'{0}/folders/0'.format(API.BASE_API_URL),
headers=ANY,
params=None,
),
call(
'POST',
'{0}/token'.format(API.OAUTH2_API_URL),
data=ANY,
headers={'content-type': 'application/x-www-form-urlencoded'},
),
c... | |
akkenoth/TSPGen | Operators/Mutation/__init__.py | Python | mit | 183 | 0 | from Operators | .Mutation.Mutator import Mutator
from Operators.Mutation.DisplacementMutator import DisplacementMutator
from Operators.Mutation.InversionMutator import InversionMut | ator
|
indashnet/InDashNet.Open.UN2000 | android/external/llvm/utils/lit/lit/ShUtil.py | Python | apache-2.0 | 12,179 | 0.003941 | from __future__ import absolute_import
import itertools
import lit.Util
from lit.ShCommands import Command, Pipeline, Seq
class ShLexer:
def __init__(self, data, win32Escapes = False):
self.data = data
self.pos = 0
self.end = len(data)
self.win32Escapes = win32Escapes
def eat(... | ed.
if self.pos == self.end:
lit.Util.warning(
"escape at end | of quoted argument in: %r" % self.data)
return str
c = self.eat()
if c == '"': #
str += '"'
elif c == '\\':
str += '\\'
else:
str += '\\' + c
else:
... |
akatsoulas/mozillians | mozillians/phonebook/tests/test_views/test_views_register.py | Python | bsd-3-clause | 3,421 | 0 | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import Client
from django.test.utils import override_settings
from mock import patch
from nose.tools import eq_, ok_
from mozillians.common.templatetags.helpers import urlparams
from mozillians.common.tests impor... | gin(user) as client:
response = client.get(url, follow=True)
user = User.objects.get(id=user.id)
ok_(user.userprofile.is_vouched)
ok_(user.userprofile.vouched_by, | voucher_1.userprofile)
ok_(not redeem_invite_mock.called)
self.assertTemplateUsed(response, 'phonebook/home.html')
def test_register_without_code_anonymous(self):
client = Client()
response = client.get(reverse('phonebook:register'), follow=True)
ok_(not self.client.session.... |
mtr/ttpd | lib/TTP/EncapsulateTUC.py | Python | gpl-3.0 | 7,681 | 0.007421 | #! /usr/bin/python
# -*- coding: latin-1 -*-
# $Id$
"""
Classes to encapsulate a sub-process and communicate with it.
Copyright (C) 2004, 2007 by Lingit AS
"""
__version__ = "$Rev$"
import fcntl
import logging
import os
import re
import select
import signal
import subprocess
import sys
import time
QUERY_TYPE_NONE ... | self.log.error('Unable to run and encapsulate "%s". %s. ' \
'Shutting down...',
self.command, e)
os.kill(os.getpid(), signal.SIGTERM)
self.set_nonblocking(self.subprocess.stdout)
def get_pid(self):
"""Return... | urn self.subprocess.pid
def read(self, timeout = None):
"""Perform non-blocking read until magic is reached.
"""
started = time.time()
data = ''
while True:
ready = select.select([self.subprocess.stdout], [], [],
... |
abdesslem/CTF | models.py | Python | mit | 1,692 | 0.002364 | from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
import ctf
class User(UserMixin, ctf.db.Model):
__tablename__ = 'users'
id = ctf.db.Column(ctf.db.Integer, primary_key=True)
user... | assword_hash(self.password_hash, password)
def __repr__(self):
return '<User %r>' % self.username
class Challenges(ctf.d | b.Model):
__tablename__ = 'challenges'
id = ctf.db.Column(ctf.db.Integer, primary_key=True)
name = ctf.db.Column(ctf.db.String(80), unique=True)
category = ctf.db.Column(ctf.db.String(80))
info = ctf.db.Column(ctf.db.String(800))
score = ctf.db.Column(ctf.db.String(20))
flag = ctf.db.Column(... |
maciekswat/dolfin_1.3.0 | test/unit/fem/python/solving.py | Python | gpl-3.0 | 2,833 | 0.001412 | """Unit tests for the solve function"""
# Copyright (C) 2011 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN 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, either version 3 of the License, or
... | solve(a == L, u4, bcs=[bc])
# Check all solutions
self.assertAlmostEqual(u1.vector().norm("l2"), 14.9362601686, 10)
self.assertAlmostEqual(u2.vector().norm("l2"), 14.9362601686, 10)
self.assertAlmostEqual(u3.vec | tor().norm("l2"), 14.9362601686, 10)
self.assertAlmostEqual(u4.vector().norm("l2"), 14.9362601686, 10)
def test_calling(self):
"Test that unappropriate arguments are not allowed"
mesh = UnitSquareMesh(4, 4)
V = FunctionSpace(mesh, "Lagrange", 1)
u = TrialFunction(V)
... |
simpletrain/pybingwallpaper | src/ntlmauth/des_data.py | Python | mit | 18,677 | 0.037265 | # This file is part of 'NTLM Authorization Proxy Server' http://sourceforge.net/projects/ntlmaps/
# Copyright 2001 Dmitry A. Rozmanov <dima@xenon.spb.ru>
#
# This library 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 Soft... | x40000040), U32(0x40010000), U32(0x01010000), U32(0x41000040),
U32(0x00000000), U32(0x01010040), U32(0x00010040), U32(0x41010000),
U32(0x40010000), U32(0x01000000), U32(0x41010040), U32(0x40000000),
U32(0x40010040), U32(0x41000000), U32(0x01000000), U32(0x41010040),
U32(0x00010000), U32(0x01000040), U32(0x41000040), U3... | U32(0x00100402), U32(0x04000400), U32(0x00000002), U32(0x04100402),
U32(0x00000000), U32(0x04100000), U32(0x04000402), U32(0x00100002),
U32(0x04100400), U32(0x04000002), U32(0x04000000), U32(0x00000402),
U32(0x04000002), U32(0x00100402), U32(0x00100000), U32(0x04000000),
U32(0x04100002), U32(0x00100400), U32(0x00000400... |
FederatedAI/FATE | python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/loss/regression_loss.py | Python | apache-2.0 | 8,346 | 0.002636 | #
# Copyright 2019 The FATE 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 appli... | distributed under the L | icense is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import numpy as np
from federatedml.feature.instance import Instance
from federatedml.util im... |
obi-two/Rebelion | data/scripts/templates/object/tangible/hair/human/shared_hair_human_male_s33.py | Python | mit | 448 | 0.046875 | #### 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 = Tangible()
result.template = "object/tangible/hair/human/shared_hair_human_male_s33.iff"
result.attribute_templat | e_id = -1
result.stfName("hair_name","hair")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
codelv/enaml-native | src/enamlnative/ios/bridge.py | Python | mit | 6,282 | 0 | """
Copyright (c) 2017-2022, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file LICENSE, distributed with this software.
Created on June 21, 2017
@author: jrm
"""
from atom.api import Atom
from enamlnative.core.bridge import (
BridgeCallback,
BridgeField,
Brid... | tionary of the available
`subnames` and their types.
For instance:
UIView `insertSubview` has the following signatures:
- (voi | d)insertSubview:(UIView *)view
atIndex:(NSInteger)index;
- (void)insertSubview:(UIView *)view
aboveSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view
belowSubview:(UIView *)siblingSubview;
This is defined ... |
zzicewind/nova | nova/api/openstack/compute/quota_classes.py | Python | apache-2.0 | 3,394 | 0 | # Copyright 2012 OpenStack Foundation
# 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the sp | ecific language governing permissions and limitations
# under the License.
import six
from nova.api.openstack.compute.schemas import quota_classes
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import db
from nova import exception
from nova i... |
apavlo/h-store | src/dtxn/stupidcompiler.py | Python | gpl-3.0 | 20,928 | 0.004062 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""A stupid message compiler for C++."""
import os.path
import re
import struct
def truncateLong(x):
"""Returns the uint32 part of a long x."""
assert x > 0
unsigned_bytes = struct.pack("<Q", x)
return struct.unpack("<I", unsigned_bytes[:4])[0]
def reinterp... | g>
#include <vector>
#include "base/assert.h"
#include "io/message.h"
#include "serialization.h"
namespace io {
class FIFOBuffer;
}
namespace %(namespace)s {\n\n""" % {'guard': self.includeGuard(), 'namespace': namespace}
self.indent_ = 0
self.loop_count_ = 0
self.defined_types = {}
def... | + "\n"
def includeGuard(self):
return self.filename.upper().replace(".", "_").replace("/", "_")
def typeString(self, type_structure):
if type_structure.typecode == Type.INT32:
return "int32_t"
if type_structure.typecode == Type.INT64:
return "int64_t"
if... |
martinpeck/broken-python | mathsquiz/mathsquiz-step2.py | Python | mit | 1,660 | 0.009036 |
# this function will print a welcome message to the user
def welcome_message():
print("Hello! I'm going to ask you 10 maths questions.")
print("Let's see how many you can get right!")
# this function will ask a maths question and return the points awarded (1 or 0)
def ask_question(first_number, second_number)... | core to zero
score = 0
# ask questions
score = score + ask_question(8,7)
score = sco | re + ask_question(4,9)
score = score + ask_question(12,6)
score = score + ask_question(6,8)
score = score + ask_question(7,7)
score = score + ask_question(11,6)
score = score + ask_question(11,2)
score = score + ask_question(7,9)
score = score + ask_question(6,6)
score = score + ask_question(4,8)
# print the final sco... |
alex/sentry | tests/sentry/coreapi/tests.py | Python | bsd-3-clause | 10,465 | 0.001147 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import datetime
import mock
import time
from django.contrib.auth.models import User
from sentry.models import Project
from sentry.exceptions import InvalidTimestamp, InvalidInterface, InvalidData
from sentry.coreapi import project_from_id, project_from_... | 'timestamp': '2012-01-01T10:30:45'
})
d = datetime.datetime(2012, 01, 01, 10, 30, 45)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], d)
def test_iso_timestamp_with_ms(self):
data = process_data_timestamp({
'timestamp': '2012-01-0... | datetime(2012, 01, 01, 10, 30, 45, 434000)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], d)
def test_timestamp_iso_timestamp_with_Z(sel |
MilyangParkJaeHoon/deeplearning | lab4/tf_reader_linear_regression.py | Python | mit | 2,101 | 0 | # Lab 4 Multi-variable linear regression
# https://www.tensorflow.org/programmers_guide/reading_data
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
filename_queue = tf.train.string_input_producer(
['data-01-test-score.csv'], shuffle=False, name='filename_queue')
reader = tf.TextLineReader... | ing the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for step in range(2001):
x_batch, y_batch = sess.run([train_x_batch, train_y_batch])
cost_val, hy_val, _ = sess.run(
[cost, hypothesis, train], feed_dict={X: x_batch, Y: y_batch})
i... | e ",
sess.run(hypothesis, feed_dict={X: [[100, 70, 101]]}))
print("Other scores will be ",
sess.run(hypothesis, feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))
'''
Your score will be [[ 177.78144836]]
Other scores will be [[ 141.10997009]
[ 191.17378235]]
'''
|
nickgeoca/idris-py | examples/np.py | Python | bsd-3-clause | 80,549 | 0.011173 | #!/usr/bin/env python
import sys
import importlib
import math
Unit = object()
World = object()
class IdrisError(Exception):
pass
def _idris_error(msg):
raise IdrisError(msg)
def _idris_pymodule(name):
return importlib.import_module(name)
def _idris_call(f, args):
return f(*list(args))
def _idris_foreach(... | 5679, e3, e4)) # {U_Python.Fields.{//.0}1}
# Prelude.Classes.==
def _idris_Prelude_46_Classes_46__61__61_(e0, e1):
while True:
return e1
# Prelude.Classes.>
def _idris_Prelude_46_Classes_46__62_(e0, e1):
while True:
assert e1[0] == 0 # constructor of Prelude | .Classes.Ord
in0, in1 = e1[1:]
return in1
return _idris_error("unreachable due to case in tail position")
# Force
def _idris_Force(e0, e1, e2):
while True:
in0 = EVAL0(e2)
return in0
# PE_Prelude.Show.Maybe a instance of Prelude.Show.Show, method show_bb6a4ac6
def _idris_PE_95_Prelude_46_Show_46... |
ipedrazas/blibb-project | blibbapi/tests/models/test_item.py | Python | apache-2.0 | 1,623 | 0.004929 | # -*- coding: utf-8 -*-
"""Tests for the Item model"""
import unittest
import sys
import os
from os.path import join, abspath, dirname
parentpath = abspath(join(dirname(__file__), '../../..'))
sys.path.append(parentpath)
from blibbapi.db import get_engine, init_db, get_db_session, Base
from blibbapi.models.blibb imp... | Collection, User, Item
class TestItem | Model(unittest.TestCase):
def cleanup(self):
self.db_session.execute("truncate blibb_collection cascade")
self.db_session.commit()
def setUp(self):
test_sql = 'postgresql://postgres:postgres@localhost/test_db'
self.engine = get_engine(test_sql)
self.db = init_db(self.en... |
Dining-Engineers/left-luggage-detection | misc/demo/ipython/demo_pclview.py | Python | gpl-2.0 | 5,742 | 0.04528 | import numpy as np
from OpenGL.GL import *
from OpenGL.GLU import *
import time
import freenect
import calibkinect
import pykinectwindow as wxwindow
# I probably need more help with these!
try:
TEXTURE_TARGET = GL_TEXTURE_RECTANGLE
except:
TEXTURE_TARGET = GL_TEXTURE_RECTANGLE_ARB
if not 'win' in globals():
... | eading import Thread
global _thread
def _run():
while _updating:
update()
_thread = Thread(target=_run)
_thread.start()
def update_off():
global _updating
_updating = False
# Get frames in a loop and | display with opencv
def loopcv():
import cv
while 1:
cv.ShowImage('hi',get_depth().astype(np.uint8))
cv.WaitKey(10)
update()
#update_on()
|
wangzitian0/BOJ-V4 | ojuser/filters.py | Python | mit | 893 | 0 | import django_filters
from django_filters.widgets import BooleanWidget
from .models import Group
from guardian.shortcuts import get_objects_for_user
class GroupFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
can_manage = django_filters.MethodFilter(widget=BooleanWid... | _(self, *args, **kwargs):
self.u | ser = kwargs.pop('user', None)
super(GroupFilter, self).__init__(*args, **kwargs)
class Meta:
model = Group
fields = ['name', 'can_manage', ]
|
sambitgaan/nupic | tests/swarming/nupic/swarming/experiments/smart_speculation_temporal/description.py | Python | agpl-3.0 | 16,827 | 0.00309 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | 'minval': 0,
'n': 150,
'name': u'attendance',
'type': 'AdaptiveScalarEncoder',
'w': 21}},
| # A dictionary specifying the period for automatically-generated
# resets from a RecordSensor;
#
# None = disable automatically-generated resets (also disabled if
# all of the specified values evaluate to 0).
# Valid keys is the desired combination of th... |
archifix/settings | sublime/Packages/SublimeCodeIntel/libs/codeintel2/lang_less.py | Python | mit | 20,867 | 0.00139 | #!/usr/bin/env python
# Copyright (c) 2010 ActiveState Software Inc.
# See LICENSE.txt for license details.
"""Less support for CodeIntel"""
import logging
from codeintel2.common import _xpcom_
from codeintel2.lang_css import CSSLexer, CSSLangIntel, CSSBuffer
from codeintel2.lang_css import isident, WHITESPACE
from ... | ggering after an | y of '#.[: '.
# For speed, let's get the common ' ' out of the way. The only
# trigger on space is 'complete-property-values'.
if styleClassifier.is_default(last_style):
if DEBUG:
print(" _trg_from_pos:: Default style: %d, ch: %r" % (last_style, ... |
ziggi0703/mymeal | docs/conf.py | Python | bsd-3-clause | 8,168 | 0.002204 | # -*- coding: utf-8 -*-
#
# 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 configuration values have a default; values that are commented out
# serve to show the default.
import sys
imp... | ---------------------
python_version = '.'.join(map(str, sys.version_info[0:2]))
intersphinx_mapping = {
'sphinx': ('http://sphinx.pocoo.org', None),
'python': ('http://docs.python.org/' + python_version, None),
'matplotlib': ('http://matplotlib.sourceforge.net', None),
'numpy': ('http://docs.scipy.org/... | ipy.org/doc/scipy/reference/', None),
}
|
rodekruis/priorityindex | scripts/calc_average_windspeed.py | Python | lgpl-3.0 | 2,134 | 0.005155 | #from osgeo import ogr
from shapely.geometry import Polygon, shape
from fiona import collection
from fiona.crs import from_epsg
import time
#admin_file_name = 'admin3.shp'
admin_file_name = 'PHL_adm3_PSA_pn_2016June/PHL_adm3_PSA_pn_2016June.shp'
typhoon_file_name = 'typhoon_melor_edited.shp/WindSpeed.shp'
output_file_... | #print ' wind_feat'
#print wind_feat['properties']
part = admin_shp.intersection(shape(wind_feat['geometry']))
#print part.area
if part.area > 0:
part_list.append({'area': part.area, 'speed': wind_f... | 'properties': {
u'OBJECTID': admin_feat['properties'][u'OBJECTID'],
u'Mun_Code':admin_feat['properties'][u'Mun_Code'],
u'average_speed': get_average(part_list)
},
'geometry': admin_feat['geometry']
})
t1 =... |
petermblair/euler | problem.4/problem4.py | Python | unlicense | 256 | 0.015625 | #!python3
num1 = 999
num2 = 999
palindrome = set()
while num1 > 100 :
whi | le num2 > 100 :
x = num1 * num2
if str(x) == str(x)[::-1] :
palindrome.add(x)
num2 -= 1
num1 -= | 1
num2 = 999
print(max(palindrome)) |
Bindernews/TheHound | identifiers/midi_identifier.py | Python | mit | 211 | 0.056872 | from ident | ifier | import Result
MIDI_PATTERNS = [
'4D 54 68 64'
]
class MidiResolver:
def identify(self, stream):
return Result('MIDI')
def load(hound):
hound.add_matches(MIDI_PATTERNS, MidiResolver())
|
mcallaghan/tmv | BasicBrowser/scoping/migrations/0121_auto_20170720_1656.py | Python | gpl-3.0 | 482 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-07-20 16:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
( | 'scoping', '0120_auto_20170720_1653'),
]
operations = [
migrations.RemoveField(
model_name='networkproperties',
| name='doc',
),
migrations.DeleteModel(
name='NetworkProperties',
),
]
|
belokop/indico_bare | indico/modules/events/models/settings.py | Python | gpl-3.0 | 2,962 | 0.00135 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | ',
lazy=True,
backref=db.backref(
cls.settings_backref_name,
lazy='dynamic'
)
)
class EventSetting(JSONSettingsBase, EventSettingsMixin, db.Model):
se | ttings_backref_name = 'settings'
@strict_classproperty
@staticmethod
def __auto_table_args():
return db.UniqueConstraint('event_id', 'module', 'name'),
@declared_attr
def __table_args__(cls):
return auto_table_args(cls)
@return_ascii
def __repr__(self):
return '<Ev... |
NativeDesign/python-tmcl | TMCL/bus.py | Python | mit | 2,876 | 0.03338 | import struct
from .motor import Module, Motor
from .reply import Reply, TrinamicException
# MSG_STRUCTURE = ">BBBBIB"
MSG_STRUCTURE = ">BBBBiB"
MSG_STRUCTURE_CAN = ">BBBI"
# REPLY_STRUCTURE = ">BBBBIB"
REPLY_STRUCTURE = ">BBBBiB"
REPLY_STRUCTURE_CAN = ">BBBI"
REPLY_STRUCTURE_IIC = ">BBBIB"
REPLY_LENGTH = 9
REPLY_L... | =1, motor_id=0 ):
"""
Returns object addressing motor number `motor_id` on module `addr | ess`.
`address` defaults to 1 (doc for TMCM310 starts counting addresses at 1).
`motor_id` defaults to 0 (1st axis).
This is an alias for `get_module(address).get_motor(motor_id)` so that
backward-compatibility with v1.1.1 is maintained.
:param address:
Bus address of the target TMCM module
:... |
mlesche/dsp | dsp/src/report/build_report.py | Python | mit | 45,655 | 0.01277 | #!/usr/bin/env python
'''
The MIT License (MIT)
Copyright (c) <2016> <Mathias Lesche>
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
... | , NoneType):
self.__options = self.__parser.parse_args()
else:
self.__options = self.__parser.parse_args(inputstring)
def show_log(self, level, message):
if level == 'debug':
self.__logger.debug(message)
elif level == 'info':
self.__logger.info(message)
elif level == 'warning'... | gger.critical(message)
'''
method check if the output directory exists
@param inputdir: list
@param inputparam: string representing the option
@return: list
'''
def check_folder(self, inputdir, inputparam):
good, bad = check_Directorylist(inputdir)
if inputparam == '-r' and len(good) != 1:
... |
byashimov/django-pkgconf | test_project/mymixinconf.py | Python | bsd-3-clause | 237 | 0 | from pkgconf import Conf
class FooMixin(object):
FOO = 'foo'
@property
def BAR(se | lf):
if self.FOO == 'foo':
return 'original bar'
return 'new bar'
class MyApp(FooMi | xin, Conf):
BAZ = 'baz'
|
Ilyushin/PortalDjango | common/wsgi.py | Python | mit | 469 | 0.006397 | """
WSGI config for common project.
It exposes the WSGI callable as a module-level variable named ``applic | ation``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os,sys
sys.path.append('/var/www/portal/')
sys.path.append('/var/www/portal/common')
os.environ | .setdefault("DJANGO_SETTINGS_MODULE", "common.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
roubert/python-phonenumbers | python/phonenumbers/shortdata/region_BE.py | Python | apache-2.0 | 1,287 | 0.006993 | """Auto-generated file, do not edit by hand. BE metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BE = PhoneMetadata(id='BE', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,5}|[2-9]\\d{3}', possible_number... | e=PhoneNumberDesc(national_number_pattern='1(?:0[25-8]|1(?:0|6\\d{3})|7(?:12|77)|813)|8\\d{3}', possible_number_pattern='\\d{3,6}', example_number='116000'),
premium_rate=PhoneNumberDesc(national_number_pattern='1(?:2(?:12|34)|3(?:07|13)|414|\\d04)|[2-79]\\d{3}', possible_number_pattern='\\d{4}', example_number='72... | ber_pattern='1(?:0[0-8]|1(?:[027]|6(?:000|117))|2(?:0[47]|12|3[0-24]|99)|3(?:0[47]|13|99)|4(?:0[47]|14|50|99)|7(?:00|1[27-9]|33|65|7[17]|89)|81[39])|[2-9]\\d{3}', possible_number_pattern='\\d{3,6}', example_number='112'),
standard_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
... |
actboy168/war3-parsecarsh | parse_carsh.py | Python | mit | 16,382 | 0.008224 | # -*- coding: utf-8 -*-
import os
import sys
import re
import shutil
#1.24.4.6387
PayloadProc = 0x0045DCC8
###############################################################
carsh_re = re.compile(r"\={78}[\s\S]*\-{78}")
war3_version_re = re.compile(r"Warcraft\ III\ \(build\ (?P<VERSION>[0-9]*)\)")
map_path_re = re.comp... | dll_list = read_loaded_modules(buf)
while True:
m = parse_loaded_modules_re.search(dll_list)
if not m:
break
if parse_game_dll_re.search(m.group('NAME').lower()):
return int(m.group('BASE'), 16)
dll_list = dll_list[m.end():]
... | t m:
break
if parse_game_dll_re.search(m.group('NAME').lower()):
return int(m.group('ADDR'), 16)-int(m.group('ADDRHI'), 16)*0x1000-int(m.group('ADDRLO'), 16)
dll_list = dll_list[m.end():]
except:
pass
#print ' ├-无法找到Game.dll的基址,将使用默认值!'
retu... |
jimporter/bfg9000 | bfg9000/environment.py | Python | bsd-3-clause | 12,905 | 0.000155 | import json
import os
import platform
from collections import namedtuple
from . import platforms
from . import tools
from . import shell
from .backends import list_backends
from .file_types import Executable, Node
from .iterutils import first, isiterable, listify
from .path import abspath, InstallRoot, Path, Root
from... | not kwargs.get('shell', False):
args = Command.convert_args(args, lambda x: x.command)
ret | urn shell.execute(args, env=env, base_dirs=self.base_dirs,
**kwargs)
def run(self, args, lang=None, *posargs, **kwargs):
return self.execute(self.run_arguments(args, lang), *posargs, **kwargs)
def save(self, path):
with open(os.path.join(path, self.envfile), 'w') a... |
redhat-cip/horizon | openstack_dashboard/dashboards/admin/defaults/urls.py | Python | apache-2.0 | 986 | 0 | # Copyright 2013 Kylin, 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
| # under the License.
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.defaults import views
urlpatterns = patterns(
'openstack_dashboard.dashboards.admin.defaults.views',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^update... |
thelabnyc/django-oscar-cch | docs/conf.py | Python | isc | 10,340 | 0.000193 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# django-oscar-cch documentation build configuration file, created by
# sphinx-quickstart on Fri Dec 16 14:04:42 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in ... | any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted a | t every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document na... |
awslabs/sockeye | test/unit/test_layers.py | Python | apache-2.0 | 7,135 | 0.002242 | # Copyright 2017--2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not
# use this file except in compliance with the License. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fi... | memory_pt, mask=None, projected_memory_kv=None)
mha.eval()
assert mha.kv_interleaved
r_te | st = mha(queries_pt, memory_pt, mask=None, projected_memory_kv=None)
assert pt.allclose(r_train, r_test, atol=1e-06)
# test with mask
valid_length = pt.randint(1, kvlen + 1, (batch_size,))
mask = sockeye.layers.prepare_source_length_mask(valid_length, heads, kvlen)
mask = mask.repeat(1, qlen, 1) #... |
niknow/scipy | scipy/spatial/tests/test_spherical_voronoi.py | Python | bsd-3-clause | 4,635 | 0.000431 | from __future__ import print_function
import numpy as np
from numpy.testing import (TestCase,
assert_almost_equal, |
assert_array_equal,
assert_array_almost_equal)
from scipy.spatial import SphericalVoronoi, distance
from scipy.spatial import _spherical_voronoi as spherical_voronoi
class TestCircumcenters(TestCase):
def test_circumcenters(self):
tetrahedrons = np.a... | [-1.2, 2.2, 3.2],
[-1.3, -2.3, 3.3]],
[[10, 20, 30],
[-10.1, -20.1, -30.1],
[-10.2, 20.2, 30.2],
[-10.3, -20.3, 30.3]]
])
result = spherical_voronoi.calc_circumcenters(tetrahedrons)
expected = [
[-0.5680861153262... |
maldroid/maldrolyzer | processing/hashes.py | Python | mit | 490 | 0.022449 | from templates import OutputProcessor
import hashlib
from pprint import pprint
class Hashes(OutputProcessor):
def process(self, filename, name, data):
filedata = open(filename).read()
result = {'ma | lware': name}
result['md5'] = hashlib.md5(filedata).hexdigest()
result['sha256'] = hashlib.sha256(filedata).hexdigest()
result['sha1'] = hashlib. | sha1(filedata).hexdigest()
result['sha512'] = hashlib.sha512(filedata).hexdigest()
if data:
result.update(data)
pprint(result)
|
guildai/guild | guild/commands/stop.py | Python | apache-2.0 | 965 | 0 | # Copyright 2017-2021 TensorHub, 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,... |
from __future__ import absolute_import
from __future__ import division
import click
from guild import click_util
from . import runs_stop
@click.command(name="stop")
@runs_stop.runs_stop_params
@click.pass_context
@click_util.use_args
@click_util.render_doc
def stop(ctx, args):
"""{{ runs_stop.stop_runs }}"""... |
FireCARES/firecares | firecares/firecares_core/migrations/0012_departmentinvitation_user.py | Python | mit | 557 | 0.001795 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import setti | ngs
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('firecares_core', '0011_auto_20161208_2205'),
]
operations = [
migrations.AddField(
model_name='departmentinvitation',
name='user',
| field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
),
]
|
mila-udem/blocks-extras | blocks_extras/bricks/__init__.py | Python | mit | 2,174 | 0 | import theano
from theano import shared, tensor
from blocks.bricks import Feedforward, Activation
from blocks.bricks.base import application, lazy
from blocks_extras.initialization import PermutationMatrix
from blocks_extras.utils import check_valid_permutation
from blocks.utils import shared_floatx
class FixedPermut... | ix.
"""
@lazy(allocation=['order'])
def __init__(self, order, dot=True, **kwargs):
self.order = order
self._dot = dot
super(FixedPermutation, self).__init__(**kwargs)
def _allocate(self):
self.order = check_valid_permutation(self.order)
if self.input_dim != len(... | "vector")
# No roles assigned here, since these are not learnable parameters.
if self._dot:
shape = (self.order.shape[0], self.order.shape[0])
self._matrix = shared_floatx(
PermutationMatrix(self.order).generate(None, shape))
else:
... |
shiminsh/youtube_analytics | youtube/youtube/settings.py | Python | mit | 2,602 | 0.000769 | """
Django settings for youtube 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/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
f... | o.contrib.staticfiles',
'bootstrap3',
'analytics',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.co... | ',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'youtube.urls'
WSGI_APPLICATION = 'youtube.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os... |
hzlf/openbroadcast | website/__filer/admin/tools.py | Python | gpl-3.0 | 1,521 | 0.000657 | #-*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
def popup_status(request):
return '_popup' in request. | REQUEST or 'pop' in request.REQUEST
def selectfolder_status(request):
return 'select_folder' in request.REQUEST
def popup_param(request):
if popup_statu | s(request):
return "?_popup=1"
else:
return ""
def check_files_edit_permissions(request, files):
for f in files:
if not f.has_edit_permission(request):
raise PermissionDenied
def check_folder_edit_permissions(request, folders):
for f in folders:
if not f.has_e... |
praekelt/casepro | casepro/msgs/migrations/0012_message_labels.py | Python | bsd-3-clause | 1,203 | 0.004156 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("msgs", "0011_auto_20160222_1422")]
operations = [
migrations.CreateModel(
name="Labelling",
fields=... | model_name="message",
name="labels",
field=models.ManyToManyField(
help_text="Labels assigned to this message", through="msgs.Labelling", to="msgs.Label"
),
),
migrati | ons.AddField(
model_name="labelling",
name="message",
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="msgs.Message"),
),
migrations.AlterUniqueTogether(name="labelling", unique_together=set([("message", "label")])),
]
|
GehirnInc/py3oauth2 | py3oauth2/exceptions.py | Python | mit | 150 | 0 | # -*- coding: utf-8 -*-
OAuthException = type('OAuthException', (Exception, ), {})
Validat | ionError = type('ValidationError', (OAuthException, ), {} | )
|
joachimmetz/plaso | tests/analyzers/hashing_analyzer.py | Python | apache-2.0 | 1,661 | 0.005418 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Hashing analyzer."""
import unittest
from plaso.containers import analyzer_result
from plaso.analyzers import hashing_analyzer
from plaso.analyzers.hashers import manager
from tests import test_lib as shared_test_lib
from tests.analyzers.hashers import ... | ingAnalyze | r()
analyzer.SetHasherNames('testhash')
analyzer.Analyze('test data')
results = analyzer.GetResults()
first_result = results[0]
self.assertIsInstance(first_result, analyzer_result.AnalyzerResult)
self.assertEqual(first_result.analyzer_name, 'hashing')
self.assertEqual(first_result.attribute_... |
vramirez/Ashgabat-Black | python3/s3_uploader.py | Python | mit | 452 | 0.033186 | #Requires .aws credentials at Home
#1 | st arg bucket name
#2nd project name or Folder
#3rd files path
import sys,os,glob,boto3
bkname=sys.argv[1]
prekee=sys.argv[2]+'/'
dir=sys.argv[3]
files=glob.glob(dir)
s3 = boto3.resource('s3')
for filename in files:
kee = os.path.basename(filename)
data = open(filename,'rb')
s3.Bucket(b | kname).put_object(Key=prekee+kee,Body=data)
print("Uploaded "+filename+" to: "+prekee+kee)
data.close()
|
hgl888/web-testing-service | wts/tests/csp/csp_object-src_cross-origin_blocked-manual.py | Python | bsd-3-clause | 2,473 | 0.000809 | def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
_CSP = "object-src " + url2
... | works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright | notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written perm... |
dairin0d/transform-utils | space_view3d_transform_utils/common.py | Python | gpl-3.0 | 3,487 | 0.005736 | # ***** BEGIN GPL LICENSE BLOCK *****
#
# 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 distri... | mport NestedLayout, tag_redraw, rv3d_from_region, messagebox
f | rom {0}dairin0d.bpy_inspect import prop, BlRna, BlEnums, BpyOp, bpy_struct
from {0}dairin0d.utils_accumulation import Aggregator, VectorAggregator
from {0}dairin0d.utils_addon import AddonManager, UIMonitor, addons_registry
""".format(dairin0d_location))
addon = AddonManager()
#=======================================... |
caronc/nzb-subliminal | Subliminal/enzyme/mkv.py | Python | gpl-3.0 | 15,995 | 0.003501 | # -*- coding: utf-8 -*-
from .exceptions import ParserError, MalformedMKVError
from .parsers import ebml
from datetime import timedelta
import logging
__all__ = ['VIDEO_TRACK', 'AUDIO_TRACK', 'SUBTITLE_TRACK', 'MKV', 'Info', 'Track', 'VideoTrack',
'AudioTrack', 'SubtitleTrack', 'Tag', 'SimpleTag', 'Chapter... | ment_names=['Void', 'CRC-32'])
self.video_tracks.extend([VideoTrack.fromelement(t) for t in tracks if t['TrackType'].data == VIDEO_TRA | CK])
self.audio_tracks.extend([AudioTrack.fromelement(t) for t in tracks if t['TrackType'].data == AUDIO_TRACK])
self.subtitle_tracks.extend([SubtitleTrack.fromelement(t) for t in tracks if t['TrackType'].data == SUBTITLE_TRACK])
elif element_name == 'Chapters':
... |
h3biomed/ansible | lib/ansible/plugins/callback/default.py | Python | gpl-3.0 | 17,488 | 0.002459 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: default
type:... | self._dump_results(result._result)),
color=C.COLOR_ERROR, stde | rr=self.display_failed_stderr)
else:
self._display.display("fatal: [%s]: FAILED! => %s" % (result._host.get_name(), self._dump_results(result._result)),
color=C.COLOR_ERROR, stderr=self.display_failed_stderr)
if ignore_errors:
self._... |
bealdav/OpenUpgrade | addons/account_voucher/__openerp__.py | Python | agpl-3.0 | 3,424 | 0.005841 | # -*- 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... | Receipt [Sales & Purchase]
* Voucher Payment [Customer & Supplier]
""",
'category': 'Accounting & Finance',
'sequen | ce': 4,
'website' : 'http://openerp.com',
'images' : ['images/customer_payment.jpeg','images/journal_voucher.jpeg','images/sales_receipt.jpeg','images/supplier_voucher.jpeg','images/customer_invoice.jpeg','images/customer_refunds.jpeg'],
'depends' : ['account'],
'demo' : [],
'data' : [
'secu... |
rdo-management/neutron | neutron/db/migration/alembic_migrations/versions/43763a9618fd_add_mtu_attributes_to_network.py | Python | apache-2.0 | 1,058 | 0.00189 | # Copyright 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 law ... | er express or implied. See the
# License for the specific language governing permissions | and limitations
# under the License.
#
"""add mtu attributes to network
Revision ID: 43763a9618fd
Revises: 16cdf118d31d
Create Date: 2015-02-05 17:44:14.161377
"""
# revision identifiers, used by Alembic.
revision = '43763a9618fd'
down_revision = '16cdf118d31d'
from alembic import op
import sqlalchemy as sa
... |
jnweiger/buttermill | scripts/buttermill_parse.py | Python | gpl-3.0 | 11,423 | 0.017333 | #!/usr/bin/python
# Copyright (c) 2010, Ciaran Farrell <cfarrell1980@gmail.com>
# 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 copyri... | ons
# | and the following disclaimer.
# * Redistributions 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.
# * Ciaran Farrell, the buttermill project and its contributors ma... |
markreidvfx/pyaaf | tests/test_SourceClip.py | Python | mit | 1,541 | 0.003894 | from __future__ import print_function
import aaf
import aaf.mob
import aaf.define
import aaf.iterator
import aaf.dictionary
import aaf.storage
import aaf.component
import aaf.util
import traceback
import unittest
import os
from aaf.util import AUID, MobID
cur_dir = os.path.dirname(os.path.abspath(__file__))
sandbox... | ef.start_time = 10
#source_ref.
source_clip = f.create.Sou | rceClip("picture", 10, source_ref)
assert source_clip.source_ref.mob_id == source_mob.mobID
print(source_clip.source_ref.slot_id)
assert source_clip.source_ref.slot_id == slot.slotID
s = str(source_clip.source_ref)
#slot = source_clip.resolve_slot()
assert source_cli... |
pmeier82/spikeval | doc/source/conf.py | Python | mit | 8,785 | 0.004553 | # -*- coding: utf-8 -*-
#
| # spikeval documentation build configuration file, created by
# sphinx-quickstart on Thu Sep 29 13:42:58 2011.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are presen | t in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, u... |
lucasgit/rl | TD/src/mountaincar.py | Python | mit | 11,073 | 0.024564 | '''
Created on Jan 14, 2016
@author: Lucas Lehnert (lucas.lehnert@mail.mcgill.ca)
Mountain car implementation without noise.
'''
import numpy as np
import matplotlib.pyplot as plt
from mdp import MDPContinuousState
from basisfunction import getTiledStateActionBasisFunction
from util.numpy_json import numpyDictionary... | ), \
# [2. / 5. * np.pi, 2. / 5. * np.pi, 8. / 6. * np.pi, 18. / 6. * np.pi], 4 )
phi = getBasisFunction( mdp )
# ''' This is good for sarsa '''
# alpha = 0.05
# traceLambda = 0.0
# temp = 0.5
# ''' This is good for Q-learning '''
# alpha = 0.05
# temp = 0.5
''' This i... | alpha = 0.05
beta = 0.05
temp = 0.5
# ''' This is good for PGQ '''
# alpha = 0.05
# beta = 0.1
# temp = 0.5
controlPolicy = BoltzmannPolicy( mdp.getActionSpace(), temperature=temp )
# controlPolicy = GreedyPolicy( mdp.getActionSpace() )
initTheta = np.zeros( len( phi( mdp.getStateSpac... |
ofer43211/unisubs | apps/videos/management/commands/setup_indexes.py | Python | agpl-3.0 | 298 | 0.010067 | from django.core.manageme | nt.base import BaseCommand
from south.db import db
class Command(BaseCommand):
help = "Adds indexes that have to be defined with raw SQL commands"
def handle(self, **opt | ions):
db.execute('alter table videos_videourl add unique url_type (url(255), type);')
|
b1-systems/kiwi | test/unit/builder/filesystem_test.py | Python | gpl-3.0 | 5,298 | 0 | import sys
from mock import (
patch, Mock
)
from pytest import raises
from ..test_helper import argv_kiwi_tests
import kiw | i
from kiwi.exceptions import KiwiFileSystemSetupError
from kiwi.builder.filesystem import FileSystemBuilder
class TestFileSystemBuilder:
@patch('kiwi.builder.filesystem.FileSystemSetup')
@patch('platform.machine')
def setup(self, mock_machine, mock_fs_setup):
mock_machine.return_value = 'x8 | 6_64'
self.loop_provider = Mock()
self.loop_provider.get_device = Mock(
return_value='/dev/loop1'
)
self.loop_provider.create = Mock()
self.filesystem = Mock()
self.filesystem.create_on_device = Mock()
self.filesystem.create_on_file = Mock()
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.