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
Morgan-Stanley/treadmill
lib/python/treadmill/spawn/tree.py
Python
apache-2.0
3,867
0
"""Creates a supervision tree which splits the jobs into buckets. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import os import shutil from treadmill import fs from treadmill import spawn from t...
join(self.paths.
svscan_tree_dir, app_dir) _LOGGER.debug('Removing bucket (%r) %r.', spawn.SVSCAN_TREE_DIR, path) shutil.rmtree(path, ignore_errors=True) for run_dir in os.listdir(self.paths.running_dir): if not run_dir.startswith('.') and run_dir not in...
DeppSRL/open-partecipate
project/open_partecipate/models.py
Python
bsd-3-clause
8,151
0.003558
# -*- coding: utf-8 -*- from django.db import models from django.utils.functional import cached_property from model_utils import Choices from territori.models import Territorio class BaseCodelist(models.Model): codice = models.CharField(max_length=6, primary_key=True) descrizione = models.CharField(max_length...
, ] class EntePartecipatoCronologiaRegioneSettore(models.Model): ente_partecipato_
cronologia = models.ForeignKey(EntePartecipatoCronologia, related_name='regioni_settori') regione = models.ForeignKey(Territorio, limit_choices_to={'tipo': Territorio.TIPO.R}, related_name='enti_settori') regione_quota = models.DecimalField(max_digits=5, decimal_places=2, null=True) settore = models.Foreign...
sdrkjt/gr-lte
python/qa_pcfich_unpack_vfm.py
Python
gpl-3.0
2,263
0.005303
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013 Communications Engineering Lab (CEL) / Karlsruhe Institute of Technology (KIT) # # This 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...
t(data[i]) for i in range(len(data))] ext_data = [] for i in range(reps): ext_data.extend(data) data = ext_data self.src = blocks.vector_source_f(data, False, 32, taglist) self.cfi = lte.pcfich_unpack_vfm(key, msg_buf_name) self.cfi.activate_debug_mode(True) ...
src, self.cfi) print "setup finished" def tearDown (self): self.tb = None def test_001_t (self): # set up fg self.tb.run () res = self.cfi.cfi_results() print res print self.cfi_list self.assertListEqual(self.cfi_list, list(res)) # check ...
pydanny/django-admin2
djadmin2/migrations/0001_initial.py
Python
bsd-3-clause
1,700
0.003529
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0002_remove_content_type_...
ssage', models.TextField(verbose_name='change message', blank=True)), ('content_type', models.ForeignKey( related_name='log_entries', null=True, blank=True, to='contenttypes.ContentType',
on_delete=models.CASCADE)), ('user', models.ForeignKey( related_name='log_entries', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ 'verbose_name': 'log entry', ...
praekelt/django-south-admin
setup.py
Python
bsd-3-clause
1,113
0.008086
from setuptools import setup, find_packages setup( name='django-south-admin', version='0.0.3', description='Django app allowing for South management through Admin.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Prae...
), dependency_links = [ ], install_requires=[ 'django', 'django-object-tools', 'south', ], tests_require=[ 'django-setuptest', ], test_suite="setuptest.setuptest.SetupTestSuite", include_package_data=True, classifiers = [
"Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], ...
kayhayen/Nuitka
nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/MSCommon/vc.py
Python
apache-2.0
19,499
0.007385
# # Copyright (c) 2001 - 2015 The SCons Foundation # # 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, modify, merge...
tDir'] } def
msvc_version_to_maj_min(msvc_version): msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.']) t = msvc_version_numeric.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric)) try: maj = int(t[0]) ...
ZenBarrier/Coding-Barrier
contact.py
Python
mit
976
0.026639
from google.appengine.api import mail import json import webapp2 class SendEmail(webapp2.RequestHandler): def post(self): to = self.request.get("to") user_name = self.request.get("name") user_address = self.request.get("email") subject = self.request.get("subject") body = se...
if "<mail@anthonybarre
ra.com>" not in to: return mail.send_mail(sender= sender_address, to = to, #cc = behalf_of, reply_to = behalf_of, subject = subject+" | "+user_name+" | "+user_address, body = body, headers = {"On-B...
ar4s/django
tests/runtests.py
Python
bsd-3-clause
25,311
0.001067
#!/usr/bin/env python import argparse import atexit import copy import gc import os import shutil import socket import subprocess import sys import tempfile import warnings from pathlib import Path try: import django except ImportError as e: raise RuntimeError( 'Django module not found, reference tests...
for test modules. SUBDIRS_TO_SKIP = { '': {'import_error_package', 'test_runner
_apps'}, 'gis_tests': {'data'}, } ALWAYS_INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.staticfiles', ] ALWAYS_MIDDLEWA...
nginx/unit
test/unit/control.py
Python
apache-2.0
1,560
0
import json from unit.http import TestHTTP from unit.option import option def args_handler(conf_func): def args_wrapper(self, *args): argcount = conf_func.__code__.co_argcount url_default = '/config' conf = None if argcount == 2: url = args[0] if len(args) == 1 else u...
lf.delete(**self._get_args(url))['body'] @args_handler def conf_post(self, conf, url): return self.post(**self._get_args(url, conf))['body'] def _get_args(self, url, conf=None): args = { 'url': ur
l, 'sock_type': 'unix', 'addr': option.temp_dir + '/control.unit.sock', } if conf is not None: args['body'] = conf return args
arkmaxim/grpc
src/python/grpcio_tests/grpc_version.py
Python
bsd-3-clause
1,643
0.001217
# Copyright 2016, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # AUTO-
GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_tests/grpc_version.py.template`!!! VERSION='1.0.1'
simontakite/sysadmin
pythonscripts/learningPython/minmax2.py
Python
gpl-2.0
380
0.007895
print('I am:', __name__) def minmax(test, *args): res = args[0] for arg in args[1:]: if test(arg, res): res = arg return res def lessthan(
x, y): return x < y def grtrthan(x, y): return x > y if __name__ == '__main__':
print(minmax(lessthan, 4, 2, 1, 5, 6, 3)) # Self-test code print(minmax(grtrthan, 4, 2, 1, 5, 6, 3))
WickedShell/ardupilot
Tools/autotest/autotest.py
Python
gpl-3.0
17,704
0.002316
#!/usr/bin/env python """ APM automatic test suite Andrew Tridgell, October 2011 """ import atexit import fnmatch import glob import optparse import os import shutil import signal import sys import time import traceback import apmrover2 import arducopter import arduplane import quadplane from pysim import util os....
= "arduplane" else: # cope with builds that don't have a specific binary return None if debug: binary_basedir = "sitl-debug" else: binary_basedir = "sitl" binary = util.reltopdir(os.path.join('build', binary_basedir, 'bin', binary_name)) if not os.path.exists(binar...
if os.path.exists(binary + ".exe"): binary += ".exe" else: raise ValueError("Binary (%s) does not exist" % (binary,)) return binary def run_step(step): """Run one step.""" # remove old logs util.run_cmd('/bin/rm -f logs/*.BIN logs/LASTLOG.TXT') if step == "prer...
jmcmurry/monarch-app
tests/behave/environment.py
Python
bsd-3-clause
7,314
0.004238
#### #### Setup gross testing environment. #### #### This currently includes the UI instance target and browser type #### (FF vs PhantomJS). #### import os import time from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities ### ### Simple (but somewhat excessive f...
# time.sleep(20) pass def dump_log(context, scenarioName): log = context.browser.get_log("browser"
) print('') print('--------- console.log for: "' + scenarioName + '"') for l in log: # if l['level'] != 'WARNING': print(l['level'] + ': ' + l['message']) print('') ### ### Working on a more complex run environment for the future. ### # ## Run this before anything else. # def before_al...
CactusBot/CactusBot
cactusbot/__init__.py
Python
gpl-3.0
89
0
"""Ca
ctusBot.""" from .cactus import run, __version__ __all__ = ["__v
ersion__", "run"]
kennydo/nyaalib
nyaalib/__init__.py
Python
mit
8,198
0
import datetime from xml.etree import ElementTree try: from urllib.parse import urlparse, parse_qs except ImportError: # Python 2 from urlparse import urlparse, parse_qs import html5lib import requests from .models import ( Category, SearchSortKey, SearchOrderKey, SearchResultPage, TorrentPage, To...
the given URL or an empty string if the query is not in the URL """ query_string = urlparse(url).query re
turn parse_qs(query_string).g
dgvicente/django-social-network
social_network/forms.py
Python
bsd-3-clause
2,353
0.003825
# coding=utf-8 from django import forms from django.core.exceptions import ValidationError from . import Manager from models import ( FriendRequest, SocialGroup, GroupComment, GroupMembershipRequest, GroupImage, FeedComment, GroupSharedLink) class FriendRequestForm(forms.ModelForm): ...
orms.ModelForm): class Meta: model = FeedComment widgets = { 'creator': forms.widgets.HiddenInput, 'receiver': forms.widgets.HiddenInput, }
baldengineers/mapper
tf2/prefabs/block.py
Python
gpl-3.0
19,942
0.016347
import os import math def rotatePoint(centerPoint,point,angle): angle = math.radians(angle) temp_point = point[0]-centerPoint[0] , point[1]-centerPoint[1] temp_point = ( temp_point[0]*math.cos(angle)-temp_point[1]*math.sin(angle) , temp_point[0]*math.sin(angle)+temp_point[1]*math.cos(angle)) temp_point...
x12 = posx*1*512 + (512) y12 = posy*-1*512 + (-512) z1
2 = level*448 + 448 x13 = posx*1*512 + (512) y13 = posy*-1*512 z13 = level*448 + 448 x14 = posx*1*512 y14 = posy*-1*512 z14 = level*448 + 448 x15 = posx*1*512 y15 = posy*-1*512 z15 = level*448 + 0 x16 = posx*1*512 + (512) y16 = posy...
tturowski/parserTools
getNameFromId.py
Python
apache-2.0
1,580
0.008228
#!/usr/bin/env python __author__ = 'Tomasz Turowski' ## script uses pyCRAC GTF Parser to get from GTF file gene name from pyCRAC.Parsers import GTF2 import sys, os, yaml from signal import signal, SIGPIPE, SIG_DFL from optparse import OptionParser def get_file(path_from_options, type='gtf'): types = {'gtf' : 'GTF_...
else: if os.environ[types
[type]]: # print "# Using "+type+" file from $"+types[type]+" variable" return os.environ[types[type]] else: exit('Provide '+type+' file path using -g/-f or setup default.aml in your bin folder') def main(): parser = OptionParser(usage="usage: List of genes as std input"...
q4478842/QQsync
server/server.py
Python
gpl-2.0
526
0.01711
from twisted.internet import react
or from twisted.internet.protocol import Protocol , Factory class SimpleLogger(Protocol): fi = open("/temp/31.log","rw+") def connectionMade(self): print 'got connection from',self.transport.client def connectionLost(self,reason): print self.transport.client,'disconnected' def dataR...
tory) reactor.run()
FeiZhan/Algo-Collection
answers/leetcode/Combinations/Combinations.py
Python
mit
505
0
class Solution(object): def combine(self, n, k): """ :type n: int :typ
e k: int :rtype: List[List[int]] """ combinations = [] self.dfs(1, 0, [], combinations, n, k) return combinations def dfs(self, begin, count, combi, combinations, n, k): if count >= k: combinations.append(combi) return for i in range(...
n, k)
ricorx7/rti-python
tests/test_plot_mag_bokeh.py
Python
bsd-3-clause
5,892
0.004073
import os.path import sys import getopt import math import pandas as pd import numpy as np from log import logger from Codecs.AdcpCodec import AdcpCodec import Ensemble.Ensemble as Ensemble import matplotlib.pyplot as plt import seaborn as sns from bokeh.charts import HeatMap, output_file, show from bokeh.models impo...
arg in opts: if opt == '-h': print('PlotMagnitude.py -i <inputfile> -v') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-v", "--verbose"): verbose = True print("Verbose ON") print('Input file is: ', inputfi...
me__ == "__main__": main(sys.argv[1:])
xudongyangwork/algo
utils/__init__.py
Python
mit
42
0
# -*- coding:u
tf-
8 -*- __author__ = 'xdy'
RaitoBezarius/mangaki
mangaki/mangaki/migrations/0002_auto_20150129_0110.py
Python
agpl-3.0
613
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mangaki', '0001_initial
'), ] operations = [ migrations.AddField( model_name='work', name='date', field=models.DateField(blank=True, null=True), preserve_default=True, ), migrat
ions.AddField( model_name='work', name='nsfw', field=models.BooleanField(default=False), preserve_default=True, ), ]
wiki-ai/revscoring
revscoring/dependencies/functions.py
Python
mit
10,779
0
""" The following functions provide a set of utilities for working with `Dependent` and collections of `Dependent`. * :func:`~revscoring.dependencies.solve` provides basic dependency solving * :func:`~revscoring.dependencies.expand` provides minimal expansion of dependency trees * :func:`~revscoring.dependencies.dig...
context. Can be specified as a set of :class:`revscoring.Dependent` or a map of :class:`revscoring.Dependent` pairs. cache : `dict` | `set` A cache of previously solved dependencies as `Dependent`:`<value>` pairs. When these items are reached while sc...
tree, "CACHED" will be printed. :Returns: None """ return "\n".join(draw_lines(dependent, context, cache, depth)) + "\n" def draw_lines(dependent, context, cache, depth): cache = cache or {} context = normalize_context(context) if dependent in cache: yield "\t" *...
dhellmann/aeromancer
aeromancer/db/alembic/env.py
Python
apache-2.0
1,979
0.001516
from __future__ import with_statement from alembic i
mport context from sqlalchemy import engine_from_config, pool #from logging.config import fileConfig # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. #f...
arget_metadata = mymodel.Base.metadata target_metadata = None # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def run_migrations_offline(): """Run migrations in 'offline' mode. This configures...
Abjad/abjad
tests/test_LilyPondParser__functions__transpose.py
Python
gpl-3.0
2,425
0.002062
import abjad def test_LilyPondParser__functions__transpose_01(): pitches = ["e'", "gs'", "b'", "e''"] maker = abjad.NoteMaker() target = abjad.Staff(maker(pitches, (1, 4))) key_signature = abjad.KeySignature("e", "major") abjad.attach(key_signature, target[0])
assert abjad.lilypond(target) == abjad.string.normalize( r""" \new Staff { \key e \major e'4
gs'4 b'4 e''4 } """ ) string = r"\transpose d e \relative c' \new Staff { \key d \major d4 fs a d }" parser = abjad.parser.LilyPondParser() result = parser(string) assert abjad.lilypond(target) == abjad.lilypond(result) and target is not result def test_...
leppa/home-assistant
homeassistant/components/foobot/sensor.py
Python
apache-2.0
4,894
0.000613
"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS...
ed(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices ass
ociated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devic...
vingtfranc/LoLAnalyzer
PlayersListing.py
Python
mit
14,631
0.003554
#!python # Collect for each region the list of players by league # Strategy: we go through the list of all the known players and check their games # As a starting list, we can take master/challenger players import os import multiprocessing import time import pickle import sys from pickle import PickleError from Inte...
.region, len(self.to_explore), 'players left to explore', file=sys.stderr) while self.to_explore: if time.time() > self.nextSave: print(self.region, len(self.to_explore), 'players left to explore', file=sys.stderr) print(self.region, 'saving...', file=sys.stderr) ...
try: accountID = self.api.getData('https://%s.api.riotgames.com/lol/summoner/v4/summoners/%s' % (self.region, sumID))['accountId'] games = \ self.api.getData('https://%s.api.riotgames.com/lol/match/v4/matchlists/by-account/%s' % (self.region, accountID), {'queue': 420...
thebjorn/dkcoverage
dkcoverage/utils/dependencies.py
Python
gpl-2.0
873
0.001145
# -*- coding: utf-8 -*- from modulefinder import ModuleFinder from ..path import normpath def dependencies(fname, root=None): """Find all dependencies (i.e. imported modules) from fname without running it. If `root` is specified, only modules having __file__ attributes under this root is i...
on is quite slow.. """ assert fname.endswith('.py') res = set() finder = ModuleFinder() try: finder.run_script(fname) except: return [] root = normpath(root, slash='/') prefix = len(r
oot) + 1 # for trailing slash for name, mod in finder.modules.iteritems(): if name.startswith('_'): continue modpath = normpath(mod.__file__, slash='/') if modpath.startswith(root): res.add(modpath[prefix:]) return list(sorted(res))
rschnapka/bank-payment
account_banking_camt/__openerp__.py
Python
agpl-3.0
1,335
0
############################################################################## # # Copyright (C) 2013 Therp BV (<http://therp.nl>) # 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 published # by...
2', 'license': 'AGPL-3', 'author': 'Therp BV',
'website': 'https://launchpad.net/banking-addons', 'category': 'Banking addons', 'depends': ['account_banking'], 'description': ''' Module to import SEPA CAMT.053 Format bank statement files. Based on the Banking addons framework. ''', 'installable': True, }
felskrone/python-confd
src/usr/local/bin/pyconfd.py
Python
apache-2.0
16,540
0.001693
#!/usr/bin/python3 ''' Gathers endpoints for services from kubernetes-api and generates a haproxy.cfg from it. Since not all endpoints should always be exposed, the endpoints have to be annotated to be considered for haproxy-config generation. The required keywords are domain - The domain-name under which the service i...
(message)s') conh = logging.StreamHandler() conh.setFo
rmatter(ch_format) conh.setLevel(logging.getLevelName(level.upper())) self.logger.addHandler(conh) def info(self, msg): self.logger.info(msg) def error(self, msg): self.logger.error(msg) def debug(self, msg): self.logger.debug(msg) def load_tmpls(conf): ''' ...
rtancman/speak
speak/wsgi.py
Python
gpl-2.0
387
0
""" WSGI config for speak 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.9/how
to/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "speak.settings") application
= get_wsgi_application()
morgoroth/pentest-scripts
scanners/oracle_pillage/ora_priv.py
Python
apache-2.0
9,996
0.039216
import time import sys import csv import re import argparse import urllib import os.path import fileinput import subprocess import socket import os import itertools from collections import defaultdict from pprint import pprint from termcolor import colored from subprocess import call sid = "" metasploitPath = "" #meta...
leep 3\n") myfile.write("use auxiliary/sqli/oracle/dbms_cdc_pub
lish3\n") myfile.write("exploit\n") myfile.write("sleep 3\n") myfile.write("use auxiliary/sqli/oracle/dbms_metadata_get_granted_xml\n") myfile.write("exploit\n") myfile.write("sleep 3\n") myfile.write("use auxiliary/sqli/oracle/dbms_metadata_get_xml\n") myfile.write("exploit\n") myfile.write("sleep 3\n") myfil...
compbiol/CAMSA
camsa/utils/agp/agp2camsa_points.py
Python
mit
10,726
0.004289
#! /usr/bin/env python # -*- coding: utf-8 -*- import datetime import enum import logging import os import sys from collections import defaultdict import configargparse sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.a...
class GapComponent(Component): def __init__(self, object_id, o
bject_beg, object_end, part_number, component_type, gap_length, gap_type, linkage, linkage_evidence): super(GapComponent, self).__init__(object_id=object_id, object_beg=object_beg, object_end=object_end, part_number=part_number, component_type=component_type) self.gap_length = gap_length self.ga...
eunsungc/gt6-RAMSES_8_5
xdd-7.0.0.rc-ramses3/tests/unit/site-packages/xdd_flow_test.py
Python
apache-2.0
15,116
0.002183
#!/bin/env python # Import modules import unittest import subprocess from xdd.flow import * # "constants" TEST_PORT = 40010 # Standard testing strategy: try to check each side of each branch statement # for correctness # Test checkPreconditions method of Flow class FlowCheckPreconditionsTestCase(unittest.TestCase):...
.assertEqual(True, flow.checkSourcePreconditions()) def test_character_device_dio
(self): flow = Flow(False, 1024, 0, 1, [("localhost", TEST_PORT, 1)], True, False, False, False, 'bin') flow.target = '/dev/zero' self.assertEqual(False, flow.checkSourcePreconditions()) def test_block_device_non_root(self): flow = Flow(False,...
plaid/plaid-python
plaid/model/numbers_international.py
Python
mit
7,184
0.000974
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal...
m values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discri
minator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, ...
chrisseto/Still
wdim/util.py
Python
mit
1,810
0.001657
import functools def pack(*args, **kwargs): return (args, kwargs) def merge(target, source, path=None, update=True): # http://stackoverflow.com/questions/7204805/python-dictionar
ies-of-dictionaries-merge path = path or [] for key in source: if key in target: if isinstance(target[key], dict) and isinstance(source[key], dict): merge(target[key], source[key], path + [str(key)]) elif target[key] == source[key]: pass # same le...
nce(target[key], list) and isinstance(source[key], list): for idx, val in enumerate(source[key]): target[key][idx] = merge(target[key][idx], source[key][idx], path + [str(key), str(idx)], update=update) elif update: target[key] = source[key] el...
atareao/cameras
src/webcam.py
Python
gpl-3.0
3,852
0.000519
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # webcam.py # # This file is part of Cameras # # Copyright (C) 2016 # Lorenzo Carbonell Cerezo <lorenzo.carbonell.cerezo@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publishe...
print("Error: %s" % (err, debug)) self.player.set_state(Gst.State.NULL) self.button.set_label("Start") def on_sync_message(self
, bus, message): struct = message.get_structure() if not struct: return message_name = struct.get_name() if message_name == "prepare-window-handle": # Assign the viewport imagesink = message.src imagesink.set_property("force-aspect-ratio", ...
jojoriveraa/titulacion-NFCOW
NFCow/categories/models.py
Python
apache-2.0
170
0.052941
from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_
length = 255) def _
_str__(self): return self.name
ahmadiga/min_edx
common/djangoapps/request_cache/tests.py
Python
agpl-3.0
602
0.001661
""" Tests for the request cache. """ from django.conf import settings from django.test import TestCase from request_cache imp
ort get_request_or_stub
class TestRequestCache(TestCase): """ Tests for the request cache. """ def test_get_request_or_stub(self): # Outside the context of the request, we should still get a request # that allows us to build an absolute URI. stub = get_request_or_stub() expected_url = "http://...
shopkeep/shpkpr
shpkpr/deployment/standard.py
Python
mit
1,338
0.001495
# stdlib imports import logging logger = logging.getLogger(__name__) class StandardDeployment(object): """StandardDeployment implements Marathon's basic deployment workflow and uses the primitives provided by the Marathon API to perform a standard rolling deploy according to application settings. T...
deployment. """ app_ids = ", ".join([a["id"] for a in self.app_definitions]) logger.info("Executing standard deployment: {0}".format(app_ids)) deployment = self.marathon_client.deploy( self.app_definitions, force=force, ) logger.info("Waiting for...
=self.timeout) logger.info("Marathon deployment complete: {0}".format(deployment.deployment_id)) return result
CTSRD-SOAAP/chromium-42.0.2311.135
v8/PRESUBMIT.py
Python
bsd-3-clause
10,311
0.008244
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
romium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl. """ import sys _EXCLUDED_PATHS = ( r"^test[\\\/].*", r"^testing[\\\/].*", r"^third_party[\\\/].*", r"^tools[\\\/].*", ) # Regular expression that matches code only used for test binar...
r'.+-unittest\.cc', # Has a method VisitForTest(). r'src[\\\/]compiler[\\\/]ast-graph-builder\.cc', # Test extension. r'src[\\\/]extensions[\\\/]gc-extension\.cc', ) _TEST_ONLY_WARNING = ( 'You might be calling functions intended only for testing from\n' 'production code. It is OK to ignor...
tylertian/Openstack
openstack F/nova/nova/api/openstack/compute/contrib/disk_config.py
Python
apache-2.0
6,719
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack 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 # ...
resp_obj = (yield) self._show(req, resp_obj) @wsgi.extends(action='resize') def _action_resize(self, req, id, body): context = req.environ['nova.context'] if authorize(context): self._set_disk_config(body['resize']) yield class Disk_config(extensions.Ex...
ace = XMLNS_DCF updated = "2011-09-27T00:00:00+00:00" def get_controller_extensions(self): servers_extension = extensions.ControllerExtension( self, 'servers', ServerDiskConfigController()) images_extension = extensions.ControllerExtension( self, 'images', Image...
simonz05/django-notice
notice/views.py
Python
bsd-3-clause
1,542
0.003243
try: import uwsgi except ImportError: pass # raise ImportError('uWSGI is required to run this package') from django.contrib.auth.decorators import login_required, user_passes_test from django.http import HttpResponse from django.template import RequestContext from django.utils.functional import Promise from...
user = request.user add_notice(user, notice) return HttpResponse( JSONEncoder().encode({'valid': True}), mimetype='application/json') @login_required @condition(etag_func=None) def get(request): data = notice_listener(request.user, {}) resp = HttpResponse(data, mimetype='app
lication/json') resp['Transfer-Encoding'] = 'chunked' return resp def notice_listener(user, context, interval=1): while True: notices = get_notices(user) if notices: yield JSONEncoder().encode({'notices': notices}) raise StopIteration() yield '' uwsg...
josiah-wolf-oberholtzer/supriya
dev/etc/pending_ugens/Timer.py
Python
mit
2,231
0.003138
import collections from supriya.enums import CalculationRate from supriya.synthdefs import UGen class Timer(UGen): """ :: >>> timer = supriya.ugens.Timer.ar( ... trigger=0, ... ) >>> timer Timer.ar() """ ### CLASS VARIABLES ### _ordered_input_na...
@classmethod def kr( cls, trigger=0, ): """ Constructs a control-rate Timer. :: >>> timer = supriya.ugens.Timer.kr( ... trigger=0, ... ) >>> timer Timer.kr() Returns ugen graph. ...
priya.synthdefs calculation_rate = supriya.CalculationRate.CONTROL ugen = cls._new_expanded( calculation_rate=calculation_rate, trigger=trigger, ) return ugen ### PUBLIC PROPERTIES ### @property def trigger(self): """ Gets `trigge...
1egoman/quail
plugins/places/pigeon.py
Python
mit
3,689
0.013554
from base import * import urllib2, json # categorized tags TYPES = [ ["restaurant", "food", "bar", "night_club", "lodging", "meal_delivery", "meal_takeaway", "cafe", \ "grocery_or_supermarket", "bakery"], ["airport", "taxi_stand", "train_station", "taxi", "plane", "train", "transport", "subway_station", "bus_st...
pos_lat, pos_long = l["latitude"], l["longitude"] # test query qry = urllib2.urlopen( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=%s&location=%s,%s&sensor=true&radius=5000" % ( key, pos_
lat, pos_long )) data = json.loads( qry.read() ) # now, get all the places from the data places = [] for p in data["results"]: place = {} # filter out whats not open if (p.has_key("opening_hours") and p["opening_hours"]["open_now"]) or not p.has_key("opening_hours"): place["n...
yichiuan/Moedict-Android
moe-converter/tasks.py
Python
apache-2.0
2,907
0.002408
# -*- coding: utf-8 -*- import platform import os import subprocess import multiprocessing from multiprocessing.pool import ThreadPool import collections import shutil from invoke import task MAX_WORKER_NUM = 4 @task def check_flatc(cxt): path = shutil.which("flatc") if path is None: print("Not foun...
{output_path}".split() # print(cmd) thread_pool.apply_async(work, (cmd,)) thread_pool.close() thread_pool.join() def get_converter(): converter_path = os.path.join('bin', 'x86_64-linux-gnu') # if 'Linux' in platform.system(): # if '64bit' in platform.architecture(): # ...
th.join('bin', 'linux-x86_64') return os.path.join(converter_path, 'moe-converter') def get_worker_num(): return MAX_WORKER_NUM if multiprocessing.cpu_count() > MAX_WORKER_NUM \ else multiprocessing.cpu_count() - 1
zstars/weblabdeusto
server/launch/sample/main_machine/main_instance/experiment_romie_labpsico/server_config.py
Python
bsd-2-clause
24,328
0.002374
# -*- coding: utf-8 -*- import os romie_sqlite = os.path.join(CURRENT_PATH, "romie_labpsico.db") romie_table = 'users' romie_time = 194.159 # 3 minutes, 14.159 seconds romie_server = 'http://192.168.0.190:8000/' romie_labpsico = True romie_demo = False questions = [ [ # 0 difficulty { "questio...
'Formato de audio digital comprimido', 'Un formato de imagen' ], "corre
ct": 1, "points": 51240, "time": 25 }, { "question": 'El número pi(π) fue encontrado por', "answers": [ 'la civilización occidental', 'varias civilizaciones simultáneamente más o menos (griega, china, india...)', ...
kennethreitz/pipenv
pipenv/vendor/vistir/_winconsole.py
Python
mit
15,863
0.001009
# -*- coding: utf-8 -*- # This Module is taken in part from the click project and expanded # see https://github.com/pallets/click/blob/6cafd32/click/_winconsole.py # Copyright © 2014 by the Pallets team. # Some rights reserved. # Redistribution and use in source and binary forms of the software as well as # document...
size_p), ("strides", c_ssize_p), ("suboffsets", c_ssize_p), ("internal", c_void_
p), ] if PY2: _fields_.insert(-1, ("smalltable", c_ssize_t * 2)) # XXX: This was added for the use of cursors class CONSOLE_CURSOR_INFO(Structure): _fields_ = [("dwSize", ctypes.c_int), ("bVisible", ctypes.c_int)] # On PyPy we cannot get buffers so our ability to operate here is # serverly limi...
googleapis/python-aiplatform
samples/generated_samples/aiplatform_v1beta1_generated_tensorboard_service_batch_create_tensorboard_runs_sync.py
Python
apache-2.0
1,839
0.001631
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
reate_tensorboard_runs(): # Create a client client = aiplatform_v1beta1.TensorboardServiceClient() # Initialize request argument(s) requests = aiplatform_v1be
ta1.CreateTensorboardRunRequest() requests.parent = "parent_value" requests.tensorboard_run.display_name = "display_name_value" requests.tensorboard_run_id = "tensorboard_run_id_value" request = aiplatform_v1beta1.BatchCreateTensorboardRunsRequest( parent="parent_value", requests=reques...
westphahl/verleihsystem
doc/code/server_accounts_models.py
Python
isc
492
0.00813
class UserProfile(models.Model): user = mod
els.ForeignKey(User, unique=True) student_number = models.PositiveIntegerField(blank=True, null=True, verbose_name=_("Student number")) phone = models.CharField(blank=True, max_length=100, verbose_name=_("Phone")) mobile_phone = models.CharField(blank=True, max_length=100, ve
rbose_name=_("Mobile phone")) picture = models.ImageField(blank=True, upload_to=get_photo_path, verbose_name=_("Photo"))
truki/logopedasur
pacientes/migrations/0002_auto_20161121_1522.py
Python
gpl-3.0
390
0
# -*- coding: utf-8 -*- # Generated by Djang
o 1.10.3 on 2016-11-21 15:22 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pacientes', '0001_initial'), ] opera
tions = [ migrations.RenameModel( old_name='Peciente', new_name='Paciente', ), ]
tanghaibao/goatools
tests/test_compare_gos.py
Python
bsd-2-clause
1,038
0.00289
#!/usr/bin/env python """Test CompareGOsCli""" import os from goatools.cli.compare_gos import CompareGOsCli __copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang, All rights reserved." REPO = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../") def test_example(): """Test CompareGOsCli""...
.tab'] kws = { 'GO_FILE': [os.path.join(REPO, 'data/compare_gos', f) for f in files], 'obo': os.path.join(REPO, 'go-basic.obo'), 'slims': os.path.join(REPO, 'goslim_generi
c.obo'), 'sections': os.path.join(REPO, 'data/compare_gos/sections.txt'), } obj = CompareGOsCli(**kws) obj.write(fout_xlsx='compare_gos_v1.xlsx', fout_txt='compare_gos_v1.txt', verbose=True) obj.write(fout_xlsx='compare_gos_v0.xlsx', fout_txt='compare_gos_v0.txt', verbose=False) if __name__ ==...
netz98/n98-magerun-doc
docs/languages/en/conf.py
Python
mit
8,208
0.007675
# -*- coding: utf-8 -*- # # n98-magerun Documentation documentation build configuration file, created by # sphinx-quickstart on Sun Oct 13 14:28:54 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 # autogener...
go.png" # For "manual" documents, if this is true, then toplevel headi
ngs are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module in...
ngageoint/scale
scale/job/configuration/data/job_data.py
Python
apache-2.0
35,293
0.002947
"""Defines the data needed for executing a job""" from __future__ import unicode_literals import logging import os from numbers import Integral from job.configuration.data.data_file import DATA_FILE_PARSE_SAVER, DATA_FILE_STORE from job.configuration.data.exceptions import InvalidData from job.configuration.results.j...
in Scale, and details need
ed to store all resulting output. """ def __init__(self, data=None): """Creates a job data object from the given dictionary. The general format is checked for correctness, but the actual input and output details are not checked for correctness against the job interface. If the data is i...
open-craft/opencraft
pr_watch/tests/test_api.py
Python
agpl-3.0
11,845
0.003799
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015-2019 OpenCraft <contact@opencraft.com> # # This program 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 Fre...
r = make_watched_pr_and_instance(branch_name='api-test-branch') response = self.api_client.get('/api/v1/pr_watch/') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, []) response = self.api_client.get('/api/v1/pr_watch/{pk}/'.format(pk=watched_p...
f.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) response = self.api_client.post('/api/v1/pr_watch/{pk}/update_instance/'.format(pk=watched_pr.pk)) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) @patch('pr_watch.github.get_pr_by_number') @ddt.data('user3', 'use...
flacjacket/sympy
sympy/solvers/ode.py
Python
bsd-3-clause
125,328
0.002338
""" This module contains dsolve() and different helper functions that it uses. dsolve() solves ordinary differential equations. See the docstring on the various functions for their uses. Note that partial differential equations support is in pde.py. Note that ode_hint() functions have docstrings describing their vari...
with other methods that can potentially solve the same ODEs. Then, put your hints in the allhints tuple in the order that they should be called. The ordering of this tuple determines which hints are default. Note that exceptions are ok, because it is easy for the user to choose individual hints with dsolve(). In gene...
uld go before the various hints they apply to. For example, the "undetermined_coefficients" hint comes before the "variation_of_parameters" hint because, even though variation of parameters is more general than undetermined coefficients, undetermined coefficients generally returns cleaner results for the ODEs that it ...
Vagab0nd/SiCKRAGE
lib3/timeago/locales/nb_NO.py
Python
gpl-3.0
665
0.003049
#!/usr/bin/env python # -*- cod
ing: utf-8 -*- ''' Created on 2017-8-30 @author: generated by @lolobosse script ''' LOCALE = [ ["akkurat nå", "om litt"], ["%s sekunder siden", "om %s sekunder"], ["1 minutt siden", "om 1 minutt"], ["%s minutter siden", "om %s minutter"], ["1 time siden", "om 1 time"], ["%s timer siden", "om %s...
"], ["1 måned siden", "om 1 måned"], ["%s måneder siden", "om %s måneder"], ["1 år siden", "om 1 år"], ["%s år siden", "om %s år"] ]
ellmetha/django-machina
machina/apps/forum_permission/handler.py
Python
bsd-3-clause
16,447
0.004256
""" Forum permission handler ======================== This module defines a ``PermissionHandler`` abstraction that allows to implement filter or access logic related to forums. """ import datetime as dt from functools import reduce from django.db import models from django.utils.timezone import now f...
user: return forums # Fetches the forums that can be read by the given user. readable_forums = self._get_forums_for_user( user, ['can_
read_forum', ], use_tree_hierarchy=True) return forums.filter(id__in=[f.id for f in readable_forums]) \ if isinstance(forums, (models.Manager, models.QuerySet)) \ else list(filter(lambda f: f in readable_forums, forums)) # Verification methods # -- # Forums def can_rea...
waseem18/oh-mainline
vendor/packages/sphinx/sphinx/environment.py
Python
agpl-3.0
70,053
0.000528
# -*- coding: utf-8 -*- """ sphinx.environment ~~~~~~~~~~~~~~~~~~ Global creation environment. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import os import sys import time import types import codecs import imghdr import st...
tils.io import FileInput, NullOutput from docutils.core import Publisher from docutils.utils import Reporter, relative_path, get_source_line from docutils.readers import standalone from docutils.parsers.rst import roles, directives from docutils.parsers.rst.languages import en as english from docutils.parsers.rst.direc...
redWriter from sphinx import addnodes from sphinx.util import url_re, get_matching_docs, docname_join, split_into, \ FilenameUniqDict from sphinx.util.nodes import clean_astext, make_refnode, WarningStream from sphinx.util.osutil import SEP, fs_encoding, find_catalog_files from sphinx.util.matching import compile...
QuanticPotato/vcoq
plugin/file.py
Python
gpl-2.0
4,084
0.029383
from utils import textAppend, textPrepend, textCut, textEditLastChar, error, textCursorPos class File: """ Represents a file (A separated class allow to open several files at a time. The class also holds the whole file content. (The vim buffers only store either the accepted chunks, or the editing statement) """ ...
# We write the compiled buffer, and then the edit buffer for i in xrange(len(self.output) - 1): file.write(self.output[i] + "\n") interline = self.output[-1][:-4] # We don't take the newline-cursor if not self.editNewLine: interline += self.input[0] file.write(inte
rline + "\n") for i in xrange(0 if self.editNewLine else 1, len(self.input)): file.write(self.input[i] + "\n") file.close() except IOError as e: error(str(e)) def open(self, filename): # First, clear the buffers self.initOutputCursor() del self.chunks[:] del self.input[:] try: file = open(...
kovidgoyal/kitty
kitty/rc/focus_tab.py
Python
gpl-3.0
1,267
0.001579
#!/usr/bin/env python # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from typing import TYPE_CHECKING, Optional from .base import ( MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window ) if TYPE_CHECKING: from kitty.cli_st...
ions', args: ArgsType) -> PayloadType: return {'match': opts.match} def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType: f
or tab in self.tabs_for_match_payload(boss, window, payload_get): if tab: boss.set_active_tab(tab) break return None focus_tab = FocusTab()
pavlova-marina/QGIS
python/plugins/processing/algs/lidar/lastools/lasoverlapPro.py
Python
gpl-2.0
4,596
0.002176
# -*- coding: utf-8 -*- """ *************************************************************************** lasoverlapPro.py --------------------- Date : October 2014 Copyright : (C) 2014 by Martin Isenburg Email : martin near rapidlasso point com *************...
eCharacteristics(self): self.name = "lasoverlapPro" self.group = "LAS
tools Production" self.addParametersPointInputFolderGUI() self.addParametersFilesAreFlightlinesGUI() self.addParametersFilter1ReturnClassFlagsGUI() self.addParameter(ParameterNumber(lasoverlapPro.CHECK_STEP, self.tr("size of grid used for overlap check"), 0, None, 2.0)) ...
david-cattermole/assetQC
python/assetQC/api/logger.py
Python
lgpl-3.0
2,078
0.001444
""" Wrapper functions for printing to a log. The log may be the console, or a text file, or the screen. NOTE: Logger does not yet write to a file. """ # TODO: Investigate how we can put loggers into 'AssetInstance' objects, to # collect info
rmation per-instance - rather than some global log that all # methods write into. This technique would allow better capturing of diagnostic # information and sorting of information. import logging as std_logging import logging.config as std_logging_config import assetQC.api.
config as config BASE_LOG_NAME = 'assetqc' # Log levels LEVEL_NOTSET = std_logging.NOTSET # 0 LEVEL_DEBUG = std_logging.DEBUG # 10 LEVEL_INFO = std_logging.INFO # 20 LEVEL_PROGRESS = 25 LEVEL_WARNING = std_logging.WARNING # 30 LEVEL_FAILURE = 35 LEVEL_ERROR = std_logging.ERROR # 40 LEVEL_CRITICAL = std_logging.C...
mattjdelia/citydictionary
main.py
Python
apache-2.0
20,156
0.012359
# -*- coding: utf8 -*-\ import sqlite3 import sys import codecs import csv import io import re import operator from fuzzywuzzy import fuzz from fuzzywuzzy import process from Tkinter import * from Tkinter import Tk import tkMessageBox import tkFileDialog from tkFileDialog import askopenfilename # Set default encoding...
warning
("File not found","Please open a '.sqlite' file from the file menu.") break if c.fetchone()[0] == 0: c.execute('''SELECT EXISTS(SELECT en FROM Glossary WHERE en=?)''', eng) if c.fetchone()[0] == 0: if tkMessageBox.askokcancel("Add term?","Are you sure about ad...
scalyr/scalyr-agent-2
tests/unit/log_processing_test.py
Python
apache-2.0
127,218
0.001273
# Copyright 2014 Scalyr Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
al("stderr", stream) self.assertEqual("P", tags) self.assertEqual("message", msg) def test_valid_line_single(self): line = "2019-04-08T15:18:20.56064743Z stdout F message" ts, stream, tags, msg = parse_cri_lo
g(line) self.assertEqual(1554736700560647430, ts) self.assertEqual("stdout", stream) self.assertEqual("F", tags) self.assertEqual("message", msg) def test_valid_line_partial(self): line = "2019-04-08T15:18:20.56064743Z stdout P message" ts, stream, tags, msg = parse_...
jinankjain/zamboni
apps/market/tests/test_models.py
Python
bsd-3-clause
16,762
0.000119
import datetime from decimal import Decimal from django.utils import translation import mock from nose.tools import eq_, ok_ import amo import amo.tests from addons.models import Addon, AddonUser from constants.payments import PROVIDER_BANGO, PROVIDER_BOKU from market.models import AddonPremium, Price, PriceCurrency...
user=self.user) def purchased(self): return (self.addon.addonpurchase_set .filter(user=self.user, type=amo.CONTRIB_PURCHASE) .exists()) def type(self): return self.addon.addonpurchase_set.get(user=self.user).type class TestContribution(C...
3615', 'base/users'] def test_purchase(self): self.create(amo.CONTRIB_PURCHASE) assert self.purchased() def test_refund(self): self.create(amo.CONTRIB_REFUND) assert not self.purchased() def test_purchase_and_refund(self): self.create(amo.CONTRIB_PURCHASE) ...
hequn8128/flink
flink-python/pyflink/ml/tests/test_pipeline_it_case.py
Python
apache-2.0
7,618
0.001444
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
self.max_sum = 0 self.load_model(table_env) def load_model(self, table_env): """ Train the model to get the max_sum value which is used to predict data. """ table_sink = source_sink_utils.TestRetractSink(["max_sum"], [DataTypes.BIGINT()]) table_env.register_table_s...
blissland/blissflixx
chls/bfch_yts_torrents/__init__.py
Python
gpl-2.0
4,386
0.024396
import chanutils.torrent from chanutils import get_json, movie_title_year from playitem import TorrentPlayItem, PlayItemList _SEARCH_URL = 'https://yts.mx/api/v2/list_movies.json' _FEEDLIST = [ {'title':'Latest', 'url':'https://yts.mx/api/v2/list_movies.json?limit=50'}, {'title':'Highest Rated', 'url':'https://yt...
title':'Mystery', 'url':'https://yts.mx/api/v2/list_movies.json?genre=mystery&sort_by=rating&limit=50'}, {'title':'Romance', 'url':'https://yts.mx/api/v2/list_movies.json?gen
re=romance&sort_by=rating&limit=50'}, {'title':'Sci-Fi', 'url':'https://yts.mx/api/v2/list_movies.json?genre=sci-fi&sort_by=rating&limit=50'}, {'title':'Sport', 'url':'https://yts.mx/api/v2/list_movies.json?genre=sport&sort_by=rating&limit=50'}, {'title':'Thriller', 'url':'https://yts.mx/api/v2/list_movies.json?g...
douglas/shopidown
setup.py
Python
mit
1,547
0
# coding: utf-8 from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ "pip==8.1.2", "future==0.15.2", "wheel==0.29.0", ] test_requirements = [ "pytest==2.9.2",...
IT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming
Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', setup_requires=test_requirements, tests_require=test_requir...
PetePriority/home-assistant
tests/components/sensor/test_tcp.py
Python
apache-2.0
11,094
0
"""The tests for the TCP sensor platform.""" import socket import unittest from copy import copy from uuid import uuid4 from unittest.mock import patch, Mock from tests.common import (get_test_home_assistant, assert_setup_component) from homeassistant.setup import setup_component from homeassistant.components.sensor i...
.tcp.TcpSensor.update') def test_config_invalid_keys(self, mock_update): """Shouldn't store invalid keys in _config.""" config = copy(TEST_CONFIG['sensor']) config.update({ 'a': 'test_a', 'b': 'test_b', 'c': 'test_c' }) sensor = tcp.TcpSens...
th invalid keys plus some extra.""" config = copy(TEST_CONFIG['sensor']) config.update({ 'a': 'test_a', 'b': 'test_b', 'c': 'test_c' }) with assert_setup_component(0, 'sensor'): assert setup_component(self.hass, 'sensor', {'tcp': config}) ...
elizabethgoldman/emerging_hotspots
emerging_hotspot_factor.py
Python
apache-2.0
4,224
0.007339
#make sure to have remapped TCD mosaic(0-31 as NoData, 31-101 as 1) #remap loss 0 values to NoData. Keep all other values #set indir to AOI (country or other AOI) #create geodatabase for results import os import arcpy from arcpy.sa import * import datetime import utilities def emerging_hs_points(country_shapefile, d...
p
rint " adding date" utilities.add_date(temp_points, short_year) # create point feature class or append to existing all_points = utilities.create_append_fc(results_gdb, f, temp_points) # create space time cube #all_points = r'U:\egoldman\scripts\emerging_hotspots\data\results.gdb\UG...
anurag03/integration_tests
sprout/appliances/admin.py
Python
gpl-2.0
7,546
0.001988
# -*- coding: utf-8 -*- from functools import wraps from celery import chain from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.db.models.query import QuerySet from django_object_actions import DjangoObjectActions # Register your models here. from appliances.models import ( ...
.format(round(instanc
e.appliance_load * 100.0, 2)) def provisioning_load(self, instance): return "{0:.2f}%".format(round(instance.provisioning_load * 100.0, 2)) def show_ip_address(self, instance): if instance.ip_address: return "<a href=\"https://{ip}/\" target=\"_blank\">{ip}</a>".format( ...
akumar21NCSU/servo
tests/wpt/harness/wptrunner/executors/base.py
Python
mpl-2.0
10,114
0.001681
# 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/. import hashlib import json import os import traceback import urlparse from abc import ABCMeta, abstractmethod from ..te...
this executor""" if self.runner is not None: return self.runner.logger def setup(self, runner): """Run steps needed before tests can be started e.g. connecting to browser instance :param runner: TestRunner instance that is going to run the tests""" self.runner =...
un_test(self, test): """Run a particular test. :param test: The test to run""" if test.environment != self.last_environment: self.on_environment_change(test.environment) try: result = self.do_test(test) except Exception as e: result = self.re...
dkkline/CanSat14-15
groundstation/parse.py
Python
mit
5,743
0
""" Contains functions and classes used to parse, handle, validate and interpret data received from the CanSat (or Faker). """ from .exceptions import (ParseError, MalformedPacket, InvalidLine, CRCValidationError) from .calculate import (calculate_temp_NTC, calculate_press, calculate_height, ...
"GyrX", "GyrY", "GyrZ", "AccX", "AccY", "AccZ", "MagX", "MagY", "MagZ", "Lat", "Sat"] VALID_PATTERN = re.compile(r"SGCanScience>(\w+:[-.0-9]+\|?)+") def validate_line(line): """ Validates ``line``. """ # if not VALID_PA
TTERN.match(line): # raise MalformedPacket("Got malformed packet: {}".format(line)) return True def handle_key(key): """ Handles ``key``. """ return key def handle_value(value): """ Handles ``value`` by stripping new lines and converting to a float value. """ value = valu...
SogeMood/sogemood-backend
sogemood/model/__init__.py
Python
mit
23
0
__au
thor__ = 'mwerlen'
anthonyndunguwanja/Anthony-Ndungu-bootcamp-17
Day 1/prime_numbers.py
Python
mit
540
0.005556
#Generating prime numbers def prime_number_generator(number):
my_numbers = [] if number in (0, 1): return "Zero or One cannot be prime numbers." if number < 2: return "Prime numbers cannot be less than two." if type(number) != int: return "Only integers are allowed." for x in range(2, number + 1): if x > 1: for y...
my_numbers.append(x) return my_numbers
drmpeg/gr-paint
docs/doxygen/doxyxml/text.py
Python
gpl-3.0
1,255
0.003187
# # Copyright 2010 Free Software Foundation, Inc. # # This file was generated by gr_modtool, a tool from the GNU Radio framework # This file is a part of gr-paint # # SPDX-License-Identifier: GPL-3.0-or-later # # """ Utilities for extracting text from generated classes. """ def is_string(txt): if isinstance(txt, s...
return True except NameError: pass return False
def description(obj): if obj is None: return None return description_bit(obj).strip() def description_bit(obj): if hasattr(obj, 'content'): contents = [description_bit(item) for item in obj.content] result = ''.join(contents) elif hasattr(obj, 'content_'): contents = [de...
hefen1/chromium
tools/telemetry/telemetry/web_perf/metrics/gpu_timeline.py
Python
bsd-3-clause
9,768
0.006654
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import math import sys from telemetry.timeline import model as model_module from telemetry.value import scalar from telemetry.value import...
support thread_duration, convert those to 0. return _CalculateFrameTimes(events_per_frame, lambda event : event.thread_duration or 0) def _GPUFrameTimes(events_per_frame): """Given a list of events per frame, returns a list of GPU frame times.""" # GPU event frames are asynchronous...
_CalculateFrameTimes(events_per_frame, lambda event : event.duration) def TimelineName(name, source_type, value_type): """Constructs the standard name given in the timeline. Args: name: The name of the timeline, for example "total", or "render_compositor". source_type: One o...
yongwen/makahiki
makahiki/apps/widgets/status/users/views.py
Python
mit
856
0.004673
"""handles request for user gchart widget.""" from apps.managers.challenge_mgr import challenge_mgr from apps.widgets.status.models import DailyStatus def supply(request, page_name): """supply view_objects for user status.""" _ = page_name _ = request #todays_users = Profile.objects.filter(last_visit...
ects.filter(short_date__gte=start).order_by('short_date') prior_day_users = 0 for status in daily_status: status.display_date = "%d/%d" % (status.short_date.month, status.short_date.day) status.new_users = status.setup_users - prior_day_users
prior_day_users = status.setup_users return { "daily_status": daily_status, }
seanthegeek/crits
crits/core/management/commands/migrate_dashboard_searches.py
Python
mit
1,865
0.005362
from djang
o.core.management.base import BaseCommand from optparse import make_option from crits.dashboards.dashboard import SavedSearch class Command(BaseCommand): """ Script Class. """ help = 'Creates the default dashboard.' def handle(self, *args, **options): """ Script Execution. ...
"left" in search and search.left > 0: search.col = search.left/multiplier elif search.isDefaultOnDashboard: convert_default_searches(search, "left") if "width" in search: search.sizex = search.width/multiplier elif search.isDefaultOnDashboard: co...
romanchyla/pylucene-trunk
samples/LuceneInAction/lia/tools/SnowballTest.py
Python
apache-2.0
1,290
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 re...
Y KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==================================================================== from unittest import Te
stCase from lucene import SnowballAnalyzer, StringReader, Version from lia.analysis.AnalyzerUtils import AnalyzerUtils class SnowballTest(TestCase): def testEnglish(self): analyzer = SnowballAnalyzer(Version.LUCENE_CURRENT, "English") AnalyzerUtils.assertAnalyzesTo(analyzer, "stemming algorithms...
radical-software/mongrey
mongrey/tests/storage/sql/flask_settings.py
Python
bsd-3-clause
233
0.012876
# -*- coding: utf-8 -*- from dec
ouple import config from mongrey.web.settings import Test as BaseTest class Test(BaseTest): DB_SETTINGS = { 'host': config('MONGRE
Y_DB', 'sqlite:///../mongrey_test.db'), }
pymedusa/Medusa
medusa/notifiers/synoindex.py
Python
gpl-3.0
2,592
0.002315
# coding=utf-8 from __future__ import unicode_literals import logging import os import subprocess from builtins import object from medusa import app from medusa.helper.exceptions import ex from medusa.logger.adapters.style import BraceAdapter log = BraceAdapter(logging.getLogger(__name__)) log.logger.addHandler(log...
cur_path): if app.USE_SYNOINDEX: synoindex_cmd = ['/usr/syno/bin/synoindex', cmd_arg, os.path.abspath(cur_path)] log.debug(u'Executing command {0}', synoindex_cmd) log.debug(u'Absolute path to command: {0}', os.path.abspath(synoindex_cmd[0])) try: ...
out, _ = p.communicate() log.debug(u'Script result: {0}', out) except OSError as e: log.error(u'Unable to run synoindex: {0}', ex(e))
MagicStack/asyncpg
asyncpg/exceptions/__init__.py
Python
apache-2.0
28,694
0
# GENERATED FROM postgresql/src/backend/utils/errcodes.txt # DO NOT MODIFY, use tools/generate_exceptions.py to update from ._base import * # NOQA from . import _base class PostgresWarning(_base.PostgresLogMessage, Warning): sqlstate = '01000' class DynamicResultSetsReturned(PostgresWarning): sqlstate = '...
: sqlstate = '01P01' class NoData(PostgresWarning): sqlstate = '02000' class NoAdditionalDynamicResultSetsReturned(NoData): sqlstate = '02001' class SQLStatementNotYetCompleteError(_base.PostgresError): sqlstate = '03000' class PostgresConnectionError(_base.Pos
tgresError): sqlstate = '08000' class ConnectionDoesNotExistError(PostgresConnectionError): sqlstate = '08003' class ConnectionFailureError(PostgresConnectionError): sqlstate = '08006' class ClientCannotConnectError(PostgresConnectionError): sqlstate = '08001' class ConnectionRejectionError(Post...
rocketgithub/l10n_gt_extra
__init__.py
Python
mit
1,172
0.000856
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2009-2012 Soluciones Tecnologócias Prisma S.A. All Rights Reserved. # José Rodrigo Fernández Menegazzo, Soluciones Tecnologócias Prisma S.A. #
(http://www.solucionesprisma.com) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th
e License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should h...
puttarajubr/commcare-hq
corehq/apps/app_manager/tests/test_xml_parsing.py
Python
bsd-3-clause
713
0.008415
from django.test import SimpleTestCase from corehq.apps.app_manager.models import _parse_xml import os class XMLParsingTest(Sim
pleTestCase): def testUnicodeError(self): """Tests a bug found in Unicode processing of a form""" file_path = os.path.join(os.path.dirname(__file__), "data", "unicode_error_form.xhtml") with open(file_path, "rb") as f: xml_data = f.read() try: _parse_xml(xml_...
code(xml_data)) except: self.fail("Parsing unicode data shouldn't fail!")
msmathers/datasift-python
__init__.py
Python
mit
105
0.009524
from datasift import (
DataSiftUser, DataSiftDefinition, DataSiftStream, DataSift
StreamListener )
elenaod/PythonScrollingShooter
misc.py
Python
gpl-3.0
659
0.007587
# define some constants SIZE = 10 MAX_HEALTH = 10 TIMER = 5 def outside_of_board(x, y): return x < 0 or y < 0 or x >=
SIZE or y >= SIZE def valid(x, y, board): return not outside_of_board(x, y) and board.rows[x][y] == None def get_command_console(): command = input(">:") command = command[0] if command == 'a': return "move_player_left" elif command == 'd': return "move_player_right" ...
_player_up" elif command == 'x': return "move_player_down" if command == 's': return "player_shoot" if command == 'q': return "game_stop"
Gustry/inasafe
safe/metadata/generic_layer_metadata.py
Python
gpl-3.0
3,730
0
# -*- coding: utf-8 -*- """ InaSAFE Disaster risk assessment tool developed by AusAid - **metadata module.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 Sof...
utilities import reading_ancillary_files, prettify_xml class GenericLayerMetadata(BaseMetadata): """ Base clas
s for generic layers such as hazard, exposure and aggregation. This class can be subclassed so you can create only a minimal concrete class that implements only _standard_properties to add specific properties. You can also add a standard XML property that applies to all subclasses here. In both cases d...
erichegt/askbot-devel
askbot/management/commands/send_unanswered_question_reminders.py
Python
gpl-3.0
3,873
0.011361
from django.core.management.base import NoArgsCommand from django.template.loader import get_template from askbot import models from askbot import const from askbot.conf import settings as askbot_settings from django.utils.translation import ungettext from askbot import mail from askbot.utils.classes import ReminderSch...
'questions': final_question_list, 'subject_line': subject_line } template = get_template('email/unanswered_question_reminder.html') body_text = template.render(Context(data))#todo: set lang if DEBUG_THIS_COMMAND:
print "User: %s<br>\nSubject:%s<br>\nText: %s<br>\n" % \ (user.email, subject_line, body_text) else: mail.send_mail( subject_line = subject_line, body_text = body_text, recipient_list = (user.email,) ...
tiexinliu/odoo_addons
smile_base/models/__init__.py
Python
agpl-3.0
1,166
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under th...
################################################## import fetchmail import ir_actions import ir_config_parameter import ir_mail_server import ir_values import mail_mail import models import module import registr
y import sql_db import update
jryans/wavelet-tinyos
compasstest/adc.py
Python
bsd-3-clause
246
0.097561
from simcore import * comm.setADCValue(1,0,1,400) comm.setA
DCValue(2,0,1,380) comm.setADCValue(3,0,1,362) comm.setADCValue(4,0,1,334) comm.setADCValue(5,0,1,412) comm.setADCValue(6,0,1,425) comm.setADCValue(7,0,1,445) comm.se
tADCValue(8,0,1,429)
Pathal/ShadowCraft-Engine
shadowcraft/calcs/__init__.py
Python
lgpl-3.0
31,557
0.004468
import gettext import __builtin__ import math __builtin__._ = gettext.gettext from shadowcraft.core import exceptions from shadowcraft.calcs import armor_mitigation from shadowcraft.objects import class_data from shadowcraft.objects import talents from shadowcraft.objects import procs from shadowcraft.objects.procs i...
et_rppm_proc_rate() * proc.duration / 60)) else: lambd = haste * proc.get_rppm_proc_rate() * proc.duration / 60 e_lambda = math.e ** lambd e_minus_lambda = math.e ** (-1 * lambd) proc.uptime = 1.1307 * (e_lambda - 1) * (1 - ((1 - e_minus_lambda...
mean_proc_time def set_uptime(self, proc, attacks_per_second, crit_rates): if proc.is_real_ppm(): self.set_rppm_uptime(proc) else: procs_per_second = self.get_procs_per_second(proc, attacks_per_second, crit_rates) if proc.icd: proc.uptime = ...
gnarayan/WDmodel
setup.py
Python
gpl-3.0
1,976
0.004049
# -*- coding: utf-8 -*- """ Setup script for the WDmodel package """ import sys impo
rt os import re import glob from setuptools import find_packages, setup dep_file = 'd
ependencies_py36.txt' with open(dep_file,'r') as f: required = f.read().splitlines() dir_path = os.path.dirname(os.path.realpath(__file__)) init_string = open(os.path.join(dir_path, 'WDmodel', '__init__.py')).read() VERS = r"^__version__\s+=\s+[\'\"]([0-9\.]*)[\'\"]$" mo = re.search(VERS, init_string, re.M) __ve...
b3j0f/requester
b3j0f/requester/driver/test/custom.py
Python
mit
12,360
0.000081
#!/usr/bin/env python # -*- coding: utf-8 -*- # -------------------------------------------------------------------- # The MIT License (MIT) # # Copyright (c) 2016 Jonathan Labéjof <jonathan.labejof@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and assoc...
nnotation() def ud(self, a, **kwargs): self_.assertEqual(a, {'>': [2]}) return [{'ud': kwargs}] @DeleteAnnotation() @CreateAnn
otation() def dc(self, a, **kwargs): self_.assertEqual(a, {'>': [2]}) return [{'dc': kwargs}] def test(self, **kwargs): self.kwargs.append(kwargs) return 'test' test = Test() driver = obj2driver(test) ...
ocefpaf/folium
folium/plugins/measure_control.py
Python
mit
1,858
0.001076
# -*- coding: utf-8 -*- from branca.element import MacroElement from folium.elements import JSCSSMixin from folium.utilities import parse_options from jinja2 import Template class MeasureControl(JSCSSMixin, MacroElement): """ Add a measurement widget on the map. Parameters ---------- position: str...
ntrol({{this.get_name()}}); {% endmacro %} """) # noqa default_js = [ ('leaflet_measure_js', 'https://cdn.jsdelivr.net/gh/ljagis/leaflet-measure@2.1.7/dist/leaflet-measure.min.js') ] default_css = [ ('leaflet_measure_css', 'https://cdn.jsdelivr.net/gh/l
jagis/leaflet-measure@2.1.7/dist/leaflet-measure.min.css') ] def __init__(self, position='topright', primary_length_unit='meters', secondary_length_unit='miles', primary_area_unit='sqmeters', secondary_area_unit='acres', **kwargs): super(MeasureControl, self).__init__...
Tithen-Firion/youtube-dl
youtube_dl/version.py
Python
unlicense
68
0
from __future__ import uni
code_literals __version__ = '2017.05.01'
Fokko/incubator-airflow
tests/executors/test_local_executor.py
Python
apache-2.0
3,328
0.000901
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ocal_executor.LocalExecutor.sync') @mock.patch('airflow.executors.base_executor.BaseExecutor.trigger_tasks') @mock.patch('airflow.stats.Stats.gauge') def test_gauge_executor_metrics(self, mock_stats_gauge, mock_trigger_tasks, mock_sync): executor = LocalExecutor() executor.heartbeat() ...
.ANY), mock.call('executor.running_tasks', mock.ANY)] mock_stats_gauge.assert_has_calls(calls) if __name__ == '__main__': unittest.main()
laurentb/weboob
contrib/boobank_indicator/setup.py
Python
lgpl-3.0
856
0.003505
from setuptools import setup from setuptools import find_packages setup(name='boobank_indicator', version='2.1', description='show your bank accounts in your System Tray', long_description='boobank_indicator will show you bank accounts and associated transactions in your system tray. Your bank accoun...
keywords='weboob boobank tray icon', url='http://weboob.org/', license='GNU LGPL 3', author='Bezleputh', author_email='bezleputh@gmail.com', packages=find_packages(), package_data={
'boobank_indicator.data': ['indicator-boobank.png', 'green_light.png', 'red_light.png', 'personal-loan.png'] }, entry_points={ 'console_scripts': ['boobank_indicator = boobank_indicator.boobank_indicator:main'], }, zip_safe=False)