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 |
|---|---|---|---|---|---|---|---|---|
Robozor-network/arom-web_ui | src/aromweb/node_handlers/pymlab_handler.py | Python | gpl-3.0 | 1,316 | 0.009119 | from handler.base import BaseHandler
import glob
import json
import rospy
class pymlabBase(BaseHandler):
def get(self, path = None):
print('OK')
file = rospy.get_param('/arom/node/pymlab_node/feature/pymlab_structure/cfg | ')
self.render('modules/features/pymlab.hbs', current_file = file)
def post(self, path = None):
operation = self.get_argument('operation', 'get_json')
print('operation>>', self.get_argument('operation', 'XXX'))
if operation == 'get_json':
filename = self.get_argument('fi... | if filename and filename != 'false':
file = filename
else:
file = glob.glob("/home/odroid/robozor/station/pymlab_presets/*.json")[0]
file = rospy.get_param('/arom/node/pymlab_node/feature/pymlab_structure/cfg')
json_data = json.load(open(file))
... |
simion/sublime-slack-integration | api.py | Python | gpl-2.0 | 1,631 | 0.000613 | import json
import subprocess
import sublime
try:
from urllib.parse import urlencode
from urllib.request import urlopen
except ImportError:
from urllib import urlencode, urlopen
BASE_URL = 'https://slack.com/api/'
def api_call(method, call_args={}, loading=None, filename=None, icon=None):
if icon:
... | stderr=subprocess.PIPE)
out, err = proc.communicate()
response = out.decode('utf8')
response = json.loads(response)
if not response['ok']:
sublime.error_message("SLACK Api error: " + response['error'])
if loading:
loading.done = True
return ... | rn response
|
lu-zero/aravis | tests/python/arv-enum-test.py | Python | lgpl-2.1 | 1,513 | 0.001322 | #!/usr/bin/env python
# Aravis - Digital camera library
#
# Copyright (c) 2011-2012 Emmanuel Pacaud
#
# 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 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public ... | n, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307, USA.
#
# Author: Emmanuel Pacaud <[email protected]>
# If you have installed aravis in a non standard location, you may need
# to make GI_TYPELIB_PATH point to the correct location. For example:
#
# export GI_TYPELIB_PATH=$GI_TYPELIB_PATH:/opt/bin/lib... |
DONIKAN/django | tests/context_processors/tests.py | Python | bsd-3-clause | 3,031 | 0 | """
Tests for Django's bundled context processors.
"""
from django.test import SimpleTestCase, TestCase, override_settings
@override_settings(
ROOT_URLCONF='context_processors.urls',
TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS':... | ntains(response, url)
response = self.client.get(url, {'path': '/blah/'})
self.assertContains(response, url)
response = self.client.post(url, {'path': '/blah/'})
self.assertContains(response, url)
@override_settings(
DEBUG=True,
INTERNAL_IPS=['127.0.0.1'],
ROOT_ | URLCONF='context_processors.urls',
TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
],
},
}],
)
class DebugContextP... |
CybOXProject/python-cybox | cybox/objects/dns_cache_object.py | Python | bsd-3-clause | 990 | 0.00101 | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities
from mixbox import fields
import cybox.binding | s.dns_cache_object as dns_cache_binding
from cybox.common import ObjectProperties, PositiveInteger
from cybox.objects.dns_record_object import DNSRecord
class DNSCacheEntry(entities.Entity):
_namespace = "http://cybox.mitre.org/objects#DNSCacheObject-2"
_binding = dns_cache_binding
_binding_class = dns_ca... | ositiveInteger)
class DNSCache(ObjectProperties):
_binding = dns_cache_binding
_binding_class = dns_cache_binding.DNSCacheObjectType
_namespace = "http://cybox.mitre.org/objects#DNSCacheObject-2"
_XSI_NS = "DNSCacheObj"
_XSI_TYPE = "DNSCacheObjectType"
dns_cache_entry = fields.TypedField("DNS... |
uudiin/bleachbit | tests/TestWinapp.py | Python | gpl-3.0 | 11,482 | 0.001132 | # vim: ts=4:sw=4:expandtab
# BleachBit
# Copyright (C) 2008-2015 Andrew Ziem
# http://bleachbit.sourceforge.net
#
# 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... | al(expected_return, actual_return, msg)
def test_fake(self):
"""Test with fake file"""
ini_fn = None
keyfull = 'HKCU\\Software\\BleachBit\\DeleteThisKey'
subkey = 'Software\\BleachBit\\DeleteThisKey\\AndThisKey'
def setup_fake(f1_filename=None):
"""Setup the te... | f1, 'w').write('')
dirname2 = os.path.join(dirname, 'sub')
os.mkdir(dirname2)
f2 = os.path.join(dirname2, 'deleteme.log')
file(f2, 'w').write('')
fbak = os.path.join(dirname, 'deleteme.bak')
file(fbak, 'w').write('')
self.assertTrue(... |
thecut/thecut-googleanalytics | thecut/googleanalytics/migrations/0001_initial.py | Python | apache-2.0 | 1,911 | 0.003663 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import oauth2client.django_orm
class Migration(migrations.Migration):
dependencies = [
('sites', | '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('web_property_id', models.CharField(help_text='The property tra... | ('profile_id', models.CharField(default='', max_length=25, verbose_name='view (profile) ID', blank=True)),
('display_features', models.BooleanField(default=False, help_text='Used for remarketing, demographics and interest reporting.', verbose_name='Use Display advertising features?')),
... |
cjaymes/pyscap | src/scap/model/dc_elements_1_1/Rights.py | Python | gpl-3.0 | 765 | 0.001307 | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms o | f 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.
#
# PySCAP 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 Ge... |
lmazuel/azure-sdk-for-python | azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/account/models/firewall_rule.py | Python | mit | 1,956 | 0.000511 | # 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 cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .sub_resource import SubResource
class FirewallRule(SubResource):
"""Data Lake Analytics firewall rule information.
... |
lenn0x/Milo-Tracing-Framework | src/py/examples/milo_server.py | Python | apache-2.0 | 861 | 0.012776 | """Basic Thrift server that uses the Milo Protocol" | ""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from helloworld import HelloWorld
from milo.protocols.thrift i... | hrift.TThreadedServer import TDebugThreadedServer
class HelloWorldHandler:
def ping(self, name):
return name
handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket(9090)
tfactory = TTransport.TFramedTransportFactory()
pfactory = TMiloProtocolFactory()
server =... |
McIntyre-Lab/papers | nanni_maize_2022/scripts/merge_tappas_DEA_results.py | Python | lgpl-3.0 | 4,326 | 0.017337 | #!/usr/bin/env python
import pandas as pd
import numpy as np
import argparse
def getOptions():
# Parse command line arguments
parser = argparse.ArgumentParser(description="Merge tappAS DEA output files with detection flags")
# Input data
parser.add_argument("-t", "--input-directory", dest="inDir", re... | o gene_id pairs
flagDF = pd.read_csv(args.inFlag, sep="\t",low_memory=False)
annotDF = pd.read_csv(args.inAnnot)
# Merge gene_id into | flags
geneDF = pd.merge(annotDF,flagDF,how='outer',on='transcript_id',indicator='merge_check')
# geneDF['merge_check'].value_counts()
# Fix the 89 single transcript genes missing in EA files
# (have the same value for transcript_id and gene_id)
geneDF = geneDF[geneDF['merge_check']!='left_only']... |
megaserg/pants | src/python/pants/backend/python/tasks/python_eval.py | Python | apache-2.0 | 6,421 | 0.009967 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import pkg... | s sources in the case of a python library or else the
# entry point in the case of a python binary.
#
# For a library with sources lib/core.py and lib/util.py a "compiler" main file would look like:
#
# if __name__ == '__main__':
# import lib.core
# import lib.util
#
# For ... | if __name__ == '__main__':
# from lib.bin import main
#
# In either case the main file is executed within the target chroot to reveal missing BUILD
# dependencies.
with self.context.new_workunit(name=target.address.spec):
modules = []
if isinstance(target, PythonBinary):
... |
Yelp/pushmanager | pushmanager/servlets/addrequest.py | Python | apache-2.0 | 2,713 | 0.001843 | import pushmanager.core.db as db
import pushmanager.core.util
from pushmanager.core.db import InsertIgnore
from pushmanager.core.mail import MailQueue
from pushmanager.core.requesthandler import RequestHandler
from pushmanager.core.xmppclient import XMPPQueue
class AddRequestServlet(RequestHandler):
def post(sel... | (
"""
<p>
%(pushmaster)s has accepted request for %(user)s into a push:
</p>
<p>
| <strong>%(user)s - %(title)s</strong><br />
<em>%(repo)s/%(branch)s</em>
</p>
<p>
Regards,<br />
PushManager
</p>"""
) % pushmanager.core.util.EscapedDict({
... |
SINGROUP/pycp2k | pycp2k/classes/_force_eval2.py | Python | lgpl-3.0 | 1,808 | 0.002212 | from pycp2k.inputsection import InputSection
from ._external_potential1 import _external_potential1
from ._rescale_forces1 import _rescale_forces1
from ._mixed1 import _mixed1
from ._dft1 import _dft1
from ._mm1 import _mm1
from ._qmmm1 import _qmmm1
from ._eip1 import _eip1
from ._bsse1 import _bsse1
from ._subsys1 im... | ()
self.BSSE = _bsse1()
self.SUBSYS = _subsys1()
self.PROPERTIES = _properties1()
self.PRINT = _print64()
self._name = "FORCE_EVAL"
self._keywords = {'Method': 'METHOD', 'Embed': 'EMBED', 'Stress_tensor': 'STRESS_TENSOR'}
self._subsections = {'PRINT': 'PRINT', 'MI... | ORCES', 'PROPERTIES': 'PROPERTIES', 'DFT': 'DFT', 'QMMM': 'QMMM', 'BSSE': 'BSSE', 'MM': 'MM'}
self._repeated_subsections = {'EXTERNAL_POTENTIAL': '_external_potential1'}
self._attributes = ['EXTERNAL_POTENTIAL_list']
def EXTERNAL_POTENTIAL_add(self, section_parameters=None):
new_section = _... |
berquist/PyQuante | Tests/integrals.py | Python | bsd-3-clause | 3,015 | 0.026866 | #!/usr/bin/env python
"""\
Test the 2e integral code.
"""
from PyQuante.pyints import contr_coulomb as pycc
from PyQuante.rys import contr_coulomb as ryscc
from PyQuante.hgp import contr_coulomb as hgpcc
from PyQuante.cints import contr_coulomb as ccc
from PyQuante.crys import contr_coulomb as cryscc
from PyQuante.c... | xps,c.pcoefs,c.pnorms,c.origin,c.powers,
d.pexps,d.pcoefs,d.pnorms,d.origin,d.powers)
return a.norm*b.norm*c.norm*d.norm*Jij
def maxdiff(a,b):
md = -1e10
for i in range(len(a)):
md = max(md,a[i]-b[i])
return md
def test() | :
#from PyQuante.Basis.sto3g import basis_data
from PyQuante.Basis.p631ss import basis_data
r = 1/0.52918
atoms=Molecule('h2o',atomlist = [(8,(0,0,0)),(1,(r,0,0)),(1,(0,r,0))])
inttol = 1e-6 # Tolerance to which integrals must be equal
bfs = getbasis(atoms,basis_data)
print "Int times:... |
s-monisha/LibreHatti | src/librehatti/bills/views.py | Python | gpl-2.0 | 7,704 | 0.005452 | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from librehatti.catalog.models import PurchaseOrder
from librehatti.catalog.models import Category
from librehatti.catalog.models import PurchasedItem
from librehatti.catalog.models import ModeOfPayment
from librehatti.cata... | cts.get(id=quoted_or | der_id)
quoted_order_obj = QuotedOrder.objects.values('id', 'date_time').\
get(id=quoted_order_id)
quoted_order_date = quoted_order_obj['date_time']
financialsession = FinancialSession.objects.\
values('id', 'session_start_date', 'session_end_date')
for value in financialsession:
start_d... |
SmartElect/SmartElect | help_desk/models.py | Python | apache-2.0 | 20,453 | 0.001125 | from datetime import timedelta
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse
from django.utils.timezone import now
from django.utils.translation import ug... | models.IntegerField(
_('staff id'),
unique=True,
validators=[
MinValueValidator(100),
MaxValueValidator(999),
]
)
phone_number = PhoneNumb | erField(_('phone number'))
suspended = models.BooleanField(_('suspended'), blank=True, default=False)
class Meta:
ordering = ['name', 'staff_id']
verbose_name = _("field staff member")
verbose_name_plural = _("field staff members")
permissions = [
('browse_fieldstaff... |
EVEModX/Mods | mods/CustomThemeColor/ThemeConfig.py | Python | mit | 143 | 0.006993 | ThemeID = 'UI/Co | lorThemes/Custom'
#themeID, baseColor, hiliteColor
THEMES = (('UI/ColorThemes/Custom | ', (0.05, 0.05, 0.05), (0.4, 0.8, 1.0)),)
|
tuxlifan/moneyguru | core/tests/gui/general_ledger_table_test.py | Python | gpl-3.0 | 4,362 | 0.005961 | # Created By: Virgil Dupras
# Created On: 2010-09-09
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-... | show_empty_accounts(app):
# When accounts have nothing to show, don't put them in the table.
app.drsel.select_prev_date_range()
eq_(len(app.gltable), 0)
@with_app(app_two_sided_txn)
def test_new_entry_with_account_row_selected(app):
# Adding a new entry when the account row is selected | doesn't cause a crash and creates a new
# entry.
app.gltable.select([0])
app.mw.new_item() # no crash
eq_(len(app.gltable), 7)
eq_(app.gltable.selected_indexes, [2])
@with_app(app_two_sided_txn)
def test_rows_data_with_two_sided_txn(app):
# In a general ledger, we end up with 6 lines: 2 account... |
bodik10/Combinatorics | core.py | Python | gpl-3.0 | 3,143 | 0.013309 | "модуль із класом Core що включає в собі деякі методи комбінаторики, які використовуються в програмі"
import itertools
from math import factorial as fact
class Core:
# Методи-генератори комбінацій/перестановок
#perm = itertools.permutations # перестановки
comb = ite... | ться)
@staticmethod
def place(seq, N, prev=[]): # розміщеня із seq по N (порядок ВРАХОВУЄТЬСЯ)
for char in seq:
| res = prev + [char]
if len(res) == N:
yield res
else:
new_s = list(seq)
new_s.remove(char)
for res in Core.place(new_s, N, prev=res):
yield res
@staticmethod
def place_w_repl(seq, d... |
dimddev/NetCatKS | examples/projects/rootapis/web_time_server/components/adapters/time/__init__.py | Python | bsd-2-clause | 587 | 0.003407 | from datetime import datetime
from NetCatKS.Logger import Logger
from NetCatKS.Components import BaseRootAPI
class Time(BaseRootAP | I):
def __init__(self, factory):
super(Time, self).__init__(factory)
self.factory = factory
self.logger = Logger()
def process_factory(self):
if self.factory.time == 'get':
self.factory.time = str(datetime.now())
else:
self.factory.ti... | turn self.factory
|
franklingu/leetcode-solutions | questions/find-the-difference/Solution.py | Python | mit | 760 | 0.001316 | """
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the le | tter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
"""
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
mapping = [0] * 26
for... | return str(chr(ord('a') + idx))
return None
|
clarkduvall/serpy | setup.py | Python | mit | 1,452 | 0 | from codecs import open
from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='serpy',
version='0.3.1',
description='ridiculously fast object ... | ',
license='MIT',
install_requires=['six'],
test_suite='tests',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License : | : OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'... |
Elucidation/ChessboardDetect | base_imgload.py | Python | mit | 538 | 0.01487 | from __future__ import print_function
from pylab im | port *
import numpy as | np
import cv2
import sys
def main(filenames):
for filename in filenames:
print("Processing %s" % filename)
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Using opencv
cv2.imshow('image %dx%d' % (img.shape[1],img.shape[0]),img)
cv2.waitKey(0)
cv2.destroyAllWindo... |
John078/DEV6B | Herkansing6B/test_unit.py | Python | mit | 2,881 | 0.03228 | import unittest
import os
import flask
from model import *
from controller import controller
from Herkansing6B import views
from Herkansing6B import app
import tempfile
modelClass = Model()
class Test_Model_InputuserTest(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.t... | ,"h","i","j"])
class Test_Model_ResultTest(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.testing = True
#test ResultTest function in combination with the /re | sulttest route (source: views.py)
def test_model_ResultTest_score_is_100(self):
self.assertTrue(modelClass.ResultTest(["a","b","c","d","e","f","g","h","i","j"], ["a","b","c","d","e","f","g","h","i","j"]), 100)
#test ResultTest function in combination with the /resulttest route (source: views.py)
de... |
antoinecarme/pyaf | tests/artificial/transf_RelativeDifference/trend_MovingAverage/cycle_0/ar_12/test_artificial_32_RelativeDifference_MovingAverage_0_12_0.py | Python | bsd-3-clause | 276 | 0.083333 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, tr | endtype = "MovingAverage", cycle_length = 0, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, | ar_order = 12); |
badele/serialkiller-plugins | setup.py | Python | gpl-3.0 | 1,664 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
PYPI_RST_FILTERS = (
# Replace code-blocks
(r'\.\.\s? code-block::\s*(\... | *', ''),
# Remove pypip.in badges
(r'.*pypip\.in/.*', ''),
(r'.*crate\.io/.*', ''),
(r'.*coveralls\.io/.*', ''),
)
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis c | i build badge
'''
content = open(filename).read()
for regex, replacement in PYPI_RST_FILTERS:
content = re.sub(regex, replacement, content)
return content
def required(filename):
with open(filename) as f:
packages = f.read().splitlines()
return packages
setup(
name="serialki... |
gem/oq-engine | openquake/hazardlib/gsim_lt.py | Python | agpl-3.0 | 22,252 | 0 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2022, GEM Foundation
#
# OpenQuake 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 Lice... | p://www.gnu.org/licenses/>.
import io
import os
import ast
import json
import logging
import operator
import itertools
from collections import namedtuple, defaultdict
import toml
import numpy
from openquake.baselib import hdf5
from openquake.baselib.node import Node as N, context
from openquake.baselib.general import... | ed, BASE94, group_array
from openquake.hazardlib import valid, nrml, pmf, lt, InvalidFile
from openquake.hazardlib.gsim.mgmpe.avg_poe_gmpe import AvgPoeGMPE
from openquake.hazardlib.gsim.base import CoeffsTable
from openquake.hazardlib.imt import from_string
BranchTuple = namedtuple('BranchTuple', 'trt id gsim weight ... |
puttarajubr/commcare-hq | corehq/ex-submodules/casexml/apps/phone/data_providers/case/load_testing.py | Python | bsd-3-clause | 1,857 | 0.001616 | from copy import deepcopy
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.data_providers.case.utils import CaseSyncUpdate
from casexml.apps.phone.xml import get_case_element
from corehq.toggles import ENABLE_LOADTEST_USERS
def get_loadtest_factor(domain, user):
"""
Gets the loadtest ... | """
if domain and ENABLE_LOADTEST_USERS.enabled(domain):
return getattr(user, 'loadtest_factor', 1) or 1
return 1
def transform_loadtest_update(update, factor):
"""
Returns a new CaseSyncUpdate object (from an existing one) with all the
case IDs and names mapped to have the factor appended... | ormat(id, count)
case = CommCareCase.wrap(deepcopy(update.case._doc))
case._id = _map_id(case._id, factor)
for index in case.indices:
index.referenced_id = _map_id(index.referenced_id, factor)
case.name = '{} ({})'.format(case.name, factor)
return CaseSyncUpdate(case, update.sync_token, requ... |
kelvan/pyspaceshooter | objects.py | Python | gpl-3.0 | 7,112 | 0 | import pygame
from utils import load_image, laserSound, rocketSound, explodeSound, \
missleExplosion, scream, load_sliced_sprites, chickenSound
import stats
class Shot(pygame.sprite.Sprite):
def __init__(self, x, y, image, enemies, power, speed, maxspeed=None):
pygame.sprite.Sprite.__init__(self)
... | f, enemies, | speed=8, maxspeed=20):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('fighter.png', -1)
self.screen = pygame.display.get_surface()
self.area = self.screen.get_rect()
self.speed = speed
self.maxspeed = maxspeed
self.dx = 0
self.ene... |
zenranda/proj10-final | test_main.py | Python | artistic-2.0 | 2,958 | 0.014875 | ###
#Various nose tests. If you want to adapt this for your own use, be aware that the start/end block list has a very specific formatting.
###
import date_chopper
import arrow
from pymongo import MongoClient
import secrets.admin_secrets
import secrets.client_secrets
MONGO_CLIENT_URL = "mongodb://{}:{}@localh... | tart times that go out of bounds
ranges = [['2016-11-20T08:30:00', '2016-11-20T10:30:00'], ['2016-11-20T11:00:00', '2016-11-20T15:00:00 | ']]
start = arrow.get('2016-11-20T05:00:00')
assert (date_chopper.date_underlap(ranges, start)) == True
ranges = [['2016-11-20T08:30:00', '2016-11-20T10:30:00'], ['2016-11-20T11:00:00', '2016-11-20T15:00:00']]
start = arrow.get('2016-11-20T10:00:00')
assert (date_chopper.date_underlap(ran... |
zzyxzz/T2-list-parser | t2-parser.py | Python | mit | 4,480 | 0.012723 | import os
import csv
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
from pdfminer.layout import LAParams... | tLine
from pdfminer.converter import PDFPageAggregator
#set the path for the pdf file of T2 sponsors list.
dir = os.path.dirname(os.path.realpath(__file__))
rel_path = "files/Tier_2_5_Register_of_Sponsors_2015-05-01.pdf"
pdfpath = os.path.join(dir,rel_path)
print pdfpath
field_names = ["Organisation Name","Town/City"... | Rating","Sub Tier"]
#open the pdf file of T2 sponsor list.
with open(pdfpath, "r") as pdf_file:
#create a parser object of the file.
parser = PDFParser(pdf_file)
#create a PDF document object to store the document structure.
doc = PDFDocument(parser)
#check whether the document allows text extract... |
msherry/PyXB-1.1.4 | tests/trac/test-trac-0071.py | Python | apache-2.0 | 5,134 | 0.002922 | import pyxb_114.binding.generate
import pyxb_114.binding.datatypes as xs
import pyxb_114.binding.basis
import pyxb_114.utils.domutils
import os.path
xsd='''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="urn:trac-0071" targetNamespace="urn:trac-0071">
<xs:elem... | t)
field.value_.append(pyxb_114.BIND('foo', lang='ENG'))
self.assertTrue(isinstance(field.value_, list))
self.assertEqual(1, len(field.value_))
| self.assertTrue(isinstance(field.value_[0], pyxb_114.BIND))
field.validateBinding()
self.assertTrue(isinstance(field.value_[0], pyxb_114.BIND))
self.assertEqual('<field><name>title</name><value lang="ENG">foo</value></field>', field.toxml("utf-8", root_only=True))
'''
NOT Y... |
csabatini/deploy-azurerm-django | azure_ad_auth/views.py | Python | bsd-3-clause | 2,354 | 0.000425 | from .backends import AzureActiveDirectoryBackend
from django.conf import set | tings
from django.contrib.auth import REDIRECT_FIELD_NAME, login
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views. | decorators.csrf import csrf_exempt
from django.views.decorators.cache import never_cache
import requests
import urlparse
import uuid
import json
@never_cache
def auth(request):
backend = AzureActiveDirectoryBackend()
redirect_uri = request.build_absolute_uri(reverse(complete))
nonce = str(uuid.uuid4())
... |
jamesbeebop/evennia | evennia/server/profiling/dummyrunner_settings.py | Python | bsd-3-clause | 8,806 | 0.000227 | """
Settings and actions for the dummyrunner
This module defines dummyrunner settings and sets up
the actions available to dummy accounts.
The settings are global variables:
TIMESTEP - time in seconds between each 'tick'
CHANCE_OF_ACTION - chance 0-1 of action happening
CHANCE_OF_LOGIN - chance 0-1 of login happenin... | amines),
# (0.1, c_help),
# (0.01, c_digs),
# | (0.01, c_creates_obj),
# (0.3, c_moves))
# "heavy" builder definition
# ACTIONS = ( c_login,
# c_logout,
# (0.2, c_looks),
# (0.1, c_examines),
# (0.2, c_help),
# (0.1, c_digs),
# (0.1, c_creates_obj),
# #(0.01, c_creates_but... |
zentralopensource/zentral | zentral/contrib/santa/migrations/0026_configuration_allow_unknown_shard.py | Python | apache-2.0 | 1,128 | 0.001773 | # Generated by Django 2.2.24 on 2021-11-11 08:49
import django.core.validators
from django.db import migrations, models
from django.db.models import Count
def add_shard_to_no_rule_configurations(apps, schema_editor):
Configuration = apps.get_model("santa", "Configuration")
for configuration in Configuration.... | =0):
configuration.allow_unknown_shard = 5
configuration.save()
class Migration(migrations.Migration):
dependencies = [
('santa', '0025_auto_20210921_1517'),
]
operations = [
migrations.AddField(
model_name='configuration',
name='allow_unknown_shar... | ult=100,
help_text="Restrict the reporting of 'Allow Unknown' events to a percentage (0-100) of hosts",
validators=[django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(100)]
),
),
migrations.RunPyth... |
mlell/tapas | scripts/src/indel.py | Python | mit | 16,326 | 0.011889 | #!/usr/bin/env python
import argparse
import csv
import random
import sys
import math
from math import inf
from textwrap import dedent
from editCIGAR import CIGAR
from textwrap import dedent
# Don't throw an error if output is piped into a program that doesn't
# read all of its input, like `head`.
from signal import ... | GGTGACATAAAGGC 8M5I
TTCCGCAGGG 10M
CTCGTGGAGT 5M2D5M
....
–––––––––––––––––––––––
(white space stands for one tab character)
If no CIGAR strings are available for the nucleotides, then use the
parameter --cigar-new. In that case, only a nucleotide stri... | ef parse_arguments(argv):
p = argparse.ArgumentParser(description=description,
formatter_class= argparse.RawTextHelpFormatter)
for s,l in [('in','insert'),('del','deletion')]:
p.add_argument('--{}-prob'.format(s), default=0,
type = checkPositive(float), metavar='P', help=
... |
amarant/servo | python/servo/testing_commands.py | Python | mpl-2.0 | 31,871 | 0.002134 | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
#... | .abspath(path_arg)
for prefix, suite in TEST_SUITES_BY_PREFIX.iteritems():
if abs_path.startswith(prefix):
return suite
return None
@Command('test-geckolib',
descript | ion='Test geckolib sanity checks',
category='testing')
def test_geckolib(self):
self.ensure_bootstrapped()
env = self.build_env()
env["RUST_BACKTRACE"] = "1"
return call(["cargo", "test"], env=env, cwd=path.join("ports", "geckolib"))
@Command('test-unit',
... |
Ajoo/pySystems | pysystems/ident/systems.py | Python | mit | 549 | 0.009107 | from .. import DStateSpace
def extension_method(cls):
def decorator(func):
| setattr(cls, func.__name__, func)
return func
return decorator
def extension_class(name, bases, namespace):
assert len(bases) == 1, "Exactly one base class required"
base = bases[0]
for name, value in namespace.iteritems():
if name != "__metaclass__":
setattr(base, n... | class
def fit(self, u, y):
pass |
edx-solutions/edx-platform | cms/lib/xblock/tagging/migrations/0002_auto_20170116_1541.py | Python | agpl-3.0 | 571 | 0.003503 | # -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tagging', '0001_initial'),
]
operations = [
migrations.AlterModelOptions( |
name='tagavailablevalues',
options={'ordering': ('id',), 'verbose_name': 'available tag value'},
),
migrations.AlterModelOptions(
name='tagcategories',
options={'ordering': ('title',), 'verbose_name': 'tag category', 'verbose_name_plural': 'tag categories... |
]
|
allenai/allennlp | allennlp/nn/chu_liu_edmonds.py | Python | apache-2.0 | 10,283 | 0.000486 | from typing import List, Set, Tuple, Dict
import numpy
from allennlp.common.checks import ConfigurationError
def decode_mst(
energy: numpy.ndarray, length: int, has_labels: bool = True
) -> T | uple[numpy.ndarray, numpy.ndarray]:
"""
Note: Counter to typical intuition, this function decodes the _maximum_
spanning tree.
Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for
maximum spanning arborescences on graphs.
# Parameters
energy : `numpy.ndarray`, required.
... | s, timesteps)
containing the energy of each edge. If has_labels is `False`,
the tensor should have shape (timesteps, timesteps) instead.
length : `int`, required.
The length of this sequence, as the energy may have come
from a padded batch.
has_labels : `bool`, optional, (default... |
joaduo/mepinta | core/python_core/common/type_checking/isiterable.py | Python | gpl-3.0 | 972 | 0 | # -*- coding: utf-8 -*-
'''
Mepinta
Copyright (c) 2011-2012, Joaquin G. Duo
This file is part of Mepinta.
Mepinta 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 opti... | ta 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 Pu | blic License
along with Mepinta. If not, see <http://www.gnu.org/licenses/>.
'''
def isiterable(instance):
try:
iterator = iter(instance)
return True
except TypeError as e:
return False
if __name__ == "__main__":
debugPrint(isiterable([]))
debugPrint(isiterable("foo"))
de... |
JPWKU/unix-agent | src/dcm/agent/messaging/utils.py | Python | apache-2.0 | 2,118 | 0 | #
# Copyright (C) 2014 Dell, 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 wri... | ither express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import threading
import uuid
import dcm.agent.utils as agent_utils
from dcm.agent.events.globals import global_space as dcm_events
_g_logger = logging.getLogger(__name__... | d.uuid4()).split("-")[0]
_g_message_id_count = 0
_g_guid_lock = threading.RLock()
def new_message_id():
# note: using uuid here caused deadlock in tests
global _g_message_id_count
global _g_message_uuid
_g_guid_lock.acquire()
try:
_g_message_id_count = _g_message_id_count + 1
finally:
... |
ageron/tensorflow | tensorflow/python/keras/layers/core_test.py | Python | apache-2.0 | 11,584 | 0.004575 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | layers.Lambda(lambda x: x + 1, output_shape=get_output_shape)
l(keras.backend.variable(np | .ones((1, 1))))
self.assertEqual('lambda', l.get_config()['output_shape_type'])
def test_lambda_output_shape_autocalculate_multiple_inputs(self):
def lambda_fn(x):
return math_ops.matmul(x[0], x[1])
l = keras.layers.Lambda(lambda_fn)
output_shape = l.compute_output_shape([(10, 10), (10, 20)])... |
zyrikby/BBoxTester | BBoxTester/main_intents_strategy.py | Python | apache-2.0 | 5,189 | 0.007901 | '''
Created on Nov 26, 2014
@author: Yury Zhauniarovich <y.zhalnerovich{at}gmail.com>
'''
import os, time
from interfaces.adb_interface import AdbInterface
from bboxcoverage import BBoxCoverage
from running_strategies import IntentInvocationStrategy
import smtplib
import email.utils
from email.mime.text import MIMET... |
try:
bboxcoverage.stopTesting("main_intents", paramsToWrite=params)
except:
print "Exception while running strategy!"
bboxcoverage.uninstallPackage()
continue
time.sleep(3)
bboxcoverage.un... | time.sleep(5)
sendMessage("[BBoxTester]", "Experiments done for directory [%s]!" % apk_dir_source)
|
google/jax | jax/_src/scipy/stats/geom.py | Python | apache-2.0 | 1,244 | 0.002412 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ero = _lax_const(k, 0)
one = _lax_ | const(k, 1)
x = lax.sub(k, loc)
log_probs = xlog1py(lax.sub(x, one), -p) + lax.log(p)
return jnp.where(lax.le(x, zero), -jnp.inf, log_probs)
@_wraps(osp_stats.geom.pmf, update_doc=False)
def pmf(k, p, loc=0):
return jnp.exp(logpmf(k, p, loc))
|
earonesty/bitcoin | test/functional/keypool.py | Python | mit | 3,529 | 0.002834 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet keypool and interaction with wallet encryption/locking."""
from test_framework.test_fr... |
addr_data = nodes[0].validateaddress(addr)
wallet_info = nodes[0].getwalletinfo()
assert(addr_before_encrypting_data['hdmasterkeyid'] != wallet_info['hdmasterkeyid'])
assert(addr_data['hdmasterkeyid'] == wallet_info['hdmasterkeyid'])
assert_raises_jsonrpc(-12, "Error: Keypool ra... | des[0].getnewaddress)
# put six (plus 2) new keys in the keypool (100% external-, +100% internal-keys, 1 in min)
nodes[0].walletpassphrase('test', 12000)
nodes[0].keypoolrefill(6)
nodes[0].walletlock()
wi = nodes[0].getwalletinfo()
assert_equal(wi['keypoolsize_hd_interna... |
grehx/spark-tk | regression-tests/sparktkregtests/testcases/dicom/take_dicom_test.py | Python | apache-2.0 | 3,835 | 0 | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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 require... | com_uncompresse | d")
self.dicom = self.context.dicom.import_dcm(self.dataset)
self.xml_directory = self.get_local_dataset("dicom_xml/")
self.image_directory = self.get_local_dataset("dicom_uncompressed/")
self.count = self.dicom.metadata.count()
def test_metadata_imagedata_row_count_same(self):
... |
antoinevg/survival | widgets/texteditor.py | Python | gpl-2.0 | 7,247 | 0.019594 |
import gtk
import pango
import math
from core.world import TheWorld
class TextEditor(object):
def __init__(self, text):
self.__text = text
self.cursorindex = 0
self.padding = 10.0
self.width = 0.0
self.height = 0.0
self.pixel_width = 0.0
self.pixel_height = 0.0
# create te... | (lines[line]) - dist)
else:
self.cursorindex -= 1
def do_key_press_down(self):
lines = self.text.splitlines()
if len(lines) == 1:
return
loc = 0
line = 0
for i in lines:
loc += len(i) + 1
if loc > self.cursorindex:
break
line += 1
if line >= len(li... | ndex += len(lines[line + 1])
else:
self.cursorindex += dist
|
willybh11/python | tetris/tetris.py | Python | gpl-3.0 | 48 | 0.083333 |
d | ef main():
pass
def generateBlock():
| |
zferentz/maproxy | maproxy/session.py | Python | apache-2.0 | 16,890 | 0.013914 | #!/usr/bin/env python
import tornado
import socket
import maproxy.proxyserver
class Session(object):
"""
The Session class if the heart of the system.
- We create the session when a client connects to the server (proxy). this connection is "c2p"
- We create a connection to the server (p2s)
- Ea... | XXX_start_write: if currently writing , add data to queue. if not writing - perform io_write...
"""
class LoggerOptions:
"""
Logging options - which messages/notifications we would like to log...
The logging is for development&maintenance. In production set all to False
... | LOG_NEW_SESSION_OP=False
LOG_READ_OP=False
LOG_WRITE_OP=False
LOG_CLOSE_OP=False
LOG_CONNECT_OP=False
LOG_REMOVE_SESSION=False
class State:
"""
Each socket has a state.
We will use the state to identify whether the connection is open or cl... |
mick-d/nipype_source | nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py | Python | bsd-3-clause | 1,344 | 0.022321 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.slicer.filtering.extractskeleton import ExtractSkeleton
def test_ExtractSkeleton_inputs():
input_m | ap = dict(InputImageFileName=dict(argstr='%s',
position=-2,
),
OutputImageFileName=dict(argstr='%s',
hash_files=False,
position=-1,
),
args=dict(argstr='%s',
),
dontPrune=dict(argstr='--dontPrune ',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception... | ),
numPoints=dict(argstr='--numPoints %d',
),
pointsFile=dict(argstr='--pointsFile %s',
),
terminal_output=dict(mandatory=True,
nohash=True,
),
type=dict(argstr='--type %s',
),
)
inputs = ExtractSkeleton.input_spec()
for key, metadata in input_map.items():
for m... |
ekamioka/gpss-research | experiments/synth/synth.py | Python | mit | 1,731 | 0.010976 | Experiment(description='Synthetic data sets of interest',
data_dir='../data/synth/',
max_depth=9,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
max_jobs=300, ... | not-const'}),
('A', 'B', {'A': 'kernel', 'B': 'base'}),
('A', ('CP', 'd', 'A'), {'A': 'kernel', 'd' : 'dimension'}),
('A', ('CW', 'd', 'A | '), {'A': 'kernel', 'd' : 'dimension'}),
('A', ('B', 'd', 'A'), {'A': 'kernel', 'd' : 'dimension'}),
('A', ('BL', 'd', 'A'), {'A': 'kernel', 'd' : 'dimension'}),
('A', ('None',), {'A': 'kernel'})])
|
ta2-1/pootle | tests/pootle_fs/receivers.py | Python | gpl-3.0 | 1,046 | 0 | # -*- coding: utf-8 - | *-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle_format.models import Format |
@pytest.mark.django_db
def test_fs_filetypes_changed_receiver(project_fs, project1, po2):
project1.filetype_tool.add_filetype(po2)
assert not project1.revisions.filter(key="pootle.fs.sync").count()
project1.treestyle = "pootle_fs"
project1.save()
xliff = Format.objects.get(name="xliff")
pro... |
alphagov/notifications-api | migrations/versions/0212_remove_caseworking.py | Python | mit | 586 | 0.005119 | """
Revision ID: 0212_remove_caseworking
Revise | s: 0211_email_branding_update
Create Date: 2018-07-31 18:00:20.457755
"""
from alembic import op
revision = '0212_remove_caseworking'
down_revision = '0211_email_branding_update'
PERMISSION_NAME = "caseworking"
def upgrade():
op.execute("delete from service_permissions where permission = '{}'".format(PERMISSI... | ervice_permission_types values('{}')".format(PERMISSION_NAME))
|
google-research/google-research | kws_streaming/layers/lstm.py | Python | apache-2.0 | 10,610 | 0.005467 | # coding=utf-8
# Copyright 2022 The Google Research 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 applicab... | ut_state1 = None
self.output_state2 = None
def call(self, inputs):
if inputs.sh | ape.rank != 3: # [batch, time, feature]
raise ValueError('inputs.shape.rank:%d must be 3' % inputs.shape.rank)
if self.mode == modes.Modes.STREAM_INTERNAL_STATE_INFERENCE:
# run streamable inference on input [batch, 1, features]
# returns output [batch, 1, units]
return self._streaming_int... |
Eigenlabs/EigenD | tools/packages/SCons/Tool/sunlink.py | Python | gpl-3.0 | 2,437 | 0.002052 | """SCons.Tool.sunlink
Tool-specific initialization for the Sun Solaris (Forte) linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Th... | ause it doesn't exist
# (IOError) or isn | 't readable (OSError) is okay.
dirs = []
for d in dirs:
linker = '/opt/' + d + '/bin/CC'
if os.path.exists(linker):
ccLinker = linker
break
def generate(env):
"""Add Builders and construction variables for Forte to an Environment."""
link.generate(env)
env['SHLINKFLAGS'] =... |
SujaySKumar/bedrock | bedrock/mozorg/forms.py | Python | mpl-2.0 | 30,635 | 0.00062 | # coding: utf-8
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from operator import itemgetter
import re
from datetime import datetime
from random import randrange
f... | = forms.ChoiceField(choices=translating_choices, required=False,
widget=L10nSelect)
area_writing = forms.ChoiceField(choices=writing_choices, required=False, widget=L10nSelect)
area_teaching = forms.ChoiceField(choices=teaching_choices, required=False, widget=L10nSelect | )
name = forms.CharField(widget=forms.TextInput(attrs=required_attr))
message = forms.CharField(widget=forms.Textarea, required=False)
newsletter = forms.BooleanField(required=False)
format = forms.ChoiceField(widget=forms.RadioSelect(attrs=required_attr), choices=(
('H', _lazy('HTML')),
... |
rj3d/PiTempController | config_reader.py | Python | gpl-2.0 | 1,798 | 0.05228 | class IoConfig:
def __init__(self, i_path, mode, o_pin=None, set_temp=None, buffer_temp=None, direction=None):
self.i_path = i_path
self.mode = mode
self.o_pin = o_pin
self.set_temp = set_temp
self.buffer_temp = buffer_temp
self.on_fn = self.get_on_fn(direction)
self.off_fn = self.get_off_fn(direction)
... | f):
str_lst = ['Input path:', str(self.i_path),
'Mode:', str(self.mode),
'Output pin:', str(self.o_pin),
'Set temp:', str(self.set_temp),
'Buffer temp:', str(self.buffer_temp)
]
return '\t'.join(str_lst)
class Config:
def __init__(self, config_path, temp_path = '/sys/bus/w1/devices/%(TEMP)s/w1_slave... | if len(splat) == 1:
self.io.append( IoConfig( temp_path % { "TEMP" :splat[0] },
'MONITOR'
) )
else:
self.io.append( IoConfig( temp_path % { "TEMP" :splat[0] },
'CONTROLLER',
int(splat[1]),
float(splat[2]),
float(splat[3]),
splat[4]
) )
f.close()
def __repr__(self):
... |
billiob/papyon | papyon/gnet/message/SOAP.py | Python | gpl-2.0 | 5,704 | 0.003857 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Ali Sabil <[email protected]>
#
# 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... | Name(default_ns, name)
return ElementTree.QName(name)
def __str__(self):
| envelope = ElementTree.Element(_SOAPSection.ENVELOPE)
if len(self.header) > 0:
envelope.append(self.header)
body = ElementTree.SubElement(envelope, _SOAPSection.BODY)
body.append(self.method)
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +\
ElementTr... |
mypaint/mypaint | gui/device.py | Python | gpl-2.0 | 22,624 | 0.000575 | # This file is part of MyPaint.
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2019 by the MyPaint Development Team.
#
# 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 Licen... | self._device_removed_cb)
self | ._device_manager = mgr
for physical_device in mgr.list_devices(Gdk.DeviceType.SLAVE):
self._init_device_settings(physical_device)
## Devices list
def get_device_settings(self, device):
"""Gets the settings for a device
:param Gdk.Device device: a physical ("slave") device... |
andrmuel/gr-dab | python/qa/qa_measure_processing_rate.py | Python | gpl-3.0 | 1,233 | 0.030819 | #!/usr/bin/env python
from gnuradio import gr, gr_unittest
from gnuradio import blocks
import grdab
class qa_measure_processing_rate(gr_unittest.TestCase):
"""
@brief QA for measure processing rate sink.
This class implements a test bench to verify the corresponding C++ class.
"""
def setUp(self):
self.tb = ... | ate(gr.sizeof_gr_complex,100000)
self.tb.connect(src, throttle, head, sink)
self.tb.run()
rate = | sink.processing_rate()
assert(rate > 900000 and rate < 1100000)
def test_002_measure_processing_rate(self):
src = blocks.null_source(gr.sizeof_char)
throttle = blocks.throttle(gr.sizeof_char, 10000000)
head = blocks.head(gr.sizeof_char, 1000000)
sink = grdab.measure_processing_rate(gr.sizeof_char,1000000)... |
andrewsmedina/django-admin2 | djadmin2/views.py | Python | bsd-3-clause | 21,359 | 0.00014 | # -*- coding: utf-8 -*-
from __future__ import division, absolute_import, unicode_literals
import operator
from datetime import datetime
from functools import reduce
import extra_views
from django.conf import settings
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import (Pass... | t):
| # If we are sorting AND the field exists on the model
sort_by = self.request.GET.get('sort', None)
if sort_by:
# Special case when we are not explicityly displaying fields
if sort_by == '-__str__':
queryset = queryset[::-1]
try:
# ... |
rcatwood/Savu | savu/plugins/loaders/multi_modal_loaders/i18_loaders/i18stxm_loader.py | Python | gpl-3.0 | 1,776 | 0.001689 | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | @diamond.ac.uk>
"""
from savu.plugins.loaders.multi_modal_loaders.base_i18_multi_modal_loader import BaseI18MultiModalLoader
from savu.plugins.utils import register_plugin
@register_plugin
class I18stxmLoader(BaseI18MultiModalLoader):
"""
A class to load tomography data from an NXstxm file
:param stxm_... | xmLoader, self).__init__(name)
def setup(self):
"""
Define the input nexus file
:param path: The full path of the NeXus file to load.
:type path: str
"""
data_str = self.parameters['stxm_detector']
data_obj = self.multi_modal_setup('stxm')
... |
dsiddharth/access-keys | keystone/tests/contrib/kds/paths.py | Python | apache-2.0 | 915 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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.
import os
TEST_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
TMP_DIR = os.path.join(TEST_DIR, '..', '..', 'tmp')
def root_path(*args):
retur... |
AlphaCluster/NewsBlur | vendor/paypal/standard/pdt/forms.py | Python | mit | 240 | 0.004167 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from paypal.standard.forms import PayPalStandardBaseForm
from paypal.standard.pdt.models import PayPalPDT
class PayPalPDTForm(PayPalStandardBaseForm):
class Meta:
model = PayP | alPDT | |
Bindernews/TheHound | identifiers/rpm_identifier.py | Python | mit | 205 | 0.04878 | from identifier im | port Result
RPM_PATTERNS = [
'ED AB EE DB'
]
class RpmResolver:
def identify(self, stream):
return Result('RPM')
def load( | hound):
hound.add_matches(RPM_PATTERNS, RpmResolver())
|
Lydwen/Mr.Statamutation | Mr.Statapython/statapython/stataspoon/__init__.py | Python | mit | 45 | 0 | fr | om .mutationstester import MutationsTe | ster
|
kvar/ansible | test/lib/ansible_test/_internal/integration/__init__.py | Python | gpl-3.0 | 11,813 | 0.00364 | """Ansible integration test infrastructure."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import contextlib
import json
import os
import shutil
import tempfile
from .. import types as t
from ..target import (
analyze_integration_target_dependencies,
walk_integrati... | ntegrationConfig):
return
def inventory_callback(files): # t | ype: (t.List[t.Tuple[str, str]]) -> None
"""
Add the inventory file to the payload file list.
This will preserve the file during delegation even if it is ignored or is outside the content and install roots.
"""
if data_context().content.collection:
working_path = data... |
tiagoft/sampleseeker | sampleseeker.py | Python | gpl-3.0 | 1,431 | 0.01188 | import web
import uuid
from jinja2 import Environment, FileSystemLoader
import os
files_directory = "db/data"
THIS_DIR = os.path.dirname(os.path.abspath(__file__)) |
urls = (
'/', 'Index',
'/upload', 'Upload'
)
class Index:
def GET(self):
j2_env = Environment(loader=FileSystemLoader(THIS_DIR+"/template/"),
trim_blocks=True)
template_values = {"things_to_show": ["one", "two", "three"]}
return j2_env.get_template('ind... | tml><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<br/>
<input type="submit" />
</form>
</body></html>"""
def POST(self):
x = web.input(myfile={})
filepath = x.myfile.filename.replace('\\','/') # replaces... |
Mitali-Sodhi/CodeLingo | Dataset/python/buildprefixdata.py | Python | mit | 8,450 | 0.002604 | #!/usr/bin/env python
"""Script to read the libphonenumber per-prefix metadata and generate Python code.
Invocation:
buildprefixdata.py [options] indir outfile module_prefix
Processes all of the per-prefix data under the given input directory and emit
generated Python code.
Options:
--var XXX : use this prefix f... | ified, prefixdata[prefix][locale] is filled in; otherwise, just prefixdata[prefix].
If separator is specified, t | he string data will be split on this separator, and the output values
in the dict will be tuples of strings rather than strings.
"""
with open(filename, "rb") as infile:
lineno = 0
for line in infile:
uline = line.decode('utf-8')
lineno += 1
dm = DATA_LINE... |
OpenGov/grid_walker | setup.py | Python | bsd-3-clause | 1,495 | 0.002676 | import os
from setuptools import setup
def read(fname):
with open(fname) as fhandle:
return fhandle.read()
def readMD(fname):
# Utility function to read the README file.
full_fname = os.path.join(os.path.dirname(__file__), fname)
if 'PANDOC_PATH' in os.environ:
import pandoc... | ts',
zip_safe=False,
url='https://github.com/OpenGov/grid_walker',
download_url='https://github.com/OpenGov/grid_walker/tarball/v' + version,
keywords=['grids' | , 'data', 'iterator', 'multi-dimensional'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Utilities',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2 :: Only'
]
)
|
skevy/django | django/utils/datastructures.py | Python | bsd-3-clause | 15,444 | 0.001684 | import copy
from types import GeneratorType
class MergeDict(object):
"""
A simple class for creating new "virtual" dictionaries that actually look
up values in more than one dictionary, passed in the constructor.
If a key appears in more than one of the given dictionaries, only the
first occurrenc... | .setdefault(key, default)
def value_for_index(self, index):
"""Returns the value of the item at the given zero-based index."""
return self[self.keyOrder[index]]
def insert(self, index, key, value):
"""Inserts the key, value pair before the item with the given index."""
if key i... | .index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value)
def copy(self):
"""Returns a copy of this object."""
# This way of initializing the copy means it works ... |
amiraliakbari/grade-analyzer | pan/pan.py | Python | mit | 414 | 0.007246 | #!/usr/bin/env python
import re
import glob
class FileReader(object):
OPTION_LINE_RE = re.compile(r'^#!\s*(.+?)\s*=(.+? | )\s*$')
de | f __init__(self):
self.opts = {
'sep': ' ',
'cols': 'sum',
}
def read_option_line(self, l):
m = self.OPTION_LINE_RE.match(l)
if not m:
raise ValueError
k = m.group(1)
v = m.group(2)
|
charris/numpy | numpy/lib/mixins.py | Python | bsd-3-clause | 7,052 | 0 | """Mixin classes for custom array types that don't inherit from ndarray."""
from numpy.core import umath as um
__all__ = ['NDArrayOperatorsMixin']
def _disables_array_ufunc(obj):
"""True when __array_ufunc__ is set to None."""
try:
return obj.__array_ufunc__ is None
except AttributeError:
... | um.subtract, 'sub')
__mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul' | )
__matmul__, __rmatmul__, __imatmul__ = _numeric_methods(
um.matmul, 'matmul')
# Python 3 does not use __div__, __rdiv__, or __idiv__
__truediv__, __rtruediv__, __itruediv__ = _numeric_methods(
um.true_divide, 'truediv')
__floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(
... |
Robpol86/terminaltables | terminaltables/ascii_table.py | Python | mit | 2,734 | 0.004389 | """AsciiTable is the main table class. To be inherited by other tables. Define convenience methods here."""
from terminaltables.base_table import BaseTable
from terminaltables.terminal_io import terminal_size
from terminaltables.width_and_alignment import column_max_width, max_dimensions, table_width
class AsciiTabl... | ef ok(self): # Too late to change API. # pylint: disable=invalid-name
"""Return True if the table fits within the terminal width, False if the table breaks."""
return self.table_width <= terminal_size()[0]
@property
def table_width(self):
"""Return the width of the tab | le including padding and borders."""
outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]
outer_border = 2 if self.outer_border else 0
inner_border = 1 if self.inner_column_border else 0
return table_width(outer_widths, outer_border, inner_border)
|
wreckJ/hamster | src/hamster/preferences.py | Python | gpl-3.0 | 22,492 | 0.006269 | # -*- coding: utf-8 -*-
# Copyright (C) 2007, 2008, 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster 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, eith... | lRendererText()
self.external_listeners.extend([
(self.activityCell, self.activityCell.connect('edited', self.activity_name_ed | ited_cb, self.activity_store))
])
self.activityColumn.pack_start(self.activityCell, True)
self.activityColumn.set_attributes(self.activityCell, text=1)
self.activityColumn.set_sort_column_id(1)
self.activity_tree.append_column(self.activityColumn)
self.activity_tree.set_... |
brioscaibriste/iarnrod | coire.py | Python | gpl-3.0 | 6,003 | 0.01316 | #!/usr/bin/python3
#
# Copyright: Conor O'Callghan 2016
# Version: v1.1.3
#
# Please feel free to fork this project, modify the code and improve
# it on the github repo https://github.com/brioscaibriste/iarnrod
#
# Powered by TfL Open Data
# This program is free software: you can redistribute it and/or modi... | her or not the next run of the retrieval of data should run.
It retrieves the previously run time from a file in /tmp if it exists, if the file does not exist
the run status will return as 1 and the current time stamp will be written into a new file.
If throttling is disabled, the file will be remo | ved from /tmp and run will be set to 1.
'''
def Throttle(PollIntervalMinutes,Throttling,TFileName):
if Throttling == "True":
# Current epoch time
# CurrentStamp = str(time.time()).split('.')[0]
CurrentStamp = int(time.time())
# Does the temporary file exist or not
... |
Metaswitch/horizon | openstack_dashboard/contrib/sahara/content/data_processing/cluster_templates/workflows/create.py | Python | apache-2.0 | 12,426 | 0.000161 | # 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... | ow):
slug = "create_cluster_template"
name = _("Create Cluster Template")
finalize_button_name = _("Next")
success_message = _("Created")
failure_message = _("Could not create")
success_url = "horizon:project:data_processing.cluster_templates:index"
default_steps = (SelectPlugin,)
class Ge... | ld = forms.CharField(
required=False,
widget=forms.HiddenInput(attrs={"class": "hidden_configure_field"}))
hidden_to_delete_field = forms.CharField(
required=False,
widget=forms.HiddenInput(attrs={"class": "hidden_to_delete_field"}))
cluster_template_name = forms.CharField(labe... |
jvlomax/Beaker-bot | plugins/arewedone.py | Python | gpl-2.0 | 1,837 | 0.006532 | __author__ = 'george'
from baseclass import Plugin
import time
from apscheduler.scheduler import Scheduler
class AreWeDone(Plugin):
def __init__(self, skype):
super(AreWeDone, self).__init__(skype)
self.command = "arewedoneyet"
self.sched = Scheduler()
self.sched.start()
sel... | Please visit http://www.nav.n | o for more information")
def set_topic(self):
channel = "#stigrk85/$jvlomax;b43a0c90a2592b9b"
chat = self.skype.Chat(channel)
cur_time = time.localtime()
days_left = 1 - cur_time.tm_mday % 31
time_left = 24 - cur_time.tm_hour + days_left * 24
if cur_time.tm_hour >= ... |
Jumpscale/go-raml | codegen/fixtures/congo/python_server/server.py | Python | bsd-2-clause | 425 | 0 | # DO NOT EDIT THIS FILE. This file will be overwritt | en when re-running go-raml.
from app import app
import gevent
from gevent.pywsgi import WSGIServer
from gevent.pool import Pool
from gevent import monkey
import signal
monkey.patch_all()
server = WSGIServer(('', 5000), app, spawn=Pool(None))
def stop():
server.stop()
gevent.signal(signal.SIGINT, stop)
i... | rve_forever()
|
michelesr/gasistafelice | gasistafelice/gf/base/const.py | Python | agpl-3.0 | 851 | 0.00235 | from django.utils.translation import ugettext, ugettext_lazy as _
from django.conf import settings
STATE_CHOICES = [
('AN', 'Ancona'),
('AP', 'Ascoli Piceno'),
('FM', 'Fermo'),
('MC', 'Macerata'),
('PU', 'Pesaro Urbino')
]
SUPPLIER_FLAVOUR_LIST = [
('COMPANY', _('Company')),
('COOPERATING'... | ),
('FREELANCE', _('Freelance')),
]
MU_CHOICES = [('Km', 'Km')]
ALWAYS_AVAILABLE = 1000000000
PHONE = 'PHONE'
EMAIL = 'EMAIL'
FAX = 'FAX'
#WWW = 'WWW'
CONTACT_CHOICES = [
(PHONE, _('PHONE')),
(EMAIL, _('EMAIL')),
(FAX, _('FAX')),
]
# (WWW, _('WWW')),
DAY_CHOICES = [
('MONDAY', _('Monday')),
... | ')),
]
|
fluggo/Canvas | fluggo/editor/model/commands.py | Python | gpl-3.0 | 38,160 | 0.004271 | # This file is part of the Fluggo Media Library for high-quality
# video and audio processing.
#
# Copyright 2010-2 Brian J. Crowell <[email protected]>
#
# 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 Foun... | g, the last item must have a positive transition_length
self.max_fadeout_length = items[-1].length
# Ditto, but at the beginning of the items
self.max_fadein_length = items[0].length
if len(items) > 1:
| self.max_fadeout_length -= items[-1].transition_length
self.max_fadein_length -= items[1].transition_length
def clone_items(self):
'''Clones all of this mover's items. The cloned items will be homeless.'''
return [item.clone() for item in self.items]
def clone(self):
... |
burzillibus/RobHome | venv/bin/rst2s5.py | Python | mit | 671 | 0.00149 | #!/home/vincenzo/Development/RobHome/venv/bin/python
# $Id: rst2s5.py 4564 2006-05-21 20:44:42Z wi | emann $
# Author: Chris Liechti <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing HTML slides using
the S5 template system.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.co... | )
publish_cmdline(writer_name='s5', description=description)
|
google-research/google-research | etcmodel/models/openkp/run_finetuning_lib_test.py | Python | apache-2.0 | 7,530 | 0.001726 | # coding=utf-8
# Copyright 2022 The Google Research 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 applicab... | [
[0, 0, 0, 1 / 3], # 1-grams
[1 / 3, 0, 1 / 3, 0], # 2-grams
[0, 0, 0, 0], # 3-grams
[0, 0, 0, 0], # 4-grams
[0, 0, 0, 0], # 5-grams
],
]
batch_size = len(reshaped_expected)
expected = tf.reshape(reshaped_expected,
| [batch_size, kp_max_length * long_max_length])
self.assertAllClose(
expected,
run_finetuning_lib.make_ngram_labels(
label_start_idx=label_start_idx,
label_phrase_len=label_phrase_len,
long_max_length=long_max_length,
kp_max_length=k... |
thesharp/botogram | tests/test_decorators.py | Python | mit | 535 | 0 | """
Tests for botogram/utils.py
Copyr | ight (c) 2015 Pietro Albini <[email protected]>
Released under the MIT license
"""
import botogram.decorators
def test_help_message_for(bot):
@bot.command("test")
def func():
"""docstring"""
pass
cmd = {cmd.name: cmd for cmd in bot.available_commands()}["test"]
assert cmd.... | on"
assert cmd.raw_docstring == "function"
|
dbcls/dbcls-galaxy | test/functional/test_get_data.py | Python | mit | 4,761 | 0.031086 | import galaxy.model
from galaxy.model.orm import *
from base.twilltestcase import TwillTestCase
class UploadData( TwillTestCase ):
def test_000_upload_files_from_disk( self ):
"""Test uploading data files from disk"""
self.logout()
self.login( email='[email protected]' )
history1 = gal... | hda3 = galaxy.model.HistoryDatasetAssociation.query() \
.order_by( desc( galaxy.model.HistoryDatasetAssociation.table.c.create_time ) ).first()
assert hda3 is not None, "Problem retrieving hda3 from database"
self.verify_dataset_correctness( '3.bed', hid=str( hda3.hid ) )
self.u... | ad_file( '4.bed.gz', dbkey='hg17', ftype='bed' )
hda4 = galaxy.model.HistoryDatasetAssociation.query() \
.order_by( desc( galaxy.model.HistoryDatasetAssociation.table.c.create_time ) ).first()
assert hda4 is not None, "Problem retrieving hda4 from database"
self.verify_dataset_correc... |
MooseDojo/myBFF | modules/jenkinsBrute.py | Python | mit | 1,691 | 0.009462 | #! /usr/bin/python
# this module is for jenkins attacks
from core.webModule import webModule
from requests import session
import requests
import re
from argparse import ArgumentParser
from lxml import html
import random
clas | s jenkinsBrute(webModule):
def __init__(self, config, display, lock):
super(jenkinsBrute, self).__init__(config, display, lock)
self.fingerprint="Jenkins"
self.respon | se="Success"
self.protocol="web"
def somethingCool(self, config, payload, proxy):
#Do something cool here
print("Something Cool not yet implemented")
def connectTest(self, config, payload, proxy, submitLoc, submitType):
#Create a session and check if account is valid
with... |
grow/grow-ext-build-server | grow_build_server/emailer.py | Python | mit | 1,438 | 0.002782 | from google.appengine.ext import vendor
vendor.add('extensions')
from google.appengine.api import mail
import jinja2
import os
import premailer
_appid = os.getenv('APPLICATION_ID').replace('s~', '')
EMAIL_SENDER = ' | noreply@{}.appspotmail.com'.format(_appid)
class Emailer(object):
def __init__(self, sender=None):
self.sender = sender or EMAIL_SENDER
def send(self, to, subject, template_path, kwargs=None):
html = self._render(template_path, kwargs=kwargs)
self._send(subject, to, html)
def _r... | te.render(params)
return premailer.transform(html)
def _send(self, subject, to, html):
message = mail.EmailMessage(sender=self.sender, subject=subject)
message.to = to
message.html = html
message.send()
@property
def env(self):
path = os.path.join(os.path.di... |
joselamego/patchwork | patchwork/migrations/0003_series.py | Python | gpl-2.0 | 2,993 | 0.003007 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('patchwork', '0002_fix_pat... | se_name='ID', serialize=False, auto_created=True, primary_key=True)),
('version', models.IntegerField( | default=1)),
('root_msgid', models.CharField(max_length=255)),
('cover_letter', models.TextField(null=True, blank=True)),
],
options={
'ordering': ['version'],
},
),
migrations.CreateModel(
name='SeriesRevisi... |
clinton-hall/nzbToMedia | libs/common/babelfish/country.py | Python | gpl-3.0 | 3,242 | 0.001851 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source code is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
from __future__ import unicode_literals
from collections import namedtuple
from functools import partial
from pkg_resour... | medtuple used in the :data:`COUNTRY_MATRIX`
IsoCountry = namedtuple('IsoCountry', ['name', 'alpha2'])
f = resource_stream('babelfish', 'data/iso-3166-1.txt')
f.readline()
for l in f:
iso_country = IsoCountry(*l.decode('utf-8').strip().split(';'))
COUNTRIES[iso_country.alpha2] = iso_country.name
COUNTRY_MAT... | nverters.ConverterManager` for country converters"""
entry_point = 'babelfish.country_converters'
internal_converters = ['name = babelfish.converters.countryname:CountryNameConverter']
country_converters = CountryConverterManager()
class CountryMeta(type):
"""The :class:`Country` metaclass
Dynamical... |
dbnicholson/merge-our-misc | generate_diffs.py | Python | gpl-3.0 | 4,253 | 0.006115 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# generate-diffs.py - generate changes and diff files for new packages
#
# Copyright © 2008 Canonical Ltd.
# Author: Scott James Remnant <[email protected]>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of version 3 of the GNU... | unpack_source(las | t)
save_patch_file(diff_filename, last.getSources(), this.getSources())
save_basis(diff_filename, last.getSources()["Version"])
logger.info("Saved diff file: %s", tree.subdir(ROOT, diff_filename))
if __name__ == "__main__":
run(main, options, usage="%prog [DISTRO...]",
description=... |
pchaitat/invrcptexporter | sample-code/misc/hello_world_librecalc.py | Python | gpl-3.0 | 1,240 | 0.006452 | #!/usr/bin/env python3
# export_to_pdf.py
#
# references
# - https://onesheep.org/scripting-libreoffice-python/
# - http://christopher5106.github.io/office/2015/12/06/openoffice-lib
# reoffice-automate-your-office-tasks-with-python-macros.html
import uno
from com.sun.star.beans import PropertyValue
localCont... | ose(True)
# access the active sheet
active_sheet = model.CurrentController.Activ | eSheet
# access cell C4
cell1 = active_sheet.getCellRangeByName("C4")
# set text inside
cell1.String = "Hello world"
# other example with a value
cell2 = active_sheet.getCellRangeByName("E6")
cell2.Value = cell2.Value + 1
import sys
sys.exit(0)
|
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_3_0_0/models/valueset.py | Python | bsd-3-clause | 21,281 | 0.007753 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 (http://hl7.org/fhir/StructureDefinition/ValueSet) on 2017-03-22.
# 2017, SMART Health IT.
from . import domainresource
class ValueSet(domainresource.DomainResource):
""" A set of codes drawn from one or more code systems.
... |
resource_type = "ValueSet"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool... | strict: If True (the default), invalid variables will raise a TypeError
"""
self.compose = None
""" Definition of the content of the value set (CLD).
Type `ValueSetCompose` (represented as `dict` in JSON). """
self.contact = None
""" Contact details for ... |
VerifiableRobotics/LTLMoP | src/lib/execute.py | Python | gpl-3.0 | 17,245 | 0.005683 | #!/usr/bin/env python
""" =================================================
execute.py - Top-level hybrid controller executor
=================================================
This module executes a hybrid controller for a robot in a simulated or real environment.
:Usage: ``execute.py [-hn] [-p liste... | r k,v in self.proj.h_instance[htype].iteritems()]
else:
handlers = [self.proj.h_instance[htype]]
for h in handlers:
if hasattr(h, "_stop"):
| logging.debug("Calling _stop() on {}".format(h.__class__.__name__))
h._stop()
else:
logging.debug("{} does not have _stop() function".format(h.__class__.__name__))
else:
logging.debug("{} handler not found in h_ins... |
lmr/avocado-vt | virttest/step_editor.py | Python | gpl-2.0 | 50,744 | 0.000158 | #!/usr/bin/python
"""
Step file creator/editor.
:copyright: Red Hat Inc 2009
:author: [email protected] (Michael Goldish)
"""
import os
import glob
import shutil
import sys
import logging
import pygtk
import gtk
from virttest import ppm_utils
pygtk.require('2.0')
# General utilities
def corner_and_size_clippe... | x()
box.pack_start(vbox)
vbox.show()
self.label_barrier_region = gtk.Label("Region:")
self.label_barrier_region.set_alignment(0, 0.5)
vbox.pack_start(self.label_barrier_region)
self.label_barrier_region.show()
self.l | abel_barrier_md5sum = gtk.Label("MD5:")
self.label_barrier_md5sum.set_alignment(0, 0.5)
vbox.pack_start(self.label_barrier_md5sum)
self.label_barrier_md5sum.show()
self.label_barrier_timeout = gtk.Label("Timeout:")
box.pack_start(self.label_barrier_timeout, False)
self.l... |
RealTimeWeb/Blockpy-Server | controllers/services.py | Python | mit | 2,386 | 0.003353 | import logging
from pprint import pprint
from flask_wtf import Form
from wtforms import IntegerField, BooleanField
from flask import Blueprint, send_from_directory
from flask import Flask, redirect, url_for, session, request, jsonify, g,\
make_response, Response, render_template
from werkzeug.utils ... | lacksburg, VA")
weather_function = getattr(weather_service, function)
return jsonify(data=weather_function(city))
@services.route('/sheets', methods=['GET'])
def sheets(sheet_url):
sheet_id = ''
if sheet | _url.startswith('http'):
sheet_url.split('/')
elif sheet_url.startswith('docs'):
sheet_url.split('/')
elif sheet_url.startswith('docs'):
sheet_url.split('/')
# sample:
# https://docs.google.com/spreadsheets/d/1eLbX_5EFvZYc7JOGYF8ATdu5uQeu6OvILNnr4vH3vFI/pubhtml
# =>
# htt... |
sil-jterm-2015/sfwebchecks | src/scripts/language picker/build-json-language-data.py | Python | mit | 8,241 | 0.004004 | #!/usr/bin/env python
"""Parses language data from IANA subtag registry plus several other files,
and outputs JSON data in the following format:
[
{
'name': 'Ghotuo',
'code': { 'three': 'aaa' },
'country': ['Nigeria'],
'altNames': [],
},
{
'name': 'Alumu',
'c... | , per spec
for line in record.splitlines():
key, val = line.split(": ", 1)
if key == 'Description':
# Descriptions can, and often do, appear more than once per record
data.setdefault(key, []).append(val)
else:
data[key] = val
... | _names=True):
"""Returns data as either:
- a list of dicts, if first_line_contains_field_names is True
- a list of lists, if first_line_contains_field_names is False
"""
result = []
lines = raw_text.splitlines()
if first_line_contains_field_names:
field_names = lines[0].split... |
TachoMex/Compiladores-14b | Parser/compilador/programa.py | Python | gpl-2.0 | 888 | 0.108108 | func int suma(int a, int b)
return a+b
endfunc
func int absdif(int a, int b)
if(a>b)
return a-b
else
return b-a
endif
endfunc
int i, a, b,B[200], aux, A[100]
int z=suma(2*5+a,aux*A[0])-absdif(10000, 500)
int w=10, C[a/b**aux]
double x=0, y, z, pi=3.141592
a=0
b=1
A[0]=10
A[a+b]=pi**x
for( | i=0, | i<10,i+=1)
print("f(")
print(i)
print(")=")
println(a)
aux=a
a=a+b
b=aux
endfor
read(x)
while(a<b)
println(x)
y=x*pi
z=ln(y)
x+=z**0.5
endwhile
if(x!=0)
println(a)
else
println(b)
endif
if(x!=0)
println(a)
elseif(x<0)
println(b)
elseif(1==1)
println(pi)
else
x+=1
endif
int MAX=1000
int lista[MAX]
... |
deepsrijit1105/edx-platform | lms/djangoapps/instructor_task/tests/test_integration.py | Python | agpl-3.0 | 29,509 | 0.003728 | """
Integration Tests for LMS instructor-initiated background tasks.
Runs tasks on answers to course problems to validate that code
paths actually work.
"""
from collections import namedtuple
import ddt
import json
import logging
from mock import patch
from nose.plugins.attrib import attr
import textwrap
from celery... | r the test course, given the `username` and problem `descriptor`.
Values checked include the number of attempts, the score, and the max score for a problem.
"""
module = self.get_student_module(user.username, descriptor)
self.asser | tEqual(module.grade, expected_score)
self.assertEqual(module.max_grade, expected_max_score)
state = json.loads(module.state)
attempts = state['attempts']
self.assertEqual(attempts, expected_attempts)
if attempts > 0:
self.assertIn('correct_map', state)
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.