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 |
|---|---|---|---|---|---|---|---|---|
itsWeller/SteamCategorizer | categorizer.py | Python | mit | 2,724 | 0.008811 | import vdf
import urllib2
import json
import time
import shelve
filters = ['basic','genres']
URL_BASE = 'http://store.steampowered.com/api/appdetails?appids='
FILTERS = '&filters=' + ','.join(filters)
OWNED_GAMES_URL = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key='
ERR_STR = '\t'*4 + 'Error:... | ['name']
if data[app]['data']['type'] != "game" and data[app]['data']['type'] != "advertising":
print ERR_STR + 'App ' + app_name + ' n | ot of type game: ' + app_id + ' ' + data[app]['data']['type']
return None
if 'genres' not in data[app]['data']:
print ERR_STR + 'App ' + app_name + ' - Genres unavailble for app: ' + app_id
return None
for entry in data[app]['data']['genres']:
for field in entry:
if... |
tedle/acdb | acdb/acdb/urls.py | Python | mit | 163 | 0 | from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^api/', include('api.urls')),
url(r'^', include('base.urls'))
) | ||
jfozard/pyvol | pyvol/mesh/algo.py | Python | mit | 602 | 0.026578 |
import numpy as np
import scipy.linalg as la
def calculate_vertex_normals(verts, | tris):
v_array = np.array(verts)
tri_array = np.array(tris, dtype=int)
tri_pts = v_array[tri_array]
n = | np.cross( tri_pts[:,1] - tri_pts[:,0],
tri_pts[:,2] - tri_pts[:,0])
v_normals = np.zeros(v_array.shape)
for i in range(tri_array.shape[0]):
for j in tris[i]:
v_normals[j,:] += n[i,:]
nrms = np.sqrt(v_normals[:,0]**2 + v_normals[:,1]**2 + v_normals[:,2]**2)
... |
k1nk33/NukeBox2000 | docs/conf.py | Python | mit | 8,447 | 0.005327 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nukebox2000 documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
#... | -------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the d | ocument tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'nukebox2000.tex',
u'NukeBox2000 Documentation',
u'Darren Dowdall', 'manual'),
]
# The name of an image file (relative to this directory) to place... |
lmazuel/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/disk_encryption_settings.py | Python | mit | 1,716 | 0.001166 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ion
key in Key Vault.
:type key_encryption_key:
~azure.mgmt.compute.v2017_12_01.models.KeyVaultKeyReference
:param enabled: Specifies whether disk encryption should be enabled on the
virtual machine.
:type enabled: bool
"""
_attribute_map = {
'disk_encryption_key': {'key': 'd... | y': {'key': 'keyEncryptionKey', 'type': 'KeyVaultKeyReference'},
'enabled': {'key': 'enabled', 'type': 'bool'},
}
def __init__(self, **kwargs):
super(DiskEncryptionSettings, self).__init__(**kwargs)
self.disk_encryption_key = kwargs.get('disk_encryption_key', None)
self.key_encr... |
marrow/web.component.page | web/component/page/render.py | Python | mit | 3,059 | 0.037267 | # encoding: cinje
: import traceback
: from marrow.package.canonical import name
: log = __import__('logging').getLogger(__name__)
: def render_page_panel context, page, wrap
: from web.component.asset.render import render_asset_panel
: using render_asset_panel context, page, True
<li class="list-group-item" id... | width', 12)
: width -= size
: if width and not columns
: columns = True
<div class="container row-fluid clearfix">
: end
: use render_block context, page, block
: if width <= 0
: width = 12 |
: if columns
: columns = False
</div>
: end
: end
: end
: if columns
</div>
: end
: end
: end
: def render_page context, asset
# First, we work out what the title should look like.
: title = [str(asset), str(context.croot)]
: if context.croot.properties.get('direction', 'rtl') == 'ltr'
: tit... |
MTG/essentia | test/src/unittests/stats/test_minmax.py | Python | agpl-3.0 | 2,805 | 0.001783 | #!/usr/bin/env python
# Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... | -45, 2, -1, 0])
self.assertEqual(value, -45.0)
self.assertEqual(index, 2)
def testMixedTypes(self):
value, index = MinMax()([4, 5, 3.3])
self.ass | ertAlmostEqual(value, 3.3)
self.assertEqual(index, 2)
def testMax(self):
value, index = MinMax(type="max")([3, 7, -45, 2, -1, 0])
self.assertEqual(value, 7)
self.assertEqual(index, 1)
suite = allTests(TestMinMax)
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite... |
soybean217/lora-python | UServer/userver/user/models.py | Python | mit | 4,041 | 0.002475 | from database.db_sql import db_sql as db
from sqlalchemy import PrimaryKeyConstraint
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer,
BadSignature, SignatureExpired)
from flask import current_app
from . import passwords
import time
from sqlalchemy.orm import relationshi... | b.Column(db.String(100), nullab | le=True)
last_name = db.Column(db.String(100), nullable=True)
# Relationships
roles = relationship('Role', secondary='lorawan.user_roles')
apps = relationship('Application')
gateways = relationship('Gateway')
def generate_auth_token(self, expiration=600):
s = Serializer(current_app.co... |
foxcarlos/pyganso | cliente_socket.py | Python | gpl-3.0 | 350 | 0.005714 | import socket
import android
droid = android.Android()
servidor = droid.dialogGetInput('Ser | vidor', 'Ingrese el Servidor').result
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#'foxcarlos.no-ip.biz'
server.connect((servidor, 8000))
mensaje = droid.dialogGetInput('Mensaje', 'Ingrese el Mensaje a Enviar').result
server.send(mensaje)
| |
Winand/pandas | pandas/core/indexes/datetimes.py | Python | bsd-3-clause | 79,180 | 0.000025 | # pylint: disable=E1101
from __future__ import division
import operator
import warnings
from datetime import time, datetime
from datetime import timedelta
import numpy as np
from pandas.core.base import _shared_docs
from pandas.core.dtypes.common import (
_NS_DTYPE, _INT64_DTYPE,
is_object_dtype, is_datetime64... | psMixin)
from pandas.tseries.offsets import DateOffset, generate_range, Tick, CDay
from pandas.core.tools.datetimes import (
parse_time_string, normalize_date, to_time)
from pandas.core.tools.timedeltas import to_timedelta
from pandas.util._decorators import (Appender, cache_readonly,
... | das.core.common as com
import pandas.tseries.offsets as offsets
import pandas.core.tools.datetimes as tools
from pandas._libs import (lib, index as libindex, tslib as libts,
algos as libalgos, join as libjoin,
Timestamp, period as libperiod)
from pandas._libs.tslibs ... |
chryswoods/Sire | corelib/build/svnmvall.py | Python | gpl-2.0 | 200 | 0.01 | #!/bin/env python
import s | ys
import os
args = sys.argv[1:]
files = args[0:-1]
newdir = args[-1]
for file in files:
cmd = "svn mv %s %s/" % (file,newdir)
print cmd
os.s | ystem(cmd)
|
floooh/fips | verbs/unset.py | Python | mit | 705 | 0.01844 | """unset a default setting
unset config
unset target
"""
from mod import log, settings
#--------------------------------------------------------- | ----------------------
def run(fips_dir, proj_dir, args) :
"""run the 'unset' verb"""
if len(args) > 0 :
noun = args[0]
settings.unset(proj_dir, noun)
else :
log.error("expected noun: {}".format(', '.join(valid_nouns)))
#---------------------------------------------- | ---------------------------------
def help() :
"""print 'unset' help"""
log.info(log.YELLOW +
"fips unset [{}]\n" .format('|'.join(settings.valid_settings)) + log.DEF +
" unset currently active config or make-target")
|
txiner/db-xiner | hustle/core/pipeline.py | Python | mit | 19,643 | 0.002851 | from disco.core import Job
from disco.worker.task_io import task_input_stream
import hustle
import hustle.core
import hustle.core.marble
from hustle.core.marble import Marble, Column, Aggregation
from functools import partial
from hustle.core.pipeworker import HustleStage
import sys
SPLIT = "split"
GROUP_ALL = "group_... | _nodes.buffer_info()
vk16_ptr, vk16_len = vid16_kids.buffer_info()
self.meta.put_raw(self.txn, '_vid_nodes', vn_ptr, vn_len)
self.meta.put_raw(self.txn, '_vid_kids', vk_ptr, vk_len)
self.meta.put_raw(self.txn, '_vid16_nodes', vn16_ptr, vn16_len)
self.meta.put_... | ble._name))
self.meta.put(self.txn, 'fields', ujson.dumps(self.result_table._fields))
self.meta.put(self.txn, 'partition', ujson.dumps(self.result_table._partition))
for index, (subdb, subindexdb, bitmap_dict, column) in self.dbs.iteritems():
if subindexdb:
... |
jocave/snapcraft | snapcraft/tests/test_commands_cleanbuild.py | Python | gpl-3.0 | 3,951 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | ]
files_no_tar = [
os.path.join(self.stage_dir, 'binary'),
os.path.join(self.snap_dir, 'binary'),
'snap-test.snap',
'snap-test_1.0_source.tar.bz2',
]
for d in dirs:
os.makedirs(d)
for f in files_tar + fi | les_no_tar:
open(f, 'w').close()
main(['cleanbuild', '--debug'])
self.assertIn(
'Setting up container with project assets\n'
'Waiting for a network connection...\n'
'Network connection established\n'
'Retrieved snap-test_1.0_amd64.snap\n',
... |
openstack/python-aodhclient | aodhclient/osc.py | Python | apache-2.0 | 1,844 | 0 | # Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | ersion',
metavar='<alarming-api-version>',
default=utils.env(
'OS_ALARMING_API_VERSION',
default=DEFAULT_ALARMING_API_VERSION),
help=('Queues API version, default=' +
DEFAULT_ALARMING_API_VERSION +
' (Env: OS_ALAR | MING_API_VERSION)'))
return parser
|
zhkzyth/a-super-fast-crawler | logmanager.py | Python | mit | 783 | 0.003995 | #coding:utf8
"""
yet another logging wrapper
- log level
logging.CRITICAL,
logging.ERROR,
logging.WARNING,
logging.INFO,
logging.DEBUG
"""
import logging
from | config import PROJECT_ROOT
def configLogger(logFile="spider.log", logLevel=logging.DEBUG, logTree=""):
logFile = PROJECT_ROOT+"/log/"+ logFile
'''配置logging的日志文件以及日志的记录等级'''
logger = logging.getLogger(logTree)
formatter = logging.Formatter(
'%(asctime)s %(threadName)s %(levelname)s %(message)s')... | leHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
logger.setLevel(logLevel)
return logger
|
ballotify/django-backend | ballotify/apps/api_v1/questions/serializers.py | Python | agpl-3.0 | 4,502 | 0.001333 | from django.db import transaction
from rest_framework import serializers
from questions.models import Question, Choice
from votes.models import Vote, VoteChoice
from streams.models import Stream
from ..accounts.serializers import AccountSerializer
class VoteChoiceUserSerializer(serializers.ModelSerializer):
use... | re | ad_only_fields = ('slug', 'modified', 'created', )
@transaction.atomic
def create(self, validated_data):
"""
Custom create method. Prepare and create nested choices.
"""
choices_data = validated_data.pop("choices", None)
question = Question(**validated_data)
qu... |
AgainFaster/django-wombat-authenticator | wombat_authenticator/migrations/0001_initial.py | Python | bsd-3-clause | 5,385 | 0.008357 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'WombatToken'
db.create_table('wombat_authenticator_wombattoken', (
('id', self.g... | b.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name' | : ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', '... |
pexip/os-pytest | src/_pytest/_version.py | Python | mit | 142 | 0 | # coding: utf-8
# file generated by setuptools_scm
| # don't change, don't track in version control
version | = '6.2.5'
version_tuple = (6, 2, 5)
|
manojklm/pywinauto-x64 | pywinauto/win32structures.py | Python | lgpl-2.1 | 32,760 | 0.004701 | # GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# 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 Software Foundation; either version 2.1
# of the License, or (at you... | n: 560 $"
from .win32defines import LF_FACESIZE, NM | TTDISPINFOW_V1_SIZE, HDITEMW_V1_SIZE
import sys
import ctypes
from ctypes import \
c_int, c_uint, c_long, c_ulong, c_void_p, c_wchar, c_char, \
c_ubyte, c_ushort, c_wchar_p, \
POINTER, sizeof, alignment, Union, c_ulonglong, c_longlong, c_size_t
def is_x64():
return sizeof(c_size_t) == 8
c... |
vaidap/zulip | zerver/views/events_register.py | Python | apache-2.0 | 2,368 | 0.005912 | from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from typing import Iterable, Optional, Sequence, Text
fro | m zerver.lib.events import do_events_register
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.validator import check_string, check_list, check_bool
from zerver.models import Stream, UserProfile
def _default_all_public_streams(user_profile, all_publ... | user_profile.default_all_public_streams
def _default_narrow(user_profile, narrow):
# type: (UserProfile, Iterable[Sequence[Text]]) -> Iterable[Sequence[Text]]
default_stream = user_profile.default_events_register_stream # type: Optional[Stream]
if not narrow and default_stream is not None:
narrow ... |
helfertool/helfertool | src/news/migrations/0002_person_token.py | Python | agpl-3.0 | 478 | 0.002092 | # -*- coding: utf-8 -*-
# Generat | ed by Django 1.10.6 on 2017-03-26 10:54
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('news', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='person',
... | fault=uuid.uuid4, editable=False, null=True),
),
]
|
Azure/azure-sdk-for-python | sdk/containerregistry/azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2018_02_01_preview/_configuration.py | Python | mit | 3,281 | 0.004572 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | als import TokenCredential
class ContainerRegistryManagementClientConfiguration(Configuration):
"""Configuration for ContainerRegistryManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to conne... | def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
super(ContainerRegistryManagementClientConfiguration, self).__init__(**kwargs)
if credential is None:
raise ValueError("Parameter 'credential' must not be... |
narfman0/challenges | algorithms/tests/sorting/test_merge.py | Python | gpl-3.0 | 1,709 | 0.00117 | from unittest import TestCase
from sorting.merge import merge_list, merge_sort, merge_sort_recursive
class TestSortingMerge(TestCase):
def test_merge_list(self):
left = [1, 4, 6]
right = [2, 3, 5]
result = merge_list(left, right)
self.assertEquals(6, len(result))
for i in ... | self.assertEquals(6, result[5])
self.assertEquals(7, result[6])
self.assertEquals(8, result[7])
self.assertEquals(9, result[8])
def test_merge_sort_recursive(self):
array = [1, 7, 5, 4, 6, 8, 5, 3, 9, 8]
result = merge_sort_recursive(array)
self.assertEquals(10, le... | .assertEquals(3, result[1])
self.assertEquals(4, result[2])
self.assertEquals(5, result[3])
self.assertEquals(5, result[4])
self.assertEquals(6, result[5])
self.assertEquals(7, result[6])
self.assertEquals(8, result[7])
self.assertEquals(8, result[8])
self... |
ingadhoc/product | product_management_group/__manifest__.py | Python | agpl-3.0 | 1,296 | 0 | ##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | nu.org/licenses/>.
#
##############################################################################
{
'name': 'Products Management Group',
| 'version': '13.0.1.0.0',
'category': 'base.module_category_knowledge_management',
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'license': 'AGPL-3',
'depends': [
'sale',
],
'data': [
'security/product_management_security.xml',
],
'installable': False,
}
|
rabipanda/tensorflow | tensorflow/python/tools/saved_model_cli.py | Python | apache-2.0 | 29,293 | 0.006111 | # Copyright 2017 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... | re__ import print_function
import argparse
import os
import re
import sys
import warnings
import numpy as np
from six import integer_types
from tensorflow.cont | rib.saved_model.python.saved_model import reader
from tensorflow.contrib.saved_model.python.saved_model import signature_def_utils
from tensorflow.core.example import example_pb2
from tensorflow.core.framework import types_pb2
from tensorflow.python.client import session
from tensorflow.python.debug.wrappers import loc... |
filipecn/lazycf | tests/Test_LazyCF.py | Python | mit | 1,628 | 0.001229 | #!/usr/bin/py
import os
import sys
import shutil
import unittest
sys.path.append(os.path.abspath('..'))
from sample.LazyCF import LazyCF
from sample.CodeForces import CodeForces
class TestLazyCF(unittest.TestCase):
def test__init__(self):
lazy_test = LazyCF()
self.assertEqual(str(lazy_test.__cla... | e(os.path.isdir(path + "/" + folder.index))
shutil.rmtree(path + "/" + folder.index)
def test_create_file(self):
cf = CodeForces()
contest_test = cf.get_contest(768)
lazy = LazyCF()
lazy.create_folder(contest_test)
path = os.path.abspath('.')
for folder ... | ath.isdir(path_folder))
i = 0
for cases in folder.test:
i += 1
name_file = "input_" + str(i)
lazy.create_file(cases.input_text, name_file, path_folder)
name_file = "output_" + str(i)
lazy.create_file(cases.output_tex... |
m-mix/djangocms-bootstrap3-grid | setup.py | Python | bsd-2-clause | 1,149 | 0 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from djangocms_bootstrap3 import __version__
INSTALL_REQUIRES = []
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Licens... | c :: Internet :: WWW/HTTP :: Dynamic Content',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
]
setup(
name='djangocms-bootstr | ap3-grid',
version=__version__,
description='Bootstrap3 grid system plugin for django CMS',
author='Maidakov Mikhail',
author_email='m-email@inbox.com',
url='https://github.com/m-mix/djangocms-bootstrap3-grid',
packages=find_packages(exclude=[]),
install_requires=INSTALL_REQUIRES,
licens... |
gangadhar-kadam/powapp | selling/doctype/device_group/device_group.py | Python | agpl-3.0 | 1,071 | 0.035481 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# For license information, please see license.txt
from __future__ import unicode_literals
import webnotes
from webnotes import msgprint, _
from webnotes.utils import cint,cstr
class DocType:
def __init__(self, d, ... | oc.name
#if self.doc.account_id:
#a=webnotes.conn.sql("select account_id from `tabFranchise`")
qry= "insert into DeviceGroup (accountID,groupID) values ('"+cstr(self.doc.account_id)+"','"+cstr(self.doc.group_id)+"')" |
webnotes.conn.sql(qry)
webnotes.errprint(qry)
#else:
# pass
|
urisimchoni/samba | third_party/pep8/testsuite/W29.py | Python | gpl-3.0 | 367 | 0.016438 | #: Okay
# 情
#: W291:1:6
print
#: W293:2:1
class Foo(object):
bang = 12
#: W291:2:35
'''multiline
string with trailing whitespace'''
#: W292:1:36 noeol
# This line doesn't have a linefeed
#: W292:1:5 E225:1:2 noeol
1+ 1
| #: W292:1:27 E261:1:12 noeol
import this # no line feed
#: | W292:3:22 noeol
class Test(object):
def __repr__(self):
return 'test'
|
haum/hms_irc | hms_irc/commands/tests/test_agenda.py | Python | gpl-3.0 | 4,323 | 0.000232 | import pytest
from hms_irc.commands.agenda import get_instance
from hms_irc.commands.tests import build_command
@pytest.fixture
def instance(irc_server, irc_chan, rabbit):
return get_instance(irc_server, irc_chan, rabbit)
# Misc
def test_commands_available(instance):
"""Test that all required subcomma... | d", "modify", "remove", "all", "help"]
present = list(instance.subcommand_names())
for item in required:
assert("cmd_" + item in present)
# Basic argument checking
def test_invalid_argument(instance):
"""Test to call the agenda c | ommand with an invalid argument."""
instance.handle(build_command("agenda lolilol"))
instance.rabbit.publish.assert_not_called()
def test_bad_argument(instance):
"""Test to call a valid command with a bad format."""
instance.handle(build_command("remove toto", voiced=True))
instance.rabbit.publish... |
rolandgeider/wger | wger/utils/generic_views.py | Python | agpl-3.0 | 10,530 | 0.00095 | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager 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 ... | b import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import (
HttpResponseForbidden,
HttpResponseRedirect
)
from django.urls import reverse_lazy
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy
from django.views.generic import ... | ButtonHolder,
Layout,
Submit
)
# wger
from wger.utils.constants import (
HTML_ATTRIBUTES_WHITELIST,
HTML_STYLES_WHITELIST,
HTML_TAG_WHITELIST
)
logger = logging.getLogger(__name__)
class WgerMultiplePermissionRequiredMixin(PermissionRequiredMixin):
"""
A PermissionRequiredMixin that... |
wk8/Brive | backend.py | Python | unlicense | 8,783 | 0 | # -*- coding: utf-8 -*-
import os
import errno
import time
import tarfile
import shutil
import re
from utils import *
import configuration
# a helper class for actual backends
class BaseBackend(object):
def __init__(self, keep_dirs):
self._root_dir = configuration.Configuration.get(
'backen... | def _get_path(self, user, document):
path = os.path.join(
user.login, document.path if self._keep_dirs else ''
)
return path
# returns Non | e if the current name is not a backup dir
# and the date for this backup if it is
def _get_backup_date(self, name):
if os.path.isdir(os.path.join(self._root_dir, name)):
try:
return self._date_from_session_name(name)
except ValueError:
# not a back... |
yunfanz/ReionBub | Choud14/FZH04.py | Python | mit | 5,526 | 0.056279 | import numpy as n, matplotlib.pyplot as p, scipy.special
import cosmolopy.perturbation as pb
import cosmolopy.density as cd
from scipy.integrate import quad,tplquad
import itertools
from scipy.interpolate import interp1d
from scipy.interpolate import RectBivariateSpline as RBS
import optparse, sys
from sigmas import si... | 6*fgrowth
######################## SIZE DI | STRIBUTION #############################
####################### FZH04 ##############################
def fFZH(S,zeta,B0,B1):
res = B0/n.sqrt(2*n.pi*S**3)*n.exp(-B0**2/2/S-B0*B1-B1**2*S/2)
return res
def BFZH(S0,deltac,smin,K):
return deltac-n.sqrt(2*(smin-S0))*K
def BFZHlin(S0,deltac,smin,K):
b0 = deltac-K*n.sqr... |
apeschar/webwinkelkeur-virtuemart | test/test.py | Python | gpl-3.0 | 3,695 | 0.001083 | #!/usr/bin/env python3
import subprocess
import sys
from os.path import abspath, dirname, join
from time import sleep, perf_counter
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditi... | e.initEvent('change', false, true)
arguments[0].dispatchEvent(e)
''', el, str(value))
def click(self, css_selector, **kwargs):
self.click_by(By.CSS_SELECTOR, css_selector, **kwargs)
def click_text(self, text, **kwargs):
self.click_by(By.PARTIAL_LINK_TEXT, text, **kwargs)... | lf.wait_by(*by, wait=wait)
self.br.execute_script('arguments[0].click()', el)
def wait_by(self, *by, wait=1):
return WebDriverWait(self.br, wait).until(EC.presence_of_element_located(by))
def focus_tab(self):
wait_until = perf_counter() + 5
while len(self.br.window_handles) < 2... |
cgvarela/vitess | test/tablet_test.py | Python | bsd-3-clause | 2,879 | 0.015283 | #!/usr/bin/env python
# coding: utf-8
"""Unit tests for vtdb.tablet"""
import unittest
import mock
from net import gorpc
import utils
from vtdb import tablet
class TestRPCCallAndExtract(unittest.TestCase):
"""Tests rpc_call_and_extract_error is tolerant to various responses."""
tablet_conn = tablet.TabletConn... | response = gorpc.GoRpcResponse()
response.reply = 'foo'
mock_client.call.return_value = response
self.tablet_conn.rpc_call_and_extract_error('method', 'req')
def test_reply_is_dict(self):
| with mock.patch.object(
self.tablet_conn, 'client', autospec=True) as mock_client:
response = gorpc.GoRpcResponse()
response.reply = {'foo': 'bar'}
mock_client.call.return_value = response
self.tablet_conn.rpc_call_and_extract_error('method', 'req')
def test_reply_has_non_dict_err(... |
UCSD-E4E/qx100-interfacing | qx100.py | Python | gpl-2.0 | 3,536 | 0.019231 | #!/usr/bin/env python
"""QX100 interfacing code for python"""
import json
import requests
import numpy as np
import cv2
import threading
from cmd import Cmd
class LiveviewThread(threading.Thread):
running = True
def __init(self, url):
threading.Thread.__init__(self)
self.url = url
self.running = True
... | acket header
start = ord(data.raw.read(1))
if(start != 0xFF):
print 'bad start byte\nexpected 0xFF got %x'%start
return
pkt_type = ord(data.raw.read(1))
if(pkt_type | != 0x01):
print 'not a liveview packet'
return
frameno = int(data.raw.read(2).encode('hex'), 16)
timestamp = int(data.raw.read(4).encode('hex'), 16)
# decode liveview header
start = int(data.raw.read(4).encode('hex'), 16)
if(start != 0x24356879):
print 'expected 0x24356879 got %x'%start
return... |
atreal/atrealtheme.alderamin | src/atrealtheme/alderamin/tests/test_setup.py | Python | gpl-2.0 | 1,242 | 0.003221 | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from atrealtheme.alderamin.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of atrealtheme.alderamin into Plone."""
def setUp(self):
"""Custom shared utility ... | rlayer.xml
def test_browserlayer(self):
"""Test that IAtrealthemeAlderaminLay | er is registered."""
from atrealtheme.alderamin.interfaces import IAtrealthemeAlderaminLayer
from plone.browserlayer import utils
self.failUnless(IAtrealthemeAlderaminLayer in utils.registered_layers())
|
duy/dhcpscapy | scripts/dhcpclientscapy.py | Python | agpl-3.0 | 11,570 | 0.005618 | #! /usr/bin/env python
# vim:ts=4:sw=4:expandtab 2
# -*- coding: utf-8 -*-
'''
Based on https://github.com/mortnerDHCPv4v6
'''
# TODO:
# * refactor
# * read conf from dhclient.conf
# * daemonize
# * requests in loop
# * send renew according to renew time
# * implement release
# * implement nak case
# FIXME:
# * bui... | self.callbacks,
self.history)
def register_callback(self, hook, func):
self.callbacks[hook] = func
def exec_callback(self, hook, args):
self.track_history("Hook:" + str(hook))
if self.callbacks.has_key(hook):
self.callbacks[hook]()
def track_history... | f genDiscover(self):
dhcp_discover = (
Ether(src=str2mac(self.client_mac), dst=self.server_mac) /
IP(src=self.client_ip, dst=self.server_ip) /
UDP(sport=self.client_port, dport=self.server_port) /
BOOTP(chaddr=[self.client_mac], xid=self.client_xid) /
... |
simpleapples/light-blog | app/auth/forms/login_form.py | Python | mit | 295 | 0.00678 | from flask.ext.wtf import Form
from wtforms import StringField, PasswordField
| from wtforms.validators import DataRequired, Length, Email
class LoginForm(Form):
email = StringField(validators=[DataRequired(), Length(1, 64), Email()])
password = PasswordField(v | alidators=[DataRequired()]) |
drestuart/delvelib | lib/pygcurse/pygcurse_old.py | Python | lgpl-3.0 | 110,209 | 0.006288 | """
Please forgive any typos or errors in the comments, I'll be cleaning them up as frequently as I can.
Pygcurse v0.1 alpha
Pygcurse (pronounced "pig curse") is a curses library emulator that runs on top of the Pygame framework. It provides an easy way to create text adventures, roguelikes, and console-style applic... | 'green': pygame.Color( 0, 128, 0),
'blue': pygame.Color( 0, 0, 255),
'navy': pygame.Color( 0, 0, 128),
'black': pygame.Color( 0, 0, 0)}
class PygcurseSurface(object):
"""
A PygcurseSurface object is the ascii-based analog of Pygam... | r, foreground color, background color, and RGB tint. The PygcurseSurface object also tracks the location of the cursor (where the print() and putchar() functions will output text) and the "input cursor" (the blinking cursor when the user is typing in characters.)
Each xy position on the surface is called a "cell".... |
passiweinberger/nupic | tests/swarming/nupic/swarming/swarming_test.py | Python | agpl-3.0 | 101,562 | 0.009561 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# 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 ... | path.abspath(thisFile))[0]
self.testSrcExpDir = os.path.join(testDir, 'experiments')
self.testSrcDataDir = os.path.join(testDir, 'data')
return
class ExperimentTestBaseClass(HelperTestCaseBase):
def setUp(self):
""" Method called to prepare the test fixture. This is called by the
unittest fr... | ely before calling the test method; any exception
raised by this method will be considered an error rather than a test
failure. The default implementation does nothing.
"""
pass
def tearDown(self):
""" Method called immediately after the test method has been called and the
result recorded. T... |
wevote/WebAppPublic | apis_v1/documentation_source/voter_star_on_save_doc.py | Python | bsd-3-clause | 4,125 | 0.003394 | # apis_v1/documentation_source/voter_star_on_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_star_on_save_doc_template_values(url_root):
"""
Show documentation about voterStarOnSave
"""
required_query_parameter_list = [
{
'name': 'api_key... | us_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
| {
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. Missing voter_id while trying to save.',
},
{
'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
{
'code': ... |
hinrek/Suvepraktika | events/migrations/0006_auto_20170620_1225.py | Python | mit | 1,100 | 0.001818 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-0 | 6-20 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import location_field.models.plain
class Migration(migrations.Migration):
dependencies = [
('events', '0005_merge_20170619_1150'),
]
operations = [
migrations.AlterField(
model_name='... | model_name='event',
name='city',
field=models.CharField(default='Tallinn', max_length=255, verbose_name='Linn'),
),
migrations.AlterField(
model_name='event',
name='descripton',
field=models.TextField(verbose_name='Kirjeldus'),
)... |
SUSE/azure-sdk-for-python | azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2016_06_01/models/location_paged.py | Python | mit | 874 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[Location]'}
}
def __init__(self, *args, **kwargs):
super(LocationPaged, self).__init__(*args, **kwar | gs)
|
tsdmgz/ansible | lib/ansible/modules/network/aci/aci_bd.py | Python | gpl-3.0 | 12,055 | 0.002323 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | arding should be allowed.
- The APIC defaults new Bridge Domains to C(yes).
choices: | [ no, yes ]
default: yes
endpoint_clear:
description:
- Clears all End Points in all Leaves when C(yes).
- The APIC defaults new Bridge Domains to C(no).
- The value is not reset to disabled once End Points have been cleared; that requires a second task.
choices: [ no, yes ]
default: no
... |
lesommer/oocgcm | oocgcm/oceanfuncs/eos/teos10.py | Python | apache-2.0 | 209 | 0.004785 | #!/usr/bin/env pyt | hon
#
"""oocgcm.oceanfuncs.eos.teos10
Equation of state of sea water and related quantities.
This module uses the formulas from the
Thermodynamic Equation Of Seawater - 2010 (TEOS-10)
" | ""
|
JulienMcJay/eclock | windows/Python27/Lib/site-packages/docutils/parsers/rst/languages/cs.py | Python | gpl-2.0 | 4,857 | 0.002059 | # $Id: cs.py 7119 2011-09-02 13:00:23Z milde $
# Author: Marek Blaha <mb@dat.cz>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each lan... | 'sidebar',
u't\u00E9ma': 'topic',
u'line-block (translation required)': 'line-block',
u'parsed-literal (translation required)': 'pars | ed-literal',
u'odd\u00EDl': 'rubric',
u'moto': 'epigraph',
u'highlights (translation required)': 'highlights',
u'pull-quote (translation required)': 'pull-quote',
u'compound (translation required)': 'compound',
u'container (translation required)': 'container',
#'questions': 'qu... |
ctrlaltdel/neutrinator | vendor/stevedore/enabled.py | Python | gpl-3.0 | 3,569 | 0 | # 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 u... | getLogger(__name__)
class EnabledExtensionManager(ExtensionManager):
"""Loads only plugins that pass a check function.
The check_func argument should return a boolean, with ``True``
indicating that the extension should be loaded and made available
and ``False`` indicating that the extension should be... | s.
:type namespace: str
:param check_func: Function to determine which extensions to load.
:type check_func: callable, taking an :class:`Extension`
instance as argument
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is... |
desihub/desispec | doc/conf.py | Python | bsd-3-clause | 10,086 | 0.005057 | # -*- coding: utf-8 -*-
#
# desispec documentation build configuration file, created by
# sphinx-quickstart on Tue Dec 9 10:43:33 2014.
#
# 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.
#
# ... | hs that contain custom static files (such as style sheets) here,
# relativ | e to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# di... |
mikeakohn/naken_asm | tests/comparison/scripts/gen_riscv.py | Python | gpl-3.0 | 1,166 | 0.030875 | #!/usr/bin/env python
import os
def create_asm(instruction):
if instruction.startswith("main:"):
if "ja" in instruction:
instruction = "." + instruction
#print instruction
out = open("temp.asm", "wb")
out.write(" " + instruction + "\n")
out.close()
# --------------------------------- fold her... | )
#os.system("as-new temp.asm")
#os.system("objcopy -F ihex a.out riscv_gnu.hex")
fp1 = open("riscv_gnu.hex", "rb")
hex = fp1.readline().strip()
#if instruction.startswith("b"):
#l = len(hex)
#old = hex + " " + hex[:l-10] + " " + hex[-2:]
#out.write(old + "\n")
#hex = hex[0:l-10] + hex[-2:]
... | ")
|
openstack/python-openstackclient | openstackclient/network/v2/l3_conntrack_helper.py | Python | apache-2.0 | 8,285 | 0 | # 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
# distrib... | **attrs)
class ShowConntrackHelper(command.ShowOne):
_description = _("Display L3 conntrack helper details")
def get_parser(self, prog_name):
parser = super(ShowConntrackHelper, self).get_parser(prog_name)
parser.add_argument(
'router',
metavar='<router>',
... | help=_('The ID of the conntrack helper')
)
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.network
router = client.find_router(parsed_args.router, ignore_missing=False)
obj = client.get_conntrack_helper(
parsed_args.connt... |
eduble/panteda | sakura/common/stream.py | Python | gpl-3.0 | 4,447 | 0.003823 | import numpy as np, gevent, traceback
from gevent.queue import Queue, Empty
from sakura.common.release import auto_release
from sakura.common.chunk import NumpyChunk
from sakura.common.exactness import EXACT, APPROXIMATE, UNDEFINED, Exactness
def reassemble_chunk_stream(it, dt, chunk_size):
if chunk_size is None:
... | self._run)
self._out_queue.get() # wait for bg greenlet init
def release(self):
if self._glet is not None:
self._glet.kill() # kill
self._in_queue = None
self._out_queue = None
self._glet = None
| self._it = None
def _run(self):
in_queue = self._in_queue
out_queue = self._out_queue
it = self._it
try:
# notify caller we are now running
out_queue.put(1)
# run main loop
while True:
# wait for next chunk reques... |
census-instrumentation/opencensus-python | tests/unit/trace/test_tracer.py | Python | apache-2.0 | 9,886 | 0 | # Copyright 2017, OpenCensus 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 or agreed to in w... | _span_sampled(self):
sampler = mock.Mock()
sampler.should_sample.return_value = True
tracer = tracer_module.Tracer(sampler=sampler)
tracer_mock = mock.Mock()
tracer.tracer = tracer_mock
tracer.span()
self.assertTrue(tracer_mock.span.called)
def test_start_s... | race.blank_span import BlankSpan
sampler = mock.Mock()
sampler.should_sample.return_value = False
span_context = mock.Mock()
span_context.trace_options.enabled = False
tracer = tracer_module.Tracer(
span_context=span_context, sampler=sampler)
span = tracer.s... |
mikewrock/phd_backup_full | build/selected_points_publisher/catkin_generated/pkg.installspace.context.pc.py | Python | apache-2.0 | 387 | 0 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFI | X = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "selected_points_publisher"
PROJECT_SPACE_DIR = "/home/m | ike/catkin_ws/install"
PROJECT_VERSION = "1.0.0"
|
benosteen/django-databank | src/frontend/utils/_old/ident_md.py | Python | mit | 1,379 | 0.000725 | # -*- coding: utf-8 -*-
"""
Copyright (c) 2012 University of Oxford
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modif... | N AN ACTION OF CONTRACT,
TORT OR OTHERWISE, A | RISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from rdfdatabank.config.users import _USERS as _DATA
class IdentMDProvider(object):
def add_metadata(self, environ, identity):
userid = identity.get('repoze.who.userid')
info = _DATA.get(useri... |
wheeler-microfluidics/mr-box-peripheral-board.py | mr_box_peripheral_board/ui/gtk/measure_dialog.py | Python | mit | 7,247 | 0.001932 | import datetime as dt
import threading
from serial_device.or_event import OrEvent
import numpy as np
import pandas as pd
import gobject
import gtk
import matplotlib as mpl
from streaming_plot import StreamingPlot
from ...max11210_adc_ui import MAX11210_read
import logging
def _generate_data(stop_event, data_ready, d... | re_dialog` function.
'''
#set the adc digital gain
# proxy.MAX11210_setGain(adc_dgain)
| #Set the pmt shutter pin to output
proxy.pin_mode(9, 1)
logger = logging.getLogger(__name__)
def _read_adc(stop_event, data_ready, data):
'''
Parameters
----------
stop_event : threading.Event
Function returns when :data:`stop_event` is set.
data_ready... |
Comcast/rulio | examples/actionendpoint.py | Python | apache-2.0 | 2,070 | 0.004831 | #!/usr/bin/python
# Copyright 2015 Comcast Cable Communications Management, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | json
PORT = 6667
def protest (response, message):
response.send_response(200)
response.send_header('Content-type','application/json')
response.end_headers()
response.wfile.write(message)
class handler(BaseHTTPRequestHandler):
def do_GET(self):
protest(self, "You should POST with json.\n"... | ntent_len = int(self.headers.getheader('content-length'))
body = self.rfile.read(content_len)
print 'body ', body
self.send_response(200)
self.send_header('Content-type','application/json')
self.end_headers()
response = '{"Got":%s}' % (body)
... |
pmisik/buildbot | master/buildbot/db/base.py | Python | gpl-2.0 | 5,687 | 0.000528 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTAB | ILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Cop... |
singleswitch/ticker | settings_editor.py | Python | mit | 9,463 | 0.012575 |
#FIXME: UNDO, click time at end to undo
from PyQt4 import QtCore, QtGui
import sys, os
import volume_editor_layout, settings_layout, cPickle
import numpy as np
from utils import Utils
class SettingsEditWidget(QtGui.QDialog, settings_layout.Ui_Dialog):
#################################################### Init
... | ings
def getCurrentChannel(self):
return self.getChannel(self.box_channels.currentIndex())
def getChannel(self, i_index):
return | int(self.box_channels.itemText(i_index))
#################################################### Set
def setSettings(self, i_settings):
#Get the parameters
click_params = (i_settings['delay'], i_settings['std'], i_settings['fr'], i_settings['fp_rate'])
(delay, std, fr, fp_rate) = se... |
111pontes/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_infra_objmgr_oper.py | Python | apache-2.0 | 57,513 | 0.016987 |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... | CE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION, ANYXML_CLASS
from ydk.errors import YPYError, YPYModelError
from ydk.providers._importer import _yang_ns
_meta_table = {
'EndPortEnum' : _MetaInfoEnum('EndPortE | num', 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_objmgr_oper',
{
'echo':'echo',
'discard':'discard',
'daytime':'daytime',
'chargen':'chargen',
'ftp-data':'ftp_data',
'ftp':'ftp',
'ssh':'ssh',
'telnet':'telnet',
... |
Mimino666/tc-marathoner | marathoner/utils/ossignal.py | Python | mit | 765 | 0 | import signal
signal_names = {}
for signame in dir(signal):
if signame.startswith('SIG'):
signum = getattr(signal, signame)
if isinstance(signum, int):
signal_names[signum] = signame
def get_signal_name(signal_code):
name = signal_names.get(signal_code, '')
if name:
r... | en function as a signal handler for all common shutdown
signals (such as SIGI | NT, SIGTERM, etc).
'''
signal.signal(signal.SIGTERM, func)
signal.signal(signal.SIGINT, func)
# Catch Ctrl-Break in windows
if hasattr(signal, 'SIGBREAK'):
signal.signal(signal.SIGBREAK, func)
|
micronicstraining/python | module_3/lesson_3/practice.py | Python | agpl-3.0 | 3,261 | 0.003068 | #! /usr/bin/env python3
# Create a rotate by 13 encoder - http://www.rot13.com/
# Use:
# hint use codecs.encode. look it up in the documentation
import codecs
def rot13_encode(data):
""" Take in unencoded data and rot13 and return new data """
return codecs.encode(data, 'rot13')
# What will be the output?
h... | ountry
# over ride the __repr__ to print out a well formatted address.
#
# Create a class call Customer
# It should have a first name, last name, ema | il and address object
#
# SKIP NEXT ONE:
# Create a product class. It hsould have an item name and cost.
# Override the __add__ method so products can be added to each other
#
# - closure, lambda review
#
|
jarcodallo/custom_modules | legacy_clients/__openerp__.py | Python | gpl-2.0 | 229 | 0.004405 | {
'nam | e': "Legacy Partner integration",
'version': "1.1",
'author': "José A. Ramírez",
'category': "Tools",
'depends': ['base'],
'data': ['legacy_partner.xml'],
'demo': [],
| 'installable': True,
} |
iw3hxn/LibrERP | stock_picking_extended/models/inherit_stock_location.py | Python | agpl-3.0 | 5,169 | 0.002902 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2010-2012 Associazione OpenERP Italia
# (<http://www.openerp-italia.org>).
# Copyright (C) 2014 Didotech srl
# (<http://www.didotech.com>).
#
# This program is free software: you can r... | vals:
for product_id in product_vals.keys():
product_val = product_vals[product_id]
if product_val:
product_val['date_product_by_location_update'] = date_product_by_location_update
product_obj.write(cr, uid, product_... | = '{sec}'.format(sec=duration_seconds)
_logger.info(u'update_product_by_location get in {duration}'.format(duration=duration))
return True
def create_product_by_location(self, cr, location_name, context):
model_id = self.pool['ir.model.data'].get_object_reference(cr, SUPERUSER_ID, 'product'... |
alephu5/Soundbyte | environment/lib/python3.3/site-packages/matplotlib/backends/backend_qt4.py | Python | gpl-3.0 | 31,660 | 0.008654 |
import math
import os
import re
import signal
import sys
import matplotlib
from matplotlib import verbose
from matplotlib.cbook import is_string_like, onetrue
from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \
FigureManagerBase, FigureCanvasBase, NavigationToolbar2, IdleEvent, \
curso... | l.SIGINT, signal.SIG_ | DFL)
QtGui.qApp.exec_()
show = Show()
def new_figure_manager( num, *args, **kwargs ):
"""
Create a new figure manager instance
"""
thisFig = Figure(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig)
def new_figure_manager_given_figure(num, figure):
"""
Create ... |
GoogleCloudPlatform/magic-modules | mmv1/provider/ansible/test_gcp_session.py | Python | apache-2.0 | 6,426 | 0.002023 | # -*- coding: utf-8 -*-
# (c) 2019, Google Inc.
#
# 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 distributed in the hope that it will be useful,
# but W | ITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from pytest i... |
ndncomm/mini-ndn | ndn/experiments/integration_tests.py | Python | gpl-3.0 | 3,981 | 0.004019 | # -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
#
# Copyright (C) 2015 The University of Memphis,
# Arizona Board of Regents,
# Regents of the University of California.
#
# This file is part of Mini-NDN.
# See AUTHORS.md for a complete list of Mini-NDN authors an... | st_multicast_strategy",
#"test_multicast",
#"test_tcp_udp_tunnel",
#"test_localhop",
"test_unixface",
"test_ndnpeekpoke",
| "test_route_expiration",
#"test_nfdc",
"test_ndnping",
"test_cs_freshness",
"test_nrd",
"test_fib_matching",
#"test_remote_register",
"test_ndntraffic"
]
for test in tests:
a.cmd("./run_tests.py", test, ve... |
plotly/python-api | packages/python/plotly/plotly/validators/funnelarea/title/font/_family.py | Python | mit | 616 | 0.001623 | import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __ini | t__(
self, plotly_name="family", parent_name="funnelarea.title.font", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit | _type", "plot"),
no_blank=kwargs.pop("no_blank", True),
role=kwargs.pop("role", "style"),
strict=kwargs.pop("strict", True),
**kwargs
)
|
mcvmcv/wurstboard | tests.py | Python | gpl-2.0 | 1,285 | 0.004669 | #!flask/bin/python
import os
import unittest
from config import basedir
from app import app, db
from app.models import User
class TestCase(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlit... | .add(u)
db.session | .commit()
nickname2 = User.make_unique_nickname('john')
assert nickname2 != 'john'
assert nickname2 != nickname
if __name__ == '__main__':
unittest.main()
|
treasure-data/luigi-td | setup.py | Python | apache-2.0 | 778 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name="luigi-td",
version='0.6.10.dev0',
description="Luigi integration for Treasure Data",
author="Treasure Data, Inc.",
author_email="support@treasure-data.com",
url="https://github.com/treasure-data/luigi-td",
insta... | license="Apache Licen | se 2.0",
platforms="Posix; MacOS X; Windows",
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Topic :: Softwar... |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_database_automatic_tuning_operations.py | Python | mit | 10,488 | 0.003719 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | ct[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _S | ERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_update_request(
resource_group_name: str,
server_name: str,
database_name: str,
subscription_id... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/PyKDE4/kdeui/KTimeComboBox.py | Python | gpl-2.0 | 3,363 | 0.011299 | # encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python2.7/dist-packages/PyKDE4/kdeui.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
impo | rt PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
from KComboBox import KComboBox
class KTimeComboBox(KComboBox):
# no doc
def assignTime(self, *args, **kwargs): # real signature unknown
pass
def displayFormat(self, *args, **kwargs): # real... | wn
pass
def focusOutEvent(self, *args, **kwargs): # real signature unknown
pass
def hidePopup(self, *args, **kwargs): # real signature unknown
pass
def isNull(self, *args, **kwargs): # real signature unknown
pass
def isValid(self, *args, **kwargs): # real signature un... |
gkotton/vmware-nsx | vmware-nsx/neutron/tests/unit/vmware/extensions/test_portsecurity.py | Python | apache-2.0 | 1,831 | 0.000546 | # Copyright (c) 2014 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... | patch_sync.start()
instance.return_value.request.side_effect = self.fc.fake_request
super(PortSecurityTestCase, self).set | Up(vmware.PLUGIN_NAME)
self.addCleanup(self.fc.reset_all)
self.addCleanup(self.mock_nsx.stop)
self.addCleanup(patch_sync.stop)
class TestPortSecurity(PortSecurityTestCase, psec.TestPortSecurity):
pass
|
tuos/FlowAndCorrelations | flowCorr/cmssw5320/FlowCorr/test/ConfFile_cfg.py | Python | mit | 2,206 | 0.031732 | import FWCore.ParameterSet.Config as cms
process = cms.Process("Demo")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
#process.MessageLogger.cerr.FwkReport.reportEvery = 100
process.source = cms.Source("PoolSource",
# replace 'my... | = cms.bool(True)
process.hltHIMB.throw = cms.bool(False)
process.TFileService = cms.Service("TFileService",
| fileName=cms.string("flowCorr2760_data.root")
)
process.flowCorr = cms.EDAnalyzer('FlowCorr',
EvtPlane = cms.InputTag("hiEvtPlane"),
EvtPlaneFlat = cms.InputTag("hiEvtPlaneFlat",""),
HiMC = cms.InputTag("heavyIon"), ... |
hanula/pypkg_template | pypkg_template/tests/test_foo.py | Python | bsd-2-clause | 449 | 0 |
import unittest
from nose.tools import assert | _equal
class TestBar(unittest.TestCase):
def call_FUT(self, count):
from | pypkg_template.foo import bar
return bar(count)
def test_friday_sunday(self):
for day in (5, 6):
assert_equal(self.call_FUT(day), "I'm in a bar")
def test_workday(self):
for day in list(range(1, 5)) + [7]:
assert_equal(self.call_FUT(day), "No bar tonight")
|
konstruktoid/ansible-upstream | lib/ansible/modules/network/eos/eos_config.py | Python | gpl-3.0 | 19,251 | 0.001454 | #!/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... | default: line
| choices: ['line', 'strict', 'exact', 'none']
replace:
description:
- Instructs the module on the way to perform the configuration
on the device. If the replace argument is set to I(line) then
the modified lines are pushed to the device in configuration
mode. If the replace argu... |
Quantipy/quantipy | quantipy/core/tools/qp_decorators.py | Python | mit | 6,656 | 0.003456 |
from decorator import decorator
from inspect import getargspec
# ------------------------------------------------------------------------
# decorators
# ------------------------------------------------------------------------
def lazy_property(func):
"""Decorator that makes a property lazy-evaluated.
"""
... |
valid = []
for v in var:
if ' > ' in v:
valid.extend(v.replace(' ', | '').split('>'))
elif not '@' == v:
valid.append(v)
# check if varaibles are categorical
not_cat = [v for v in valid if not ds._has_categorical_data(v)]
if not_cat:
msg = "'{}' argument for {}() must reference categorical "
... |
frossigneux/python-kwrankingclient | kwrankingclient/v1/shell_commands/nodes.py | Python | apache-2.0 | 1,816 | 0 | # Copyright (c) 2014 Bull.
#
# 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, sof... | t-by', metavar="<node_column>",
help='column name used to sort result',
default='node'
)
return parser
class ShowNode(command.ShowCommand):
"""Show node status."""
resource = 'node'
json_indent = 4
allow_names = False
log = logging | .getLogger(__name__ + '.ShowNode')
class UpdateNode(command.UpdateCommand):
"""Update node status."""
resource = 'node'
allow_names = False
log = logging.getLogger(__name__ + '.UpdateNode')
def get_parser(self, prog_name):
parser = super(UpdateNode, self).get_parser(prog_name)
par... |
Bystroushaak/abclinuxuapi | tests/test_blogpost.py | Python | mit | 4,767 | 0.001049 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
impo | rt os.path
import pytest
import abclinuxuapi
from abclinuxuapi import shared
@pytest.fixture
def bp_ur | l():
return "http://www.abclinuxu.cz/blog/bystroushaak/2015/2/bolest-proxy"
@pytest.fixture
def do_that_fucking_monkey_patch(monkeypatch):
def mock_download(*args, **kwargs):
fn = os.path.join(os.path.dirname(__file__), "mock_data/blogpost.html")
with open(fn) as f:
return f.read(... |
lawki/get_flash_videos_assembler | create_exec_.py | Python | gpl-3.0 | 628 | 0.007962 | #!usr/bin/python
try:
f = open("link.txt","r")
except IOError:
print "ERROR!\n"
exit
o = open("download_all_files.sh","w")
for line in f:
if len(line)==0 | :
continue
file_name = line.split("/")
file_name = file_name[len(file_name)-1]
file_name = "\""+file_name[:len(file_name)-1]+".mp4\""
command = "if test -f "+file_name+"\nthen\n continue\n else\n get_flash_videos "+line[:len(line)-1]+" -f "+file_name+""+"\nfi\n"+"if test $? -ne 0\n then\n if te... | e)-1]+"\">>\"problem_downloading.txt\"\nfi\n"
o.write(command)
|
bossiernesto/uLisp | uLisp/parser/uLispParser.py | Python | bsd-3-clause | 2,979 | 0.004028 | """
BNF reference: http://theory.lcs.mit.edu/~rivest/sexp.txt
<sexp> :: <string> | <list>
<string> :: <display>? <simple-string> ;
<simple-string> :: <raw> | <token> | <base-64> | <hexadecimal> |
<quoted-string> ;
<display> :: "[" <simple-string> "]" ;
<raw> :: <decimal> ":" <bytes> ;
<deci... | t=None)("len") + VBAR + OneOrMore(Word(alphanums + "+/=")).setParseAction(
lambda t: b64decode("".join(t))) + VBAR).setParseAction(verifyLen)
qString = Group(Optional(decimal, default=None)("len") +
dblQuotedString.setParseAction(removeQuotes)).setParseAction(verifyLen)
simpleString = base64_ |... | (r"[+-]?\d+\.\d*([eE][+-]?\d+)?").setParseAction(lambda tokens: float(tokens[0]))
token = Word(alphanums + "-./_:*+=!<>")
simpleString = real | base64_ | raw | decimal | token | hexadecimal | qString
display = LBRK + simpleString + RBRK
string_ = Optional(display) + simpleString
uLisp_parse = Forward()
sexpList = G... |
grap/OpenUpgrade | addons/stock/stock.py | Python | agpl-3.0 | 273,917 | 0.005732 | # -*- 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... | 'comment': fields.text('Additional Information'),
'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
'posz': fields.integer('H... | ight Parent', select=1),
'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between companies'),
'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.... |
heibanke/python_do_something | Code/Chapter5/meta_04.py | Python | apache-2.0 | 1,022 | 0.016634 | #!/usr/bin/env python
# coding: utf-8
#http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Metaprogramming.html
class RegisterClasses(type):
def __init__(cls, name, bases, atts):
super(RegisterClasses, cls).__init__(name, bases, atts)
if not hasattr(cls, 'registry'):
... | # Remove base classes
# Metamethods, called on class objects:
def __iter__(cls):
return iter(cls.registry)
def __str__(cls):
if cls in cls.registry:
return cls.__name__
return cls.__name__ + ": " + ", ".join([sc.__name__ for sc in cls])
class Shape(object):
... | ss
class Ellipse(Round): pass
print Shape
for s in Shape: # Iterate over subclasses
print s
|
CodeCarrots/warsztaty | sesja07/bigmeal.py | Python | cc0-1.0 | 955 | 0.007592 | """
Prosta klasa reprezentująca posiłek składający się z wielu innych
obiektów jadalnych.
"""
class BigMeal:
def __init__(self, edibles):
# TODO: zainicjuj obiekt przekazaną listą obiektów jadalnych
# "edibles"
def get_name(self):
# TODO: zaimplementuj metodę zwracającą nazwę obiektu
... | banana = Food("Banan", 60)
fruitmix = BigMeal([apple, carrot, banana])
print (fruitmix.get_name()) # "Jablko i Marchewka i Banan"
| print (fruitmix.get_calories()) # 210
|
JeroenBosmans/nabu | nabu/distributed/local_cluster.py | Python | mit | 1,506 | 0.001992 | '''@file main.py
this function is used to run distributed training on a local cluster'''
import os
import atexit
import subprocess
import tensorflow as tf
def local_cluster(expdir, class_type):
'''main function'''
#read the cluster file
clusterfile = os.path.join(expdir, 'cluster', 'cluster')
machin... | rfile) as fid:
for line | in fid:
if len(line.strip()) > 0:
split = line.strip().split(',')
machines[split[0]].append(
(split[1], int(split[2]), split[3]))
#start all the jobs
processes = []
for job in machines:
task_index = 0
for _ in machines[job]:
... |
windmill/windmill | windmill/dep/_mozrunner/__init__.py | Python | apache-2.0 | 7,224 | 0.006506 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
| # under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions... |
xzturn/caffe2 | caffe2/python/net_printer.py | Python | apache-2.0 | 12,712 | 0.000393 | ## @package net_printer
# Module caffe2.python.net_printer
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto.caffe2_pb2 import OperatorDef, NetDef
from caffe2.python.checkpoint import Job
from caffe2.py... | for x in chain(
[factor_prefix(inputs_v, factor_prefixes)],
('%s=%s' % kv for kv in inputs_kv),
)
if x
)
call = '%s(%s)' % (op, inputs)
return call if not outputs else '%s = %s' % (
factor_prefix(outputs, factor_prefixes), call)
... | n call(
'DeviceOption',
[dev_opt.device_type, dev_opt.cuda_gpu_id, "'%s'" % dev_opt.node_name])
@Printer.register(OperatorDef)
def print_op(text, op):
args = [(a.name, _arg_val(a)) for a in op.arg]
dev_opt_txt = format_device_option(op.device_option)
if dev_opt_txt:
|
Akrog/cinder | cinder/api/common.py | Python | apache-2.0 | 15,127 | 0 | # Copyright 2010 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 requ... | bob.exc.HTTPBadRequest: If both 'sort' and either 'sort_key' or
| 'sort_dir' are supplied parameters
"""
if 'sort' in params and ('sort_key' in params or 'sort_dir' in params):
msg = _("The 'sort_key' and 'sort_dir' parameters are deprecated and "
"cannot be used with the 'sort' parameter.")
raise webob.exc.HTTPBadRequest(explan... |
mpolden/jarvis2 | jarvis/jobs/calendar.py | Python | mit | 1,462 | 0.000684 | # -*- coding: utf-8 -*-
import os
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from datetime import datetime
from jobs import AbstractJob
class Calendar(AbstractJob):
def __init__(self, conf):
self.interval = conf["interval"]
self.timeout = conf.get... | now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
result = (
self.service.events()
.list(
calendarId=" | primary",
orderBy="startTime",
singleEvents=True,
timeMin=now,
)
.execute()
)
return {"events": self._parse(result["items"])}
|
crmccreary/openerp_server | openerp/addons/procurement/wizard/orderpoint_procurement.py | Python | agpl-3.0 | 2,927 | 0.003416 | # -*- 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... | ic=proc.automatic, use_new_cursor=new_cr.dbname, context=context)
#close the new cursor
new_cr.close()
return {}
def procure_calculation(self, cr, uid, ids, context=None):
"""
@param self: The object | pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selected
@param context: A standard dictionary
"""
threaded_calculation = threading.Thread(target=self._procure_calculation_orderpoint, args=(cr, uid, ids, context... |
ellak-monades-aristeias/enhydris | enhydris/permissions/tests.py | Python | agpl-3.0 | 1,553 | 0.007083 | import unittest
from django.contrib.auth.models import User, Group
from enhydris.hcore.models import Gentity
class PermissionsTestCase(unittest.TestCase):
def setUp(self):
self.object = Gentity.objects.create(name='testgent')
self.object.save()
self.user = User.objects.create(username='test... | self.user.save()
self.group = Group.objects.create(name='testgroup')
self.group.save()
def tearDown(self):
self.object.delete()
self.user.delete()
self.group.delete()
def testUserPerms(self):
assert self.user.has_row_perm(self.object, 'permission') == False
... | on') == True
self.user.del_row_perm(self.object, 'permission')
assert self.user.has_row_perm(self.object, 'permission') == False
def testGroupPerms(self):
assert self.user.has_row_perm(self.object, 'permission') == False
assert self.group.has_row_perm(self.object, 'permission') == F... |
rssenar/PyToolkit | ValidateFiles.py | Python | bsd-2-clause | 2,072 | 0.034749 |
#!/usr/bin/env python3.4
# ---------------------------------------------------------------------------- #
import csv, os
# ---------------------------------------------------------------------------- #
def Validate():
Message1 = 'VALIDATED!!!'
Message2 = '''
$$$$$$$$\
$$ | $$$$$$\ $$$$$$\ $$$$$$\ $$$$$... | der(PurchaseFile)
next(PurchaseFile)
for line in Purchase:
Entries.add((line[1],line[2],line[3],line[4],line[5],line[6]))
if File1 != '':
ErrorCounter = 0
with open(InputFile,'rU') as InputFile:
Input = csv.reader(InputFile)
next(InputFile)
for line in Input:
key... | le:
Error = csv.writer(ErrorFile)
Error.writerow(line)
ErrorCounter += 1
if ErrorCounter > 0:
print('{} Errors Found'.format(ErrorCounter))
print(Message2)
else:
print(Message1)
# ---------------------------------------------------------------------------- #
if __name_... |
sulaweyo/torrentflux-b4rt-php7 | html/bin/clients/fluazu/fluazu/output.py | Python | gpl-2.0 | 3,408 | 0.012911 | ################################################################################
# $Id: output.py 2552 2007-02-08 21:40:46Z b4rt $
# $Date: 2007-02-08 15:40:46 -0600 (Thu, 08 Feb 2007) $
# $Revision: 2552 $
################################################################################
# ... | ANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# | #
# To read the license please visit http://www.gnu.org/copyleft/gpl.html #
# #
# #
###################################################################... |
yeming233/rally | rally/plugins/openstack/cfg/nova.py | Python | apache-2.0 | 12,529 | 0 | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | loat(2),
help="Time to sleep after %s before polling"
" for status" % "suspend"),
cfg.FloatOpt("nova_server_%s_timeout" % "suspend",
default=float(300),
help="Server %s timeout" % "suspend") | ,
cfg.FloatOpt("nova_server_%s_poll_interval" % "suspend",
default=float(2),
help="Server %s poll interval" % "suspend"),
# "resume": (2, 300, 2)
cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resume",
default=float(2),
help="Time to sleep ... |
kynikos/lib.py.configfile | configfile/__init__.py | Python | mit | 60,029 | 0.000983 | # This file is part of ConfigFile - Parse and edit configuration files.
# Copyright (C) 2011-present Dario Giovannetti <dev@dariogiovannetti.net>
# Licensed under MIT
# https://github.com/kynikos/lib.py.configfile/blob/master/LICENSE
"""
This library provides the :py:class:`ConfigFile` class, whose goal is to
provide... | ace for parsing, modifying and writing configuration files.
Main features:
* Support for subsections. Support for sectionless options (root options).
* Read from multiple sources (files, file-like objects, dictionaries or special
compatible objects) and compose them in a single :py:class:`ConfigFile`
object.
* Wh... |
* Import a configuration source into a particular subsection of an existing
object. Export only a particular subsection of an existing object.
* Preserve the order of sections and options when exporting. Try the best to
preserve any comments too.
* Access sections and options with the
``root('Section', 'Subsecti... |
examachine/pisi | tests/buildtests/merhaba-pisi-1.0/usr/bin/merhaba-pisi.py | Python | gpl-3.0 | 107 | 0.009346 | #!/ | usr/bin/env python
# -*- coding: u | tf-8 -*-
import os
print "Sana da merhaba %s" % (os.getenv("USER"))
|
spatuloricaria/Uncap | eve_site/eve_site/wsgi.py | Python | gpl-3.0 | 391 | 0.002558 | """
WSGI config for eve_site 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.6/howto/deplo | yment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eve_site.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.2/Lib/test/test_cfgparser.py | Python | mit | 7,274 | 0 | import ConfigParser
import StringIO
from test_support import TestFailed, verify
def basic(src):
print "Testing basic accessors..."
cf = ConfigParser.ConfigParser()
sio = StringIO.StringIO(src)
cf.readfp(sio)
L = cf.sections()
L.sort()
verify(L == [r'Commented Bar',
r'Foo ... | ,
"remove_option() failed to report non-existance of option"
" that was removed")
try:
cf.remove_option('No Such Section', 'foo')
except ConfigParser.NoSectionError:
pass
else:
raise TestFailed(
"remove_option() failed to report non-existance of opti... | vity():
print "Testing case sensitivity..."
cf = ConfigParser.ConfigParser()
cf.add_section("A")
cf.add_section("a")
L = cf.sections()
L.sort()
verify(L == ["A", "a"])
cf.set("a", "B", "value")
verify(cf.options("a") == ["b"])
verify(cf.get("a", "b", raw=1) == "value",
... |
madcore-ai/containers | kfn/examples/producer.py | Python | mit | 207 | 0.009662 | from kafka import KafkaProducer
#oducer = KafkaProducer(bootstrap_servers='kafka-kf.kafka.svc.cluster.local:90 | 92')
producer = KafkaPr | oducer(bootstrap_servers='localhost:9092')
producer.send('test', 'hello')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.