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
leprikon-cz/leprikon
leprikon/models/orderables.py
Python
bsd-3-clause
11,902
0.002016
from collections import namedtuple from datetime import date, datetime, timedelta from cms.models import CMSPlugin from django.db import models from django.utils.formats import date_format, time_format from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from ..c...
ext=_("Keep empty to skip searching by leaders."), ) template = models.CharField( _("template"), max_length=100, choices=settings.LEPRIKON_ORDERABLELIST_TEMPLATES, default=settings.LEPRIKON_ORDERABLELIST_TEMPLATES[0][
0], help_text=_("The template used to render plugin."), ) class Meta: app_label = "leprikon" def copy_relations(self, oldinstance)
szandara/celery-one
tests/unit/test_helpers.py
Python
bsd-2-clause
2,483
0
# -*- coding: utf-8 -*- from celeryone.helpers import queue_one_key, kwargs_to_list, force_string import pytest import six def test_force_string_1(): assert force_string('a') == 'a' def test_force_string_2(): assert force_string(u'a') == 'a' def test_force_string_3(): assert force_string('é') == 'é' ...
': {u'é': 'c'}, 'b': [u'a', 'é'], u'c': 1, 'd': 'é', 'e': u'é'}) assert keys == [ "a-{'\\xc3\\xa9': 'c'}", "b-['a', '\\xc3\\xa9']", "c-1", "d-\xc3\xa9", "e-\xc3\xa9", ] @pytest.mark.skipif(six.PY2, reason='requires python 3') def test_kwargs_to_list_6(): keys = kwar...
': 'c'}", "b-['a', 'é']", "c-1", "d-é", 'e-é'] def test_queue_one_key(): key = queue_one_key("example", {}) assert key == "qo_example" def test_queue_one_key_kwargs(): key = queue_one_key("example", {'pk': 10}) assert key == "qo_example_pk-10" def test_queue_one_key_kwargs_restrict_keys(): key...
Gebesa-Dev/Addons-gebesa
global_privilege_button/models/mrp_bom_line.py
Python
agpl-3.0
1,447
0
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import api, _, models from openerp.exceptions import UserError class MrpBomLine(models.Model): _inherit = 'mrp.bom.line' @api.model def create(self, vals): if not s...
_group( 'global_privilege_button.group_manager_ldm'): raise UserError(_('Error!\nYou do not have privileges to Modify' ' Material(s) list.\nCheck with your' ' System Administrator.')) return super(MrpBomLine, self).write(val...
: raise UserError(_('Error!\nYou do not have privileges to Delete' ' Material(s) list.\nCheck with your' ' System Administrator.')) return super(MrpBomLine, self).unlink()
myarjunar/QGIS
tests/src/python/test_qgspointdisplacementrenderer.py
Python
gpl-2.0
9,082
0.000991
# -*- coding: utf-8 -*- """ *************************************************************************** test_qgspointdisplacementrenderer.py ----------------------------- Date : September 2016 Copyright : (C) 2016 by Nyall Dawson Email : nyall dot dawson at...
* *************************************************************************** """ __author__ = 'Nyall Dawson' __date__ = 'September 2016' __copyright__ = '(C) 2016, Nyall Dawson' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H...
rt QDomDocument from qgis.core import (QgsVectorLayer, QgsProject, QgsRectangle, QgsMultiRenderChecker, QgsPointDisplacementRenderer, QgsFontUtils, QgsUnitTypes, ...
Fatman13/gta_swarm
hc_pool.py
Python
mit
11,408
0.028927
#!/usr/bin/env python # coding=utf-8 import pprint import csv import click import requests import datetime as datetime from b
s4 import BeautifulSoup # from splinter import Browser import time import re import copy import os import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC fr...
common.exceptions import StaleElementReferenceException from selenium.common.exceptions import WebDriverException from selenium.common.exceptions import TimeoutException from requests.exceptions import ConnectionError from requests.exceptions import ChunkedEncodingError from requests.exceptions import ReadTimeo...
rochacbruno/dynaconf
example/envvar_prefix/app.py
Python
mit
548
0
from dynaconf import
settings print("EXAMPLE_ prefix") settings.configure(ENVVAR_PREFIX_FOR_DYNACONF="EXAMPLE") print(settings.VAR1) print(settings.VAR2) print("_ prefix") settings.configure(ENVVAR_PREFIX_FOR_DYNACONF="") print(settings.VAR1) print(settings.VAR2) print("no prefix at all") settings.configure(ENVVAR_PREFIX_FOR_DYNACONF=F...
figure(GLOBAL_ENV_FOR_DYNACONF=False) print(settings.VAR1) print(settings.VAR2)
geometalab/osmaxx
tests/conversion/model_test.py
Python
mit
1,375
0.002909
import os import pytest from osmaxx.conversion import status @pytest.mark.django_db() def test_job_statuses_for_jobs(started_conversion_job, failed_conversion_job, finished_conversion_job): assert started_conversion_job.status == status.STARTED assert failed
_conversion_job.status == status.FAILED assert finished_conversion_job.status == status.FINISHED @pytest.mark.django_db() def test_job_removes_file_when_deleted(finished_conversion_job): a
ssert finished_conversion_job.status == status.FINISHED file_path = finished_conversion_job.resulting_file.path assert file_path is not None assert os.path.exists(file_path) finished_conversion_job.delete() assert not os.path.exists(file_path) @pytest.mark.django_db() def test_job_get_absolute_fil...
jaredly/codetalker
tests/tokenize/idchars.py
Python
mit
737
0.009498
#!/usr/bin/env python from codetalker.pgm import Grammar from codetalker.pgm.tokens import STRING, ID, NUMBER, WHITE, NEWLINE, IdToken from codetalker.pgm.special import star from codetalker.pgm.errors import TokenError def start(rule): rule | ID g1 = Grammar(start=start, tokens=[ID,WHITE], idchars='$') def test_1(...
n$e to$d $me') assert len(tks) == 9 g2 = Grammar(start=start, tokens=[ID, WHITE], idchars='-') def test_2(): tks = g2.get_tokens('so-me body on-ce told me-') assert len(tks) == 9 def test_3(): try: g2.get_tokens('som$one and me') except TokenError: pass else: raise Ass...
nError('was supposed to fail') # vim: et sw=4 sts=4
villeneuvelab/vlpp
pipelines/templates/qa_mosaics_T1w.py
Python
mit
2,115
0.010402
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from glob import glob from vlpp.utils import save_json from vlpp.qamosaic import Mosaic def main(): # Usefull directories os.mkdir("data") # Informations participant_id = "${sub.sub}" # Images Path try: anat =
glob("${sub.anat}")[0] except: anat = None try: brainmask = glob("${sub.brainmask}")[0] except: brainmask = None try: atlas = glob("${sub.atlas}")[0] except: atlas = None try: pet = glob("${sub.pet}")[0] except: pet = None try: cerebellumCortex = glob("${sub.cerebellumCortex}")[0] ...
lumCortex = None try: atlasBaker = glob("${sub.atlasBaker}")[0] except: atlasBaker = None try: suvrBaker = glob("${sub.suvrBaker}")[0] except: suvrBaker = None # Anat tag = "anat" m = Mosaic(anat, mask=brainmask, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, t...
pavelzag/MIQLog
miqlog.py
Python
gpl-3.0
4,880
0.003074
#!/usr/bin/env python import random import string from tailer import SSHTailer from termcolor import colored from time import sleep import smtplib from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate im...
one' in send_to: send_mail(send_to=send_to, subject='{}{} {}'.format(log_type, '.log incoming for', server_address), file_name=logfile.name) else: print('skipping e-mail') def get_log(log_type='None', send_to='None'):
logs_directory = 'logs' if not os.path.exists(logs_directory): os.makedirs(logs_directory) log_file_path = path.join(logs_directory, '{}_{}_{}{}'.format(log_type, 'log', random_string, '.txt')) logfile = open(log_file_path, 'w') print('{} {}'.format('Printing local log at:', logfile.name)) ...
4shadoww/usploit
modules/bluetooth_pod.py
Python
mit
1,294
0.002322
# Copyright (C) 2015 – 2021 Noa-Emil Nissinen (4shadoww) from core.hakkuframework import * import os import subprocess import time conf = { "name": "bluetooth_pod", "version": "1.0", "shortdesc": "bluetooth ping of death", "github": "4shadoww", "author": "4shadoww", "ema
il": "4shadoww0@gmail.com", "initdate": "2016-02-24", "lastmod": "2016-12-29", "apisupport": False, "needroot": 1, "dependencies": ["xterm", "hcitool", "l2ping"] } # List of variables variables = OrderedDict(( ('interface', ['hci0', 'interface']), ('bdaddr', ['none', 'target bluetooth add...
'scan': 'scan for devices' } # Simple changelog changelog = "Version 1.0:\nrelease" def run(): print_info("bluetooth ping of death attack started...") try: for i in range(1, 10000): xterm_1 = "l2ping -i %s -s %s -f %s &" % (variables['interface'][0], variables['size'][0], variables['bda...
rwatson/chromium-capsicum
o3d/plugin/idl/codegen.py
Python
bsd-3-clause
1,322
0.000756
#!/usr/bin/python2.4 # Copyright 2009 Google 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 ...
path.join(os.path.dirname(__file__)) third_party = os.path.normpath( os.path.join(script_dir
, '..', '..', 'third_party')) pythonpath = os.pathsep.join([os.path.join(third_party, 'gflags', 'python'), os.path.join(third_party, 'ply')]) orig_pythonpath = os.environ.get('PYTHONPATH') if orig_pythonpath: pythonpath = os.pathsep.join([pythonpath, orig_pythonpath]) os.environ['PYTHO...
bradleyg/django-s3direct
s3direct/fields.py
Python
mit
511
0
from django.db.models import Field from s3direct.widgets import S3DirectWidget class S3DirectField(Field): def __init__(self,
*args, **kwargs): dest = kwargs.pop('dest', None) self.widget = S3DirectWidget(dest=dest) super(S3DirectField, self).__init__(*args, **kwargs) def get_internal_type(self): return 'TextField' def formfield(self, *args, **kwargs): kwargs['widget'] = self.widget re...
(S3DirectField, self).formfield(*args, **kwargs)
tanonev/codewebs
src/prototypes/ListIncorrects.py
Python
mit
5,059
0.017592
import sys import os.path sys.path.append(os.path.abspath('../../')) sys.path.append(os.path.abspath('../../site/cwsite')) import src.util.DBSetup from src.util.MLClass import MLClass from src.util.FileSystem import FileSystem from src.util.AstNetwork import AstNetwork from models.models import Octave, Original_submi...
ntinue return submissionMap def writeASTs(self, astList, label, parts,dirName): logging.info('writeASTs(...'+str(label) + ', ' \ + str(parts) + ', ' + str(dirName)+ ')') suffASTs = self
.getSuff('',label,parts) fileNameASTs = os.path.join(dirName,suffASTs) self.writeToFile(fileNameASTs, astList) def writeNumSubmissions(self, submissionsList, label, parts, dirName): logging.info('writeNumSubmissions(...'+str(label) + ', ' \ + str(parts) + ', ' + str(...
nikdval/cloudSolar
solarApp/solar/settings.py
Python
artistic-2.0
11,845
0
from __future__ import absolute_import, unicode_literals import os from django import VERSION as DJANGO_VERSION from django.utils.translation import ugettext_lazy as _ ###################### # MEZZANINE SETTINGS # ###################### # The following settings are already defined with default values in # the ``de...
s.py DEBUG = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = True SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False AUTHENTICATION_BACKENDS = ("mezzani...
a mode you'd pass directly to os.chmod. FILE_UPLOAD_PERMISSIONS = 0o644 ############# # DATABASES # ############# DATABASES = { "default": { # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.", # DB name or path to database file if using sqlite3. ...
cxyxc/webgis-house
spider/fangjiawang/test_mysql_insert.py
Python
apache-2.0
634
0.020677
#!/usr/bin/python3 import pymysql # 打开数据库连接 db = pymysql.connect("localhost","root","","webgis_house",charset='utf8')
# 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = "INSERT INTO HOUSE(address, \ total, price, area, type, floor, info_url) \ VALUES ('%s', '%d', '%d', '%d', '%s', '%s', '%s')" %
\ ('费县职业中专', 98, 1, 100, '3室1厅', '6/6', 'http://www.example.com') try: # 执行sql语句 cursor.execute(sql) # 执行sql语句 db.commit() except: # 发生错误时回滚 db.rollback() # 关闭数据库连接 db.close()
pypt/shaibos
shaibos/util/iterable.py
Python
lgpl-2.1
304
0.003289
# -*- coding: utf-8 -*- import inspect class Iterable: # Jinja2 wants to iterate over all properties; __dict__ doesn't return the @property ones def __iter__(self): for attr, value in inspect.getmembers(self): if not attr.startswith('_'):
yield attr, v
alue
teddywing/pubnub-python
python/examples/cr.py
Python
mit
2,698
0.007784
## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 ## PubNub Real-time Push APIs and Notifications Framework ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ import sys from pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' subscribe_key = len(sys.a...
gv) > 5 and bool(sys.argv[5]) or False ## --------------------------------------------------------------
--------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on, auth_key="abcd") channel = 'hello_world' def callback(message)...
nlchap0/nlcpython
pywip/curve.py
Python
mit
816
0.014706
from . import header def curve(**args): '''Add a curve to the list plotted by legend(). A curve is a dictionary that is set by the plot command and can be used with the legend command to make it easier to make legends. This allows you to add an extra curve to those listed by legend() without ...
Allowed optional **args: color - the color for the data size - The size for each data point style - line style for the data width - the thickness of the line for drawing the curve text - Text to describe the curve fillcolor - Color to fill symbols with''' _al...
header._checkallowed('curve',args.keys(),_allowed) header._makecurve(**args)
seanli9jan/tensorflow
tensorflow/compiler/tests/resampler_ops_test.py
Python
apache-2.0
6,753
0.008145
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
, 2, 2, 3] input_rgb_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] input_np = np.array(input_rgb_data, dtype=dtype).reshape(input_shape) warp_shape = [1, 2] warp_data = [0.7, 0.6] warp_np = np.array(warp_data, dtype=dtype).reshape(warp_shape) expected = [[59.58000183, 146....
d(input_np, warp_np, expected) grad_output = np.ones([1, 3], dtype=dtype) expected_grad_data = [[[[0.12, 0.12, 0.12], [0.27999997, 0.27999997, 0.27999997]], [[0.18000001, 0.18000001, 0.18000001], [0.42000002, 0.420000...
vishnu-kumar/PeformanceFramework
rally_os/plugins/openstack/scenarios/fuel/environments.py
Python
apache-2.0
3,333
0
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
m rally.task import validation class FuelEnvironments(utils.FuelScenario): """Benchmark scenarios for Fuel environments. Scenarios take Fuel related parameters: release_id: OpenStack release available in Fuel deployment_mode: accepts 'ha_compact' or 'multinode' network_provider: accepts 'nova' or...
ation.required_openstack(admin=True) @scenario.configure(context={"admin_cleanup": ["fuel"]}) def create_and_delete_environment(self, release_id=1, network_provider="neutron", deployment_mode="ha_compact", ...
openmicroscopy/omero-marshal
omero_marshal/decode/decoders/permissions.py
Python
gpl-2.0
817
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2015 Glencoe Software, Inc. All rights reserved. # # This software is distributed under the terms described by the LICENCE file # you can find at the root of the dis
tribution bundle. # If the file is missing please request a copy by contacting # jason@glencoesoftware.com. # from .. import Decoder from omero.model import PermissionsI class PermissionsDecoder(Decoder): TYPE = 'TBD#Permissions' OMERO_CLASS = PermissionsI def decode(self, data): o = Permissio...
e'], not data['canAnnotate'] ] return o decoder = (PermissionsDecoder.TYPE, PermissionsDecoder)
PnMercantour/autorisations_circulation
auth_circu/conf.py
Python
gpl-3.0
3,368
0.000595
import os import sys import locale import warnings import configparser from pathlib import Path from textwrap import dedent from flask import Flask LOCALE = ('fr_FR', 'UTF-8') STATIC_DIR = Path(__file__).absolute().parent / 'static' UPLOAD_DIR = STATIC_DIR / 'upload' try: locale.setlocale(locale.LC_ALL, LOCALE...
tall the proper locale on your OS or change the locale settings in conf.py. """)) app = Flask('auth_circu') # load config file config_file = os.environ.get("AUTH_CIRCU_CONFIG_FILE", "") need_config_file = not any(( 'generate_config_file' in sys.argv, '--help' in sys.argv, '-h' in sys.argv, ))...
if not config_file and need_config_file: config_file = Path('./settings.ini') if not config_file.is_file(): sys.exit( 'Please provide a config file with the --config-file option ' 'in runserver or using the "AUTH_CIRCU_CONFIG_FILE" env var. ' 'You can generate one u...
hero78119/account-management-deploy-system
src/conf/projConst.py
Python
mit
2,609
0.007282
import subprocess import os defaultUser = 'root' defaultSudoGroup = 'sudo' try: #master git_root_path = subprocess\ .Popen(["git", 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\ .communicate()[0].rstrip() + '/' except Exception as e: #slave ...
": "rm -rf run; mkdir run; mv FILE run/; cd run/; tar -xf FILE ./
;" + "mv %s src/; cd src/; python Slave.py;" % (defaultRes,) + "cd; rm -rf run;", "ssh_with_cmd" : 'ssh %s@IP -p PORT -i SSHKEYPATH -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "CMD"' % (defaultUser,), #"set_user_password": "echo USERNAME:PASSWORD | chpasswd;", "add_user_with...
rajeevs1992/pyhealthvault
src/healthvaultlib/itemtypes/appspecificinformation.py
Python
mit
961
0
from lxml import etree from healthvaultlib.utils.xmlutils import XmlUtils from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem class AppspecificInformation(HealthRecordItem): def __init__(self, thing_xml=None): super(AppspecificInformation, self).__init__() self.type_id = 'a503...
if thing_xml is not None: self.thing_xml = thing_xml self.parse_thing() def __str__(self): return 'AppspecificInformation' def parse_thing(self): super(AppspecificInformation, self).parse_thing() xmlutils = XmlUtils(self.thing_xml) def write_xml(self): ...
tion, self).write_xml() data_xml = etree.Element('data-xml') appspecificinformation = etree.Element('appspecificinformation') data_xml.append(appspecificinformation) thing.append(data_xml) return thing
abel-von/commons
src/python/twitter/common/decorators/threads.py
Python
apache-2.0
5,130
0.006433
# ================================================================================================== # Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
method): """Simple decorator to expose Linux thread-IDs on an object. On Linux, each thread (aka light-weight process) is represented by a unique thread ID, an integer in the same namespace as process IDs. (This is distin
ct from the opaque identifier provided by the pthreads interface, which is essentially useless outside the context of the pthreads library.) This decorator provides a means to expose this thread ID on Python objects - most likely, subclasses of threading.Thread. The benefit of this is that operating-system level ...
i3thuan5/gi2_liau7_khoo3
語料庫/apps.py
Python
mit
1,078
0
from os.path import join from tempfile import TemporaryDirectory from django.apps import AppConfig from 臺灣言語工具.語音辨識.聲音檔 import 聲音檔 from 臺灣言語工具.系統整合.程式腳本 import 程式腳本 class 語料庫Config(AppConfig): name = '語料庫' def ready(self): with TemporaryDirectory() as 資料夾: 檔名 = join(資料夾, 'audio.wav') ...
as 檔案: 檔案.write(音檔.wav格式資料()) try: 程式腳本._走指令(['normalize-audio', 檔名]) except RuntimeError: raise OSError( '請裝normalize-audio!! ' '`sudo apt-get in
stall normalize-audio`' ) try: 程式腳本._走指令(['sox', 檔名, '-t', 'wav', '/dev/null', 'remix', '1'],) except RuntimeError: raise OSError('請裝sox!! `sudo apt-get install sox`')
ionelmc/python-tblib
tests/examples.py
Python
bsd-2-clause
251
0
def func_a(_): func_b() def func_b(): func_c() def func_c(): func_d
() def func_d(): raise Exception("Guessing time !") def bad_syntax(): import badsyntax badsyntax def bad_module():
import badmodule badmodule
sparkslabs/kamaelia_
Sketches/RJL/Util/Lagger.py
Python
apache-2.0
1,090
0.010092
# -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "Lic...
w.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and #...
er(component): def __init__(self, sleeptime = 0.01): super(Lagger, self).__init__() self.sleeptime = sleeptime def main(self): while 1: yield 1 sleep(self.sleeptime)
txsl/mail-trends
jwzthreading.py
Python
apache-2.0
10,294
0.003497
"""jwzthreading.py Contains an implementation of an algorithm for threading mail messages, as described at http://www.jwz.org/doc/threading.html. To use: Create a bunch of Message instances, one per message to be threaded, filling in the .subject, .message_id, and .references attributes. You can use the .messa...
st): set = {} return [set.setdefault(e,e) for e in alist if e not in set.keys()] msgid_pat = re.compile('<([^>]+)>') restrip_pat = re.compile("""( (Re(\[\d+\])?:) | (\[ [^]]+ \]) \s*)+ """, re.I | re.VERBOSE) def make_message (msg): """(msg:rfc822.Message) : Message Create a Message object for threa...
rror("Message does not contain a Message-ID: header") new.message_id = m.group(1) # Get list of unique message IDs from the References: header refs = msg.get("References", "") new.references = msgid_pat.findall(refs) new.references = uniq(new.references) new.subject = msg.get('Subject', "No su...
AIFDR/inasafe-django
django_project/realtime/templatetags/__init__.py
Python
bsd-2-clause
108
0
# coding=
utf-8 __author__ = 'Rizky Maulana Nugraha "lucernae" <l
ana.pcfre@gmail.com>' __date__ = '02/09/15'
progwriter/tmgen
src/tmgen/inject/__init__.py
Python
mit
1,005
0.000995
# coding=utf-8 from abc import abstractmethod, ABCMeta from tmgen import Tr
afficMatrix class InjectorBase(object): __metaclass__ = ABCMeta def __init__(self, tm_fname, epoch_length, ID, destinations): """ Create a new traffic injector :param tm_fname: the traffic matrix filename :param epoch_length: length of a single epoch, in seconds :para...
s strings) """ self.epoch_length = epoch_length self.ID = ID self.destinations = destinations self._load_tm(tm_fname) def _load_tm(self, tm_fname): """ Load the traffic matrix from disk :param tm_fname: the TM fileame (file must be in pickle format) ...
facoy/facoy
IndexerByFuncs/Method_Extractor.py
Python
apache-2.0
4,944
0.005866
# -*- coding: utf-8 -*- import sys sys.path.append("/Libs/jython-standalone-2.7.0.jar") sys.path.append("/Libs/mysql-connector-java-5.1.22-bin.jar") import codecs import os # import pathlib from GitSearch.DBManager_IJA import DBManager # source_path = '/Users/Falcon/Desktop/IJA/Original_data/' # dest_path = '/Users/...
start_end id_list.
append(id) project_path = dest_path + str(project) if not os.path.exists(project_path): os.makedirs(project_path) file_path = project_path + "/" + str(name.split('.')[0]) if not os.path.exists(file_path): os.makedirs(file_path) id_path = file_path + "/"...
angoraking/hcomic-project
hcomic/manage.py
Python
mit
6,153
0.004982
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载后的漫画整理模块 ==================== 请参考注释部分的整理步骤。 """ from __future__ import print_function, unicode_literals import os, re import shutil import random, string from hcomic.lib.filetool.files import WinDir, FileCollection from hcomic.lib.filetool.winzip import zip_everyt...
Success!", 1) except Exception as e: print(" Failed! Error: %s" % e) if __name__ == "__main__": from hcomic.config import DOWNLOAD_DIR, PROCESSED_DIR # 漫画整理工作流程如下 # 1. 删除工作目录下的无关Html文件, 对漫画文件夹内的文件进行重命名。 # remove_non_image_and_rename(DOWNLOAD_DI
R, sort_by="ctime") # 2. 删除不必要的封面图, 字幕组宣传图。 # 请手动删除封面图 # 3. 对漫画文件夹内的文件进行再次重命名。 # remove_non_image_and_rename(DOWNLOAD_DIR, sort_by="ctime") # 4. 添加正确的图片数量。 # correct_pic_num(DOWNLOAD_DIR) # 5. 制作漫画压缩包。 # make_archive(DOWNLOAD_DIR) # 6. 将其按照一定规则整理好。 # organize(PROCESSED_D...
mxamin/youtube-dl
youtube_dl/extractor/nuvid.py
Python
unlicense
2,587
0.002319
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( parse_duration, ) class NuvidIE(InfoExtractor): _VALID_URL = r'https?://(?:www|m)\.nuvid\.com/video/(?P<id>[0-9]+)' _TEST = { 'url': 'http://m.nuvid.com/video/1310741/', 'md5': 'eab2...
'url': thumb_url, } for thumb_url in re.findall(r'<img src="([^"]+)" alt="" />', webpage) ] thumbnail = thumbna
ils[0]['url'] if thumbnails else None duration = parse_duration(self._html_search_regex( [r'<i class="fa fa-clock-o"></i>\s*(\d{2}:\d{2})', r'<span[^>]+class="view_time">([^<]+)</span>'], webpage, 'duration', fatal=False)) return { 'id': video_id, 'title...
jainaman224/Algo_Ds_Notes
Palindrome/palindrome_no.py
Python
gpl-3.0
690
0.013043
# Python program to find whether a number is a palindrome or not # Function to reverse a number def reverse(num): # Initialize variable rev = 0 while ( num > 0 ) : dig = num % 10 rev = rev * 10 + dig num = num // 10 # Returning reversed number return rev # --- main...
) else: print("Number entered is not a palindrome!") ''' TEST CASES INPUT Enter a number:3445443 Number entered is palindrome! OUTPUT Enter a number:234 Number entered is not a pa
lindrome! '''
Dabomstew/goldenrod
commands/reloadconfig.py
Python
mit
297
0.020202
import config def execu
te(parser, bot, user, args): if not parser.checkPerms(bot, user, "owner"): return reload(config) bot.addressUser(user, "Got it, reloaded my config.") def require
dPerm(): return "owner" def canUseByWhisper(): return True
aricchen/openHR
openerp/addons/analytic/__openerp__.py
Python
agpl-3.0
1,877
0.002131
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
/>. # ############################################################################## { 'name' : 'Analytic Accounting', 'version': '1.1', 'author' : 'Ope
nERP SA', 'website' : 'http://www.openerp.com', 'category': 'Hidden/Dependency', 'depends' : ['base', 'decimal_precision', 'mail'], 'description': """ Module for defining analytic accounting object. =============================================== In OpenERP, analytic accounts are linked to general acco...
shinmorino/quant_sandbox
VS/sqaodpy_cext/gen_projects.py
Python
bsd-3-clause
2,396
0.008347
import subprocess import shutil def generate_cpu_project(project) : f = open('template_cpu.vcxproj') text = f.read() f.close() text = text.replace("@name@", project[0]) text = text.replace("@GUID@", project[1]) f = open(project[0] + ".vcxproj", 'w') f.write(text) f.close() def gene
rate_cuda_project(project) : f = open('template_cuda.vcxproj') text = f.read() f.c
lose() text = text.replace("@name@", project[0]) text = text.replace("@GUID@", project[1]) f = open(project[0] + ".vcxproj", 'w') f.write(text) f.close() config='Release' generate=True build=True copy=True # build subprocess.call('msbuild ../sqaodc/sqaodc.vcxproj /property:Configuration=' + confi...
haoyutan/MSA-Framework
modules/msa/msa/contrib/authstoken/models.py
Python
mit
2,048
0.004395
import binascii import os from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class SUser(models.Model): sid = models.CharField(_("sid"), max_length=20, pr...
dated"), auto_now=True) class Meta: verbose_name = _("SUser") verbose_name_plural = _("SUsers") @property def id(self): return '${}'.format(self.sid) def __str__(self): return self.sid @python_2_unicode_compatible class SToken(models.Model): """ The defau...
suser = models.ForeignKey( SUser, related_name='auth_stoken', on_delete=models.CASCADE, verbose_name=_("SUser") ) host = models.CharField(_("Host"), max_length=128, null=False, blank=True, default='*') created = models.DateTimeField(_("Crea...
ndsol/volcano
src/gn/toolchain/mac/get_tool_mtime.py
Python
gpl-3.0
608
0.001645
# Copyright 2016 The Chromium Authors. All rights reserved. # Copyright (c) 2017-2018 the Vo
lcano Authors. All rights reserved. # Licensed under the GPLv3. import os import sys # Usage: python get_tool_mtime.py path/to/file1.py path/to/file2.py # # Prints a GN scope with the variable name being the basename sans-extension # and the value being the file modification time. A variable is emitted
for # each file argument on the command line. if __name__ == '__main__': for f in sys.argv[1:]: variable = os.path.splitext(os.path.basename(f))[0] print('%s = %d' % (variable, os.path.getmtime(f)))
craigyk/pystar
frames.py
Python
mit
1,984
0
from collections import OrderedDict as odict from values import decode_kv_pairs, encode_kv_pairs from loops import decode_loops, encode_loops def split_frames(lines): '
'' splits a list of lines into lines that are not part of a frame, and a list of lines, where each list is part of the same frame. frames sta
rt with a `save_` and end with a `stop_`. They also end with the next data block, but this function is only called with lines from a single data block. ''' def parse_frame_name(line): return line.split()[0][len('save_'):] def frame_starts(line): return line.startswith('save_') ...
dcramer/django-db-log
djangodblog/helpers.py
Python
bsd-3-clause
9,425
0.002546
from django.conf import settings from django.template import (Template, Context, TemplateDoesNotExist, TemplateSyntaxError) from django.utils.encoding import smart_unicode from django.utils.hashcompat import md5_constructor from django.views.debug import ExceptionReporter class ImprovedExceptionReporter(ExceptionR...
unicode_hint = smart_unicode(unicode_str[max(start-5, 0):min(end+5, len(unicode_str))], 'ascii', errors='replace') t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template') c = Context({ 'exception_type': self.exc_type.__name__, 'exception_value': smart_unicode(self.e...
uest, 'template_info': self.template_info, 'template_does_not_exist': self.template_does_not_exist, }) return t.render(c) def construct_checksum(error): checksum = md5_constructor(str(error.level)) checksum.update(error.class_name or '') message = error.traceback or ...
google/pymql
test/best_hrid_test.py
Python
apache-2.0
3,260
0.007362
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
tEquals(self.mql_result.result["create"], "created") return self.mql_result.result["guid"] def query_assert(self, q, r, exc_response=None, type="mqlread", asof=None): self.env = {} if asof is not None: self.env["as_of_time"] = asof self.DoQuery(q, exp_respons
e=r, exc_response=exc_response) def test_missing_hrid(self): """Test that MQL still finds an id even if best_hrid is not present""" q= '{"id":null, "guid":"#9202a8c04000641f8000000000092a01", "mid":null}' r= ('{"guid": "#9202a8c04000641f8000000000092a01",' '"id": "/en/sting","mid":"/m/0lbj1"}') ...
zorroz/microblog
flask/lib/python2.7/site-packages/sqlparse/engine/grouping.py
Python
bsd-3-clause
11,428
0
# -*- coding: utf-8 -*- # # Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com # # This module is part of python-sqlparse and is released under # the BSD License: https://opensource.org/licenses/BSD-3-Clause from sqlparse import sql from sqlparse import tokens as T from sqlparse.utils import recurse, imt T_NUM...
) def valid_next(token): # issue261, allow invalid next token return True def post(tlist, pidx, tidx, nidx): # next_ validation is being performed here. issue261 sqlcls = sql.SquareBrackets, sql.Function ttypes = T.Name, T.String.Symbol, T.Wildcard next_ = tlist...
x is not None else None valid_next = imt(next_, i=sqlcls, t=ttypes) return (pidx, nidx) if valid_next else (pidx, tidx) _group(tlist, sql.Identifier, match, valid_prev, valid_next, post) def group_as(tlist): def match(token): return token.is_keyword and token.normalized == 'AS' ...
BackwardSpy/leaderboard
app/urls.py
Python
mit
645
0
from django.conf.urls import url from django.contrib.auth import views as auth_views from app.views import IndexView, RegisterView, UserProfileView urlpatterns = [ url(r'^$', IndexView.as_view(), name='in
dex'), url(r'^register/$', RegisterView.as_view(), name='register'), url(r'^login/$', auth_views.login, {'template_name': 'login.djhtml'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'), url(r'^us...
iew.as_view(), name='user-profile'), ]
JASchilz/AnkiSyncDuolingo
duolingo_sync/duolingo_model.py
Python
mit
1,630
0.004908
from aqt.utils import askUser, showInfo _field_names = ["Gid", "Gender", "Source", "Target", "Target Language", "Pronunciation"] _model_name = "Duolingo Sync" def create_model(mw): mm = mw.col.models m = mm.new(_(_model_name)) for field_name in _field_names: fm = mm.newField(_(field_name)) ...
if field_name not in mw.col.models.fieldNames(m)] if fields_to_add: showInfo(""" <p>The Duolingo Sync plugin has recently bee
n upgraded to include the following attributes: {}</p> <p>This change will require a full-sync of your card database to your Anki-Web account.</p> """.format(", ".join(fields_to_add))) for field_name in fields_to_add: pass fm = mw.col.models.newField(_(field_name)) ...
silverjack3303/hackerrank
fibonacci_modified.py
Python
apache-2.0
179
0.050279
f=[] x=raw_input() x=x.split(' ') a
=int(x[0]) b=int(x[1]) n=int(x[2]) print n f.append(a) f.append(b) for i in xrange(2,n): f.append(f[i-1]**2+f[i-2]) print f[n-1]
h4ck3rm1k3/gcc-ontology
lib/ontologies/com/usefulinc/ns/__init__.py
Python
gpl-3.0
32
0.0625
#lib/ontologies/com/
usefulinc/ns
gasbasd/tgapp-stroller2
sample-ecommerce/sample_ecommerce/config/ecommerce_hooks.py
Python
mit
2,901
0.005519
# coding=utf-8 from __future__ import unicode_literals import tw2.forms as twf import tw2.core as twc from tg.i18n import lazy_ugettext as l_ class EditOrderForm(twf.ListForm): css_class = 'admin-form' order_id = twf.HiddenField(key='_id') bill = twf.HiddenField(validator=twc.BoolValidator()) class S...
a: [('IT', l_('Stato'))])) class Details(twf.ListFieldSet): label = None key = 'details' emai
l = twf.TextField(validator=twc.Validator(required=True), css_class="form-control", label=l_("Email")) phone = twf.TextField(validator=twc.Validator(), css_class="form-control", label=l_("Telefono")) class BillInfo(twf.ListFieldSet): label = l_("Dati Fatturazione") ...
joopert/home-assistant
homeassistant/components/wemo/config_flow.py
Python
apache-2.0
459
0
"""Config flow for We
mo.""" import pywemo from homeassistant.helpers import config_entry_flow from homeassistant import config_entries from . import DOMAIN async def _async_has_devices(hass): """Return if there are devices that can be discovered.""" return bool(await hass.async_add_executor_job(pywemo.discover_devices)) conf...
)
mdoucet/reflectivity_ui
reflectivity_ui/interfaces/generated/ui_smooth_dialog.py
Python
apache-2.0
13,216
0.001286
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'designer/ui_smooth_dialog.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): D...
bel_11") self.gridLayout
.addWidget(self.label_11, 3, 2, 1, 1) spacerItem1 = QtWidgets.QSpacerItem(20, 15, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Maximum) self.gridLayout.addItem(spacerItem1, 13, 3, 1, 1) self.buttonBox = QtWidgets.QDialogButtonBox(self.widget) self.buttonBox.setOrientation(QtCore....
dimkal/mne-python
mne/dipole.py
Python
bsd-3-clause
23,401
0.000043
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # # License: Simplified BSD import numpy as np from scipy import linalg from copy import deepcopy import re from .cov import read_cov, _get_whitener_data from .io.constants import FIFF from .io.pic...
ct): """Dipole class Used to store positions, orientations, amplitudes, times, goodness of fit
of dipoles, typically obtained with Neuromag/xfit, mne_dipole_fit or certain inverse solvers. Parameters ---------- times : array, shape (n_dipoles,) The time instants at which each dipole was fitted (sec). pos : array, shape (n_dipoles, 3) The dipoles positions (m). amplit...
Ebiroll/qemu_esp32
examples/41_http_server/scripts/client.py
Python
apache-2.0
6,113
0.001309
#!/usr/bin/env python # # Copyright 2018 Espressif Systems (Shanghai) PTE LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
eader-2":"Test-Value-2"} verbose_print(verbosity, "Sending GET to URI : ", uri) verbose_print(verbosity, "Sending additional headers : ") for k, v in test_headers.items(): verbose_print(verbosity, "\t", k, ": ", v) sess.request("GET", url=uri, headers=test_headers) resp = sess
.getresponse() resp_hdrs = resp.getheaders() resp_data = resp.read().decode() try: if resp.getheader("Custom-Header-1") != "Custom-Value-1": return False if resp.getheader("Custom-Header-2") != "Custom-Value-2": return False except Exception: return False ...
edx-solutions/projects-edx-platform-extensions
edx_solutions_projects/management/commands/fix_existing_groups_cohorts.py
Python
agpl-3.0
2,252
0.002664
from django.core.management.base import BaseCommand from edx_solutions_api_integration.courseware_access import get_course_key from openedx.core.djangoapps.course_groups.models import CourseUserGroup, CohortMembership class Command(BaseCommand): help = "Cohort fixation of specific courses" def add_arguments...
'user_id', 'course_user_group_id' ) total_fixed_members
= 0 GroupUserModel = CourseUserGroup.users.through._meta.model for user_id, course_user_group_id in memberships: member, created = GroupUserModel.objects.get_or_create( courseusergroup_id=course_user_group_id, user_id=user_id ) ...
robclewley/compneuro
Ch6_4_old.py
Python
bsd-3-clause
1,528
0.009162
# Example from Ch. 6.4 from __future__ import division from WC_net import * from PyDSTool.Toolbox.phaseplane import * builder = rate_network() S = thresh_Naka_Rushton_fndef(2, 120, 100, with_if=Fa
lse) builder.a
dd_neuron('E1', tau=20, ic=15, thresh_fn=S) builder.add_neuron('E2', tau=20, ic=25, thresh_fn=S) builder.add_syn_input_to_neuron('E1', 'E2', 3) builder.add_syn_input_to_neuron('E2', 'E1', 3) net = builder.make_network() net.set(tdata=[0,300], algparams={'init_step': 0.5}) traj = net.compute('test') pts = traj...
capuccinatore/krobot
krobot/mail.py
Python
mit
1,324
0.02568
#http://stackoverflow.com/questions/882712/sending-html-email-using-python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class MailAgent(object): """docstring for MailAgent""" def __init__(self, mail, smtp, pseudo, passw): super(MailAgent, self).__init__() s...
er - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = self.mail msg['To'] = dest # Create the body of the message (a plain-text and an HTML version). html = "<html><head></head><body>{0}</body></html>".format(text) # Record the MIME...
rt1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mail =...
etrombly/snort-rule-tool
snort-rule-tool.py
Python
gpl-3.0
14,091
0.003761
#!/usr/bin/env python2 import sys import math from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore from mainwindow import Ui_MainWindow from scapy.all import * """ dump any string, ascii or encoded, to formatted hex output """ def dumpString(src, length=16): FILTER = ''.join([(len(repr(chr...
t = syn[TCP].dport L3 = IP try: #try underlayer
foot = syn[TCP].underlayer srcip = foot.src dstip = foot.dst if type(foot) == IPv6: L3 = IPv6 except: #try other, but upper layer if IPv6 in...
ronaldahmed/labor-market-demand-analysis
preprocessing/doc_majors_map.py
Python
mit
1,522
0.025641
""" GENERATE DOC: [MAJORS] csv/tsv for R processing """ import os, sys import pymongo from pymongo import MongoClient import json import ipdb BASE_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ) counts_dir = os.path.join(BASE_DIR,'dataR/counts') ne_counts = os.path.join(counts_d...
s(open('hierarchy/carreras.json','r').read()) fileByName = {} for k,v in temp.items(): fileByName[v]=k ######################################################################### if __name__ == '__main__': major_eng = [] for level1 in hierarchy["children"]: if level1["name"]=='Ingeniería': for career in level1...
= [line.strip('\n') for line in open(os.path.join(curr_count,'title_map.dat')) if line.strip('\n')!=''] majors_by_doc = open(os.path.join(curr_count,'majors_by_doc.dat'),'w') for doc_name in title_map: p = db.prueba.find_one({'name':doc_name}) majors = [a for a in p['carreras'] if a in major_eng] majors_by_do...
suriya/rasikapriya
rasikapriya/sitemaps.py
Python
mit
770
0.005195
from django.contrib.sitemaps import Sitemap from .models import Concert, Artist, Venue class ConcertSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Concert.objects.all() def lastmod(self, obj): return obj.modify_date class ArtistSiteMap(Sitemap): ch...
): changefreq = "daily" priority = 0.5 def items(self): return Venue.objects.all() def lastmod(self, obj): return obj.modify_date site
maps = { 'concert': ConcertSitemap, 'artist': ArtistSiteMap, 'venue': VenueSiteMap, }
edx/ecommerce
ecommerce/extensions/catalogue/tests/test_migrate_course.py
Python
agpl-3.0
13,728
0.002841
# coding=utf-8 import datetime import json import logging from decimal import Decimal from urllib.parse import urlparse import httpretty import mock import pytz from django.core.management import call_command from django.test import override_settings from oscar.core.loading import get_model from testfixtures import ...
JSON = 'application/json' EDX_API_KEY = ACCESS_TOKEN = 'edx' EXPIRES = datetime.datetime(year=1985, month=1
0, day=26, hour=1, minute=20, tzinfo=pytz.utc) EXPIRES_STRING = EXPIRES.strftime(ISO_8601_FORMAT) LOGGER_NAME = 'ecommerce.extensions.catalogue.management.commands.migrate_course' logger = logging.getLogger(__name__) Category = get_model('catalogue', 'Category') Product = get_model('catalogue', 'Product') StockRecord...
UM-ARM-Lab/arc_utilities
tests/test_conversions.py
Python
bsd-2-clause
681
0.001468
import unittest
from arc_utilities.conversions import parse_file_size class TestConversions(unittest.TestCase): def test_parse_file_size(self):
self.assertEqual(parse_file_size('1'), 1) self.assertEqual(parse_file_size('12.2'), 12) self.assertEqual(parse_file_size('1k'), 1_000) self.assertEqual(parse_file_size('1.2mB'), 1_200_000) self.assertEqual(parse_file_size('1Gb'), 1_000_000_000) self.assertEqual(parse_file_...
beeftornado/sentry
src/sentry/models/savedsearch.py
Python
bsd-3-clause
2,419
0.000827
from __future__ import absolute_import, print_function from django.db import models from django.utils import timezone from sentry.db.models import FlexibleForeignKey, Model, sane_repr from sentry.models.search_common import SearchType class SavedSearch(Model): """ A saved search query. """ __core__...
y("sentry.Organization", null=True) type = models.PositiveSmallIntegerField(default=SearchType.ISSUE.value, null=True) name = models.CharField(max_length
=128) query = models.TextField() date_added = models.DateTimeField(default=timezone.now) # TODO: Remove this column once we've completely removed Sentry 9 is_default = models.BooleanField(default=False) is_global = models.NullBooleanField(null=True, default=False, db_index=True) owner = Flexible...
cloudbau/glance
glance/store/sheepdog.py
Python
apache-2.0
10,437
0.000096
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Taobao Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/lic...
port glance.store.base import glance.store.location LOG = logging.getLogger(__name__) DEFAULT_ADDR = 'localhost' DEFAULT_PORT = '7000' DEFAULT_CHUNKSIZE = 64 # in MiB LOG = logging.getLogger(__name__) sheepdog_opts = [ cfg.IntOpt('sheepdog_store_chunk_size', default=DEFAULT_CHUNK
SIZE, help=_('Images will be chunked into objects of this size ' '(in megabytes). For best performance, this should be ' 'a power of two.')), cfg.StrOpt('sheepdog_store_port', default=DEFAULT_PORT, help=_('Port of sheep daemon.')), cfg.St...
ddsnowboard/FantasyStocks
fantasyStocks/stocksApi/migrations/0001_initial.py
Python
apache-2.0
996
0.004016
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2017-04-05 23:08 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import stocksApi.models class Migration(migrations.Migration): initial = True dependenci...
SessionId', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('id_string', models.CharField(default=stocksApi.models.generateRandomId, max_length=64, unique=True)), ('exp_date', models.DateTimeField(de...
irationDate)), ('associated_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
lmiphay/gentoo-oam
oam/fact/checkconfig.py
Python
gpl-2.0
450
0.008889
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import os import click from oam.facts import facts from oam.checkconfig import
CheckConfig def fact(day=None): """Return a list configuration problems""" return { 'check_config': [ x for x in CheckConfig().its() ] } @facts
.command() def checkconfig(): """Print list of configuration problems""" print(fact()['check_config']) return 0
YzPaul3/h2o-3
h2o-py/tests/testdir_hdfs/pyunit_INTERNAL_HDFS_kmeans.py
Python
apache-2.0
1,878
0.015974
from __future__ import print_function import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils #---------------------------------------------------------------------- # Purpose: This tests k-means on a large dataset. #----------------------
------------------------------------------------ def hdfs_kmeans(): # Check if we are running inside the H2O network by seeing if we can touch # the namenode. hadoop_namenode_is_accessible = pyunit_utils.hadoop_namenode_is_accessible() if hadoop_namenode_is_accessible: hdfs_name_node...
rint("Import iris_wheader.csv from HDFS") url = "hdfs://{0}{1}".format(hdfs_name_node, hdfs_iris_file) iris_h2o = h2o.import_file(url) n = iris_h2o.nrow print("rows: {0}".format(n)) assert n == 150, "Wrong number of rows. Got {0}. Should have got {1}".format(n, 150) prin...
hashbrowncipher/pushmanager
pushmanager/tests/test_core_git.py
Python
apache-2.0
8,866
0.00485
# -*- coding: utf-8 -*- from contextlib import contextmanager from contextlib import nested import copy import os import mock from pushmanager.core import db from pushmanager.core.settings import Settings from pushmanager.testing.mocksettings import MockedSettings import pushmanager.core.git import pushmanager.testin...
%s.pushmanager.core.git.GitQueue.update_request_successful" % __name__), # This will fail, stop logging errors mock.patch("%s.pushmanager.core.git.logging.error" % __name__), mock.patch( "%
s.pushmanager.core.git.GitQueue._get_request_with_sha" % __name__, return_value = {'id': 10, 'state': 'requested'} ), self.mocked_update_request(self.fake_request, self.fake_request) ): # GitQueue._get_request_with_sha returning a value means # we ...
ChantyTaguan/zds-site
zds/tutorialv2/views/editorialization.py
Python
gpl-3.0
4,855
0.002687
from django.contrib import messages from django.core.exceptions import PermissionDenied from django.shortcuts import get_obje
ct_or_404, red
irect from django.utils.translation import gettext_lazy as _ from zds.member.decorator import LoggedWithReadWriteHability from zds.tutorialv2.forms import RemoveSuggestionForm, EditContentTagsForm from zds.tutorialv2.mixins import SingleContentFormViewMixin from zds.tutorialv2.models.database import ContentSuggestion,...
goozbach/ansible
test/units/module_utils/basic/test_heuristic_log_sanitize.py
Python
gpl-3.0
3,908
0.001535
# -*- coding: utf-8 -*- # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (a...
return hostvars def test_did_not_hide_too_much(self): self.assertEquals(heuristic_log_sanitize(self.clean_data), self.clean_data) def test_hides_url_secrets(self): url_output = heuristic_log_sanitize(self.url_data) # Basic functionality: Successfully hid the password self.as...
ementation we replace the password with 8 "*" which is # also the length of our password. The url fields should be able to # accurately detect where the password ends so the length should be # the same: self.assertEqual(len(url_output), len(self.url_data)) def test_hides_ssh_secret...
kimiscircle/fdfs_client-py
fdfs_client/fdfs_test.py
Python
gpl-3.0
13,799
0.001015
#!/usr/bin/env python # -*- coding: utf-8 -*- # filename: fdfs_test.py import os, sys, time try: from fdfs_client.client import * from fdfs_client.exceptions import * except ImportError: import_path = os.path.abspath('../') sys.path.append(import_path) from fdfs_client.client import * from fdf...
on fdfs_test.py listgroup {group_name} if len(sys.argv) < 3: usage() return None try: group_name = sys.argv[2] ret = client.list
_one_group(group_name) print(ret) except (ConnectionError, ResponseError, DataError) as e: print(e) def listall_func(): # List all group info # usage: python fdfs_test.py listall if len(sys.argv) < 2: usage() return None try: ret_dict = client.list_all_group...
valbertovc/blog_django_bootstrap_ajax
core/admin.py
Python
mit
481
0.006237
# -*- coding:utf8
-*- from __future__ import unicode_literals from django.contrib import admin from core.models import Post from core.models import Category from core.models import Comment from core.models import Tag from core.forms import PostForm @admin.register(Post) class PostAdmin(admin.ModelAdmin): # raw_id_fields = ('tags',...
ister(Tag)
sqzr1/Getter-Setter-Generator
tests/regression_test_samples/python/cgiPractice.py
Python
gpl-3.0
222
0.004505
#!/usr/b
in/env python import sys import cgi contentTemplate = "Content-Type: text/html \n" openingPageTemplate = """ <html> <head> <style type="text/css"> </style> </head> <body> </body> </
html> """
smillerpy/timeline
timeline/users/models.py
Python
bsd-3-clause
701
0.001427
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.cont
rib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do n...
def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username})
D4wN/brickv
src/brickv/plugin_system/plugins/red/program_wizard_new.py
Python
gpl-2.0
7,091
0.005219
# -*- coding: utf-8 -*- """ RED Plugin Copyright (C) 2014 Matthias Bolte <matthias@tinkerforge.com> Copyright (C) 2014 Olaf Lüke <olaf@tinkerforge.com> program_wizard_new.py: New Program Wizard This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as...
rogramPageArguments from brickv.plugin_system.plugins.red.program_p
age_stdio import ProgramPageStdio from brickv.plugin_system.plugins.red.program_page_schedule import ProgramPageSchedule from brickv.plugin_system.plugins.red.program_page_summary import ProgramPageSummary from brickv.plugin_system.plugins.red.program_page_upload import ProgramPageUpload class ProgramWizardNew(Program...
urosjarc/maestro
maestro/core/exc.py
Python
mit
301
0.036545
class Error(Exception): """Generic errors.""" def __init__(self, msg: str) -> None: Exception.__init__(self) self.msg = msg def __str__(self): return self.msg class ConfigError(Error): """Config related errors.""" pas
s class RuntimeError(Erro
r): """Generic runtime errors.""" pass
SirAnthony/nagu
tests.py
Python
mit
2,974
0.004371
#!/usr/bin/python # -*- coding: utf-8 -*- from nagu import (get_color, pack_color, pack, reset, sequence, parse_line, html) def test_get_color(): """ >>> assert get_color(0) == "" >>> assert get_color(13) == "color: #ff0;" >>> assert get_color(64) == 'background-color: #ff0;' >>> assert ge...
olor(30, 0) == 14 >>> assert pack_color(44, 14) == 158 >>> assert pack_color(36, 158) == 148 >>> assert pack_color(39, 148) == 144 >>> assert pack_color(49, 144) == 0 """ pass def test_pack(): """ >>
> assert pack(0, 0) == 0 >>> assert pack(30, 0) == 14 >>> assert pack(1, 14) == 270 >>> assert pack(4, 270) == 1294 >>> assert pack(21, 1294) == 1038 >>> assert pack(39, 1038) == 1024 >>> assert pack(24, 1024) == 0 """ pass def test_reset(): """ >>> assert reset() is None >>...
tseaver/google-cloud-python
vision/google/cloud/vision_v1/types.py
Python
apache-2.0
2,229
0
# -*- co
ding: utf-8 -*- # # Copyright 2019
Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distri...
astroScott/TeachingUtilities
seat_randomizer.py
Python
gpl-2.0
1,374
0.017467
import classutils from random import shuffle class _Seat(object): def __init__(self,table,seat,student): self.table = table self.seat = seat self.student=student def __str__(s
elf): return s
tr(self.student) def seat_randomizer(section,tables,seats, filename=None, msg=None): """ randomize students. input: section number list of student instances output: None, but produces formatted txt file to be used as seating chart """ if filename is None: filena...
dretta/EmbassyEmergency
finder/migrations/0003_auto_20170309_2010.py
Python
agpl-3.0
634
0.001577
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-03-10 03:1
0 from __future__ import unicode_literals from django.db import migrations, models import
finder.models class Migration(migrations.Migration): dependencies = [ ('finder', '0002_auto_20170303_0253'), ] operations = [ migrations.AlterField( model_name='country', name='code', field=models.CharField(max_length=2, primary_key=True, serialize=Fal...
alexzatsepin/omim
tools/python/ResponseProvider.py
Python
apache-2.0
7,364
0.007333
from __future__ import print_function import jsons import logging import os BIG_FILE_SIZE = 47684 class Payload: def __init__(self, message, response_code=200, headers={}): self.__response_code = response_code self.__message = message self.__headers = headers def respo...
200 def pong(self): self.delegate.got_pinged()
return Payload("pong") def my_id(self): return Payload(str(os.getpid())) def strip_query(self, url): query_start = url.find("?") if (query_start > 0): return url[:query_start] return url def response_for_url_and_headers(self, url, headers): sel...
csparpa/pyowm
tests/unit/agroapi10/test_imagery.py
Python
mit
6,355
0.006766
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from da
tetime import datetime from unittest.mock import patch from pyowm.commons.image import Image, ImageTypeEnum from pyowm.agroapi10.enums import PresetEnum, SatelliteEnum from pyowm.agroapi10.imagery import MetaImage, SatelliteImage class TestMetaImage(unittest.TestCase): test_acquisition_time = 1378459200 tes...
e) test_instance = MetaImage('http://a.com', PresetEnum.FALSE_COLOR, SatelliteEnum.SENTINEL_2.name, test_acquisition_time, 98.2, 0.3, 11.7, 7.89, polygon_id='my_polygon', stats_url='http://stats.com') def test_init_fails_with_wrong_parameters(self): ...
SciTools/iris
lib/iris/cube.py
Python
lgpl-3.0
164,190
0.000207
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """ Classes for representing multi-dimensional data with metadata. """ from collections import OrderedDict from collections....
beList, and return it. Raise an error if the extract produces no cubes, or more than one. Args: * constraint (:class:`~iris.Constraint`): The constraint to extract with. .. see also:: :meth:`~iris.cube.CubeList.extract` """ # Just validate this...
rict=True, return_single_cube=True ) def extract_cubes(self, constraints): """ Extract specific cubes from a CubeList, one for each given constraint. Each constraint must produce exactly one cube, otherwise an error is raised. Args: * constraints (iterable ...
masashi-y/depccg
depccg/allennlp/predictor/parser_predictor.py
Python
mit
3,044
0.000329
from typing import Dict, Any, List, Optional import numpy from allennlp.common.util import JsonDict from allennlp.data import DatasetReader from allennlp.models import Model from allennlp.predictors.predictor import Predictor import depccg.parsing from depccg.types import ScoringResult, Token from depccg.allennlp.pre...
self.apply_binary_rules, self.apply_unary_rules, self.category_dict, self.root_categories, ) = read_params( grammar_json_path, disable_category_dictionary, disable_seen_rules ) self.parsing_kwargs = parsing_kwargs or {} ...
Dict]: categories = None score_results = [] doc = [] for output_dict in super()._make_json(output_dicts): if categories is None: categories = [ Category.parse(category) for category in output_dict['categories'] ...
Walt280/cosmos
code/computational_geometry/2d_line_intersection/line.py
Python
gpl-3.0
1,392
0.02658
# computational geometry | 2D line intersecton | Python def parallel_int(verticeX,verticeY): k = (verticeY[2]-verticeY[0])*(verticeX[1]-verticeX[0]) - (verticeX[2]-verticeX[0])*(verticeY[1]-verticeY[0]) if k==0: return "infinite" else: return "no" def line_int(verticeX,verticeY): x12 = verticeX[0]-verticeX[1] ...
-point form of each line") X.append(float(input("X of point 1, line 1: "))) Y.append(float(input("Y of point 1, line 1: "))) X.append(float(input("X of point 2
, line 1: "))) Y.append(float(input("Y of point 2, line 1: "))) X.append(float(input("X of point 1, line 2: "))) Y.append(float(input("Y of point 1, line 2: "))) X.append(float(input("X of point 2, line 2: "))) Y.append(float(input("Y of point 2, line 2: "))) intersectn = line_int(X,Y) if intersectn[0]=="NoInt": pr...
jmiserez/sts
tests/unit/sts/socket_multiplexer_test.py
Python
apache-2.0
4,969
0.013685
# Copyright 2011-2013 Colin Scott # Copyright 2011-2013 Andreas Wundsam # # 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...
bug("waiting for socket %s in rl %s..." % ( str(mock_sock), repr(rl))) last = time.time() (rl, _, _) = mux_select.select([mock_sock], [], []) time.sleep(0.05) d = mock_sock.recv(2048) # order should be deterministic self.assertEqual(self.client_messages[i], d) ...
if ServerSocketDemultiplexer.instance is not None: ServerSocketDemultiplexer.instance = None try: os.unlink(address) except OSError: if os.path.exists(address): raise RuntimeError("can't remove PIPE socket %s" % str(address))
hronellenfitsch/nesting
cycle_basis.py
Python
mit
11,955
0.002008
#!/usr/bin/env python """ cycle_basis.py functions for calculating the cycle basis of a graph """ from numpy import * import networkx as nx import matplotlib import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.path import Path if matplotlib.__version__ >= '1.3.0': from matplotlib.p...
areas = sorted(areas, reverse=True) total_area = areas[0] - sum(areas[1:]) else: total_area = areas[0] return list(chain.from_iterable( sorted(component_sorted_edges, key=len, reverse=True))), \ total_area def intersection(self, other): ...
n(other.edgeset) return inters def union(self, other, data=True): """ Returns the edge set corresponding to the union of two cycles. Will overwrite edge/vertex attributes from other to this, so only use if both cycle graphs are the same graph! """ union = self.edges...
piotr1212/whisper
contrib/update-storage-times.py
Python
apache-2.0
7,256
0.000965
#!/usr/bin/env python # @package update_storage_schemas.py # Correct/Update storage schemas\n # @code # # Usage example for update_storage_schemas.py # sudo ./update_storage_schemas.py --path /opt/graphite/whisper --cfg /opt/graphite/conf/schemas # @endcode import sys import os import logging import subprocess imp...
G: LOG.info("Created command: %s" % command_string) if _compare_retention(retention, metric): LOG.debug('%s has the same retention as before!' % metric) return [(False, metric)] if DRY_RUN: res = 0 else: LOG.debug('Retention will be %s' % retention) # record...
st = os.stat(metric) if DEBUG: res = subprocess.check_call(command_string) else: res = subprocess.check_call(command_string, stdout=devnull) os.chmod(metric, st.st_mode) os.chown(metric, st.st_uid, st.st_gid) dev...
mcallaghan/tmv
BasicBrowser/scoping/migrations/0252_duplicate_created_at.py
Python
gpl-3.0
410
0
# Gener
ated by Django 2.1.2 on 2018-11-07 16:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scoping', '0251_auto_20181107_1558'), ] operations = [ m
igrations.AddField( model_name='duplicate', name='created_at', field=models.DateTimeField(auto_now_add=True, null=True), ), ]
PGower/PyCanvas
pycanvas/apis/sis_imports.py
Python
mit
28,128
0.003306
"""SisImports API Version 1.0. This API client was generated using a template. Make sure this code is valid before using it. """ import logging from datetime import date, datetime from base import BaseCanvasAPI from base import BaseModel import os class SisImportsAPI(BaseCanvasAPI): """SisImports API...
Get SIS import list. Returns the list of SIS imports for an account Example: curl 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports' \ -H "Authorization: Bearer <token>" """ path = {} data = {} params = {} # REQUIRE...
created_since """If set, only shows imports created after the specified date (use ISO8601 format)""" if created_since is not None: if issubclass(created_since.__class__, basestring): created_since = self._validate_iso8601_string(created_since) elif issubclass...
mrooney/wxbanker
wxbanker/bankobjects/account.py
Python
gpl-3.0
15,100
0.004636
#!/usr/bin/env python # # https://launchpad.net/wxbanker # account.py: Copyright 2007-2010 Mike Rooney <mrooney@ubuntu.com> # # This file is part of wxBanker. # # wxBanker is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
in. if self._preTransactions: # Iterate over this first (and thus once) since it is probably larger than _pre. for i, newT in enumerate(self._Transactions): for oldT in self._preTransactions: # Compare just IDs otherwise TDD is impo...
# will cause the objects to not be properly replaced and break tests. if oldT.ID == newT.ID: self._Transactions[i] = oldT break return self._Transactions def GetName(self): return self._Name def SetName(self, ...
ichuang/sympy
sympy/physics/quantum/tests/test_printing.py
Python
bsd-3-clause
27,828
0.008999
# -*- encoding: utf-8 -*- """ TODO: * Fix problems with Issue 2510, ascii printing using unicode * Address Issue 2251, printing of spin states """ from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.cg import CG, Wigner3j from sympy.physics.quantum.commutator import Commutator fro...
sert latex(g4) == r'U_{0}' sT(g4, "UGate(Tuple(Integer(0)),Matrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))") def test_hilbert(): h1 = HilbertSpace() h2 = ComplexSpace(2) h3 = FockSpace() h4 = L2(Interval(0,oo)) assert str(h1) == 'H' assert pretty(h1) == 'H' assert upre...
{H}' sT(h1, "HilbertSpace()") assert str(h2) == 'C(2)' ascii_str = \ """\ 2\n\ C \ """ ucode_str = \ u"""\ 2\n\ C \ """ assert pretty(h2) == ascii_str assert upretty(h2) == ucode_str assert latex(h2) == r'\mathcal{C}^{2}' sT(h2, "ComplexSpace(Integer(2))") assert str(h3) == 'F' ...
snower/TorThrift
torthrift/pool.py
Python
mit
5,311
0.001695
# -*- coding: utf-8 -*- # 14-8-19 # create by: snower import time import logging from collections import deque from tornado.ioloop import IOLoop from tornado.gen import Future from tornado.iostream import StreamClosedError from thrift.transport.TTransport import TTransportException from .transport.stream import TStrea...
am) IOLoop.current().add_future(open_future, finish) if self._idle_seconds > 0 and not self._check_idle: IOLoop.current().add_timeout(time.time() + self._idle_seconds, self.check_idle) self._check_idle = True def get_stream(self): if self._closed: raise ...
ms.pop() self._used_streams[id(stream)] = stream stream.used_time = time.time() if not stream.closed(): future.set_result(stream) return future if self._stream_count < self._max_stream: self.init_stream(future) else: ...
dbr/tvnamer
tests/test_fileparse_api.py
Python
unlicense
1,577
0
#!/usr/bin/en
v python """Tests the FileParser API """ from tvnamer.files import FileParser from tvnamer.data import EpisodeInfo, DatedEpisodeInfo, NoSea
sonEpisodeInfo from helpers import assertType, assertEquals def test_episodeinfo(): """Parsing a s01e01 episode should return EpisodeInfo class """ p = FileParser("scrubs.s01e01.avi").parse() assertType(p, EpisodeInfo) def test_datedepisodeinfo(): """Parsing a 2009.06.05 episode should return Da...
jmfranck/pyspecdata
pyspecdata/load_files/bruker_nmr.py
Python
bsd-3-clause
14,840
0.035916
from ..core import * from ..datadir import dirformat from .open_subpath import open_subpath import os.path import re import struct import numpy as np from numpy import nan bruker_data = nddata # should work by inheritance but doesn't def det_phcorr(v): if v['DIGMOD']==1: logger.debug('DIGMOD is 1') ...
fp = open_subpath(file_reference, *(subpath+('gradient_calib',)),mode='r') data.set_prop('gradient_calib', fp.read()) fp.close() if open_subpath(file_reference, *(subpath+('difflist',)), test_only=True): data.set_prop('dif
f', load_vdlist(file_reference, *subpath, **dict(name='difflist'))) else: logger.debug(strm("difflist doesn't exist",file_reference,'difflist')) logger.debug(strm('data from bruker file =',data)) #}}} return data def load_1D(file_reference, *subpath, **kwargs)...
Jamlum/pytomo
pytomo/dns/rdtypes/ANY/NSEC.py
Python
gpl-2.0
5,407
0.003329
# Copyright (C) 2004-2007, 2009, 2010 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED ...
rdlen], current) current += cused rdlen -= cused windows = [] while rdlen > 0: if rdlen < 3: raise dns_exception.FormError("NSEC too short") window = ord(wire[current]) octets = ord(wire[current + 1]) if octets == 0 or octe...
rdlen -= 2 if rdlen < octets: raise dns_exception.FormError("bad NSEC bitmap length") bitmap = wire[current : current + octets] current += octets rdlen -= octets windows.append((window, bitmap)) if not origin is None: next ...
otuk/m2
test_permuter.py
Python
mit
1,702
0.0047
import permuter from util import AppException class TestPermuter: SAMPLE_WORDS = ["aat", "eat", "istanbul", "stress", "x", "", None] SAMPLE_PERM_COUNTS = [3, 6, 40320, 120, 1, 0, 0] SAMPLE_MAX_REPEAT_COUNTS = [2, 1, 1, 3, 1, 0, 0] def setup_class(self): pass def teardown_class(self): ...
p = permuter.Permutator(word) except AppException: assert word is None or len(word) == 0, "Exception raised for a non 0-length word" continue l = p.list_permutations() assert len(l) == count, "list_permutations returns wrong number of perm
s"
GNOME/dots
dots/document.py
Python
gpl-3.0
1,096
0.010949
# Dots - A braille translation program. # # Copyright (C) 2010 Consorcio Fernando de los Rios # Author: Fernando Herrera <fherrera@onirica.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,...
ral Public License fo
r more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from translator import Translator class Document(): def __init__(self, input_file): self.input_file = input_file self.braille_text = None self.out...
kumar303/rockit
vendor-local/boto/gs/acl.py
Python
bsd-3-clause
10,641
0.002537
# Copyright 2010 Google Inc. # # 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, publish, dis- # trib...
from boto.exception import InvalidAclError ACCESS_CONTROL_LIST = 'AccessControlList' ALL_AUTHENTICATED_USERS = 'AllAuthenticatedUsers' ALL_USERS = 'AllUsers' DISPLAY_
NAME = 'DisplayName' DOMAIN = 'Domain' EMAIL_ADDRESS = 'EmailAddress' ENTRY = 'Entry' ENTRIES = 'Entries' GROUP_BY_DOMAIN = 'GroupByDomain' GROUP_BY_EMAIL = 'GroupByEmail' GROUP_BY_ID = 'GroupById' ID = 'ID' NAME = 'Name' OWNER = 'Owner' PERMISSION = 'Permission' SCOPE = 'Scope' TYPE = 'type' USER_BY_EMAIL = 'UserByEma...
dirtycoder/pets
pets/meupet/tests/test_command_requestaction.py
Python
mit
797
0.001255
from unittest import mock from model_mommy import mommy from djan
go.conf import settings from django.core.management import call_command from django.test import TestCase from django.utils import timezone from meupet.models import Pet, PetStatus class RequestActionTest(TestCase): @staticmethod def test_requestaction(): """Command should call request_action in stale...
"" pet_status = mommy.make(PetStatus, final=False) pet = mommy.make(Pet, status=pet_status) pet.modified = timezone.now() - timezone.timedelta(days=settings.DAYS_TO_STALE_REGISTER) pet.save(update_modified=False) with mock.patch("meupet.models.Pet.request_action") as mock_method...