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
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/ttfquery/glyphquery.py
Python
lgpl-3.0
3,146
0.013986
"""Glyph-specific queries on font-files""" from ttfquery import describe try: from OpenGLContext.debug.logs import text_log except ImportError: text_log = None def hasGlyph( font, char, encoding=None ): """Check to see if font appears to have explicit glyph for char""" glyfName = explicitGlyph( font, c...
nt['OS/2'].sTypoDescender if descent > 0: descent = - descent return ascent - desce
nt def charDescent( font ): """Determine the general descent for the font (for scaling)""" return font['OS/2'].sTypoDescender
mozillazg/ShortURL
shorturl/settings.py
Python
mit
569
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import os SITE_ROOT = os.path.dirn
ame(os.path.abspath(__file__)) DEBUG = True # 调试模式 TEMPLATE_DIR = os.path.join(SITE_ROOT, 'templates') # 模板目录 BASE_TEMPLATE = 'base' # 基础模板 # URL 映射 URLS = ( '/', 'Index', '(/j)?/shorten', 'Shorten', '/([0-9a-zA-Z]{5
,})', 'Expand', '/j/expand', 'Expand', '/.*', 'Index', ) # 数据库配置 DATABASES = { 'dbn': 'mysql', 'db': 'shorturl', 'user': 'py', 'pw': 'py_passwd', 'host': 'localhost', 'port': 3306, }
sahikaru/DP
chapter1/strategymode.py
Python
gpl-2.0
1,364
0.012463
#!/usr/env python class Flyable: def fly(self): pass class Quackable(object): def quack(self): pass class ReadHeadDuckFly(Flyable): def fly(self): print "I am a readheadduck, I can fly" class ReadHeadDuckQack(Quackable): def quack(self): print "I am a readheadduck,Dc...
return self.q.quack() class Mallardduckflyable(Flyable): def fly(self): print "I am a Mallardduck....,I can fly" class MallardduckQuackble(Quackable): def quack(self): print "I am a Mallardduck,Duck.duck..duck.." class Mallardduck(Duck): def __init__(self,fl
yable,quackable): self.f = flyable self.q = quackable def fly(self): return self.f.fly() def quack(self): return self.q.quack() if __name__ == "__main__": duck = Duck() duck.swim() rhduck = ReadHeadDuck(ReadHeadDuckFly(),ReadHeadDuckQack()) rhduck.fly() ...
huntzhan/magic-constraints
magic_constraints/types.py
Python
mit
15,147
0
# -*- coding: utf-8 -*- from __future__ import ( division, absolute_import, print_function, unicode_literals, ) from builtins import * # noqa from future.builtins.disabled import * # noqa from future.utils import with_metaclass from abc import ABCMeta # collections.abc dosn't esist in Python 2.x....
subclass isn't MagicType. if not issubclass(subclass, BasicMagicType): return issubclass(subclass, cls.main_cls) # subclass is MagicType. if cls.partial_cls or subclass.partial_cls: # if subclass has partial_cls, return False. return False else: ...
n_cls, cls.main_cls) def __instancecheck__(cls, instance): return safe_getmethod(cls, 'check_instance')(instance) def __repr__(cls): name = conditional_repr(cls.main_cls) if cls.partial_cls: partial = ', '.join( map( conditional_repr, ...
thaim/ansible
lib/ansible/modules/cloud/ovirt/ovirt_vmpool_info.py
Python
mit
4,023
0.002237
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #...
sult) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth
.get('token') is None) if __name__ == '__main__': main()
ArcherSys/ArcherSys
Lib/idlelib/FormatParagraph.py
Python
mit
22,001
0.003273
<<<<<<< HEAD <<<<<<< HEAD """Extension to format a paragraph or selection to a max width. Does basic, standard text formatting, and also understands Python comment blocks. Thus, for editing Python source code, this extension is really only suitable for reformatting these comment blocks or triple-quoted strings. Known...
get_comment_header(line)==comment_header and \ not is_all_white(line[comment_header_len:]
): lineno = lineno - 1 line = text.get("%d.0" % lineno, "%d.end" % lineno) first = "%d.0" % (lineno+1) return first, last, comment_header, text.get(first, last) # This should perhaps be replaced with textwrap.wrap def reformat_paragraph(data, limit): """Return data reformatted to specified...
cvegaj/ElectriCERT
venv3/lib/python3.6/site-packages/pycoin/tx/script/errno.py
Python
gpl-3.0
1,047
0
OK = 0 UNKNOWN_ERROR = 1 EVAL_FALSE = 2 OP_RETURN = 3 # Max sizes SCRIPT_SIZE = 4 PUSH_SIZE = 5 OP_COUNT = 6 STACK_SIZE = 7 SIG_COUNT = 8 PUBKEY_COUNT = 9 # Failed verify operations VERIFY = 10 EQUALVERIFY = 11 CHECKMULTISIGVERIFY
= 12 CHECKSIGVERIFY = 13 NUMEQUALVERIFY = 14 # Logical/For
mat/Canonical errors BAD_OPCODE = 15 DISABLED_OPCODE = 16 INVALID_STACK_OPERATION = 17 INVALID_ALTSTACK_OPERATION = 18 UNBALANCED_CONDITIONAL = 19 # CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY NEGATIVE_LOCKTIME = 20 UNSATISFIED_LOCKTIME = 21 # Malleability SIG_HASHTYPE = 22 SIG_DER = 23 MINIMALDATA = 24 SIG_PUSHONLY ...
SuliacLEGUILLOU/computor
srcs/Array.py
Python
mit
575
0.001739
""" Module of mathematical array """ class Array(object): """ Multidimentionnal Array of Number """ def __init__(self): self.data = [] def add(self, target): """ Add another Array to self """ for (i, table) in enumerate(target
.data): for (j, val) in enumerate(table): self.data[i][j] += val def
sub(self, target): """ Substract another Array to self """ for (i, table) in enumerate(target.data): for (j, val) in enumerate(table): self.data[i][j] -= val
40123148/2015cdb_40123148
wsgi.py
Python
gpl-3.0
34,518
0.004126
#@+leo-ver=5-thin #@+node:2014fall.20141212095015.1775: * @file wsgi.py # coding=utf-8 # 上面的程式內容編碼必須在程式的第一或者第二行才會有作用 ################# (1) 模組導入區 # 導入
cherrypy 模組, 為了在 OpenShift 平台上使用 cherrypy 模組, 必須透過 setup.py 安裝 #@@language python #@@tabwidth -4 #@+<<declarations>> #@+node:2014fall.20141212095015.1776: ** <<d
eclarations>> (wsgi) import cherrypy # 導入 Python 內建的 os 模組, 因為 os 模組為 Python 內建, 所以無需透過 setup.py 安裝 import os # 導入 random 模組 import random # 導入 gear 模組 import gear ################# (2) 廣域變數設定區 # 確定程式檔案所在目錄, 在 Windows 下有最後的反斜線 _curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) # 設定在雲端與近端的資料儲存目錄 if 'OPENSHI...
vicnet/weboob
weboob/applications/qgalleroob/__init__.py
Python
lgpl-3.0
61
0
from .qgalleroob import QGalleroob __all
__ = ['QGalleroob'
]
martinezmizael/Escribir-con-la-mente
object/entrenarFannNormalizado.py
Python
mit
5,218
0.043887
# -*- encoding: utf-8 -*- ''' Created on: 2015 Author: Mizael Martinez ''' from pyfann import libfann from login import Login from escribirArchivo import EscribirArchivo import inspect, sys, os sys.path.append("../model") from baseDatos import BaseDatos class CtrlEntrenarRNANormalizado: def __init__(self): ...
self.__epocas def getIteracionesEntreReporte(self): return self.__iteraciones_en
tre_reporte def getErrorReal(self): return self.__error_real def getUrlPrueba(self): return self.__url_prueba def getUrlGuardar(self): return self.__url_guardar def getInterfaz(self): return self.__interfaz ''' #Entrenar para todos los valores o=CtrlEntrenarRNANormalizado() o.setConeccion(1) o.setTasaApre...
zozo123/buildbot
master/buildbot/scripts/stop.py
Python
gpl-3.0
2,284
0.000876
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
CH: raise else: if not config['quiet']: print "buildmaster not running" try: os.unlink(pidfile) except: pass return 0 if not w
ait: if not quiet: print "sent SIG%s to process" % signame return 0 time.sleep(0.1) # poll once per second until twistd.pid goes away, up to 10 seconds, # unless we're doing a clean stop, in which case wait forever count = 0 while count < 10 or config['clean']: ...
pbougue/navitia
source/eitri/ed_handler.py
Python
agpl-3.0
6,071
0.001812
# Copyright (c) 2001-2015, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public tr...
a non ending quest to the respon
sive locomotion way of traveling! # # LICENCE: This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is ...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/checkbox/lib/__init__.py
Python
gpl-3.0
54
0.018519
../../..
/../../share/pyshared/checkbox/lib/__i
nit__.py
shollen/evennia
evennia/objects/models.py
Python
bsd-3-clause
12,067
0.002818
""" This module defines the database models for all in-game objects, that is, all objects that has an actual existence in-game. Each database object is 'decorated' with a 'typeclass', a normal python class that implements all the various logics needed by the game in question. Objects created of this class transparentl...
same as the # field, but without the db_* prefix (e.g. th
e db_key field is set with # self.key instead). The wrappers are created at the metaclass level and # will automatically save and cache the data more efficiently. # If this is a character object, the player is connected here. db_player = models.ForeignKey("players.PlayerDB", null=True, verbose_name='pl...
doriancoins/doriancoin
test/functional/wallet_basic.py
Python
mit
21,630
0.005457
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Doriancoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet.""" from test_framework.test_framework import DoriancoinTestFramework from test_fram...
# but 10 will go to node2 and the rest will go to node0 balance = self.nodes[0].getbalance() assert_equ
al(set([txout1['value'], txout2['value']]), set([10, balance])) walletinfo = self.nodes[0].getwalletinfo() assert_equal(walletinfo['immature_balance'], 0) # Have node0 mine a block, thus it will collect its own fee. self.nodes[0].generate(1) self.sync_all([self.nodes[0:3]]) ...
dimagi/commcare-hq
corehq/apps/app_manager/management/commands/migrate_advanced_form_preload.py
Python
bsd-3-clause
1,053
0.001899
from corehq.apps.app_manager.management.commands.helpers
import ( AppMigrationCommandBase, ) from corehq.apps.app_manager.models import Application class Command(AppMigrationCommandBase): help = "Migrate preload dict in advanced forms to " \ "allow loading the same case property into multiple questions." include_builds = False def migrate_app(...
', '') == 'advanced'] should_save = False for module in modules: forms = module['forms'] for form in forms: load_actions = form.get('actions', {}).get('load_update_cases', []) for action in load_actions: preload = action['preloa...
jniediek/combinato
tools/parse_cheetah_logfile.py
Python
mit
19,113
0.000262
#!/usr/bin/env python3 # JN 2015-07-29 """ Log file parser for Cheetah by Johannes Niediek This script reads out the reference settings by sequentially following all crs, rbs, and gbd commands. Please keep in mind that the following scenario is possible with Cheetah: Start the recording Stop the recording Change the...
# name2num is unique ch_name2num = dict() # num2name is *not* unique, values are lists ch_num2name = defaultdict(list) # save the settings all_setting
s = [] variables = dict() temp_setting = None for line in protocol: time, timestamp, msg1, msg2 = line if temp_setting is None: temp_setting = Setting() if msg1 == 'mov': temp_setting.folder = msg2 elif '::SendDRSCommand()' in msg1: # l...
privacyidea/privacyidea
tests/test_api_applications.py
Python
agpl-3.0
799
0
""" This test case test the REST API api/applications.py """ import json from .base import MyApiTestCase class APIApplicationsResol
verTestCase(MyApiTestCase): def test_get_applications(self): with self.app.test_request_context('/application/', method='GET', headers={'Authorization': self.at}): res = self.app.full_dispatch_request() ...
self.assertTrue("ssh" in value) self.assertTrue("luks" in value) self.assertTrue(value["ssh"]["options"]["optional"] == ["user"])
stdweird/aquilon
tests/broker/test_del_10gig_hardware.py
Python
apache-2.0
2,595
0.000385
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
est_300_delaux(self): for i in range(1, 25): hostname = "evh%d-e1.aqd-unittest.ms.com" % (i + 50) self.dsdb_expect_delete(self.net.vm_storage_net[0].usable[i - 1]) command = ["del", "auxiliary", "--auxiliary", hostname] (out, err) = self.successtest(command) ...
out, command) self.dsdb_verify() def test_700_delmachines(self): for i in range(0, 8) + range(9, 17): machine = "evm%d" % (10 + i) self.noouttest(["del", "machine", "--machine", machine]) def test_800_verifydelmachines(self): for i in range(0, 18): m...
boxed/RegexAsYouType
main.py
Python
mit
420
0.004762
# # main.py # RegexAsYouType # # Created by Anders Hovmoll
er on 5/19/09. # Copyright Calidris 2009. All rights reserved. # #import modules required by application i
mport objc import Foundation import AppKit from PyObjCTools import AppHelper # import modules containing classes required to start application and load MainMenu.nib import RegexAsYouTypeAppDelegate # pass control to AppKit AppHelper.runEventLoop()
aninoy/cowsnbulls
checker.py
Python
mit
432
0.032407
# import s
ys def check(answer, guess): bulls = 0 cows = 0 answer = str(answer) guess = str(guess) for x in range(0, len(answer)): # foundX = false; for y in range(0, len(guess)): if answer[x] == guess[y]: if x == y: bulls += 1 else: cows += 1 retVal = {'bulls': bulls, 'cows': cows} return retVal ...
check(9370, guess) # print result
freelancer/freelancer-sdk-python
examples/delete_user_jobs.py
Python
lgpl-3.0
794
0
from freelancersdk.re
sources.users import delete_user_jobs from freelancersdk.session import Session from freelancersdk.exceptions import UserJobsNotDeletedException import os def sample_delete_user_jobs(): url = os.environ.get('FLN_URL') oauth_to
ken = os.environ.get('FLN_OAUTH_TOKEN') session = Session(oauth_token=oauth_token, url=url) user_jobs_data = { 'job_ids': [ 1, 2, 3 ] } try: m = delete_user_jobs(session, **user_jobs_data) except UserJobsNotDeletedException as e: p...
eggsandbeer/scheduler
synergy/mx/base_request_handler.py
Python
bsd-3-clause
1,418
0.000705
__author__ = 'Bohdan Mushkevych' import functools from werkzeug.wrappers import Request from synergy.mx.utils import jinja_env def valid_action_request(method): """ wraps method with verification for is_request_valid""" @functools.wraps(method) def _wrapper(self, *args, **kwargs): assert isinst...
k(self): return {'status': 'OK'} def reply_bad_request(self): self.logger.error('Bad request: {0}'.format(self.request)) return {} def reply_server_error(self, e): self.logger.error('MX Processing Exception: {0}'.format(e), exc_info=True) return {'status': 'Server Inter...
'}
glumu/django-redis-cluster
django_redis_cluster/serializers/msgpack.py
Python
bsd-3-clause
311
0.003215
#coding:ut
f8 from __future__ import absolute_import, unicode_literals import msgpack from .base import BaseSerializer class MSGPackSerializer(BaseSerializer): def dumps(self, value): return msgpack.dumps(value) def loads(self, value): return msgpack.loads(value, enco
ding="utf-8")
arunkgupta/gramps
gramps/gui/editors/displaytabs/__init__.py
Python
gpl-2.0
2,332
0.013722
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Donald N. Allingham # Copyright (C) 2011 Tim G L Lyons # # 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; eith...
02111-1307 USA # # $Id$ #------------------------------------------------------------------------- # # set up logging # #------------------------------------------------------------------------- import logging log = logging.getLogger("gui.editors
.displaytabs") # first import models from childmodel import ChildModel # Then import tab classes from grampstab import GrampsTab from embeddedlist import EmbeddedList from addrembedlist import AddrEmbedList from attrembedlist import AttrEmbedList from backreflist import BackRefList from dataembedlist import DataEmbe...
fsufitch/homeweb
src/homeweb/handlers/demos/chess.py
Python
gpl-2.0
231
0.004329
from tornado.web import RequestHandler from homeweb.util imp
ort apply_template, write_return class ChessBoardHandler(RequestHandler): @
write_return @apply_template("demos/chess.html") def get(self): return {}
jjhelmus/adventofcode
day01.py
Python
mit
390
0.002564
from __future__ import print_function f = open('inputs/input_01.txt') contents = f.read
() print("Floor:", contents.count('(') - contents.count(')')) # Part Two change = {'(': 1, ')': -1} floor = 0 position = 1 for
c in contents: if c in change: floor += change[c] if floor == -1: print("Basement entered at position:", position) break position += 1
chokribr/inveniotest
modules/websearch/lib/websearch_regression_tests.py
Python
gpl-2.0
256,725
0.003771
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 CERN. ## ## Invenio 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 ve...
sect_results_with_collrecs from invenio.bibrank_bridge_utils import get_external_word_similarity_ranker from invenio.search_engine_query_parser_unit_tests import DATEUTIL_AVAILABLE from invenio.bibindex_engine_utils import get_index_tags from invenio.bibindex_engine_config import CFG_BIBINDEX_INDEX_TABLE_TYPE if 'fr' ...
= False def parse_url(url): parts = urlparse.urlparse(url) query = cgi.parse_qs(parts[4], True) return parts[2].split('/')[1:], query def string_combinations(str_list): """Returns all the possible combinations of the strings in the list. Example: for the list ['A','B','Cd'], it will return [...
stackingfunctions/scrapeforum
python/src/mylogger.py
Python
gpl-3.0
862
0.00232
import os import logging.config cla
ss MyLogger(object): # set logging to both file and screen def __init__(self): logging.config.fileConfig(
'../config/logging.conf') self.logger = logging.getLogger('scrapeforum') self.logger.addHandler(logging.StreamHandler()) self.errorIndicated = False def isErrorIndicated(self): return self.errorIndicated def debug(self, msg): self.logger.debug(msg) def info(self, m...
myd7349/DiveIntoPython3Practices
chapter_11_Files/read_line.py
Python
lgpl-3.0
804
0.003759
# -*- coding: utf-8 -*- # 2014-11-24 22:43 line_number = 0 with open('favorite-people.txt', encoding = 'utf-8') as a_file: # To read a file one line at a time, use a for loop. That’s it. # Besides having explicit methods like read() , the stream object # is also an iterator which spits out a single line ev...
lows you to omit the argument indexes in your # format specifiers. print('{:>4} {}'.for
mat(line_number, a_line.rstrip()))
karllessard/tensorflow
tensorflow/python/distribute/mirrored_run.py
Python
apache-2.0
19,404
0.005978
# Copyright 2020 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...
d-access yield def _cpu_device(device): cpu_device = tf_device.DeviceSpec.from_string(device) cpu_device = cpu_device.replace(device_type="CPU", device_index=0) ret
urn cpu_device.to_string() class _RequestedStop(Exception): # pylint: disable=g-bad-exception-name pass def _call_for_each_replica(distribution, fn, args, kwargs): """Run `fn` in separate threads, once per replica/worker device. Args: distribution: the DistributionStrategy object. fn: function to ru...
mediatum/mediatum
core/nodecache.py
Python
gpl-3.0
1,485
0.006061
# -*- coding: utf-8 -*- """ :copyright: (c) 2016 by the mediaTUM auth
ors :license: GPL3, see COPYING for details """ from __future__ import absolute_import from sqlalchemy.orm import undefer, joinedload from sqlalchemy.orm.exc import NoResultFound from core import db as _db from utils.lrucache import lru_cache as _lru_cache @_lru_cache(maxsize=128) def get_singleton_node_from_cac...
e. """ return _db.session.query(nodeclass).options(undefer(nodeclass.attrs), undefer(nodeclass.system_attrs), joinedload(nodeclass.file_objects)).one() def get_root_node(): """Root object may not change during runtime, so we c...
josauder/procedural_city_generation
procedural_city_generation/building_generation/roofs.py
Python
mpl-2.0
6,492
0.008164
# -*- coding: utf-8 -*- from __future__ import division import numpy as np import numpy.linalg as la import matplotlib.pyplot as plt from procedural_city_generation.building_generation.cuts import * from procedural_city_generation.building_generation.building_tools import * from procedural_city_generation.buil...
ersion of the roofwalls box=scaletransform(roofwalls, random.uniform(0.07, 0.14)) if not roofwalls.l == 4:
#Constructs a box with 4 sides if the box did not have 4 sides a, b=box.vertices[0], box.vertices[1] n=(b-a) n=np.array([-n[1], n[0], 0]) box=Walls(np.array([a, b, b+n, a+n]), 4) #Checks if every vertex of the box is "inside" the roof polygon so that the box does not float. ...
olavph/builds
lib/versions_repository.py
Python
gpl-3.0
2,326
0.00086
import logging import os from lib import exception from lib import repository from lib.constants import REPOSITORIES_DIR LOG = logging.getLogger(__name__) def get_versions_repository(co
nfig): """ Get the
packages metadata Git repository, cloning it if does not yet exist. Args: config (dict): configuration dictionary Raises: exception.RepositoryError: if the clone is unsuccessful """ path = os.path.join(config.get('work_dir'), REPOSITORIES_DIR) url = con...
davidwaroquiers/custodian
tasks.py
Python
mit
1,962
0.001529
""" Deployment file to facilitate releases of custodian. """ from __future__ import division __author__ = "Shyue Ping Ong" __copyright__ = "Copyr
ight 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyue@mit.edu" __date__ = "Apr 29, 2012" import glob from invoke import task from monty.os import cd from custodian import __version__ as ver @task def make_doc(ctx): with cd("docs"): ctx.run("sphinx-apid...
dian*.tests.rst") for f in glob.glob("docs/*.rst"): if f.startswith('docs/custodian') and f.endswith('rst'): newoutput = [] suboutput = [] subpackage = False with open(f, 'r') as fid: for line in fid: ...
lukw00/powerline
setup.py
Python
mit
4,260
0.026069
#!/usr/bin/env python # vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys import subprocess import logging import shlex from traceback import print_exc from setuptools import setup, find_packages CURRENT_DIR = os.path.abspath(os.pat...
e :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'P
rogramming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], download_url='https://github.com/powerline/powerline/archive/de...
home-assistant/home-assistant
homeassistant/components/switchbot/__init__.py
Python
apache-2.0
4,051
0.001234
"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNo...
MMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, ...
TIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: ...
adaptive-learning/proso-apps
proso_tasks/migrations/0001_initial.py
Python
mit
4,601
0.003043
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-08-01 07:59 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import jsonfield.fields import proso.django.models class Migration(migrations.Migration): initial = True dependencies = [...
d(auto_created=True, primar
y_key=True, serialize=False, verbose_name='ID')), ('identifier', models.SlugField()), ('lang', models.CharField(max_length=2)), ('name', models.TextField()), ('content', jsonfield.fields.JSONField(blank=True, null=True)), ('active', models....
shobhitmishra/CodingProblems
LeetCode/Session3/ipo.py
Python
mit
880
0.023864
from heapq import * from typing import List class Solution: def findMaximizedCapital(self, k: int, wealth: int, profits: List[int], capitals: List[int]) -> int: minCapitalHeap, maxProfitHeap = [], [] for i in range(len(capitals)): heappush(minCapitalHeap, (capitals[i], profits[i])) ...
appush(maxProfitHeap, -profit) if not maxProfitHeap: break wealth += -heappop(maxProfitHeap) return wealth k=0 W=0 Profits=[1,2,3,5] Capital=[0,1,2,3] ob = Solution() print(ob.find
MaximizedCapital(k, W, Profits, Capital))
CERNDocumentServer/invenio
modules/bibfield/lib/functions/check_field_existence.py
Python
gpl-2.0
4,158
0.004329
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 th...
lso modify the record if the field is not repeatable, meaning that min_value=1 or min_value=0,max_value=1 """ from invenio.bibfield_utils import InvenioBibFieldContinuableError, \ InvenioBibFieldError error = continuable and InvenioBibFieldContinuableError or Inve...
n field and field[:-3] or field key = subfield and "%s.%s" % (field, subfield) or field if min_value == 0: # (0,1), (0,'n'), (0,n) if not max_value: raise error("Minimun value = 0 and no max value for '%s'" % (key,)) if key in record: value = record[key] if ...
KhronosGroup/COLLADA-CTS
StandardDataSets/collada/library_lights/_reference/_reference_directional_white/_reference_directional_white.py
Python
mit
3,987
0.006521
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ...
lidation steps are not in error. # JudgeExemplary: same as intermediate badge. # We import an assistant script that includes the common verifications # methods. The assistant buffers its checks, so that running them again # does not incurs an unnecessary performance hint. from StandardD
ataSets.scripts import JudgeAssistant # Please feed your node list here: tagLst = ['library_lights', 'light', 'technique_common', 'directional'] attrName = '' attrVal = '' dataToCheck = '' class SimpleJudgingObject: def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst ...
open-mmlab/mmdetection
mmdet/models/detectors/fast_rcnn.py
Python
apache-2.0
2,164
0
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class FastRCNN(TwoStageDetector): """Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_""" def __init__(self, backbone, ...
st[List[dict]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates i
mages in a batch. proposals (List[List[Tensor]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates images in a batch. The Tensor should have a shape Px4, where P is the number of proposals. """ for v...
Brett55/moto
moto/apigateway/urls.py
Python
apache-2.0
2,102
0.007612
from __future__ import unicode_literals from .responses import APIGatewayResponse url_bases = [ "https?://apigateway.(.+).amazonaws.com" ] url_paths = { '{0}/restapis$': APIGatewayResponse().restapis, '{0}/restapis/(?P<function_id>[^/]+)/?$': APIGatewayResponse().restapis_individual, '{0}/restapis/(?P...
yments/(?P<deployment_id>[^/]+)/?$': APIGatewayResponse().individual_deployment, '{0}/restapis/(?P<function_id>[^/]+)/resources/(?P
<resource_id>[^/]+)/?$': APIGatewayResponse().resource_individual, '{0}/restapis/(?P<function_id>[^/]+)/resources/(?P<resource_id>[^/]+)/methods/(?P<method_name>[^/]+)/?$': APIGatewayResponse().resource_methods, '{0}/restapis/(?P<function_id>[^/]+)/resources/(?P<resource_id>[^/]+)/methods/(?P<method_name>[^/]+)...
ayepezv/GAD_ERP
addons/mail/models/mail_message.py
Python
gpl-3.0
38,977
0.003746
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from email.header import decode_header from email.utils import formataddr from odoo import _, api, fields, models, SUPERUSER_ID, tools from odoo.exceptions import UserError, AccessError from odoo.osv imp...
@api.multi def _get_needaction(self): """ Need action on a mail.message = notified on my channel """ my_messages = self.sudo().filtered(lambda msg: self.env.user.partner_id in msg.needaction_partner_ids) for message in self: message.needaction = message in my_messages ...
ef _search_needaction(self, operator, operand): if operator == '=' and operand: return [('needaction_partner_ids', 'in', self.env.user.partner_id.id)] return [('needaction_partner_ids', 'not in', self.env.user.partner_id.id)] @api.depends('starred_partner_ids') def _get_starred(self...
jmartinm/invenio-oauthclient
invenio_oauthclient/contrib/github.py
Python
gpl-2.0
3,966
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
.py`` package installed: .. code-block:: console cdvirtualenv src/invenio pip install -e .[github] 2. Edit your configuration and add: .. code-block:: python from invenio_oauthclient.contrib import github OAUTHCLIENT_REMOTE_APPS = dict( github=github.REMOTE_APP, ...
w application: https://github.com/settings/applications/new. When registering the application ensure that the *Authorization callback URL* points to: ``CFG_SITE_SECURE_URL/oauth/authorized/github/`` (e.g. ``http://localhost:4000/oauth/authorized/github/`` for development). 4. Grab the *Client ID* and *Cli...
jeffque/circle-quest-squareland
elements/geometry.py
Python
unlicense
969
0.001032
def pitagoras_quad(coordenada): return coordenada[0] ** 2 + coordenada[1] ** 2 def pitagoras(coordenada): return pitagoras_quad(coordenada)**0.5 def coords_delta(coord_a, coord_b): delta = [] delta.append(coord_a[0] - coord_b[0]) delta.append(coord_a[1] - coord_b[1]) return delta def coord...
o_a, ponto_b): return distancia_quad(ponto_a, ponto_b)**0.5 def direction2module(direcao, mo
dulo_desejado): modulo_atual = pitagoras(direcao) try: fator = modulo_desejado/modulo_atual return [x * fator for x in direcao] except ZeroDivisionError: return [0,0] def direction_module_mutiply(direcao, fator): return [x * fator for x in direcao]
valhallasw/phabricator-tools
py/abd/abdt_repooptions.py
Python
apache-2.0
6,892
0.000145
"""Per-repository configuration options.""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # abdt_repooptions # # Public Classes: # Data # # Public Functions: # merge_override_into_data # me...
s json :returns: a json string based on 'data' """ return json.dumps( data, default=lambda x: x.__dict__, sort_keys=True, indent=4) def validate_data(data): """Raise if th
e supplied data is invalid in any way. :data: a Data() to be validated :returns: None """ # make sure that 'data' has the same attributes as a blank data data_key_set = set(data.__dict__.keys()) blank_data_key_set = set(Data().__dict__.keys()) if data_key_set != blank_data_key_set: ...
getsmarter/bda
utils/__init__.py
Python
mit
235
0.004255
from utils.haversine import haversine from utils.geo import
llaToECEF from utils.geo import ECEFTolla from utils.median import getmedian from utils.graph import draw_partitioned_graph from utils.fancy_dendrogram imp
ort fancy_dendrogram
fgmacedo/django-awards
awards/urls.py
Python
mit
121
0
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.awards_list, name='list'), ]
d4rt/SplunkModularInputsPythonFramework
implementations/rest/bin/authhandlers.py
Python
apache-2.0
1,678
0.014303
from requests.auth import AuthBase import hmac import base64 import hashlib import urlparse import urllib #add your custom auth handler class to this module class MyCustomAuth(AuthBase): def __init__(self,**args): # setup any auth-related data here #self.username = args['username'] #self.p...
params:
url_params[param] = url_params[param][0] url_params['apikey'] = self.apikey keys = sorted(url_params.keys()) sig_params = [] for k in keys: sig_params.append(k + '=' + urllib.quote_plus(url_params[k]).replace("+", "%20")) query = '&'.join(si...
cjekel/piecewiseLinearFitPython
examples/fitWithKnownLineSegmentLocations.py
Python
mit
3,127
0
# fit and predict with known line segment x locations # import our libraries import numpy as np import matplotlib.pyplot as plt import pwlf # your data y = np.array([0.00000000e+00, 9.69801700e-03, 2.94350340e-02, 4.39052750e-02, 5.45343950e-02, 6.74104940e-02, 8.34831790e-02, 1.02580042e-...
1.31196948e-01, 0.00000000e+00, 1.56706510e-02, 3.54628780e-02, 4.63739040e-02, 5.61442590e-02, 6.78542550e-02, 8.16388310e-02, 9.77756110e-02, 1.16531753e-01, 1.37038283e-01, 0.00000000e+00,
1.16951050e-02, 3.12089850e-02, 4.41776550e-02, 5.42877590e-02, 6.63321350e-02, 8.07655920e-02, 9.70363280e-02, 1.15706975e-01, 1.36687642e-01, 0.00000000e+00, 1.50144640e-02, 3.44519970e-02, 4.55907760e-02, 5.59556700e-02, 6.88450940e-02, 8.413...
pgandev/RocketMap
pogom/utils.py
Python
agpl-3.0
43,916
0.000023
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import configargparse import os import math import json import logging import random import time import socket import struct import zipfile import requests from uuid import uuid4 from s2sphere import CellId, LatLng from . import config log = logging.getLogger(__na...
add_argument('-hlvl', '--high-lvl-accounts', help=('Load high level accounts from CSV file ' + ' containing ' + '"auth_service,username,passwd"' + ' lines.')) parser.add_arg
ument('-bh', '--beehive', help=('Use beehive configuration for multiple ' + 'accounts, one account per hex. Make sure ' + 'to keep -st under 5, and -w under the total ' + 'amount of accounts available.'), ...
endlessm/chromium-browser
third_party/llvm/lldb/third_party/Python/module/unittest2/unittest2/test/test_new_tests.py
Python
bsd-3-clause
1,677
0
from cStringIO import StringIO import unittest import unittest2 from unittest2.test.support import resultFactory class TestUnittest(unittest2.TestCase): def assertIsSubclass(self, actual, klass): self.assertTrue(issubclass(actual, klass), "Not a subclass.") def testInheritance(self): self....
self.assertIsSubclass(unittest2.TextTestResult, unitte
st.TestResult) def test_new_runner_old_case(self): runner = unittest2.TextTestRunner(resultclass=resultFactory, stream=StringIO()) class Test(unittest.TestCase): def testOne(self): pass suite = unittest2.TestSuite((Test...
moden-py/SWAPY-deleting
proxy.py
Python
lgpl-2.1
26,563
0.010014
# GUI object/properties browser. # Copyright (C) 2011 Matiychuk D. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at your option) any later ve...
def _get_additional_properties(self): ''' Get additonal useful properties, like a handle, process ID, etc. Can be overridden by derived class ''' add
itional_properties = {} pwa_app = pywinauto.application.Application() #-----Access names try: #parent_obj = self.pwa_obj.Parent() parent_obj = self.pwa_obj.TopLevelParent() except: pass else: try: #all_controls = par...
vitalti/sapl
sapl/api/forms.py
Python
gpl-3.0
7,717
0.00013
from django.db.models import Q from django.forms.fields import CharField, MultiValueField from django.forms.widgets import MultiWidget, TextInput from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django_filters.filters import DateFilter, MethodFilter, ModelChoiceFilter from ...
if not tipo and not data_relativa: return qs if tipo: # não precisa de try except, já foi validado em filter_tipo tipo = TipoAutor.objects.get(pk=tipo) if not tipo.content_type: return qs filter_for_model = 'filter_%s' % tipo.cont...
turn getattr(self, filter_for_model)(qs, data_relativa).distinct() def filter_parlamentar(self, queryset, data_relativa): # não leva em conta afastamentos legislatura_relativa = Legislatura.objects.filter( data_inicio__lte=data_relativa, data_fim__gte=data_relativa).first() ...
nk113/tastypie-rpc-proxy
rpc_proxy/test.py
Python
bsd-3-clause
3,241
0.002468
# -*- coding: utf-8 -*- import base64 import inspect import json import logging import requests import types from django.conf import settings from django.core.management import call_command from django_nose import FastFixtureTestCase from functools import wraps from mock import patch from tastypie.test import Resource...
se, TestApiClient from rpc_proxy.proxies import get_setting INITIAL_DATA = ('initial_data',) TEST_DATA = ('test_data',) logger = logging.getLogger(__name__) def mock_request(obj, method, url, **kwargs): client = TestApiClient() authentication = 'Basic %s' % base64.b64encode(':'.join([ get_setti
ng('SUPERUSER_USERNAME', None), get_setting('SUPERUSER_PASSWORD', None), ])) if method == 'GET': data = kwargs.get('params', {}) djresponse = client.get(url, data=data, authentication=authentication) elif method == 'POST': data = json.loads(kwargs.get('data', '{}')) ...
osks/pylyskom
tests/test_datatypes.py
Python
gpl-2.0
6,849
0.004672
# -*- coding: utf-8 -*- import pytest from .mocks import MockSocket from pylyskom.errors import ReceiveError from pylyskom.connection import ReceiveBuffer from pylyskom.datatypes import ArrayInt32, Int32, String, ConfType, ExtendedConfType def test_Array_can_parse_empty_array_with_star_format(): s = MockSocket(...
= b"11110000" def test_ExtendedConfType_to_string(): ct1 = ExtendedConfType() assert ct1.to_string() == b"00000000" ct2 = ExtendedConfType([1, 0, 1, 0, 1, 0, 1, 0]) assert ct2.to_string() == b"10101010" ct3 = ExtendedConfType([1, 1, 1, 1, 1, 1...
# Must have an extra character, so this will fail ect = ExtendedConfType.parse(ReceiveBuffer(MockSocket(b"00110011"))) ect = ExtendedConfType.parse(ReceiveBuffer(MockSocket(b"00110011 "))) assert ect.to_string() == b"00110011" def test_ArrayInt32_parse(): a = ArrayInt32.parse(Rece...
mdsmus/MusiContour
tests/test_contour.py
Python
gpl-3.0
12,322
0.000487
# -*- coding: utf-8 -*- import contour.contour as contour from contour.contour import Contour import py def test_build_classes_card(): fn = contour.build_classes_card assert fn(4) == [(4, 1, (0, 1, 2, 3), True), (4, 2, (0, 1, 3, 2), False), (4, 3, (0, 2, 1, 3), True), (4, 4, (0, 2, 3, 1)...
8, 12, 9, 5, 7, 3, 12, 3, 7]) assert cseg.subsets_adj(4) == [[2, 8, 12, 9], [8, 12, 9, 5], [12, 9, 5, 7], [9, 5, 7, 3], [5, 7, 3, 12], [7, 3, 12, 3], [3, 12, 3, 7]] def test_cps_position(): cseg = Con
tour([2, 8, 12, 9, 5, 7, 3, 12, 3, 7]) assert cseg.cps_position() == [(2, 0), (8, 1), (12, 2), (9, 3), (5, 4), (7, 5), (3, 6), (12, 7), (3, 8), (7, 9)] def test_reduction_morris_1(): cseg = Contour([0, 4, 3, 2, 5, 5, 1]) assert cseg.reduction_morris() == [[0, 2, 1], 2] ...
huntzhan/magic-constraints
magic_constraints/argument.py
Python
mit
2,768
0
# -*- coding: utf-8 -*- from __future__ import ( division, absolute_import, print_function, unicode_literals, ) from builtins import * # noqa from future.builtins.disabled import * # noqa from magic_constraints.exception import MagicSyntaxError, MagicTypeError def transform_to_slots(constraints...
ument(s).', parameters=constraints_package.parameters, slots=slots, ) return slots def check_and_bind_arguments(parameters, sl
ots, bind_callback): plen = len(parameters) for i in range(plen): arg = slots[i] parameter = parameters[i] wrapper = parameter.wrapper_for_deferred_checking() # defer checking by wrapping the element of slot. if wrapper: slots[i] = wrapper(arg) # ...
YuxuanLing/trunk
trunk/code/study/python/Fluent-Python-example-code/attic/sequences/slice_dump.py
Python
gpl-3.0
581
0.001721
""" >>> sd = SliceDump() >>> sd[1] 1 >>> sd[2:5] slice(2, 5, None) >>> sd[:2] slice(None, 2, None) >>> sd[7:] slice(7, None, None) >>> sd[:] slice(None, None, None) >>> sd[1:9:3] slice(1, 9, 3) >>> sd[1:9:3, 2:3] (slice(1, 9, 3), slice(2, 3, N...
, 1, 3) >>> s.indices(0) (0, 0, 3) """ class SliceDump: def __getitem__(self, pos): return pos
mgx2/python-nvd3
examples/discreteBarChart.py
Python
mit
899
0.003337
#!/usr/bin/python # -*- coding: utf-8 -*- """ Examples for Python-nvd3 is a Python wrapper for NVD3 graph library. NVD3 is an attempt to build re-usable charts and chart components for d3.js without taking away the power that d3.js gives you. Project location : https://github.com/areski/python-nvd3 """ from nvd3 imp...
e for test output_file = open('test_discreteBarChart.html', 'w') type = "discreteBarChart" chart = discreteBarChart(name='mygraphname', height=400, width=600) chart.set_containerheader("\n\n<h2>" + type + "</h2>\n\n") xdata = ["A", "B", "C", "D", "E", "F", "G"] ydata = [3, 12, -10, 5, 25, -7, 2] extra_serie = {"toolt...
ml() output_file.write(chart.htmlcontent) #--------------------------------------- #close Html file output_file.close()
NLeSC/noodles
noodles/lib/__init__.py
Python
apache-2.0
3,960
0
""" Coroutine streaming module ========================== .. note:: In a break with tradition, some classes in this module have lower case names because they tend to be used as function decorators. We use coroutines to communicate messages between different components in the Noodles runtime. Coroutines can ha...
msg = yield print(msg) def g_pushes(coroutine, lines): for l in lines: coroutine.send(l) sink = f_receives() sink.send(None) # the co-routine needs to be initialised # alternatively, .next() does the same as .send(None) g_pushes(sink, lin...
oroutine and setting it to the first `yield` statement can be performed by a little decorator: .. code-block:: python from functools import wraps def coroutine(f): @wraps(f) def g(*args, **kwargs): sink = f(*args, **kwargs) sink.send(None) return sink ...
rcbops-qe/horizon-selenium
pages/navigation_bars.py
Python
apache-2.0
9,234
0
import basepage class NavigationBars(basepage.BasePage): def expand_project_panel(self): elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-project"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() e...
er.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-project-compute"]') state = elm.get_attribute('class') if 'collapsed' in state:
elm.click() else: pass def click_project_compute_overview(self): NavigationBars.expand_project_compute(self) self.driver.find_element_by_css_selector( 'a[href="/project/"]').click() def click_project_compute_instance(self): NavigationBars.expa...
jorvis/biocode
gff/report_gff_intron_and_intergenic_stats.py
Python
mit
9,713
0.008545
#!/usr/bin/env python3 import argparse from biocode import utils, gff def main(): ''' This script reports statistics on the areas of a genome where features aren't - introns and intergenic space. Pass a valid GFF3 file (along with FASTA data) and get a report like this: Molecule count: 9 Gene...
tion of intergenic region sizes and the other the intron lengths. Because these can often have long tails, you can limit both the Y- and X-axes values with the --ylimit and --xlimit options, respectively. FASTA: If your FASTA isn't embedded at the end of your GFF3 file after a ##FASTA directive you'll...
as I started writing this. Does one count the space from the beginning of the contig until the first gene, or only between them? What about short contigs which have no annotated genes at all? From the Sequence Ontology: SO:0000605: A region containing or overlapping no genes that is bounded on either si...
oleg-chubin/let_me_play
let_me_app/migrations/0008_auto_20150809_1341.py
Python
apache-2.0
474
0.00211
# -*- coding: utf-8 -*- from __future__ import un
icode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('let_me_app', '0007_auto_20150723_2238'), ] operations = [ migrations.Alt
erField( model_name='event', name='start_at', field=models.DateTimeField(verbose_name='date started', db_index=True), preserve_default=True, ), ]
MozillaSecurity/peach
Peach/Publishers/raw.py
Python
mpl-2.0
11,798
0.000424
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import socket import time import sys from Peach.publisher import Publisher class RawEther(Publisher): """ A si...
g(1) return ret class RawIp(Publisher): """ A simple Raw p
ublisher. """ def __init__(self, interface, timeout=0.1): """ @type host: string @param host: Remote host @type timeout: number @param timeout: How long to wait for response """ Publisher.__init__(self) self._host = None self._socket = Non...
LucasMagnum/pyexplain
pyexplain/attach/examples/models.py
Python
mit
547
0
# coding: utf-8 from django.db import models from attach.mo
dels import ContentTypeModel class Example(ContentTypeModel): """ Exemplos serão adicionados como pedaços de códigos para ajudar no entendime
nto do usuário sobre algum item. """ name = models.CharField(u'Nome', max_length=150, blank=True) code = models.TextField(u'Código') class Meta: verbose_name = 'Exemplo' verbose_name_plural = 'Exemplos' ordering = ['-added'] def __unicode__(self): return self.name
quentinhardy/odat
UtlHttp.py
Python
lgpl-3.0
4,947
0.03679
#!/usr/bin/python # -*- coding: utf-8 -*- from Http import Http import logging from sys import exit from Utils import ErrorSQLRequest, checkOptionsGivenByTheUser from Constants import * class UtlHttp (Http): ''' Allow the user to send HTTP request ''' def __init__(self,args): ''' Constructor ''' logging.d...
_INVALID_ID ==> For Oracle 10g logging.info('Not enough privileges: {0}'.format(str(respo
nse))) self.args['print'].badNews("KO") return False else: self.args['print'].goodNews("OK") return True def runUtlHttpModule(args): ''' Run the UTL_HTTP module ''' status = True if checkOptionsGivenByTheUser(args,["test-module","scan-ports","send"]) == False : return EXIT_MISS_ARGUMENT utlHtt...
simplegeo/trialcoverage
twisted/plugins/trialcoveragereporterplugin.py
Python
gpl-2.0
1,724
0.00174
#! /usr/bin/env python from zope.interface import implements from twisted.trial.itrial import IReporter from twisted.plugin import IPlugin # register a plugin that can create our CoverageReporter. The reporter itself # lives separately, in trialcoverage/trialcoverage.py. # note that this trialcoveragereporterplugin....
ce tells the application how to # create a plugin by naming the module and class that should be instantiated. # When installing our package via setup.py, arrange for this file to be # installed to the system-wide twisted/plugins/ directory. class _Reporter(object): implements(IPlugin, IReporter) def __ini
t__(self, name, module, description, longOpt, shortOpt, klass): self.name = name self.module = module self.description = description self.longOpt = longOpt self.shortOpt = shortOpt self.klass = klass bwcov = _Reporter("Code-Coverage Reporter (colorless)", ...
hill-a/stable-baselines
stable_baselines/trpo_mpi/utils.py
Python
mit
1,008
0.00496
import numpy as np def add_vtarg_and_adv(seg,
gamma, lam): """ Compute target value using TD(lambda) estimator, and advantage with GAE(lambda) :param seg: (dict) the current segment of the trajectory (see traj_segment_generator return for more information) :param gamma: (float) Discount factor :param lam: (float) GAE factor """ # last ...
rew_len = len(seg["rewards"]) seg["adv"] = np.empty(rew_len, 'float32') rewards = seg["rewards"] lastgaelam = 0 for step in reversed(range(rew_len)): nonterminal = 1 - float(episode_starts[step + 1]) delta = rewards[step] + gamma * vpred[step + 1] * nonterminal - vpred[step] ...
zitouni/ucla_zigbee_phy
src/python/crc16.py
Python
bsd-3-clause
1,996
0.043587
#!/usr/bin/env python """ Translation from a C code posted to a forum on the Internet. @translator Thomas Schmid """ from array import array def reflect(crc, bitnum): # reflects the lower 'bitnum' bits of 'crc' j=1 crcout=0 for b in range(bitnum): i=1<<(bitnum-1-b) i...
crc ^= 0x1021
crc = reflect(crc, 16) return crc class CRC16(object): """ Class interface, like the Python library's cryptographic hash functions (which CRC's are definitely not.) """ def __init__(self, string=''): self.val = 0 if string: self.update(string) ...
leanrobot/contestsite
team/scripts/python/correct.py
Python
gpl-3.0
79
0
import sys
import time sys.stdout.write("stdout!
") sys.stderr.write("stderr!")
kivy/pyjnius
tests/test_interface.py
Python
mit
620
0
from __future__ import pri
nt_function from __future__ import division from __future__ import absolute_import import unittest from jnius import autoclass, JavaException class Interface(unittest.TestCase): def test_reflect_interface(self): Interface = autoclass('org.jnius.InterfaceWithPublicEnum') self.assertTrue(Interface...
aceWithPublicEnum$ATTITUDE') self.assertTrue(ATTITUDE) self.assertTrue(ATTITUDE.GOOD) self.assertTrue(ATTITUDE.BAD) self.assertTrue(ATTITUDE.UGLY)
rnoldo/django-avatar
storages/backends/s3.py
Python
bsd-3-clause
10,680
0.003839
import os import mimetypes import warnings try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.conf import settings from django.core.files.base import File from django.core.files.storage import Storage from django.core.exceptions import ImproperlyConfigured try: ...
le(mode='wb', compresslevel=6, fileobj=zbuf) zfile.write(s) zfile.close() return zbuf.getvalue() def _put_file(self, name, content): if self.encrypt: # Create a key object key = self.crypto_ke
y() # Read in a public key fd = open(settings.CRYPTO_KEYS_PUBLIC, "rb") public_key = fd.read() fd.close() # import this public key key.importKey(public_key) # Now encrypt some text against this public key content = key.en...
iwxfer/wikitten
library/nlp/semantic_simi.py
Python
mit
376
0.00266
import spacy nlp = spacy.load
('en') text = open('customer_feedback_627.txt').read() doc = nlp(text) for entity in doc.ents: print(entity.text, entity.label_) # Determine seman
tic similarities doc1 = nlp(u'the fries were gross') doc2 = nlp(u'worst fries ever') doc1.similarity(doc2) # Hook in your own deep learning models nlp.add_pipe(load_my_model(), before='parser')
weechat/weechat.org
weechat/doc/models.py
Python
gpl-3.0
9,804
0
# # Copyright (C) 2003-2022 Sébastien Helleu <flashcode@flashtux.org> # # This file is part of WeeChat.org. # # WeeChat.org 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 #...
_cvss_vector(self): """Return URL to CVSS vector detail.""" if self.cvss_vector: return URL_CVSS_VECTOR % {'vector': self.cvss_vector} return '' def url_tracker(self): """Return URL with links to tracker items.""" return mark_safe(tracker_links(self.tracker)) ...
lf): """Return severity index based on CVSS score.""" return get_severity(self.cvss_score) def severity_i18n(self): """Return translated severity based on CVSS score.""" text = dict(SECURITY_SEVERITIES).get(self.severity_index(), '') return gettext(text) if text else '' ...
sprockets/sprockets.mixins.redis
setup.py
Python
bsd-3-clause
2,498
0.0004
import codecs import sys import setuptools def read_requirements_file(req_name): requirements = [] try: with codecs.open(req_name, encoding='utf-8') as req_file: for req_line in req_file: if '#' in req_line: req_line = req_line[0:req_line.find('#')].str...
mming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :
: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['sprockets', ...
huntxu/neutron
neutron/cmd/ovs_cleanup.py
Python
apache-2.0
4,457
0
# Copyright (c) 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ridge_deletable_ports(ovs) return ports def delete_neutron_ports(ports): """Delete non-internal ports created by Neutron Non-internal OVS ports need to be removed manually. """ for port in ports: device = ip_lib.IPDevice(port) if device.exists(): device.link.delete() ...
.info("Deleting port: %s", port) def main(): """Main method for cleaning up OVS bridges. The utility cleans up the integration bridges used by Neutron. """ conf = setup_conf() conf() config.setup_logging() do_main(conf) def do_main(conf): configuration_bridges = set([conf.ovs_integ...
TacticalGoat/reddit
SubDumpPost/subdumppost.py
Python
mit
5,238
0.009927
#/u/GoldenSights import traceback import praw # simple interface to the reddit API, also handles rate limiting of requests import time import sqlite3 '''USER CONFIGURATION''' APP_ID = "" APP_SECRET = "" APP_URI = "" APP_REFRESH = "" # https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/ USERAGENT =...
Reddit(USERAGENT) r.set_oauth_app_info(APP_ID, APP_
SECRET, APP_URI) r.refresh_access_information(APP_REFRESH) def scansub(): print('Searching '+ SUBREDDIT + '.') subreddit = r.get_subreddit(SUBREDDIT) posts = subreddit.get_new(limit=MAXPOSTS) result = [] authors = [] for post in posts: pid = post.id pbody = post.title.lower() + ...
ctgk/BayesianNetwork
test/linalg/test_det.py
Python
mit
626
0
import unittest import numpy as np import bayesnet as bn class TestDeterminant(unittest.TestCase): def test_determinant(self): A = np.array([ [2., 1.], [1., 3.] ]) detA = np.linalg.det(A) self.ass
ertTrue((detA == bn.linalg.det(A).value).all()) A = bn.Parameter(A) for _ in range(100): A.cleargrad() detA = bn.linalg.det(A) loss = bn.square(detA - 1) loss.backward() A.value -= 0.1 * A.grad self.assertAlmostEqual(detA.value, 1.) ...
unittest.main()
gracfu/618_map_reduce
map_reduce_part2.py
Python
apache-2.0
802
0.03616
''' SI 618 - HW 4: Map-Reduce Part 2 Uniqname: gracfu ''' from mrjob.job import MRJob from mrjob.step import MRStep import re WORD_RE = re.compile(r"\b[\w']+\b") class MRMostUsedWord(MRJob): def mapper_get_words(self, _, line): for word in WORD_RE.findall(line): yield (word.lower(), 1) def combiner_count_wo...
nt_words), MRStep(re
ducer = self.reducer_find_max_words) ] if __name__ == '__main__': MRMostUsedWord.run()
CooperLuan/devops.notes
taobao/top/api/rest/ItemQuantityUpdateRequest.py
Python
mit
406
0.03202
''' Created by auto_sdk on
2014-12-17 17:22:51 ''' from top.api.base import RestApi class ItemQuantityUpdateRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.num_iid = None self.outer_id = None self.quantity = None self.sku_id = None self.type = None def ...
ntity.update'
levilucio/SyVOLT
UMLRT2Kiltera_MM/MT_pre__match_contains.py
Python
mit
4,951
0.029085
""" __MT_pre__match_contains.py_____________________________________________________ Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY) Author: gehan Modified: Sun Feb 15 10:22:14 2015 ________________________________________________________________________________ """ from ASGNode import * from ...
ce(objTuple, 20) oc.resolve() # Resolve immediately after creating entity & constraint def autoIncrLabel(self, params): #=============================================================================== # Auto increment the label #=========================================...
f there is already one, ignore if not self.MT_label__.isNone(): return # Get the maximum label of all MT_pre__ elements label = 0 for nt in self.parent.ASGroot.listNodes: if nt.startswith('MT_pre__'): for node in self.parent.ASGroot.listNodes[nt]: ...
Zlash65/erpnext
erpnext/startup/report_data_map.py
Python
gpl-3.0
9,520
0.03771
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals # mappings for table dumps # "remember to add indexes!" data_map = { "Company": { "columns": ["name"], "conditions": ["docstatus < 2"] }, "Fisc...
der_by": "parent", "links": { "parent": ["Sales Order", "name"], "item_code": ["Item", "name"] } }, "Delivery Note": { "columns": ["name", "customer", "posting_date", "company"], "conditions": ["docstatus
=1"], "order_by": "posting_date", "links": { "customer": ["Customer", "name"], "company":["Company", "name"] } }, "Delivery Note Item[Sales Analytics]": { "columns": ["name", "parent", "item_code", "stock_qty as qty", "base_net_amount"], "conditions": ["docstatus=1", "ifnull(parent, '')!=''"], "orde...
ThiefMaster/indico
indico/modules/events/contributions/controllers/management.py
Python
mit
34,546
0.003503
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import uuid from operator import attrgetter from flask import flash, jsonify, redirect, request, session ...
rt send_csv, send_xlsx from indico.util.string import handle_legacy_description from indico.web.flask.templating import get_template_module from indico.web.flask.util import send_file, url_for from indico.web.forms.base import FormDefaults from indico.web.forms.fields.principals import serialize_principal from indico.w...
tpl = get_template_module('events/contributions/management/_subcontribution_list.html') subcontribs = (SubContribution.query.with_parent(contrib) .options(undefer('attachment_count')) .order_by(SubContribution.position) .all()) return tpl.render_subco...
looker/sentry
tests/acceptance/test_member_list.py
Python
bsd-3-clause
1,244
0.000804
from __future__ import absolute_import from sentry.models import OrganizationMember from sentry.testutils import AcceptanceTestCase class ListOrganizationMembersTest(AcceptanceTestCase): def setUp(self): super(ListOrganizationMembersTest, self).setUp() self.user = self.create_user('foo@example.co...
elf.org,
role='admin', teams=[self.team], ) self.login_as(self.user) def test_list(self): self.browser.get('/organizations/{}/members/'.format(self.org.slug)) self.browser.wait_until_not('.loading-indicator') self.browser.snapshot(name='list organization members')
emakis/erpnext
erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
Python
gpl-3.0
26,853
0.025435
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, erpnext from frappe.utils import cint, formatdate, flt, getdate from frappe import _, throw import frappe.defaults from erpnext.controll...
ock_items \ and
self.is_opening == 'No' and not item.is_fixed_asset \ and (not item.po_detail or not frappe.db.get_value("Purchase Order Item", item.po_detail, "delivered_by_supplier")): if self.update_stock: item.expense_account = warehouse_account[item.warehouse]["account"] else: item.expense_account = s...
PinguinoIDE/pinguino-multilanguage
files/frames/libraries_widget.py
Python
gpl-2.0
14,604
0.003287
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/frames/libraries_widget.ui' # # Created: Fri Dec 19 15:43:21 2014 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be l...
self.pushButton_add.setObjectName("pushButton_add") self.gridLayout_3.addWidget(self.pushButton_add, 0, 1, 1, 1) self.tableWidget_sources = QtGui.QTableWidget(self.tab_2) self.tableWidget_sources.setAutoFillBackgro
und(True) self.tableWidget_sources.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.tableWidget_sources.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.tableWidget_sources.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.tableWidget_sources.setAlt...
mpirnat/lets-be-bad-guys
manage.py
Python
mit
250
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANG
O_SETTINGS_MODULE", "badguys.
settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Kakarot/PythonIO
FileManipulator.py
Python
mit
696
0.025862
def printFileContents(myFile): print(open(myFile).read().splitlines()) def writeFileContents(myFile, somethingToWrite): f = open(myFile,'a') f.write(somethin
gToWrite +'\n') # python will convert \n to os.linesep f.close() # you can omit in most cases as the destructor will call if printFileContents("alive.txt") writeFileContents("writer.txt", "All for one!") #Consider for Example #def writeToDatabase(): # import pyodbc # cnxn = pyodbc.connect('DRIVER={SQL Server};SERVE...
users") # rows = cursor.fetchall() # for row in rows: # print row.user_id, row.user_name
erikdejonge/puffin
puf/cli.py
Python
mit
3,395
0.003829
# coding=utf-8 """ - """ from __future__ import division, unicode_literals, absolute_import from __future__ import print_function from future import standard_library standard_library.install_aliases() import argparse from puf import cli_lib def main(params=None): """ :param params: :return: """ p...
ay this help message.') parser.add_argument('--version', action='store_true', help='Display the version.') parser.add_argument('command', nargs='?') parser.add_argument('file', nargs='*') args = parser.parse_args(params) if args.tab_separator: args.separator = '\t' if args.version: ...
_resources print(pkg_resources.get_distribution('puffin').version) return if not (args.command or args.command_file): return parser.print_help() glob = {} if args.before: exec(args.before, glob) for stream_in, stream_out in cli_lib.determine_streams(args): for...
xpenatan/dragome-backend
extensions/gdx-bullet/gdx-bullet-build/jni/emscripten/webidl_binder.py
Python
apache-2.0
25,177
0.01267
''' WebIDL binder http://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.html ''' import os, sys sys.path.append(sys.argv[3]) import shared sys.path.append(shared.path_from_root('third_party')) sys.path.append(shared.path_from_root('third_party', 'ply')) import WebIDL # ...
uffer temps: [], // extra allocations needed: 0, // the total size we need next time prepare: function() { if (this.needed) { // clear the temps for (var i = 0; i < this.temps.length; i++) { Module['_free'](this.temps[i]); } this.temps.length = 0; // prepare to allocate ...
his.needed = 0; } if (!this.buffer) { // happens first time, or when we need to grow this.size += 128; // heuristic, avoid many small grow events this.buffer = Module['_malloc'](this.size); assert(this.buffer); } this.pos = 0; }, alloc: function(array, view) { assert(this.buffe...
MartinAltmayer/pokerserver
tests/integration/controllers/test_table.py
Python
gpl-3.0
14,923
0.000804
from http import HTTPStatus from json import loads from unittest.mock import Mock, patch from uuid import uuid4 from tornado.testing import gen_test from pokerserver.database import PlayerState, UUIDsRelation from pokerserver.models import InvalidTurnError, NotYourTurnError, Player, PositionOccupiedError from tests.u...
-1},
raise_error=False ) self.assertEqual(response.code, HTTPStatus.BAD_REQUEST.value) class TestFoldController(IntegrationHttpTestCase): async def async_setup(self): self.uuid = uuid4() self.player_name = 'player' await UUIDsRelation.add_uuid(self.uuid, self.player_name) ...
arnavd96/Cinemiezer
myvenv/lib/python3.4/site-packages/music21/test/testStream.py
Python
mit
284,928
0.006914
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: testStream.py # Purpose: tests for stream.py # # Authors: Michael Scott Cuthbert # Christopher Ariza # # Copyright: Copyright © 2009-2014 Michael Scott Cuthbert and the mu...
.TimeSignature("10/4") ) a.show() def testMultipartStreams(self): '''Test the creation of multi-part streams by simply having streams within streams. ''' q = Stream() r = Stream() for x in ['c3','a3','g#4','d2'] * 10: n =
note.Note(x) n.quarterLength = .25 q.append(n) m = note.Note(x) m.quarterLength = 1.125 r.append(m) s = Stream() # container s.insert(q) s.insert(r) s.insert(0, meter.TimeSignature("3/4") ) s.insert(3, meter.TimeSignat...
fusionbox/django-extensions
django_extensions/management/commands/validate_templates.py
Python
mit
3,269
0.003059
import os from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.core.management.color import color_style from django.template.base import add_to_builtins from django.template.loaders.filesystem import Loader from django_extensions.utils import validatingtemplatet...
try: template_loader.load_template(filename, [root]) except Exception, e: errors += 1 print "%s: %s" % (filepath, style.ERROR("%s %s" % (e.__class__.__name__, str(e)))) template_errors = validatin...
print "%s(%s): %s" % (origin, line, style.ERROR(message)) if errors and options.get('break', False): raise CommandError("Errors found") if errors: raise CommandError("%s errors found" % errors) print "%s errors found" % errors
potix2/crazyflie_rospy
scripts/crazyflie_add.py
Python
mit
1,867
0.002142
#!/usr/bin/env python import sys import rospy from crazyflie_rospy.srv import AddCrazyflie, AddCrazyflieRequest, AddCrazyflieResponse def main(args): rospy.init_node('crazyflie_add') uri = rospy.get_param("~uri") tf_prefix = rospy.get_param("~tf_prefix") roll_trim = rospy.get_param("~roll_trim", 0.0)...
param("~enable_parameters", True) use_ros_time = rospy.get_param("~use_ros_time", True) enable_logging_imu = rospy.get_param("~enable_logging_imu", True) enable_logging_temperature = rospy.get_param("~enable_logging_temperature", True) enable_logging_magnetic_field = rospy.get_param("~enable_logging_mag...
ing_pressure", True) enable_logging_battery = rospy.get_param("~enable_logging_battery", True) height_hold = rospy.get_param("~height_hold", False) rospy.loginfo("wait_for_service add_crazyflie...") rospy.wait_for_service('/add_crazyflie') rospy.loginfo("done") try: add_crazyflie = rosp...
makinacorpus/Geotrek
geotrek/outdoor/templatetags/outdoor_tags.py
Python
bsd-2-clause
1,633
0
from django import template from django.conf import settings import json from geotrek.outdoor.models import Practice, RatingScale, Site register = template.Library() @register.simple_tag def is_outdoor_enabled(): return 'geotrek.
outdoor' in settings.INSTALLED_APPS @register.simple_tag def site_practices(): practices = { str(practice.pk): { 'types': { str(type.pk): type.name for type in practice.site_types.all() }, 'scales': { str(scale.pk): scale....
}, } for practice in Practice.objects.all() } return json.dumps(practices) @register.simple_tag def course_sites(): sites = { str(site.pk): { 'types': { str(type.pk): type.name for type in site.practice.course_types.all() ...
twitter/pants
contrib/scrooge/src/python/pants/contrib/scrooge/tasks/thrift_util.py
Python
apache-2.0
2,327
0.011603
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import re from builtins import open INCLUDE_PARSER = re.compile(r'^\s*include...
ft files included by the given thrift source. :basedirs: A set of thrift source file base directories to look for includes in. :source: The thrift source file to scan for includes. :log: An optional logger """ all_bas
edirs = [os.path.dirname(source)] all_basedirs.extend(basedirs) includes = set() with open(source, 'r') as thrift: for line in thrift.readlines(): match = INCLUDE_PARSER.match(line) if match: capture = match.group(1) added = False for basedir in all_basedirs: inc...
DeanSherwin/django-dynamic-scraper
tests/scraper/scraper_test.py
Python
bsd-3-clause
10,956
0.011044
from __future__ import unicode_literals from builtins import str from builtins import object import logging, os, os.path, shutil from django.test import TestCase from scrapy import signals from scrapy.exceptions import DropItem from scrapy.utils.project import get_project_settings settings = get_project_settings() ...
], priority='cmdline') settings.set('COOKIES_DEBUG', True) settings.set('LOG_LEVEL', 'DEBUG') settings.set('LOG_ENABLED', False) #self.crawler = Crawler(settings) #self.crawler.signals.connect(reactor.stop, signal=signals.spider_closed) #self.crawler.con...
ss(settings) self.sc = ScrapedObjClass(name='Event') self.sc.save()