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
Ernestyj/PyStudy
DataScience/python/tools/test/test_example.py
Python
apache-2.0
577
0.003466
# -*- coding: utf-8 -*- import unittest
class TestExample(unittest.TestCase): @classmethod def setUpClass(cls): print("**************************************** setUpClass ****************************************") @classmethod def tearDownClass(cls): print("************************************** tearDownClass *************...
***") def setUp(self): print("****** setUp *******") def tearDown(self): print("***** tearDown *****") def _example(self): print("This is a test example.")
CZ-NIC/knot
tests-extra/tests/modules/onlinesign_rollovers/test.py
Python
gpl-3.0
7,474
0.006422
#!/usr/bin/en
v python3 """ Check of automatic algorithm rollover scenario. """ import collections import os import shutil import datetime import random import subprocess from subprocess im
port check_call from dnstest.utils import * from dnstest.keys import Keymgr from dnstest.test import Test from dnstest.module import ModOnlineSign def pregenerate_key(server, zone, alg): class a_class_with_name: def __init__(self, name): self.name = name server.gen_key(a_class_with_name(...
MSeifert04/astropy
astropy/timeseries/periodograms/lombscargle/tests/test_statistics.py
Python
bsd-3-clause
7,519
0.000532
import numpy as np import pytest from numpy.testing import assert_allclose try: import scipy except ImportError: HAS_SCIPY = False else: HAS_SCIPY = True import astropy.units as u from astropy.timeseries.periodograms.lombscargle import LombScargle from astropy.timeseries.periodograms.lombscargle._statisti...
not use_errs: dy = None fap = np.linspace(0, 1, 11) method = 'bootstrap' method_kwds = METHOD_KWDS['bootstrap'] ls = LombScargle(t, y, dy, normalization=normalization) z = ls.false_alarm_level(fap, maximum_frequency=fmax, method=method, method_kwds=me
thod_kwds) fap_out = ls.false_alarm_probability(z, maximum_frequency=fmax, method=method, method_kwds=method_kwds) # atol = 1 / n_bootstraps assert_allclose(fap, fap_out, atol=0.05) @pytest.mark.parametrize('method', sorted...
ludwiktrammer/tikn
apps/books/migrations/0008_auto_20170821_2100.py
Python
gpl-3.0
534
0.001873
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-21 19:00 from __future__ import unicode_literals from django.db import migrations, models class Migration
(migrations.Migration): dependencies = [ ('books', '0007_auto_20170821_2052'), ]
operations = [ migrations.AlterField( model_name='book', name='slug', field=models.SlugField(help_text='wykorzystywane w adresie strony', max_length=100, unique=True, verbose_name='identyfikator'), ), ]
drix00/pymcxray
pymcxray/FileFormat/Results/Phirhoz.py
Python
apache-2.0
2,697
0.002595
#!/usr/bin/env python """ .. py:currentmodule:: FileFormat.Results.Phirhoz .. moduleauthor:: Hendrix Demers <[email protected]> MCXRay phirhoz result file. """ # Script information for the file. __author__ = "Hendrix Demers ([email protected])" __version__ = "" __date__ = "" __copy...
.setter def intensity(self, intensity): self._parameters[KEY_INTENSITY] = intensity @property def depths_A(self): return self._parameters[KEY_DEPTHS_A] @depths_A.setter def depths_A(self, depths_A): self._parameters[KEY_DEPTHS_A] = depths_A @property def...
f._parameters[KEY_VALUES] = values
adelinesharla/CtrlVET
cadastro/models.py
Python
gpl-3.0
12,567
0.05463
# -*- encoding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.forms import ModelForm from django.views.generic.list import ListView,View import abc import datetime from django.utils import timezone from django.core.validators import RegexValidator from django.core.urlresolve...
class Endereco(AcoesEndereco): def _get_logradouro(self): return self._logradouro def _get_numero(self): return self._numero def _get_bairro(self): return self._bairro def _get_cidade(self): return self._cidade def _get_cep(self): return self._ce
p def _get_uf(self): return self._uf def _set_logradouro(self,logradouro): self._logradouro = logradouro def _set_numero(self,numero): self._numero = numero def _set_bairro(self,bairro): self._bairro = bairro def _set_cidade(self,cidade): self._cidade = cidade def _set_cep(self,cep)...
kartoza/geonode
geonode/qgis_server/migrations/0001_initial.py
Python
gpl-3.0
597
0.00335
# -*- coding: utf-8
-*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('layers', '24_to_26'), ] operations = [ migrations.CreateModel( name='QGISServerLayer', fields=[ ('layer...
, max_length=100, verbose_name=b'Base Layer Path')), ], ), ]
lduarte1991/edx-platform
openedx/core/djangoapps/heartbeat/default_checks.py
Python
agpl-3.0
4,002
0.004248
""" A set of built-in default checks for the platform heartbeat endpoint Other checks should be included in their respective modules/djangoapps """ from datetime import datetime, timedelta from time import sleep, time from django.conf import settings from django.core.cache import cache from django.db import connectio...
EARTBEAT_CELERY_TIMEOUT)) try: task = sample_task.apply_async(expires=expires)
while expires > datetime.now(): if task.ready() and task.result: finished = str(time() - now) return 'celery', True, unicode({'time': finished}) sleep(0.25) return 'celery', False, "expired" except Exception as fail: return 'celery', False,...
zsdonghao/tensorlayer
docker/pypi_list.py
Python
apache-2.0
1,987
0.003523
import argparse import requests import logging import pip._internal if __name__ == "__main__": parser = argparse.ArgumentParser(description='Get the nth version of a given package') parser.add_argument('--package', type=str, required=True, help='The PyPI you want to inspect') parser.add_argument('--nth_l...
("%s" % tmp_versions) versions = list() for el in tmp_versions: if el not in versions: versions.append(el) pos = -1 nth_version = 1 while True: fetched_version = versions[pos] logger.debug("Version: %s" % fetched_version) if nth_version == args.nth_la...
ease or not ("rc" in fetched_version or "a" in fetched_version or "b" in fetched_version): break else: pos -= 1 continue pos -= 1 nth_version += 1 print(fetched_version)
HugoKuo/keystone-essex3
keystone/backends/sqlalchemy/migrate_repo/versions/005_add_tenants_uid.py
Python
apache-2.0
996
0.002008
# pylint: disable=C0103,R0801 import sqlalchemy import migrate meta = sqlalchemy.MetaData() # define the previous state of tenants tenant = {} tenant['id'] = sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True, autoincrement=True) tenant['name'] = sqlalchemy.Column('name', sqlalchemy.String(255)...
tenant_uid, tenants) assert tenants.c.uid is tenant_uid def downgrade(migrate_engine): meta.bind = migrate_engine migrate.drop_column(tenant_uid, tenants)
assert not hasattr(tenants.c, 'uid')
erikjuhani/thefortressheart
cursor.py
Python
gpl-3.0
2,603
0.006915
from pygame import * from key_dict import * ''' The player class ''' class Cursor: def __init__(self, x, y, size): self.x = int(x) self.y = int(y) self.size = size self.speed = 1 self.cooldown = 0 self.block = 0 self.menu_switch = {'Build' : True} se...
level.gold > 0: if tile.passable: level.create_tile(self.x, self.y, self.menu_block[self.block]) elif not self.menu_switch['Build']: if not tile.passable: level.break_tile(self.x, self.y) ...
255, 255, 255), ((self.x + xoff) * self.size, (self.y + yoff) * self.size, self.size, self.size), int(self.size/(self.size/3)))
diplomacy/research
diplomacy_research/models/policy/token_based/v004_language_model/tests/test_model.py
Python
mit
4,186
0.005256
# ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: 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 rest...
orithmSetup.__init__(self, algorithm_ctor, algo_load_args, 'token_based') def get_policy_model(self): """ Returns the PolicyModel """ return PolicyModel def get_policy_builder(self): """ Returns the Policy's BaseDatasetBuilder """ return BaseDatasetBuilder def get_policy_a...
eturn PolicyAdapter def get_policy_load_args(self): """ Returns the policy args """ return load_args() # ----------- Launch Scripts -------------- def launch_a2c(): """ Launches tests for a2c """ test_object = BaseTestClass(A2CAlgo, a2c_args) test_object.run_tests() def launch_ppo(): ...
letsencrypt/letsencrypt
tools/venv.py
Python
apache-2.0
8,641
0.002315
#!/usr/bin/env python3 # Developer virtualenv setup for Certbot client """Aids in creating a developer virtual environment for Certbot. When this module is run as a script, it takes the arguments that should be passed to pip to install the Certbot packages as command line arguments. If no arguments are provided, all C...
ecreasing priority order: * the current Python interpreter * 'pythonX' executable in PATH (with X the given major version) if available * 'python' executable in PATH if available * Windows Python launcher 'py' executable in PATH if available Incompatible python versions for Certbot will be evicted...
ions less than 3.6). :rtype: str :return: the relevant python executable path :raise RuntimeError: if no relevant python executable path could be found """ python_executable_path = None # First try, current python executable if _check_version('{0}.{1}.{2}'.format( sys.version_i...
ging/horizon
openstack_dashboard/enabled/_35_help_about.py
Python
apache-2.0
250
0
# The name of the dashboard to be added to HORIZON['dashboards']. Required. DASHBOARD = 'help_about' DISABLED = Fa
lse # A list of applications to be added to INSTALLED_APPS. ADD_INSTALLED_APPS = [ 'opensta
ck_dashboard.dashboards.help_about', ]
acuriel/nahuatilli
core/urls.py
Python
gpl-3.0
840
0.007143
from django.conf.urls im
port url from core.views.generic import get_dashboard, delete from users.views.individuals import RegisterView from users.views.base import LoginView, logout_user from core.views.display import IndexView urlpatterns = [#url(r'^$', LoginView.as_view(), name='index'),
url(r'^$', IndexView.as_view(), name='index'), url(r'^login$', LoginView.as_view(), name='login'), url(r'^logout$', logout_user, name='logout'), url(r'^register$', RegisterView.as_view(), name='register'), #url(r'^delete/(?...
tweiss1234/Cras
db_actions.py
Python
apache-2.0
5,095
0.005299
from requests import HTTPError from database import Database import simplejson as json db = Database.getDatabaseConnection()["cras"] from log_session import LogSession import datetime class DB: def __init__(self): pass @staticmethod def add_user(user_id, user_name, mail,picture,fcm_token): ...
y exists" return data @staticmethod def get_user_by_ID(user_ID): try: return db[user_ID] except Exception: print "DB exception : User does not exists" return None @staticmethod def add_supervisor(user_i
d, other_id): user = get_user_by_id(user_id) other_user = get_user_by_id(other_id) user["supervised_by"].append(other_id) other_user["supervise"].append(user_id) user.save() other_user.save() @staticmethod def get_user_supervise(user_id): currently_monito...
GCStokum/ECS-Game
ecs-0.1/docs/source/conf.py
Python
mit
8,695
0.00483
# -*- coding: utf-8 -*- # # This file is based upon the file generated by sphinx-quickstart. However, # where sphinx-quickstart hardcodes values in this file that you input, this # file has been changed to pull from your module's metadata module. # # This file is execfile()d with the current directory set to its contai...
ault; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root,
use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) # Import project metadata from ecs import metadata # -- General configuration ---------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphi...
artwr/airflow
airflow/contrib/operators/gcs_operator.py
Python
apache-2.0
5,140
0.000778
# -*- coding: utf-8 -*- # # 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 #...
ample:: The
following Operator would create a new bucket ``test-bucket`` with ``MULTI_REGIONAL`` storage class in ``EU`` region :: CreateBucket = GoogleCloudStorageCreateBucketOperator( task_id='CreateNewBucket', bucket_name='test-bucket', storage_class='MULTI_REGIONAL', ...
dumoulinj/ers
ers_backend/emotion_annotator/serializers.py
Python
mit
267
0.007491
from rest_framework import serializers from emotion_annotator.
models import FrameEmotions class FrameEmotionsSerializer(serializ
ers.HyperlinkedModelSerializer): class Meta: model = FrameEmotions fields = ('video', 'frameTime', 'emotionType')
lbouma/Cyclopath
pyserver/bin/rpy2/rinterface/tests/test_Sexp.py
Python
apache-2.0
4,549
0.005935
import unittest import copy import gc import rpy2.rinterface as rinterface rinterface.initr() class SexpTestCase(unittest.TestCase): def testNew_invalid(self): x = "a" self.assertRaises(ValueError, rinterface.Sexp, x) def testNew(self): sexp = rinterface.baseenv.get("letters") ...
sertEquals("bar", slot[0]) def testSexp_rsame_true(self): sexp_a = rinterface.baseenv.get("letters") sexp_b = rinterface.baseenv.get("letters") self.assertTrue(sexp_a.rsame(sexp_b)) def testSexp_rsame_false(self): sexp_a = rinterface.baseenv.get("letters") sexp_b = rint...
xp_a = rinterface.baseenv.get("letters") self.assertRaises(ValueError, sexp_a.rsame, 'foo') def testSexp_sexp(self): sexp = rinterface.IntSexpVector([1,2,3]) cobj = sexp.__sexp__ sexp = rinterface.IntSexpVector([4,5,6,7]) self.assertEquals(4, len(sexp)) sexp.__sexp__...
kashif/chainer
chainer/functions/array/flatten.py
Python
mit
1,211
0
from chainer import function class Flatten(function.Function): """Flatten function.""" def forward(self, inputs): self.retain_inputs(()) self._in_shape = inputs[0].shape return inputs[0].ravel(), def backward(self, inputs, grads): return grads[0].reshape(self._in_shape),...
into one dimension. Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. Returns: ~chai
ner.Variable: Output variable flatten to one dimension. .. note:: When you input a scalar array (i.e. the shape is ``()``), you can also get the one dimension array whose shape is ``(1,)``. .. admonition:: Example >>> x = np.array([[1, 2], [3, 4]]) >>> x.shape (2, 2) ...
drix00/pymcxray
pymcxray/FileFormat/SimulationParameters.py
Python
apache-2.0
15,335
0.004695
#!/usr/bin/env python """ .. py:currentmodule:: FileFormat.SimulationParameters .. moduleauthor:: Hendrix Demers <[email protected]> MCXRay simulation parameters input file. """ # Script information for the file. __author__ = "Hendrix Demers ([email protected])" __version__ = "" __d...
fromatMethods[
KEY_NUMBER_WINDOWS] = "%i" fromatMethods[KEY_NUMBER_FILMS_X] = "%i" fromatMethods[KEY_NUMBER_FILMS_Y] = "%i" fromatMethods[KEY_NUMBER_FILMS_Z] = "%i" fromatMethods[KEY_NUMBER_CHANNELS] = "%i" fromatMethods[KEY_ENERGY_CHANNEL_WIDTH] = "%s" fromatMethods[KEY_SPECTRA_I...
jolyonb/edx-platform
lms/djangoapps/instructor/tests/test_email.py
Python
agpl-3.0
7,373
0.003119
""" Unit tests for email feature flag in new instructor dashboard. Additionally tests that bulk email is always disabled for non-Mongo backed courses, regardless of email feature flag, and that the view is conditionally available when Course Auth is turned on. """ from __future__ import absolute_import from django.ur...
factories import AdminFactory from xmodule.modulestore.tests.django_utils import TEST_DATA_MIXED_MODULESTORE, SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory class TestNewInstructorDashboardEmailViewMongoBacked(SharedModuleStoreTestCase): """ Check for email view on the...
ongoBacked, cls).setUpClass() cls.course = CourseFactory.create() # URL for instructor dash cls.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(cls.course.id)}) # URL for email view cls.email_link = '<button type="button" class="btn-link send_email" data-sec...
ebigelow/LOTlib
LOTlib/Hypotheses/Lexicon/RecursiveLexicon.py
Python
gpl-3.0
1,491
0.004695
from SimpleLexicon import SimpleLexicon from LOTlib.Evaluation.Evalu
ationException import RecursionDepthException class RecursiveLexicon(SimpleLexicon): """ A lexicon where word meanings can call each other. Analogous to a RecursiveLOTHypothesis from a LOTHypoth
esis. To achieve this, we require the LOThypotheses in self.values to take a "recurse" call that is always passed in by default here on __call__ as the first argument. This throws a RecursionDepthException when it gets too deep. See Examples.EvenOdd """ def __init__(self, recursive_depth_bou...
GuessWhoSamFoo/pandas
pandas/testing.py
Python
bsd-3-clause
158
0
# flake
8: noqa """ Public testing utility fu
nctions. """ from pandas.util.testing import ( assert_frame_equal, assert_index_equal, assert_series_equal)
mozilla/telemetry-analysis-service
atmo/clusters/migrations/0021_rename_cluster_emr_release.py
Python
mpl-2.0
1,083
0.001847
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-03-21 12:36 from __future__ import unicode_literals from django.db import migrations, models impor
t django.db.models.deletion class Migration(migrations.Migration):
dependencies = [("clusters", "0020_emr_release_model")] operations = [ migrations.RenameField( model_name="cluster", old_name="emr_release", new_name="emr_release_version" ), migrations.AddField( model_name="cluster", name="emr_release", f...
ammaritiz/pulp_puppet
pulp_puppet_extensions_consumer/pulp_puppet/extensions/consumer/structure.py
Python
gpl-2.0
635
0
from gett
ext import gettext as _ SECTION_ROOT = 'puppet' DESC_ROOT = _('manage Puppet bindings') def ensure_puppet_root(cli):
""" Verifies that the root of puppet-related commands exists in the CLI, creating it using constants from this module if it does not. :param cli: CLI instance being configured :type cli: pulp.client.extensions.core.PulpCli """ root_section = cli.find_section(SECTION_ROOT) if root_sect...
sb2gh/flask_login_1
app/__init__.py
Python
mit
988
0
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from conf
ig import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) print 'in app __init__.py', config_name, config[con...
onfig_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(au...
josherich/mindynode-parsers
mindynode_nltk/utils/opencc.py
Python
mit
117
0.025641
im
port subprocess def convert_c
hinese(text): return subprocess.getoutput("echo '%s' | opencc -c hk2s.json" % text)
Mohamad1994HD/LinkArchiever
app/createDBTables.py
Python
gpl-3.0
1,118
0.006261
import sqlite3 from config import appConfig def createTBLS(path=None): conn = sqlite3.connect(path) cursor = conn.cursor() cursor.execute("""CREATE TABLE links(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, name TEXT NOT NULL );""") c...
links_id INTEGER NOT NULL, tags_id INTEGER NOT NULL, FOREIGN KEY (links_id) REFERENCES links(id), FOREIGN KEY (tags_id) REFERENCES tags(id)
);""") conn.commit() conn.close() if __name__ == '__main__': try: path = appConfig.db_path print path createTBLS(str(path)) except IOError as e: print (str(e))
simontakite/sysadmin
pythonscripts/thinkpython/CellWorld.py
Python
gpl-2.0
6,080
0.004441
"""This module is part of Swampy, a suite of programs available from allendowney.com/swampy. Copyright 2011 Allen B. Downey Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. """ import math from World import World class CellWorld(World): """Contains cells and animals that move betwe...
self.marked: options = self.marked_options else: options = self.unmarked_options # bounds returns all four corners, so slicing every other # element yields two opposing corners, which is what we # pass to Canvas.rectangle coords = self.bounds[::2] ...
f): """Delete any items with this cell's tag.""" self.item.delete() self.item = None def get_config(self, option): """Gets the configuration of this cell.""" return self.item.cget(option) def config(self, **options): """Configure this cell with the given...
PisiLinux-PyQt5Port/package-manager
src/settingsdialog.py
Python
gpl-2.0
20,739
0.003809
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2010 TUBITAK/UEKAE # # 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) # a...
settings.cacheDirPath.text()) if path.exists(cache_dir): QDesktopServices.openUrl(QUrl("file://%s" % cache_dir, QUrl.TolerantMode)) def selectCacheDir(self): selected_dir = QFileDialog.getExistingDirectory(self.settings, self.tr("Open Directory"), "/",
QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) if not selected_dir == '': if not selected_dir == self.settings.cacheDirPath.text(): self.settings.cacheDirPath.setText(selected_dir) self.markChanged() def clearCache(self): ...
montanier/pandora
bin/joinResults.py
Python
lgpl-3.0
2,368
0.029561
#!/usr/bin/python3 import os, sys, random import argparse # this script processes all the log simulations in one dir, and writes the values of one particular attribute into one single file. def prepareProcess(inputDir,simulationFile, separator, output, attribute ): output = open(output, 'w') simulation = open(inpu...
ut.readline().strip('\n')+separator splittedLine = simulationLine.split(separator) value = splittedLine[attributeIndex] outputTmp.write(previousLine+value+'\n') simulation.close() output.close() outputTmp.close() os.rename('tmp', outputName) def main(): parser = argparse.ArgumentParser() parser.add_arg...
re simulated files are stored') parser.add_argument('-o', '--output', default='results.csv', help='output file') parser.add_argument('-s', '--separator', default=';', help='separator token between values') parser.add_argument('-a', '--attribute', default='Number of agents', help='name of the attribute column to proc...
mF2C/COMPSs
tests/sources/python/8_argument_error/src/args_error.py
Python
apache-2.0
392
0.002551
#!/usr/bin/python # -*- coding: utf-8 -*- """ PyCOMPSs Testbench Arguments Warnings ===================================== """ # Imports import unittest from modules.testArgumentError import testArgumentError def main(): suite = unittest.TestLoader().loadTestsFro
mTestCase(testArgumentError) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == "__ma
in__": main()
amitassaraf/angular2-django-boilerplate
{{cookiecutter.github_repository_name}}/src/{{cookiecutter.app_name}}/config/production.py
Python
mit
3,763
0.000797
import os from configurations import values from boto.s3.connection import OrdinaryCallingFormat from {{cookiecutter.app_name}}.config.common import Common try: # Python 2.x import urlparse except ImportError: # Python 3.x from urllib import parse as urlparse class Production(Common): # Honor th...
AGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = values.Value('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = values.Value('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = values.Value('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_AUTO_CREATE_BUCKE
T = True AWS_QUERYSTRING_AUTH = False MEDIA_URL = 'https://s3.amazonaws.com/{}/'.format(AWS_STORAGE_BUCKET_NAME) AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() # https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#cache-control # Response can be ca...
stackforge/os-ansible-deployment
playbooks/library/git_requirements.py
Python
apache-2.0
10,270
0
#!/usr/bin/python # -*- coding: utf-8 -*- from ansible.module_utils.basic import AnsibleModule import git import itertools import multiprocessing import os import signal import time DOCUMENTATION = """ --- module: git_requirements short_description: Module to run a multithreaded git clone options: repo_info: d...
te or fix it manually" failures.append(failtxt) return False # if repo exists if os.path.exists(role["dest"]): repo = get_repo(role["dest"])
if not repo: return False # go to next role repo_url = list(repo.remote().urls)[0] if repo_url != role["src"]: repo.remote().set_url(role["src"]) # if they want master then fetch, checkout and pull to stay at latest # master if required_version == "m...
krahman/node-java
touch.py
Python
mit
68
0.073529
import
os; f = open('depsVerified', 'w'); f.write('ok'); f.close();
SmartcitySantiagoChile/onlineGPS
beacon/models.py
Python
mit
2,058
0.006317
from django.db import models from django.utils import timezone # Create your models here. def formatDateTime(dateTime): return timezone.localtime(dateTime).strftime("%Y-%m-%d %H:%M:%S") class Beacon(models.Model): macAddr = mode
ls.CharField(max_length=20, unique=True) uuid = models.UUIDField(editable=False) major = models.CharField(max_length=10, null=False) minor = models.CharField(max_length=10, null=False) def getDict(self): dict = {} dict['macAddr'] = self.macAddr dict['uuid'] = str(self.uui...
dict class Meta: unique_together = ('uuid', 'major', 'minor') class DetectorDevice(models.Model): """ device which detects beacons, now only cellphones """ externalId = models.CharField(max_length=32, unique=True) def getDict(self): dict = {} dict['deviceId'] = self.external...
kinoreel/kino-gather
processes/insert_movies.py
Python
mit
3,618
0.003317
import json import os from processes.postgres import Postgres from processes.gather_exception import GatherException try: DB_SERVER = os.environ['DB_SERVER'] DB_PORT = os.environ['DB_PORT'] DB_DATABASE = os.environ['DB_DATABASE'] DB_USER = os.environ['DB_USER'] DB_PASSWORD = os.environ['DB_PASSW...
id varchar(15), title varchar(1000), runtime integer , release_date date, plot varchar(4000), original_language varchar(1000)) on x.imdb_id = y.imdb_id join kino.iso2language z on y.original_la
nguage = z.iso3166 """ self.pg.pg_cur.execute(sql, (json.dumps(omdb_movie_data), json.dumps(tmdb_movie_data))) if self.pg.pg_cur.rowcount != 1: raise GatherException(omdb_movie_data[0]['imdb_id'], 'No insert into movies, most likely due to a new language') self.pg.pg_co...
damienjones/sculpt-model-tools
setup.py
Python
lgpl-2.1
1,198
0.022538
"""A modest set of tools to work with
Django models.""" # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file # with open(path.join(here, 'DES...
del_tools', version='0.1', description='A modest set of tools to work with Django models.', long_description='', url='https://github.com/damienjones/sculpt-model-tools', author='Damien M. Jones', author_email='[email protected]', license='LGPLv2', classifiers=[ 'Development Status :: 3 - Alpha...
Jumpscale/jumpscale_core8
apps/agentcontroller/jumpscripts/jumpscale/network_info.py
Python
apache-2.0
312
0.003205
from JumpScale import j descr = """ Thi
s jumpscript returns network info """ c
ategory = "monitoring" organization = "jumpscale" author = "[email protected]" license = "bsd" version = "1.0" roles = [] def action(): return j.sal.nettools.getNetworkInfo() if __name__ == "__main__": print(action())
muhkuh-sys/org.muhkuh.tools-flasher
jonchki/dulwich/pack.py
Python
gpl-2.0
68,723
0.000029
# pack.py -- For dealing with packed git objects. # Copyright (C) 2007 James Westby <[email protected]> # Copyright (C) 2008-2013 Jelmer Vernooij <[email protected]> # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; ...
: E402 from dulwich.lru_cache import ( # noqa: E402 LRUSizeCache, ) from dulwich.objects import ( # noqa: E402 ShaFile, hex_to_sha, sha_to_hex, object_header, ) OFS_DELTA = 6 REF_DELTA = 7 DELTA_TYPES = (OFS_DELTA, REF_DELTA) DEFAULT_PACK_DELTA_WINDOW_SIZE =
10 def take_msb_bytes(read, crc32=None): """Read bytes marked with most significant bit. :param read: Read function """ ret = [] while len(ret) == 0 or ret[-1] & 0x80: b = read(1) if crc32 is not None: crc32 = binascii.crc32(b, crc32) ret.append(ord(b[:1])) ...
SCECcode/BBP
bbp/comps/bbtoolbox_cfg.py
Python
apache-2.0
5,200
0.000769
#!/usr/bin/env python """ Copyright 2010-2018 University Of Southern California Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by appli...
buted 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. This module defines the configuration parameters for the BBToolbox script """ from __future__ impor
t division, print_function # Import Python modules import os import sys # Import Broadband modules import cc import bband_utils class BBToolboxCfg(object): """ Define the configuration parameters for the SDSU BBToolbox program """ cfgdict = {} def getval(self, attr): try: val...
zouppen/simulavr
regress/test_opcodes/test_LD_X_decr.py
Python
gpl-2.0
3,080
0.017857
#! /usr/bin/env python ############################################################################### # # simulavr - A simulator for the Atmel AVR family of microcontrollers. # Copyright (C) 2001, 2002 Theodore A. Roth # # This program is free software; you can redistribute it and/or modify # it under the terms of th...
= got: self.fail('LD_X_decr X not decr: expect=%04x, got=%04x' % (expect, got)) # # Template code for test case. # The fail method will raise a test specific exception. # template = """ class LD_X_decr_r%02d_X%04x_v%02x_TestFail(LD_X_decr_TestFail): pass class test_LD_X_decr_r%02d_X%04x_v%02x(base_LD_X_decr): Rd ...
defined for d = 26 and d = 27. # code = '' for d in range(0,26)+range(28,32): for x in (0x10f, 0x1ff): for v in (0xaa, 0x55): args = (d,x,v)*4 code += template % args exec code
kernsuite-debian/lofar
CEP/Pipeline/recipes/sip/master/imager_finalize.py
Python
gpl-3.0
7,155
0.004612
import sys import lofarpipe.support.lofaringredient as ingredient from lofarpipe.support.baserecipe import BaseRecipe from lofarpipe.support.remotecommand import RemoteCommandRecipeMixIn from lofarpipe.support.remotecommand import ComputeJob from lofarpipe.support.data_map import DataMap, validate_data_maps, \ ...
ing placed hdf5 imag
es: {0}".format( self.inputs['placed_image_mapfile'])) self.outputs["placed_image_mapfile"] = self.inputs[ 'placed_image_mapfile'] return 0 if __name__ == '__main__': sys.exit(imager_finalize().main())
Outernet-Project/librarian
librarian/core/utils/iterables.py
Python
gpl-3.0
2,296
0
""" Functions and decorators for making sure the parameters they work on are of iterable types. Copyright 2014-2015, Outernet Inc. Some rights reserved. This software is free software licensed under the terms of GPLv3. See COPYING file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt. """ impor...
j): """ Det
ermine if the passed in object is a string. """ try: return isinstance(obj, basestring) except NameError: return isinstance(obj, str) def is_iterable(obj): """ Determine if the passed in object is an iterable, but not a string or dict. """ return (hasattr(obj, '__iter__') a...
yasar11732/arch-package-quiz
packagequiz/questionGenerator.py
Python
gpl-3.0
4,801
0.005626
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright 2011 Yaşar Arabacı This file is part of packagequiz. packagequiz 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 y...
0: correct_answer_name = choice(question.correctAnswer) correct_answer_package = localdb.get_pkg(correct_answer_name) correct_answer = correct_answer_name + "(" + correct_answer_package.desc + ")" else: return None wrong_answers = [] while len(wrong_answers) < n...
pkg = getRandomPackage([pkg for pkg in question.correctAnswer]) answer = pkg.name + "(" + pkg.desc + ")" if answer not in wrong_answers and answer is not None: wrong_answers.append(answer) return (question.text, correct_answer, wrong_answers,question.points) #@qgenerator #def _...
tiagocoutinho/bliss
bliss/common/shutter.py
Python
lgpl-3.0
10,215
0.004307
# -*- coding: utf-8 -*- # # This file is part of the bliss project # # Copyright (c) 2017 Beamline Control Unit, ESRF # Distributed under the GNU LGPLv3. See LICENSE for more info. import functools from gevent import lock from bliss.config.conductor.client import Lock from bliss.config.channels import Cache from bli...
value = True except: self._init_flag = False raise def _init(self): """ This method should contains all software initialization like comm
unication, internal state... """ raise NotImplementedError def _initialize_hardware(self): """ This method should contains all commands needed to initialize the hardware. It's will be call only once (by the first client). """ pass @property d...
chromium/chromium
third_party/android_deps/libs/io_github_java_diff_utils_java_diff_utils/3pp/fetch.py
Python
bsd-3-clause
2,503
0
#!/usr/bin/env python3 # Copyright 2021 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. # This is generated, do not edit. Update BuildConfigGenerator.groovy and # 3ppFetch.template instead. import argparse import json imp...
e). latest = re.findall('<version>([^<]+)</version>', metadata)[-1] print(latest + f'.{_PATCH_VERSION}') def get_download_url(version): # Remove the patch version when getting the download url version_no_patch, patch = version.rsplit('.', 1) if patch.startswith('cr'): v
ersion = version_no_patch file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, _MODULE_NAME, version, _FILE_EXT) file_name = file_url.rsplit('/', 1)[-1] partial_manifest = { 'u...
duoduo369/django-scaffold
myauth/models.py
Python
mit
1,991
0.00387
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils.translation import ugettext as _ class UserProfile(models.Model): ''' ...
=User) def post_save_user_ha
ndler(sender, instance, created, **kwargs): try: profile = instance.profile except UserProfile.DoesNotExist: profile = UserProfile(user=instance) profile.save() @receiver(pre_save, sender=UserProfile) def pre_save_userprofile_handler(sender, instance, **kwargs): ''' 保存profile前,如果用户名...
OpenBCI/OpenBCI_Python
scripts/test.py
Python
mit
937
0.004269
from __future__ import pr
int_function import sys sys.path.append('..') # help python find cyton.py relative to scripts folder from openbci import cyton as bci import logging import time def printData(sample): # os.system('clear') print("------------
----") print("%f" % (sample.id)) print(sample.channel_data) print(sample.aux_data) print("----------------") if __name__ == '__main__': # port = '/dev/tty.OpenBCI-DN008VTF' port = '/dev/tty.usbserial-DB00JAM0' # port = '/dev/tty.OpenBCI-DN0096XA' baud = 115200 logging.basicConfig(f...
diegoberaldin/PyRequirementManager
src/controller/printers.py
Python
gpl-3.0
4,793
0.000417
from src import model as mdl class LaTeXPrinter(object): def __init__(self, target_file_path): self._target_file_path = target_file_path def run(self): with open(self._target_file_path, 'w') as output: text = self._generate_text() output.write(text) def _generate...
= mdl.dal.get_all_requirement_ids_spec( req_type, priority) def _get_table_definition(self): return '\\begin{longtable}{lp{.5\\textwidth}ll}\n' def _get_headers(self): return ('\\sffamily\\bfseries ID & \\sffamily\\bfseries Descrizione & ' '\\sffamily\\bfse...
family\\bfseries Padre\\\\\n') def _get_content(self): for req_id in self._req_id_list: req = mdl.dal.get_requirement(req_id) source = mdl.dal.get_source(req.source_id) yield (req.req_id, req.description, source.name, req.parent_id or '--') def _g...
praus/shapy
tests/emulation/test_shaping.py
Python
mit
3,245
0.010478
#import logging #logging.basicConfig(level=logging.INFO, datefmt='%H:%M:%S', # format='%(asctime)s %(levelname)s: %(message)s') import unittest import SocketServer, socket import random, time import threading import cStringIO from datetime import datetime from shapy import register_settings registe...
ver_addr = ('127.0.0.2', 55000) self.client_addr = ('127.0.0.3', 55001) # shaping init ShaperMixin.setUp(self) ServerMixin.run_server(self) with open('/dev/urandom', 'rb') as f: self.randomfile = bytearray(f.read(self.files
ize)) def test_transfer(self): self.sock_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SO_REUSEADDR: http://stackoverflow.com/questions/3229860/what-is-the-meaning-of-so-reuseaddr-setsockopt-option-linux s = self.sock_client s.setsockopt(socket.SOL_SOCKET, so...
luispedro/jug
jug/tests/test_store.py
Python
mit
3,891
0.003084
import os import jug.backends.redis_store import jug.backends.file_store import jug.backends.dict_store from jug.backends.redis_store import redis import pytest if not os.getenv('TEST_REDIS'): redis = None try: redisConnectionError = redis.ConnectionError except: redisConnectionError = SystemError @pytes...
assert lock1.get() assert not lock2.get() assert not lock1.is_failed() assert not lock2.is_failed() lock1.fail() assert lock2.is_failed() assert len(list(store.listlocks())) == 1 store.remove_locks() assert not lock1.is_failed() assert not lock2.is_failed() assert len(list(sto...
test_numpy_array(tmpdir): try: import numpy as np except ImportError: pytest.skip() store = jug.backends.file_store.file_store(str(tmpdir)) arr = np.arange(100) % 17 arr = arr.reshape((10,10)) key = 'mykey' store.dump(arr, key) arr2 = store.load(key) assert np.all(ar...
WeCase/WeCase
utils/depgraph.py
Python
gpl-3.0
898
0.004454
#!/usr/bin/python3 import sys def process_import(filename, statement): statement = statement.replace(",", " ")
modules = statement.split() for module in modules[1:]: print('"%s" -> "%s"' % (filename, module)) def process_from(filename, statement): statement = statement.replace(",", " ") modules = statement.split() main_module = modules[1] for module in
modules[3:]: print('"%s" -> "%s" -> "%s"' % (filename, main_module, module)) def print_header(): print("digraph WeCase {") print("ratio=2") def print_footer(): print("}") print_header() for line in sys.stdin: line = line.replace("\n", "") if line.endswith(".py"): filename = line ...
Suor/flaws
astpp.py
Python
bsd-2-clause
2,283
0.001752
""" A pretty-printing dump function for the ast module. The code was copied fro
m the ast.dump function and modified slightly to pretty-print. Alex Leone (acleone ~AT~ gmail.com), 2010-01-30 """ from ast import * def dump(node, annotate_fields=True, include_attributes=False, indent=' '): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purpose...
nd the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. """ def _format(no...
TomAugspurger/pandas
pandas/core/arrays/sparse/__init__.py
Python
bsd-3-clause
273
0.003663
# flake8: noqa: F401 from pandas.core.arrays.sparse.accessor import SparseAccessor, SparseFrameAccessor from pandas.core.arrays.sparse.array import ( BlockIndex, IntInde
x, SparseArray
, _make_index, ) from pandas.core.arrays.sparse.dtype import SparseDtype
DexterLB/stard
src/stard/test_samples/father.py
Python
mit
144
0.006944
fro
m stard.services import BaseService class Service(BaseService): def init_service(self): self.children = {self.service('child')}
amaozhao/basecms
cms/forms/widgets.py
Python
mit
10,371
0.004339
# -*- coding: utf-8 -*- from itertools import chain from django.contrib.sites.models import Site from django.core.urlresolvers import NoReverseMatch, reverse_lazy from django.forms.widgets import Select, MultiWidget, TextInput from django.utils.encoding import force_text from django.utils.safestring import mark_safe ...
item.path + ')'} } ) }; } }, // Allow creation of new entries createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {re...
tion : function (element, callback) { var initialValue = element.val() callback({id:initialValue, text: initialValue}); } }); }) })(django.jQuery); </script>''' % { 'element_id': id_, 'placeholder_text': final_attrs.get('placeholder_text', ...
timorieber/wagtail
wagtail/admin/rich_text/editors/draftail/features.py
Python
bsd-3-clause
2,173
0.001381
from django.forms import Media from wagtail.admin.staticfiles import versioned_static # Feature objects: these are mapped to feature identifiers within the rich text # feature registry (wagtail.core.rich_text.features). Each one implements # a `construct_options` method which modifies an options dict as appropriate t...
A feature which is enabled by a boolean flag at the
top level of the options dict """ def __init__(self, option_name, **kwargs): super().__init__(**kwargs) self.option_name = option_name def construct_options(self, options): options[self.option_name] = True class ListFeature(Feature): """ Abstract class for features th...
zhongql/summer
tool/initdb.py
Python
mit
448
0.002232
from contextlib import closing from flask import current_app from summer.app import create_app from summer.db.connect import connect_db def init_db():
app = create_app('product') _context = app.app_context() _context.push() with closing(connect_db()) as db: with open('./sum
mer/schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() if __name__ == '__main__': init_db()
joshrule/LOTlib
LOTlib/Projects/NumberGame/__init__.py
Python
gpl-3.0
21
0
from Model impor
t *
idjaw/netman
netman/api/api_utils.py
Python
apache-2.0
3,822
0.00157
# Copyright 2015 Internap. # # 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...
governing permissions and # limitations under the License. from functools import wraps import json import logging from flask import make_response, request, Response, current_app from werkzeug.routing import BaseConverter from netman.api import NETMAN_API_VERSION from netman.core.objects.exceptions import UnknownReso...
krafczyk/spack
var/spack/repos/builtin/packages/bwtool/package.py
Python
lgpl-2.1
1,568
0.000638
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
e Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-130...
ethan-nelson/osm-tasking-manager2
osmtm/__init__.py
Python
bsd-2-clause
7,927
0.007191
import bleach from pyramid.config import Configurator from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from pyramid.session import UnencryptedCookieSessionFactoryConfig from sqlalchemy import engine_from_config from .models import ( DBSession,...
authz_policy = ACLAuthorizationPolicy() config = Configurator(settings=settings, root_factory=RootFactory,
authentication_policy=authn_policy, authorization_policy=authz_policy) # fixes backwards incompatibilities when running Pyramid 1.5a # https://pypi.python.org/pypi/pyramid#features config.include('pyramid_mako') # pyramid_tm uses the transaction module to begin/...
justinmnoor/geodjangotemplate
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/settings/local.py
Python
mit
457
0.002188
# DJANGO 1.10.5 LOCAL SETTINGS # https://docs.djangoproject.com/en/1.10/topics/settings/ # ============================================================================
====================== from .base import * DEBUG = True # APP CONFIGURATION # https://docs.djangoproject.com/en/1.10/ref/applications # ================================================================================================== # Add your local apps here I
NSTALLED_APPS += []
jtaghiyar/kronos
kronos/plumber.py
Python
mit
28,257
0.008635
""" Created on Mar 8, 2014 @author: jtaghiyar """ from helpers import validate_argument import logging class Plumber(object): """ pipe components into a pipeline based on the given configuration and generate a python script. """ def __init__(self, pipeline_script, workflow=None): ## the ...
'kronos.helpers' :[ 'JobFa
ilureError', 'flushqueue' ], 'kronos.logger' :[ 'PipelineLogger', 'LogWarnErr', ...
wasw100/pycaldav
pycaldav/lib/url.py
Python
gpl-3.0
5,906
0.004233
#!/usr/bin/env python # -*- encoding: utf-8 -*- import urlparse def uc2utf8(input): ## argh! this feels wrong, but seems to be needed. if type(input) == unicode: return input.encode('utf-8') else: return input class URL: """ This class is for wrapping URLs into objects. It's use...
e maintaining backward compatibility. Basically, all methods should accept any kind of URL. """ def __init__(self, url): if isinstance(url, urlparse.ParseResult) or isinstance(url, urlparse.SplitResult): self.url_parsed = url self.url_raw = None else: ...
url_raw = url self.url_parsed = None def __nonzero__(self): if self.url_raw or self.url_parsed: return True else: return False def __ne__(self, other): return not self == other def __eq__(self, other): if str(self) == str(other): ...
subssn21/notorm
notorm/momoko.py
Python
mit
919
0.015234
import notorm import momoko from tornado import gen import psycopg2.extras class AsyncRecord(notorm.record): @gen.coroutine def update(self, **args): for k,v in args.items(): setattr(self, k, v) cursor = yield notorm.db.execute( self.update_...
self.update() else: cursor = yield notorm.db.execute(
self.insert_qry, self.__dict__, cursor_factory=psycopg2.extras.NamedTupleCursor) results = cursor.fetchone() if results: self.id = results[0]
DanielNeugebauer/adhocracy
src/adhocracy/lib/tiles/selection_tiles.py
Python
agpl-3.0
2,711
0.000369
from pylons import tmpl_context as c from adhocracy.lib.auth import can from util import render_tile, Bas
eTile class VariantRow(object): def __init__(self, tile, variant, poll): self.tile = tile self.variant = variant self.poll = poll if tile.frozen: freeze_time = tile.selection.proposal.adopt_poll.beg
in_time self.text = tile.selection.page.variant_at(variant, freeze_time) else: self.text = tile.selection.page.variant_head(variant) @property def selected(self): return self.tile.selected == self.variant @property def show(self): return not self.tile.fr...
tjanez/celery-demo-app
test/test.py
Python
gpl-3.0
350
0.002857
from __future__ import absolute_import # Start a Celery worker by execu
ting: # celery -A proj worker -l info # Import available tasks from proj.tasks import add, mul, xsum, fib # Test short-running tasks add.delay(2, 2) mul.delay(10, 12) xsum.delay(range(100)) fib.delay(10)
# Test medium-running tasks fib.delay(35) fib.delay(35) fib.delay(35)
heytcass/homeassistant-config
deps/cherrypy/test/test_etags.py
Python
mit
3,093
0
import cherrypy from cherrypy._cpcompat import ntou from cherrypy.test import helper class ETagTest(helper.CPWebCase): @staticmethod def setup_server(): class Root: @cherrypy.expose def resource(self): return "Oh wah ta goo Siam." @cherrypy.expose...
Status(200) etag1 = self.assertHeader('ETag') self.getPage("/unicoded", headers=[('If-Match', etag1)]) self.assertStatus(200)
self.assertHeader('ETag', etag1)
daryllstrauss/tango
test_mat.py
Python
mit
2,661
0.001127
import unittest import matmath import numpy as np import math class TestMatrix(unittest.TestCase): def testRotX(self): mat = matmath.xRotationMatrix(math.radians(90)) pt = np.array([1, 0, 0, 1]) npt = pt.dot(mat) np.testing.assert_almost_equal(npt, [1, 0, 0, 1]) pt = np.ar...
np.testing.assert_almost_equal(qmat, rmat) def testMultipleRotates(self): r1 = matmath.xRotationMatrix(np.radians(90)) r2 = matmath.zRotationMatrix(np.radians(90)) mat = r1.dot(r2) pt = np.array([0, 0, 1, 1])
npt = pt.dot(mat) np.testing.assert_almost_equal(npt, [1, 0, 0, 1]) def test2M(self): # 2 Meters away depth scan pt = np.array([0, 0, 2, 1]) print "PC", pt mat = matmath.pcToSoSMatrix() npt = pt.dot(mat) print "SoS ", npt trans = np.array([0, 0,...
iulian787/spack
var/spack/repos/builtin/packages/voropp/package.py
Python
lgpl-2.1
1,349
0.001483
# Copyright 2013-2020 Lawrence Livermore National Sec
urity, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Voropp(MakefilePackage): """Voro++ is a open source software library for the computation of the Voronoi diagr
am, a widely-used tessellation that has applications in many scientific fields.""" homepage = "http://math.lbl.gov/voro++/about.html" url = "http://math.lbl.gov/voro++/download/dir/voro++-0.4.6.tar.gz" variant('pic', default=True, description='Position independent code') version(...
servalproject/nikola
nikola/plugins/compile_rest/youtube.py
Python
mit
2,306
0
# Copyright (c) 2012 Roberto Alsina y otros. # 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, pub...
'height': 344, } options.update(self.options) return [nodes.raw('', CODE.form
at(**options), format='html')] def check_content(self): if self.content: raise self.warning("This directive does not accept content. The " "'key=value' format for options is deprecated, " "use ':key: value' instead") directives.reg...
LettError/glyphNameFormatter
Lib/glyphNameFormatter/rangeProcessors/gujarati.py
Python
bsd-3-clause
668
0.008982
def process(self): #GUJARATI VOWEL SIGN CANDRA E #GUJARATI VOWEL CANDRA E self.edit("GUJARATI") self.edit("LETTER") self.edit("DIGIT") self.processAs("Helper Indic") self.edit("VOWEL SIGN", "sign") self.edit("VOWEL") self.edit("SIGN") self.edit("THREE-DOT NUKTA ABOVE", "threedotnuk...
") self.edit("TWO-CIRCL
E NUKTA ABOVE", "twocirclenuktaabove") self.processAs("Helper Numbers") self.lower() self.compress() self.scriptPrefix() if __name__ == "__main__": from glyphNameFormatter.exporters import printRange from glyphNameFormatter.tools import debug printRange("Gujarati") debug(0x0AFA)
micolous/helvetic
helvetic/views/aria_api.py
Python
agpl-3.0
5,411
0.030309
# -*- mode: python; indent-tabs-mode: nil; tab-width: 2 -*- """ aria_api.py - implements handlers which are for the Aria to talk to helvetic. """ from __future__ import absolute_import from base64 import b16encode from crc16 import crc16xmodem from datetime import timedelta from decimal import Decimal from django.cont...
pResponseBadRequest('ssid missing') serial = request.GET['serialNumber'].upper() token = request.GET['token'] ssid = request.GET['ssid'] if len(serial) != 12: return HttpResponseBadRequest('serialNumber must be 12 bytes') if any(((x not in hexdigits) for x in serial)): return HttpRespon
seBadRequest('serial must only contain hex') # Lookup the authorisation token auth_token = AuthorisationToken.lookup_token(token) if auth_token is None: return HttpResponseForbidden('Bad auth token') owner = auth_token.user # Delete the token. auth_token.delete() # Register the Aria scale = Scal...
sbesson/zeroc-ice
scripts/IceGridAdmin.py
Python
gpl-2.0
11,612
0.007492
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # *************************************...
") sys.stdout.flush() iceGridAdmin("registry shutdown replica-" + str(i)) print("ok") i = i - 1 sys.stdout.write("shutting down icegrid registry... ") sys.std
out.flush() iceGridAdmin("registry shutdown") print("ok") for p in procs: p.waitTestSuccess() def iceGridNodePropertiesOverride(): # # Create property overrides from command line options. # overrideOptions = '' for opt in shlex.split(TestUtil.getCommandLineProperties("", Te...
ildar-band/rd90
rd90.py
Python
mit
18
0.055556
pr
int("My sc
ript")
nigusgirma/https-svn.pjsip.org-repos-pjproject-trunk-
tests/pjsua/scripts-sipp/uas-answer-200-reinvite-without-sdp.py
Python
gpl-2.0
136
0
# $Id$ # import inc_const as const PJSUA = ["--null-audio --max-calls=1 $SIPP_URI"] PJSUA_EXPECTS
= [[0, const.STATE_C
ONFIRMED, "v"]]
iamgyz/remote-system-control
server.py
Python
mit
2,750
0.020364
import paho.mqtt.publish as publish import paho.mqtt.client as mqtt import socket import json from datetime import datetime import configparser ''' Author: GYzheng, [email protected] ###Server side We have two topic, one is from client to server, the other one is from client to server 1. Server->Client : sc_topic ...
nnect == False: pass#donothig... def send_msg(self,msg): publish.single(self.sc_topic,msg, hostname=self.host, port=self.port) def on_connect(self,client, userdata, flags, rc): self.is_connect = True #subscribe data from server client.subscribe(se
lf.cs_topic); def on_message(self,client,user_data,msg): try: tmp = json.loads(msg.payload.decode('utf-8','ignore')) client_name = tmp['name'] client_ip = tmp['ip'] client_status = tmp['status'] client_result = tmp['result'] pri...
analogue/pyramid_swagger
tests/includeme_test.py
Python
bsd-3-clause
3,308
0
from bravado_core.spec import Spec import mock from pyramid.config import Configurator from pyramid.registry import Registry import pytest from swagger_spec_validator.common import SwaggerValidationError import pyramid_swagger from pyramid_swagger.model import SwaggerSchema @mock.patch('pyramid_swagger.register_api_...
er.swagger_versions': ['1.2'] } mock_config = mock.Mock(registry=mock.Mock(settings=settings)) pyramid_swagger.includeme(mock_config) assert isinstance(settings['pyramid_swagger.schema12'], SwaggerSchema) assert mock_register.call_count == 1 @mock.patch('pyramid_swagger.register_api_doc_endpoints'...
_swagger.swagger_versions': ['2.0'] } mock_config = mock.Mock(registry=mock.Mock(settings=settings)) pyramid_swagger.includeme(mock_config) assert isinstance(settings['pyramid_swagger.schema20'], Spec) assert not settings['pyramid_swagger.schema12'] assert mock_register.call_count == 1 @mock.p...
minhphung171093/GreenERP_V8
openerp/addons/website/controllers/main.py
Python
agpl-3.0
20,190
0.003566
# -*- coding: utf-8 -*- import cStringIO import datetime from itertools import islice import json import xml.etree.ElementTree as ET import logging import re import werkzeug.utils import urllib2 import werkzeug.wrappers from PIL import Image import openerp from openerp.addons.web.controllers.main import WebClient fr...
'apps': apps, 'modules': modules, 'v
ersion': openerp.service.common.exp_version() } return request.render('website.info', values) #------------------------------------------------------ # Edit #------------------------------------------------------ @http.route('/website/add/<path:path>', type='http', auth="user", website=...
willprice/weboob
weboob/browser/elements.py
Python
agpl-3.0
9,532
0.001154
# -*- coding: utf-8 -*- # Copyright(C) 2014 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
None _loaders = None klass = None condition = None validate = None class Index(object): pass def __init__(self, *args, **kwargs): super(ItemElement, self).__init__(*args, **kwargs) self.logger = getLogger(self.__class__.__name__.lower()) self.obj = None de...
ne: self.obj = obj for obj in self: return obj def __iter__(self): if self.condition is not None and not self.condition(): return try: if self.obj is None: self.obj = self.build_object() self.parse(self.el) ...
TNT-Samuel/Coding-Projects
Machine Learning with Python/Chapter 1/P_15.py
Python
gpl-3.0
90
0
from P_14 import * print("Shape of data:
{}".format(iris_dataset[
"data"].shape)) input()
biggihs/python-pptx
features/steps/chartdata.py
Python
mit
7,361
0
# encoding: utf-8 """Gherkin step implementations for chart data features.""" from __future__ import ( absolute_import, division, print_function, unicode_literals ) import datetime from behave import given, then, when from pptx.chart.data import ( BubbleChartData, Category, CategoryChartData, XyChartData )...
iven_a_Categories_object_with_number_format_init_nf(context, init_nf): categories = CategoryChartData().categories if init_nf != 'left as default': categories.number_format = init_nf context.categories = categories @given('a Category object') def given_a_Category_object(context): context.categ...
def given_a_CategoryChartData_object(context): context.chart_data = CategoryChartData() @given('a CategoryChartData object having date categories') def given_a_CategoryChartData_object_having_date_categories(context): chart_data = CategoryChartData() chart_data.categories = [ datetime.date(2016, ...
gawel/irc3
tests/test_slack.py
Python
mit
2,123
0
# -*- coding: utf-8 -*- import pytest from irc3.plugins import slack pytestmark = pytest.mark.asyncio async def test_simple_matches(irc3_bot_factory): bot = irc3_bot_factory(includes=['irc3.plugins.slack']) plugin = bot.get_plugin(slack.Slack) setattr(plugin, 'config', {'token': 'xoxp-faketoken'}) as...
actory(includes=['irc3.plugins.slack']) plugin = bot.get_plugin(slack.Slack) setattr(plugin, 'config', {'token': 'xoxp-faketoken'}) async def api_call(self, method, date=None): return ({'channel': {'name': 'testchannel'}}) plugin.api_call = api_call asse
rt '#testchannel' == await plugin.parse_text('<#C12345>') assert 'channel' == await plugin.parse_text('<#C12345|channel>') async def test_user_matches(irc3_bot_factory): bot = irc3_bot_factory(includes=['irc3.plugins.slack']) plugin = bot.get_plugin(slack.Slack) setattr(plugin, 'config', {'token': 'xo...
feus4177/socketIO-client-2
socketIO_client/symmetries.py
Python
mit
897
0.001115
import six try: from lo
gging import NullHandler except ImportError: # Python 2.6 from logging import Handler class NullHandler(Handler): def emit(self, record): pass try: from urllib import urlencode as format
_query except ImportError: from urllib.parse import urlencode as format_query try: from urlparse import urlparse as parse_url except ImportError: from urllib.parse import urlparse as parse_url try: memoryview = memoryview except NameError: memoryview = buffer def get_int(*args): try: r...
f0lie/RogueGame
src/room.py
Python
mit
3,171
0
from random import randint from position import Position, Size from block import Room, Block class Room(object): def __init__(self, pos_row=0, pos_col=0, rows=1, cols=1, fill=Block.empty, left=Room.left, right=Room.right, top=Room.top, bottom=Room.bottom, top_le...
other_room_pos_2.row and pos_2.row >= other_room.pos.row) @class
method def generate(cls, min_pos, max_pos, min_size, max_size): """ Create room from min_size to max_size between min_pos and max_pos """ size = Size(randint(min_size.rows, max_size.rows), randint(min_size.cols, max_size.cols)) pos = Position(randint(min_p...
V-Paranoiaque/Domoleaf
domomaster/usr/bin/domomaster/domomaster_postinst.py
Python
gpl-3.0
4,613
0.017993
#!/usr/bin/python3 ## @package domomaster # Master daemon for D3 boxes. # # Developed by GreenLeaf. import sys; import os; import random; import string; from hashlib import sha1 from subprocess import * import socket; sys.path.append("/usr/lib/domoleaf"); from DaemonConfigParser import *; MASTER_CONF_FILE_BKP ...
ysql/debian.cnf', 'domoleaf',
'-e', query1]); call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'domoleaf', '-e', query2]); if __name__ == "__main__": #Upgrade if os.path.exists(MASTER_CONF_FILE_BKP): master_conf_copy() os.remove(MASTER_CONF_FILE_BKP); else: master_conf_init() master_conf...
VinnieJohns/ggrc-core
src/ggrc/migrations/versions/20170105231037_579239d161e1_create_missing_snapshot_revisions.py
Python
apache-2.0
1,087
0.0046
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Create missing snapshot revisions. Create Date: 2017-01-05 23:10:37.257161 """ # disable Invalid constant name pylint warning for mandatory Alembic variables. # pylint: disable=invalid-name from ggrc.mi...
tion", "Vendor", "Policy", "Regulation", "Standard", "Contract", "System", "
Process", "Risk", "Threat", ]) handle_objects(snapshot_objects) def downgrade(): """Data correction migrations can not be downgraded."""
lueschem/edi
edi/commands/version.py
Python
lgpl-3.0
1,351
0
# -*- coding: utf-8 -*- # Copyright (C) 2017 Matthias Luescher # # Authors: # Matthias Luescher # # This file is part of edi. # # edi is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of...
ver
sion = self.run() print(version) @staticmethod def run(): return get_edi_version()
Macmod/rgb-remote-tts
remote-gtts/remote2gtts.py
Python
mit
507
0
#!/bin/python import sys import vlc import os import re from t
empfile import * from gtts import gTTS from remote2text import RGBRemote2Text parser = RGBRemote2Text(verbose=True) while True: ir_out = input() response = parser.process(ir_out) if response: tts = gTTS(text=response, lang='pt') tmp = NamedTemporaryFile(delete=False) tts.write_to...
close()
everypony/ponyFiction
ponyFiction/views/chapter.py
Python
gpl-3.0
5,461
0.001492
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.db.models import Max, F from django.shortcuts import render, get_object_or_404, redirect from django.utils.decorators import method_decorator from django.views.generic.edit i...
, queryset=queryset) if self.chapter.story.editable_by(self.request.user): return self.chapter else: raise PermissionDenied def form_valid(self, form): self.chapter = form.save() return redirect('chapter_edit', self.chapter.id) def get_context_data(self,...
extra_context = {'page_title': 'Редактирование «%s»' % self.chapter.title, 'chapter': self.chapter} context.update(extra_context) return context class ChapterDelete(DeleteView): model = Chapter chapter = None story = None chapter_id = None template_name = 'chapter_confirm_d...
beernarrd/gramps
gramps/gen/display/name.py
Python
gpl-2.0
45,844
0.004319
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2004-2007 Donald N. Allingham # Copyright (C) 2010 Brian G. Matherly # Copyright (C) 2014 Paul Franklin # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publ...
-------------------------------------------------------------------- # # NameDisplayError class # #--------------
----------------------------------------------------------- class NameDisplayError(Exception): """ Error used to report that the name display format string is invalid. """ def __init__(self, value): Exception.__init__(self) self.value = value def __str__(self): return self.v...
ddalex/python-prompt-toolkit
prompt_toolkit/search_state.py
Python
bsd-3-clause
1,105
0.002715
from .enums import IncrementalSearchDirection from .filters import SimpleFilter, Never __all__ = ( 'SearchState', ) class SearchState(object): """ A search 'query'. """ __slots__ = ('text', 'direction', 'ignore_case') def __init__(self, text='', direction=IncrementalSearchDirection.FORWARD, ...
ion, self.ignore_case) def __invert__(self): """ Create a new SearchState where backwards becomes forwards and the other way around. """ if self.direction == IncrementalSearchDirection.BACKWARD: direction = IncrementalSearchDirection.FORWARD else: ...
irection, ignore_case=self.ignore_case)
jcushman/pywb
pywb/utils/loaders.py
Python
gpl-3.0
9,733
0.002055
""" This module provides loaders for local file system and over http local and remote access """ import os import hmac import urllib #import urllib2 import requests import urlparse import time import pkg_resources from io import open, BytesIO try: from boto import connect_s3 s3_avail = True except ImportError...
file_or_resource(url, offset, length) def load_file_or_resource(self, url, offset=0, length=-1): """ Load a file-like reader from the local file system """ # if starting with . or /, can only be a file path.. file_only = url.startswith(('/', '.')) # convert to file...
True url = urllib.url2pathname(url[len('file://'):]) try: # first, try as file afile = open(url, 'rb') except IOError: if file_only: raise # then, try as package.path/file pkg_split = url.split('/', 1) ...
fin-ger/logitech-m720-config
setup.py
Python
gpl-3.0
2,072
0.02027
""" logitech-m720-config - A config script for Logitech M720 button mappings Copyright (C) 2017 Fin Christensen <[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 ver...
"Development Status :: 2 - Pre-Alpha", "Environment :: Console", "Intended Audience :: System Administrators", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3.5", "P...
age :: Python :: 3 :: Only", ], keywords = "config logitech m720 hid++", packages = find_packages (), install_requires = ["solaar"], extras_require = {}, package_data = { "m720_config": [], }, data_files = [], entry_points = { "console_scripts": [ "m720-co...
plotly/plotly.py
packages/python/plotly/plotly/validators/layout/ternary/aaxis/title/font/_family.py
Python
mit
553
0
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="famil
y", parent_name="layout.ternary.aaxis.title.font", **kwargs ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), no_blank=kwargs.pop("no_blank", True), ...
**kwargs )
TailorDev/django-tailordev-biblio
td_biblio/__init__.py
Python
mit
139
0
"""TailorDev Biblio Bibliography management with Django. """ __version__ = "2.0.0" default_app_conf
ig = "td_biblio.apps
.TDBiblioConfig"