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 |
|---|---|---|---|---|---|---|---|---|
axeleratio/CurlySMILESpy | csm_notation.py | Python | gpl-3.0 | 36,184 | 0.027609 | """
This file: csm_notation.py
Last modified: November 8, 2010
Package: CurlySMILES Version 1.0.1
Author: Axel Drefahl
E-mail: axeleratio@yahoo.com
Internet: http://www.axeleratio.com/csm/proj/main.htm
Python module csm_notation implements a class for managing
a Cur... | version.
The CurlySMILES package is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the CurlySMILES package.
If not, see <http://www.gnu.org/licenses/>.
"""
import csm_dataface, csm_annsmi, csm_molform, csm_sfn, csm_curlyann
import re
class Notation:
... |
BlackSmith/GreenTea | apps/report/migrations/0003_externalpage.py | Python | gpl-2.0 | 661 | 0.001513 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('report', '0002_auto_20160401_1609'),
]
operations = [
migrations.CreateModel(
name='ExternalPage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_lengt... | )),
('is_enabled', models.BooleanField(default=True)),
],
),
]
|
trevor/calendarserver | txdav/common/idirectoryservice.py | Python | apache-2.0 | 2,527 | 0.006727 | ##
# Copyright (c) 2013-2014 Apple 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/licenses/LICENSE-2.0
#
# Unless required by applicable l... | is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| ##
"""
Common directory service interfaces
"""
from zope.interface.interface import Interface, Attribute
__all__ = [
"IStoreDirectoryService",
"IStoreDirectoryRecord",
]
class IStoreDirectoryError(Exception):
"""
Base class for directory related errors.
"""
class DirectoryRecordNotFoundError... |
joachimmetz/dfvfs | dfvfs/vfs/extent.py | Python | apache-2.0 | 844 | 0.00237 | # -*- coding: utf-8 -*-
"""The Virtual File System (VFS) extent."""
class Extent(object):
"""Extent.
Attributes:
extent_type (str): type of the extent, for example EXTENT_TYPE_SPARSE.
offset (int): offset of the extent relative f | rom the start of the file
system in bytes.
size (int): size of the extent in bytes.
"""
def __init__(self, extent_type=None, offset=None, size=None):
"""Initializes an extent.
Args:
extent_type (Optional[str]): type of the e | xtent, for example
EXTENT_TYPE_SPARSE.
offset (Optional[int]): offset of the extent relative from the start of
the file system in bytes.
size (Optional{int]): size of the extent in bytes.
"""
super(Extent, self).__init__()
self.extent_type = extent_type
self.offset = offs... |
ProvidencePlan/Profiles | communityprofiles/maps/migrations/0009_auto__add_field_polygonmapfeature_geo_level__add_field_linestringmapfe.py | Python | mit | 6,613 | 0.006956 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'PolygonMapFeature.geo_level'
db.add_column(u'maps_polygonmapfeature', 'geo_level', self.gf... | u'maps.pointmapfeature': {
'Meta': {'object_name': 'PointMapFeature'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'geo_key': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}),
'geo_leve... | |
PressLabs/django-bnr | django_bnr/app.py | Python | mit | 193 | 0 | # -*- coding: u | tf-8 -*-
# vim: ft=python:sw=4:ts=4:sts=4:et:
from django.apps import AppConfig
class DjangoBNRApp(AppConfig):
name = 'django_bnr'
verbose_name = | 'BNR Exchange Rates'
|
sandhujasmine/conda-build | tests/test-recipes/metadata/numpy_run/run_test.py | Python | bsd-3-clause | 559 | 0.005367 | import os
import json
import glob
def main():
prefix = os.environ['PREFIX']
info_files = glob.glob(os.path.join(prefix, 'conda-me | ta',
'conda-build-test-numpy-run-1.0-py*0.json'))
assert len(info_fi | les) == 1
info_file = info_files[0]
with open(info_file, 'r') as fh:
info = json.load(fh)
assert len(info['depends']) == 2
depends = sorted(info['depends'])
# With no version
assert depends[0] == 'numpy'
assert depends[1].startswith('python ')
if __name__ == '__main__':
main()
|
monsta/pluma | plugins/externaltools/tools/__init__.py | Python | gpl-2.0 | 10,313 | 0.002812 | # -*- coding: UTF-8 -*-
# Pluma External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either versi... | (self, language, item):
if not item.languages:
return True
if not language and 'plain' in item.language | s:
return True
if language and (language.get_id() in item.languages):
return True
else:
return False
def filter(self, document):
if document is None:
return
titled = document.get_uri() is not None
remote = not documen... |
uraxy/qiidly | tests/test_feedly.py | Python | mit | 1,969 | 0.001016 | # -*- coding: utf-8 -*-
import unittest
import qiidly.feedly
class TestFeedly(unittest.TestCase):
"""Test for qiidly.feedly
Getting Started with Sandbox
https://developer.feedly.com/v3/sandbox/
OAuth clientId: sandbox
OAuth clientSecret: CNKEATM7ICEGVOZ3P5A1 (expires on October 1st 2016)
AP... | feed_url = 'https://example.com/feed'
expected = 'feed/https://example.com/feed'
actual = qiidly.feedly.feed_id_from_feed_url(feed_url)
self.assertEqual(expected, actual)
def test_feed_url_from_feed_id(self):
feed_id = 'feed/https://example.com/feed'
expected = 'https:/... | f test_category_id_from_user_id_and_category(self):
USER_ID = 'UUU'
CATEGORY = 'CCC'
expected = 'user/UUU/category/CCC'
actual = qiidly.feedly.category_id_from_user_id_and_category(USER_ID, CATEGORY)
self.assertEqual(expected, actual)
def test_category_from_category_id(self)... |
tonypeng/tensorstyle | utils.py | Python | mit | 1,610 | 0.00559 | import numpy as np
import os
import scipy.misc
import shutil
import tensorflow as tf
from functools import reduce
from operator import | mul
def read_image(path, mode='RGB', size=None):
img = scipy.misc.imread(path, mode=mode)
if size is not None:
img = scipy.misc.imresize(img, size)
return img
def write_image(img, path):
img = np.clip(img, 0, 255).astype(np.uint8)
scipy.misc.imsave(path, img)
def get_output_filepath(outpu... | e, suffix='', ext='jpg'):
return os.path.join(output_path, name+'_'+suffix+'.'+ext)
def gram_matrix(mat):
mat = mat.reshape((-1, mat.shape[2]))
return np.matmul(mat.T, mat) / mat.size
def tf_batch_gram_matrix(batch):
_, height, width, channels = tensor_shape(batch)
batch = tf.reshape(batch, (-1, h... |
mostafa-mahmoud/sahwaka | docs/conf.py | Python | apache-2.0 | 8,086 | 0.007668 | # -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... | ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the do... | eme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None... |
franziz/artagger | artagger/Utility/LexiconCreator.py | Python | apache-2.0 | 5,852 | 0.000684 | # -*- coding: utf-8 -*-
import os
import re
import sys
os.chdir("../")
sys.setrecursionlimit(100000)
sys.path.append(os.path.abspath(""))
os.chdir("./Utility")
from .Utils import getWordTag
def add2WordTagFreqDict(word, tag, inDict):
if word not in inDict:
inDict[word] = {}
inDict[word][tag] = ... | ms(), key=itemgetter(0)))
# Get the most frequent tag in the lexicon to label unknown words and numbers
tagCounter_Alphabet = OrderedDict(
sorted(tagCounter_Alphabet.items(), key=itemgetter(1), reve | rse=True)
)
tagCounter_CapitalizedWord = OrderedDict(
sorted(
tagCounter_CapitalizedWord.items(), key=itemgetter(1), reverse=True
)
)
tagCounter_Numeric = OrderedDict(
sorted(tagCounter_Numeric.items(), key=itemgetter(1), reverse=True)
)
tag4UnknWord = tagCoun... |
kubernauts/pyk | setup.py | Python | apache-2.0 | 962 | 0.006237 | from setupt | ools import setup, find_packages
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
ex | cept (IOError, ImportError):
long_description = ''
setup(
name="pyk",
version="0.3.2",
description="A simple, yet useful Kubernetes toolkit in Python",
long_description=long_description,
author="Michael Hausenblas",
author_email="michael.hausenblas@gmail.com",
license="Apache",
url="... |
kmacinnis/sympy | sympy/core/exprtools.py | Python | bsd-3-clause | 41,487 | 0.000386 | """Tools for manipulating of large commutative expressions. """
from __future__ import print_function, division
from sympy.core.add import Add
from sympy.core.compatibility import iterable, is_sequence, SYMPY_INTS
from sympy.core.mul import Mul, _keep_coeff
from sympy.core.power import Pow
from sympy.core.basic impor... | iners import Tuple, Dict
from sympy.utilities import default_sort_key
from sympy.utilities.iterables import (common_prefix, common_suffix,
variations, ordered)
from collections import defaultdict
def _isnumber(i):
retu | rn isinstance(i, (SYMPY_INTS, float)) or i.is_Number
def decompose_power(expr):
"""
Decompose power into symbolic base and integer exponent.
This is strictly only valid if the exponent from which
the integer is extracted is itself an integer or the
base is positive. These conditions are assumed a... |
community-ssu/telepathy-gabble | tests/twisted/jingle/call-state.py | Python | lgpl-2.1 | 11,183 | 0.006885 | """
Test exposing incoming <hold/>, <ringing/> and <active/> notifications via the
CallState interface.
"""
from twisted.words.xish import xpath
from gabbletest import make_result_iq
from servicetest import (
wrap_channel, make_channel_proxy, EventPattern, sync_dbus)
import ns
import constants as cs
from jinglet... | NG]),
)
call_states = chan.CallState.GetCallStates()
assert call_states == { handle: cs.CALL_STATE_RINGING }, call_states
sync_dbus(bus, q, conn)
q.unforbid_events(forbidden)
jt.accept()
if jp.is_modern_jingle():
# The other person's client decides i | t's not ringing any more
node = jp.SetIq(jt.peer, jt.jid, [
jp.Jingle(jt.sid, jt.jid, 'session-info', [
('active', ns.JINGLE_RTP_INFO_1, {}, []) ]) ])
stream.send(jp.xml(node))
# Gabble tells s-e to start sending, and removes the Ringing flag, either
# because we got... |
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/blackfellas/app.py | Python | mit | 143 | 0.006993 | #encoding:utf-8
su | breddit = 'Blackfellas'
t_channel = '@blackfellas'
def send_post(submission, r2t):
return r2t.send_simple(submission | )
|
ikargis/horizon_fod | openstack_dashboard/dashboards/admin/projects/tests.py | Python | apache-2.0 | 74,820 | 0.000254 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Nebula, 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
#
# ... | ('is_extension_supported',), |
quotas: ('get_default_quota_data',)})
def test_add_project_get(self):
quota = self.quotas.first()
default_role = self.roles.first()
default_domain = self._get_default_domain()
domain_id = default_domain.id
users = self._get_all_users(domain_id)
... |
tomviner/upyflashed | upyflashed/__init__.py | Python | apache-2.0 | 26 | 0 | from .reflash imp | ort m | ain
|
aterrel/blaze | blaze/data/tests/test_dynd.py | Python | bsd-3-clause | 854 | 0.002342 | from blaze.data.dynd import *
from dynd import n | d
from unittest import TestCase
class TestDyND(TestCase):
data = [[1, 1], [2, 2]]
def setUp(self):
arr = nd.array(self.data, dtype='2 * 2 * int32')
| self.dd = DyND(arr)
def test_dshape(self):
assert str(self.dd.dshape) == '2 * 2 * int32'
assert str(self.dd.schema) == '2 * int32'
def test_iteration(self):
assert tuple(map(tuple, self.dd)) == ((1, 1), (2, 2))
def test_chunks(self):
chunks = list(self.dd.chunks())
... |
plotly/python-api | packages/python/plotly/plotly/validators/heatmap/_uirevision.py | Python | mit | 447 | 0.002237 | import _plotly_utils.basevalidators
class UirevisionValidator(_plotly_u | tils.basevalidators.AnyValidator):
def __init__(self, plotly_name="uirevision", parent_name="heatmap", **kwargs):
super(UirevisionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
role=kwarg... |
)
|
robofit/ar-table-itable | art_helpers/src/art_helpers/__init__.py | Python | lgpl-2.1 | 720 | 0.002778 | from art_helpers.instructions_helper import | InstructionsHelper, InstructionsHelperException
from art_helpers.program_helper import ProgramHelper, ProgramHelperException
from art_helpers.art_robot_helper import ArtRobotArmHelper, ArtRobotHelper, UnknownRobot,\
RobotParametersNotOnParameterServer
from art_helpers.interface_state_manager import InterfaceStateMa... |
for s in rospy.get_param(param).split(","):
tmp.append(target_type(s.strip()))
if expected_length is not None:
assert len(tmp) == expected_length
return tmp
|
pbmanis/acq4 | acq4/util/Canvas/items/simpleitems.py | Python | mit | 1,421 | 0.008445 | # -*- coding: utf-8 -*-
from __future__ import print_function
from acq4.util import Qt
import acq4.pyqtgraph as pg
from .CanvasItem import CanvasIt | em
from .itemtypes import registerItemType
class GridCanvasItem(CanvasItem):
_typeName = "Grid"
def __init__(self, **kwds):
kwds.pop('viewRect', None)
item = pg.GridItem()
CanvasItem.__init__(self, item, **kwds)
registerItemType(GridCanvasItem)
class RulerCanvasItem(CanvasItem... | points = ((0, 0), (1, 1))
else:
p1 = vr.center()
p2 = p1 + 0.2 * (vr.topRight()-p1)
points = ((p1.x(), p1.y()), (p2.x(), p2.y()))
item = pg.graphicsItems.ROI.RulerROI(points)
CanvasItem.__init__(self, item, **kwds)
registerItemType(Rule... |
frappe/erpnext | erpnext/payroll/doctype/employee_benefit_claim/test_employee_benefit_claim.py | Python | gpl-3.0 | 163 | 0.006135 | # Copyright (c) 2018, Frappe Technologies P | vt. Ltd. and Contributors
# See license.txt
import unittest
class TestEmployeeBenefitClaim(unittes | t.TestCase):
pass
|
muk-it/muk_dms | muk_dms_access/tests/test_benchmark.py | Python | lgpl-3.0 | 1,933 | 0.005173 | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Access
# (see https://mukit.at).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Le... | WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu... | ########################################
import os
import time
import logging
import unittest
import threading
import functools
from odoo.tests import tagged
from odoo.tools.profiler import profile
from odoo.tools import config, convert_file
from odoo.modules.module import get_resource_path
from odoo.modules.module i... |
igoralmeida/corvogame | client/games/wargame_client.py | Python | gpl-3.0 | 1,978 | 0.002528 | # -*- coding: utf-8 -*-
# This file is part of corvogame.
#
# corvogame is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | abstract_game.GameHandler.__init__(self, msg_sender, ui)
self.read_handler = self.lobby_handler
def lobby_handler(self, msg):
logging.debug('Wargame handling message {0}'.format(msg))
action = m | sg[u'action'][14:] #remove 'wargame_lobby_' from msg
if action == 'game_capabilities':
colors = msg[u'available_colors']
self.update_colors(colors)
caps = msg[u'capabilities']
self.update_capabilities(caps)
self.ui.register_connection_handler(self)
... |
ARTFL-Project/PhiloLogic4 | www/reports/table_of_contents.py | Python | gpl-3.0 | 998 | 0.003006 | #!/usr/bin/env python3
import os
from wsgiref.handlers import CGIHandler
import orjson
import sys
sys.path.append("..")
import custom_functions
try:
from custom_functions import generate_toc_object
except ImportError:
from philologic.runtime import generate_toc_object
try:
from custom_functions import ... | table_of_contents(environ, start_response):
config = WebConfig(os.path.abspath(os.path.dirname(__file__)).replace("reports", ""))
request = WSGIHandler(environ, config)
headers = [("Content-type", "application/json; charset=UTF-8"), ("Access-Control-Allow-Origin", "*")]
start_response("200 OK", headers... | :
CGIHandler().run(table_of_contents)
|
anselmobd/fo2 | src/cd/queries/functions.py | Python | mit | 898 | 0.002227 | from pprint import pprint
import lotes.models
def where_ende_disponivel(campo):
filter_local = ""
end_disp = list(lotes.models.EnderecoDisponivel.objects.filter(disponivel=True).values())
if len(end_disp) != 0:
filter_end = """--
AND l.local ~ '^("""
filter_sep = ""
f... | nd_indisp = list(lotes.models.EnderecoDisponivel.objects.filter(disponiv | el=False).values())
if len(end_indisp) != 0:
filter_end = """--
AND l.local !~ '("""
filter_sep = ""
for regra in end_indisp:
filter_end += f"{filter_sep}{regra['inicio']}"
filter_sep = "|"
filter_local += filter_end + """)'
"""
return ... |
fmoro/django-mongodbforms | mongodbforms/util.py | Python | bsd-3-clause | 4,265 | 0.000703 | from collections import defaultdict
from django.conf import settings
from mongodbforms.documentoptions import DocumentMetaWrapper, LazyDocumentMetaWrapper
from mongodbforms.fieldgenerator import MongoDefaultFormFieldGenerator
try:
from django.utils.module_loading import import_by_path
except ImportError:
# t... | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions... | F ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISI... |
krimkus/stipplebot | servo.py | Python | unlicense | 934 | 0 | #!/usr/bin/env python
import time
import os
# Base class for a servo motor controller using ServoBlaster
class ServoMotor(object):
# how long it takes to get the pen down before lifting back up
wait_time | = .9
def __init__(self, **kwargs):
for key in kwargs:
if hasattr(self.__class__, key):
setattr(self, key, kwargs[key])
def tap(self):
os.system('echo 0=100 > /dev/servoblaster')
time.sleep(self.wait_time)
os.system('echo 0=142 > /dev/servoblaster')
... | > /dev/servoblaster' % position)
# To test tapping five times with .4 second pauses between each tap
if __name__ == "__main__":
pen = ServoMotor()
start_time = time.time()
time_between_taps = .4
for i in range(5):
pen.tap()
time.sleep(time_between_taps)
print time.time() - start_t... |
rbarlow/pulp_packaging | ci/promote-brach.py | Python | gpl-2.0 | 3,501 | 0.003713 | #!/usr/bin/env python2
import os
import subprocess
import argparse
from lib import builder
from lib import promote
current_directory = os.path.realpath(os.path.dirname(__file__))
parser = argparse.ArgumentParser()
description = "Used to promote from one branch to another. For example, from 2.6-dev to " \
... | y)
promote.merge_forward(git_directory)
print "Don't forget the following branches need to be pushed t | o github:"
print promotion_chain
|
davy39/eric | Cooperation/CooperationServer.py | Python | gpl-3.0 | 2,057 | 0.003889 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 - 2014 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the cooperation server.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtNetwork import QTcpServer
from .Connection import Connection
import Prefere... | lic method to start listening for new connections.
@param port port to list | en on (integer)
@param findFreePort flag indicating to search for a free port
depending on the configuration (boolean)
@return tuple giving a flag indicating success (boolean) and
the port the server listens on
"""
res = self.listen(self.__address, port)
i... |
tomborine/tomb_migrate | tomb_migrate/main.py | Python | mit | 4,125 | 0 | import click
import os
import sys
from tomb_migrate.utils import get_databases_from_settings
from tomb_migrate.utils import get_upgrade_path, get_downgrade_path
from tomb_migrate.utils import create_new_revision
from tomb_migrate.utils import (
AlreadyInitializedException,
NoMigrationsFoundException,
NotI... | pgrade_path = get_upgrade_path(c | tx.obj.db_path)
except NoMigrationsFoundException:
click.echo(
"Did not find any migrations to run in %s" % ctx.obj.db_path
)
click.echo(
"Have you tried running `tomb db revision -m <description>`?"
)
sys.exit(1)
for revision in upgrade_path:
... |
johcheun/ops-pmd | ops-tests/feature/bgp/vtysh_utils.py | Python | gpl-2.0 | 3,609 | 0.000277 | # -*- coding: utf-8 -*-
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# 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.a... | routes = switch("show ip bgp")
if print_routes:
print("### Ro | utes for switch %s ###\n" % switch.name)
print("%s\n" % routes)
routes = routes.split(vtysh_cr)
for rte in routes:
if (network in rte) and (next_hop in rte):
return True
routes = switch("show ipv6 bgp")
if print_routes:
print("### R... |
SkyLapse/DMS | src/Server/model/basemodel.py | Python | mit | 1,731 | 0.002311 | from bson import DBRef
from pymongo.database import Database
__author__ = 'SkyLapse'
from abc import ABCMeta, abstractmethod
class Bas | eModel():
__metaclass__ = ABCMeta
def __init__(self, base, config, client, db):
self.base = base
self.config = config
self.client = client
self.db = db
def get(self, spec=None, limit | =0):
return self.get_collection().find(spec, limit=limit)
@abstractmethod
def get_collection(self):
pass
def get_single(self, spec = None):
return self.get_collection().find_one(spec)
def insert(self, data):
return self.get_collection().insert(self._populate(data))
... |
thegaps/GEB | floop/bloop/tortoise.py | Python | gpl-3.0 | 544 | 0.025735 | # Not bloop.
# There are p | lenty of numbers greater than N, I can even think of
# three off-the-cuff; N+7, N+37, N+101!
# Don't know how long we might have to wait until we get a good one. . .
# Tortoise property:
# An even number, 2N, has the Tortoise | property if it is the
# difference of two odd primes.
# Check if a given number, N, has the tortoise property
#--------------------------------
Psuedocode:
def TORTOISE(N):
poke around for a few different prime1's and prime2's:
if prime1-prime2 = N
return true
else
return false
|
czcorpus/kontext | lib/plugins/redis_db/cleanup.py | Python | gpl-2.0 | 1,129 | 0.004429 | #!/usr/bin/env pyth | on3
import os
import sys
import redis
app_path = os.path.realpath('%s/../../..' % os.path.dirname(os.path.absp | ath(__file__)))
sys.path.insert(0, '%s/lib' % app_path)
import settings
def get_db(conf):
return redis.StrictRedis(host=conf['host'], port=int(conf['port']), db=int(conf['id']))
if __name__ == '__main__':
import argparse
argparser = argparse.ArgumentParser(description="RedisDB clean-up utility")
a... |
wagnerand/zamboni | apps/devhub/tests/test_views_versions.py | Python | bsd-3-clause | 31,061 | 0.000129 | import re
from datetime import datetime, timedelta
import mock
from nose.tools import eq_
from pyquery import PyQuery as pq
import amo
import amo.tests
from amo.urlresolvers import reverse
from amo.tests import formset, initial
from addons.models import Addon
from applications.models import Application, AppVersion
fr... | 1)
eq_(Addon.objects.get(id=3615).status, amo.STATUS_PUBLIC)
def test_version_delete_status_unreviewd(self):
self._extra_version_and_file(amo.STATUS_BETA)
res = self.client.post(self.delete_url, self.delete_data)
eq_(res.status_code, 302)
eq_(self.addon.versions.count(), 1... | o.STATUS_UNREVIEWED)
@mock.patch('files.models.File.hide_disabled_file')
def test_user_can_disable_addon(self, hide_mock):
self.addon.update(status=amo.STATUS_PUBLIC,
disabled_by_user=False)
res = self.client.post(self.disable_url)
eq_(res.status_code, 302)
... |
hbp-brain-charting/public_protocols | stanford_battery/protocol/design_files/stop_signal/GA_design.py | Python | bsd-3-clause | 937 | 0.104589 | from neurodesign import geneticalgorithm, generate, msequence
import sys
design_i = sys.argv[1]
EXP = geneticalgorithm.experiment(
TR = 0.68,
P = [.6,.4],
C = [[0.5, -0.5]],
rho = 0.3,
n_stimuli = 2,
n_trials = 125,
duration = 310,
resolution = 0.136,
stim_duration = 1.85... | = 3,
ITImodel = 'exponential',
ITImin = 0.0,
ITImean = 0.225,
ITImax = 6.0,
restnum = 0,
restdur = 0.0)
POP = geneticalgorithm.population(
experiment = EXP,
G = 20,
R = [0.4, 0.4, 0.2],
q = 0.01,
weights = [0.0, 0.1, 0.4, 0.5],
I = 4,
preruncycles = 10 | 00,
cycles = 4000,
convergence = 1000,
outdes = 4,
folder = '../fmri_experiments/design_files/stop_signal/stop_signal_designs_'+design_i)
POP.naturalselection()
POP.download()
|
debian-live/live-magic | LiveMagic/controllers/wizard.py | Python | gpl-3.0 | 3,487 | 0.003441 | # -*- coding: utf-8 -*-
#
# live-magic - GUI frontend to create Debian LiveCDs, etc.
# Copyright (C) 2007-2010 Chris Lamb <lamby@debian.org>
#
# 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 Found... | OUT ANY WARRANTY; without even the i | mplied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import gtk
import time
import... |
111pontes/ydk-py | cisco-ios-xe/ydk/models/cisco_ios_xe/_meta/_Cisco_IOS_XE_eem.py | Python | apache-2.0 | 858 | 0.013986 |
import re
import collectio | ns
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_i | nfo import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST, REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION, ANYXML_CLASS
from ydk.errors import YPYError, YPYModelError
from ydk.providers._importer import _yang_ns
_meta_table = {
'OperatorTypeEnum' : _MetaInfoEnum... |
asmltd/gosports | webapp/ui/migrations/0001_initial.py | Python | gpl-3.0 | 3,109 | 0.004503 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-23 05:52
from __future__ import unicode_literals
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... | 'user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
| ],
options={
'abstract': False,
'verbose_name': 'user',
'verbose_name_plural': 'users',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
|
unixboy/stashboard | stashboard/handlers/api.py | Python | mit | 20,209 | 0.000891 | # The MIT License
#
# Copyright (c) 2008 William T. Katz
#
# 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,... | data = [s.rest(self.base_url(version)) for s in query]
data = {"services": data}
self.json(data)
@authorized.api("admin")
def post(self, version):
if not self.valid_vers | ion(version):
self.error(404, "API Version %s not supported" % version)
return
name = self.request.get('name', default_value=None)
description = self.request.get('description', default_value=None)
slist = self.request.get('list', default_value=None)
l = None
... |
krischer/jane | src/jane/quakeml/plugins.py | Python | gpl-3.0 | 12,262 | 0.000082 | # -*- coding: utf-8 -*-
"""
QuakeML Plug-in for Jane's Document Database.
This file also serves as a template/tutorial to create new plug-ins and is
thus extensively commented.
"""
# In the interest of quick import/startup times, please try to import within
# the functions and not at the file level.
from jane.document... | Point,
DocumentPluginPoint,
RetrievePermissionPluginPoint)
class QuakeMLPlugin(DocumentPluginPoint):
"""
| Each document type for Jane's Document Database must have a
DocumentPluginPoint with some basic meta information.
"""
# Each plug-in for a certain document type must share the same name.
# That's how the plug-ins are grouped per document type.
name = 'quakeml'
# The title is only for this part... |
OpenSolutionsFinland/exporting | __openerp__.py | Python | agpl-3.0 | 1,635 | 0.008563 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) Open Solutions Finland 2013.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gen... | License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; w | ithout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###... |
michaelld/gnuradio | grc/gui/canvas/connection.py | Python | gpl-3.0 | 8,832 | 0.001019 | """
Copyright 2007, 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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... | - x_pos, y_start - y_pos
p1, p2, (dx_e1, dy_e1), (dx_e2, dy_e2), (dx_e3, dy_e3) = self._rel_points
p3 = x_ | e + dx_e1, y_e + dy_e1
p4 = x_e + dx_e2, y_e + dy_e2
p5 = x_e + dx_e3, y_e + dy_e3
self._bounding_points = p0, p1, p4, p5 # ignores curved part =(
if cr:
cr.move_to(*p0)
cr.line_to(*p1)
cr.curve_to(*(p2 + p3 + p4))
cr.line_to(*p5)
... |
Paul-Ezell/cinder-1 | cinder/volume/drivers/san/hp/hp_3par_common.py | Python | apache-2.0 | 113,633 | 0.000141 | # (c) Copyright 2012-2015 Hewlett-Packard Development Company, L.P.
# 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... | array
The 3PAR drivers requires 3.1.3 firmware on the 3PAR array.
You will need to install the python hp3parclient.
sudo pip install hp3parclient
The drivers uses both the REST service and the SSH
command line to correctly operate. Since the
ssh credentials and the REST credentials can be different
we need to have ... | AR
array. It also requires the setting of
hp3par_api_url, hp3par_username, hp3par_password
for credentials to talk to the REST service on the 3PAR
array.
"""
import ast
import base64
import json
import math
import pprint
import re
import six
import uuid
from oslo_utils import importutils
hp3parclient = importutils... |
jmckaskill/subversion | build/generator/gen_make.py | Python | apache-2.0 | 21,368 | 0.008564 | #
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may n... | not isinstance(source, gen_base.TargetLib) or source.external_lib:
continue
elif | source.name in self.installed_libs:
continue
deps.append(source.filename)
link.append(build_path_join(retreat, source.filename))
data.modules.append(_eztdata(name=name, deps=deps, link=link))
# write a list of directories in which things are built
# get all the test ... |
OpenPhilology/nidaba | docs/conf.py | Python | gpl-2.0 | 1,597 | 0 | # -*- coding: utf-8 -*-
#
# nidaba documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 4 18:48:48 2014.
from subprocess import Popen, PIPE
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'celery.contrib.sphinx',
'sphinxcontrib.httpdomain',
'sphinxcontrib.... | atex_elements = {}
latex_documents = [('index', 'nidaba.tex', u'nidaba Documentation', u'Open\
| Greek and Latin', 'manual')]
man_pages = [('index', 'nidaba', u'nidaba Documentation', [u'Open Greek and\
Latin'], 1)]
texinfo_documents = [('index', 'nidaba', u'nidaba Documentation', u'Open Greek\
and Latin', 'nidaba', '... |
veger/ansible | lib/ansible/modules/network/f5/bigip_routedomain.py | Python | gpl-3.0 | 22,327 | 0.000627 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2016, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | from ansible.module_utils.network.f5.common import transform_name
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
from ansible.module_utils.network.f5.compare imp... | onLimit': 'connection_limit',
'servicePolicy': 'service_policy',
'bwcPolicy': 'bwc_policy',
'flowEvictionPolicy': 'flow_eviction_policy',
'routingProtocol': 'routing_protocol',
'fwEnforcedPolicy': 'fw_enforced_policy',
'fwEnforcedPolicyReference': 'fw_policy_link',
}
... |
glow-mdsol/fhirton | servers.py | Python | mit | 278 | 0 | # -*- coding: utf-8 -*-
__author__ = 'glow'
import requests
import json
server = "http://fhir.careevolution.com/apitest/fhir"
client = requests.Session()
response = client.get(server + "/Patient?_id=23&_format=appli | cation/json+fhir")
print(response)
print(response.json())
| |
Pfiver/penview | data_region.py | Python | gpl-3.0 | 1,947 | 0.005136 | # encoding: utf-8
from Tkinter import *
from penview import *
from graph_view import *
from table_view import *
class DataRegion(Frame):
def __init__(self, parent, window):
Frame.__init__(self, parent)
self.window = window
# set up the graph view, consisting of a controls and a scrollab... | is actually not yet packed
# URK - use the pack-widgets-that-should-stay-visible-on | -window-resize-first hack here
# i.e.: don't change the pack()ing order !
#
self.controls_region.pack(side=BOTTOM, fill=X, expand=0)
self.plot_region.pack(fill=BOTH, expand=1)
def show_table(self):
self.plot_region.pack_forget() # FIXME: on the first call the widget... |
ioparaskev/cenotes | cenotes/cli.py | Python | gpl-3.0 | 798 | 0 | import click
from cenotes import create_app, db, models
@click.command()
@click.option('--cleanup', is_flag=True, default=False,
help="Cleanup expired notes")
@click.option('--settings', show_default=True, type=click.Choice(
["Production", | "Development", "Testing"]), default="Production")
@click.option("--host", type=str, default="localhost", show_default=True)
@click.option("--port", type=int, default=8080, show_default=True)
def main(cleanup, settings, host, port):
app = create_app(app_settings="cenotes.config_backend.{0}"
.f... | db.session.commit()
if __name__ == '__main__':
main()
|
Answeror/torabot | torabot/lang/targets/base64_decode.py | Python | mit | 227 | 0 | import base64
from asyncio import coroutine
from .base import Base
class Target(Base): |
unary = False
@coroutine
| def __call__(self, text, encoding='utf-8'):
return base64.b64decode(text).decode(encoding)
|
mainulhossain/phenoproc | app/biowl/libraries/pear/adapter.py | Python | mit | 1,170 | 0.010256 | import os
from os import path
from ...exechelper import func_exec_run
from ...fileop import PosixFileSystem
from ....util import Utility
pear = path.join(path.abspath(path.dirname(__file__)), path.join('bin', 'pear'))
def run_pear(*args):
fs = Posix | FileSystem(Utility.get_rootdir(2))
input1 = fs.normalize_path(Utility.get_quota_path(args[0]))
input2 = fs.normalize_path(Utility.get_quota_path(args[1]))
forward_fastq = "-f {0}".format(input1)
reverse_fastq = "-r {0}".format(input2)
cmdargs = []
output_file = fs.normalize_path(Utilit... | s.normalize_path(Utility.get_quota_path(args[2]))
cmdargs.append("-o {0}".format(output_file))
else:
raise ValueError("Invalid call format for PEAR.")
for arg in args[3:]:
cmdargs.append(arg)
cmdargs.append(forward_fastq)
cmdargs.append(reverse_fastq)
func_exec_... |
eduNEXT/edunext-ecommerce | ecommerce/extensions/catalogue/management/commands/convert_course.py | Python | agpl-3.0 | 5,363 | 0.00261 |
import logging
from django.core.management import BaseCommand
from django.db import transaction
from oscar.core.loading import get_model
from oscar.test.utils import RequestFactory
from threadlocals.threadlocals import set_thread_variable
from ecommerce.courses.models import Course
from ecommerce.extensions.catalog... | led to convert | [%s]!', course_id)
def _convert_audit_to_honor(self, course):
audit_seats = [
seat for seat in course.seat_products
if getattr(seat.attr, 'certificate_type', '') == ''
]
if len(audit_seats) != 1:
logger.error('Course [%s] has [%d] audit seats.', course.id... |
hujiajie/chromium-crosswalk | tools/perf/measurements/page_cycler.py | Python | bsd-3-clause | 6,509 | 0.004916 | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The page cycler | measurement.
This measurement registers a window load handler in which is forces a layout and
then records the value of performance.now(). This call to now() measures the
time from navigationStart (immediately after the previous page's b | eforeunload
event) until after the layout in the page's load event. In addition, two garbage
collections are performed in between the page loads (in the beforeunload event).
This extra garbage collection time is not included in the measurement times.
Finally, various memory and IO statistics are gathered at the very e... |
adleff/python_ansible | class4/ex6.py | Python | apache-2.0 | 1,008 | 0.00496 | #!/usr/bin/env python
'''
Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
'''
from netmiko import ConnectHandler
from getpass import getpass
from routers import pynet_rtr1, pynet_rtr2, pynet_jnpr_srx1
def main():
'''
Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, an... | print ">>> {}: \n".format(ssh_conn.ip)
print output
print ">>>\n"
if __name__ == '__main__':
main()
| |
ueshin/apache-spark | python/pyspark/sql/catalog.py | Python | apache-2.0 | 16,780 | 0.001669 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | base")
>>> spark.catalog.databaseExists("test_new_database")
True
>>> df = spark.sql("DROP DATABASE test_new_database")
"""
return self._jcatalog.databaseExists(dbName)
@ | since(2.0)
def listTables(self, dbName: Optional[str] = None) -> List[Table]:
"""Returns a list of tables/views in the specified database.
If no database is specified, the current database is used.
This includes all temporary views.
"""
if dbName is None:
dbName ... |
Shouqun/node-gn | tools/depot_tools/third_party/pylint/checkers/spelling.py | Python | mit | 9,020 | 0.002106 | # Copyright 2014 Michal Nowikowski.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in... | instr)}),
('spelling-ignore-words',
{'default' : '',
'type' : 'string',
'metavar' : '<comma separated words>',
'help' : 'List of comma separated words that '
'should not be checked.'}),
('spelling-... | p' : 'A path to a file that contains private '
'dictionary; one word per line.'}),
('spelling-store-unknown-words',
{'default' : 'n', 'type' : 'yn', 'metavar' : '<y_or_n>',
'help' : 'Tells whether to store unknown words to '
... |
hugegreenbug/libgestures | include/build/android/bb_run_sharded_steps.py | Python | bsd-3-clause | 1,441 | 0.00694 | #!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""DEPRECATED!
TODO(bulach): remove me once all other repositories reference
'test_runner.py perf' directly.
"""
import optparse... | '--print-step', options.print_results])
flaky_options = []
if options.flaky_steps:
flaky_options = ['--flaky-steps', options.flaky_steps]
return cmd_helper.RunCmd(['build/android/test_runner.py', | 'perf', '-v',
'--steps', options.steps] + flaky_options)
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
skuda/client-python | kubernetes/test/test_logs_api.py | Python | apache-2.0 | 964 | 0.004149 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | kubernetes.client.rest import ApiException
from kubernetes.client.apis.logs_api import LogsApi
class TestLogsApi(unittest.TestCase):
""" LogsApi unit test stubs """
def setUp(self):
self.api = kubernetes.client.apis.logs_api.LogsApi()
def tearDown(self):
pass
def test_log_file_handl... | ndler(self):
"""
Test case for log_file_list_handler
"""
pass
if __name__ == '__main__':
unittest.main()
|
antong/ldaptor | ldaptor/test/test_svcbindproxy.py | Python | lgpl-2.1 | 25,999 | 0.01227 | """
Test cases for ldaptor.protocols.ldap.svcbindproxy module.
"""
from twisted.trial import unittest
from twisted.internet import reactor
from ldaptor.protocols.ldap import svcbindproxy, ldaperrors
from ldaptor.protocols import pureldap, pureber
from ldaptor import ldapfilter, testutil
class ServiceBindingProxy(unit... | rver.now
return server
def | test_bind_noMatchingServicesFound_noFallback(self):
server = self.createServer(
services=['svc1',
'svc2',
'svc3',
],
fallback=False,
responses=[
[ pureldap.LDAPSearchResultDone(ldaperrors.Success.re... |
AnimeDB/adb-browser-frontend | adb/frontend/auth/decorators.py | Python | unlicense | 2,476 | 0.003635 |
class PermissionRequired(Exception):
"""
Exception to be thrown by views which check permissions internally.
Takes a single C{perm} argument which defines the permission that caused
the exception.
"""
def __init__(self, perm):
self.perm = perm
def require_permissions(user, *permissio... | om django.conf import settings
error_view = settings.PERMISSIONS_VIEW
from django.core.urlresolvers import get_callable
self.error_view = get_callable(error_view)
def __call__(s | elf, view_or_request, *args, **kwargs):
if not self.wrapped:
self.view = view_or_request
def dec(*args, **kwargs):
try:
return self.view(*args, **kwargs)
except PermissionRequired as e:
kwargs['_perm'] = e.perm
... |
hasielhassan/AgnosticQueue | python/ui/queue_overview_form.py | Python | mit | 2,703 | 0.005919 | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'queue_overview_form.ui'
##
## Created by: Qt User Interface Compiler version 5.15.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
######... | ByName(Form)
# setupUi
def retranslateUi(self, Form):
Form.setWindowTitle(QCoreApplication.tra | nslate("Form", u"Form", None))
self.label.setText(QCoreApplication.translate("Form", u"Overall Progress", None))
self.lapsed_time_label.setText(QCoreApplication.translate("Form", u"Lapsed time: 00:00:00", None))
self.estimated_time_label.setText(QCoreApplication.translate("Form", u"Estimated tim... |
jcastp/syslog_parsing | sysparse/libparser.py | Python | gpl-3.0 | 1,244 | 0.003215 | # Generic functions used by all the parsers
import time, datetime
import sysparse.syslog_parser
import sysparse.audit_parser
def time_convert(date):
year = time.localtime()[0]
date = str(year) + " " + date
intermediate_date = datetime.datetime.strptime(date, "%Y %b %d %H:%M:%S")
converted_date = inter... | te.strftime("%Y-%m-%d %H:%M:%S")
return converted_date
def clean_message(bytes_object):
"""Gets a bytes object and, converts it to string, divides it by new line
and ..."""
text = bytes_object.decode("utf-8")
# Get rid of the "<nn> header, thst is not interesting for
## our purposes
text ... |
return text
def classify_lines(message):
"""Given a text line, detect what kind of event it is, to classify it."""
if message.startswith('type'):
return "audit"
# TODO modify this to ascertain if it is a syslog entry
else:
return "syslog"
return
def parse(kind, text):
""... |
co/TheLastRogue | ondeath.py | Python | bsd-2-clause | 1,983 | 0.001009 | import random
from compositecore import Leaf
import spawner
from messenger import msg
class RemoveEntityOnDeath(Leaf):
"""
Will remove the parent from the dungeon when parent Entity dies.
"""
def __init__(self):
super(RemoveEntityOnDeath, self).__init__()
self.component_type = "remove_... | ealth.is_dead():
msg.send_visual_message(self.parent.entity_messages.death, self.parent.position.value)
class LeaveCorpseOnDeath(Leaf):
"""
Will remove the parent from the dungeon when parent Entity dies.
"""
def __init__(self):
super(LeaveCorpseOnDeath, self).__init__()
se... | _corpse_on_death"
def on_tick(self, time):
if self.parent.health.is_dead():
spawner.spawn_corpse_of_entity(self.parent)
class LeaveCorpseTurnIntoEntityOnDeath(Leaf):
"""
Will remove the parent from the dungeon when parent Entity dies.
"""
def __init__(self, entity_factory, fai... |
tpoy0099/option_calculator | qt_ui/ui_main_window.py | Python | gpl-2.0 | 10,023 | 0.002295 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_window.ui'
#
# Created: Thu Oct 22 15:37:08 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except At... | )
| self.plot_button = QtGui.QPushButton(self.centralwidget)
self.plot_button.setObjectName(_fromUtf8("plot_button"))
self.gridLayout.addWidget(self.plot_button, 1, 1, 1, 1)
self.edit_position_button = QtGui.QPushButton(self.centralwidget)
self.edit_position_button.setObjectName(_fromUt... |
glassesfactory/Shimehari | shimehari/testsuite/test_cache.py | Python | bsd-3-clause | 3,089 | 0.000324 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import shimehari
import time
from shimehari.cache import Cache
from shimehari.core.cachestore import NullCacheStore, SimpleCacheStore
from shimehari.testsuite import ShimehariTestCase
from shimehari.testsuite.testApp.controllers impo | rt IndexController, ChildController
class TestCache(S | himehariTestCase):
def testCacheGetterSetter(self):
cache = Cache(storetype='simple')
cache.set('sake', 'shimehari')
rv = cache.get('sake')
self.assertEqual(rv, 'shimehari')
self.assert_(cache.get('osake') is None)
def testCacheGetAndSetMany(self):
cache = Cache(... |
agiovann/Constrained_NMF | use_cases/motion_correction_paper/demo_motion_correction_nonrigid.py | Python | gpl-2.0 | 36,419 | 0.005547 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 21 15:53:15 2016
@author: agiovann
"""
from __future__ import division
from __future__ import print_function
#%%
from builtins import zip
from builtins import str
from builtins import map
from builtins import range
from past.utils import old_div
im... | in enumerate(imgs):
if count % 10 == 0:
print(count)
mc[count], total_shift, start_step, xy_grid = tile_and_correct(img, template, strid | es, overlaps, max_shifts, add_to_movie=add_to_movie, newoverlaps=newoverlaps, newstrides=newstrides,
upsample_factor_grid=upsample_factor_grid, upsample_factor_fft=10, show_movie=False, max_deviation_rigid=max_deviation_rigid, shifts_opencv=shifts_o... |
jeroendoggen/blackboard-analysis-tools | blackboard_analysis_tools/main.py | Python | mit | 434 | 0.002304 | """
Blackboard Analysis Tools
Copyright 2013, Jeroen Doggen, jeroendoggen@gmail.com
"""
import sys
from blackboard_analysis_tools.blackboard import BlackboardAnalysisTools
def run():
"""Run the main program"""
assignment_analyser = Blac | kboardAnalysisTool | s()
#assignment_analyser.init()
assignment_analyser.run()
return(assignment_analyser.exit_value())
if __name__ == "__main__":
sys.exit(run())
|
JoyMonteiro/parSpectral | pspec/testIntegrator.py | Python | bsd-3-clause | 337 | 0.059347 | from pylab import *;
import RungeKutta;
def dummy(t, f, args):
return zeros(f.shape);
def dummyVel(f, args):
return 1.3;
u = zeros((10,10));
v | = ze | ros((10,10));
z = zeros((10,10));
delta = 0.1;
stepfwd = RungeKutta.RungeKutta4(delta, dummy, dummy, dummyVel);
tnew, fnew = stepfwd.integrate(0, [u,v,z],0.1);
print tnew;
|
tikuta/nachune | nachune/align.py | Python | gpl-3.0 | 581 | 0.003442 | def smith_waterman(s1: str, s2: str) -> int:
match = 2
mismatch = -2
gap = -1
mat = [[0 for i in | range(len(s1) + 1)] for j in range(len(s2) + 1)]
for | j in range(len(mat)):
for i in range(len(mat[j])):
if i == 0 or j == 0:
continue
upper_left = mat[j - 1][i - 1] + match if s1[i - 1] == s2[j - 1] else mat[j - 1][i - 1] + mismatch
left = mat[j - 1][i - 1] + gap
upper = mat[j - 1][i - 1] + gap
... |
landscape-test/all-messages | messages/pylint/E1304.py | Python | unlicense | 55 | 0 | """
E1 | 304
Missing key in format string dict | ionary
"""
|
petroniocandido/pyFTS | pyFTS/benchmarks/Util.py | Python | gpl-3.0 | 47,305 | 0.004229 | """
Facilities for pyFTS Benchmark module
"""
import matplotlib as plt
import matplotlib.cm as cmx
import matplotlib.colors as pltcolors
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sqlite3
#from mpl_toolkits.mplot3d import Axes3D
from copy import deepcopy
from pyFTS.common import Ut... | le with the benchmark data with format:
ID: integer incremental primary key
Date: Date/hour of benchmark execution
Dataset: Identify on which dataset the dataset was performed
Tag: a user defined word that indentify a benchm | ark set
Type: forecasting type (point, interval, distribution)
Model: FTS model
Transformation: The name of data transformation, if one was used
Order: the order of the FTS method
Scheme: UoD partitioning scheme
Partitions: Number of partitions
Size: Number of rules of the FTS model
Step... |
jodal/comics | comics/comics/whiteninja.py | Python | agpl-3.0 | 443 | 0 | from comics.aggregator.crawler import CrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
| name = "White Ninja"
language = "en"
url = "http://www.whiteninjacomics.com/"
start_date = "2002-01-01"
end_date = "2012-08-04"
active = False
rights = "Scott Bevan & Kent Earle"
class Crawler(CrawlerBase):
def crawl(s | elf, pub_date):
pass # Comic no longer published
|
gustavla/self-supervision | selfsup/multi/methods/jigsaw.py | Python | bsd-3-clause | 5,694 | 0.004566 | from __future__ import division, print_function, absolute_import
import selfsup
import tensorflow as tf
import os
from .base import Method
from collections import OrderedDict
import deepdish as dd
import numpy as np
import itertools
import selfsup.jigsaw
PERMUTATIONS = selfsup.jigsaw.load_permutations(selfsup.res('ji... | self.losses = OrderedDict([
('main', primary_loss),
('+weight_decay', weight_decay),
])
self.primary_loss = primary_loss
self.loss = loss
self.feedback | _variables = []
info['activations']['primary_loss'] = primary_loss
info['activations']['loss'] = loss
info['activations']['weight_decay'] = weight_decay
return info
def feedback(self, variables, iteration):
pass
|
folti/subuser | logic/subuserlib/classes/subuserSubmodules/run/runtimeCache.py | Python | lgpl-3.0 | 1,842 | 0.019001 | # -*- coding: utf-8 -*-
"""
Stores metadata about images which are built to encorporate changes to subuser images which are required in order to implement various permissions.
"""
#external imports
import os
import json
#internal imports
from subuserlib.classes.userOwnedObject import UserOwnedObject
from subuserlib.c... | ct import FileBackedObject
class RuntimeCache(dict,UserOwnedObject,FileBackedObject):
def __init__(self,user, | subuser):
self.__subuser = subuser
UserOwnedObject.__init__(self,user)
self.load()
def getPathToCurrentImagesRuntimeCacheDir(self):
return os.path.join(self.getUser().getConfig()["runtime-cache"],self.getSubuser().getImageId())
def getRuntimeCacheFilePath(self):
return os.path.join(self.getPat... |
lukas-hetzenecker/home-assistant | homeassistant/components/panasonic_viera/media_player.py | Python | apache-2.0 | 5,620 | 0.000356 | """Media player support for Panasonic Viera TV."""
import logging
from panasonic_viera import Keys
from homeassistant.components.media_player import DEVICE_CLASS_TV, MediaPlayerEntity
from homeassistant.components.media_player.const import (
MEDIA_TYPE_URL,
SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE,
SUPPORT_P... | rieve the latest data."""
await self._remote.async_update()
async def async_turn_on(se | lf):
"""Turn on the media player."""
await self._remote.async_turn_on(context=self._context)
async def async_turn_off(self):
"""Turn off media player."""
await self._remote.async_turn_off()
async def async_volume_up(self):
"""Volume up the media player."""
await... |
PinguinoIDE/pinguino-multilanguage | files/frames/board_config_advance.py | Python | gpl-2.0 | 5,588 | 0.002863 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/frames/board_config_advance.ui'
#
# Created: Fri Dec 19 15:43:20 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will ... | cts that are being defined.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("AdvanceBoardConfig", "Heap Size:", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setToolTip(QtGui.QApplication.translate("AdvanceBoardConfig", "<html><head/><body... | nd without taking too much compilation time.</p><p>-O3: This is the highest level of optimization possible. It enables optimizations that are expensive in terms of compile time and memory usage, in many cases can slow down a system due to larger binaries and increased memory usage.</p><p>-Os: This option will optimize ... |
PixelActions/django-static-template | project_name/manage-stage.py | Python | gpl-2.0 | 265 | 0.003774 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os | .environ.setdefault("DJANGO_SETTINGS_MODULE", "{{project_name}}.settings.stage")
from django.core.manageme | nt import execute_from_command_line
execute_from_command_line(sys.argv)
|
Haynie-Research-and-Development/jarvis | deps/lib/python3.4/site-packages/google/protobuf/duration_pb2.py | Python | gpl-2.0 | 2,780 | 0.006475 | # Generated by the protocol buffer compiler. DO NOT | EDIT!
# source: google/protobuf/duration. | proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from go... |
ZhaoYonggang198/xpdiff | __init__.py | Python | gpl-2.0 | 512 | 0.013672 | from element_tree import xml_compare_with_visitor, MyElementTree
from default_visitor import StdVisitor
import sys
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
if len(sys.argv) != 3:
sys.stderr.write("Usage: python %s oldfile newfile" % sys.ar | gv[0])
else:
oldTree = MyElementTree(ET.parse(sys.argv[1]).getroot())
newTree = MyElementTree(ET.parse(sys.argv[2]).getroot())
visitor = StdVisitor()
xml_compare_with_visitor(oldTree, newTree, visi | tor) |
WaveBlocks/WaveBlocksND | WaveBlocksND/Plot/stemcf3d.py | Python | bsd-3-clause | 1,964 | 0.004073 | """The WaveBlocks Project
Function for stem-plotting functions of the type f:IxI -> C
with abs(f) as z-value and phase(f) as color code.
This function makes a three dimensional stem plot.
@author: R. Bourquin
@copyright: Copyright (C) 2012, 2014, 2016 R. Bourquin
@license: Modified BSD License
"""
from numpy import ... | cf()
axes = fig.add_subplot(1, 1, 1, projection='3d')
for ui, vi, wi, col in zip(gridu, gridv, modulus, rgb_colors):
line = art3d.Line3D(*list(zip((ui, vi, 0), (ui, vi, wi))), marker=markerp, markevery=(1, 1), color=col)
axes.add_line(line)
axes.set_xlim3d(real(gridu).min(), real(gridu).m... | .set_zlim3d(real(modulus).min(), real(modulus).max())
|
YaroslavMolchan/lctv | errbot/backends/graphic.py | Python | gpl-3.0 | 8,312 | 0.002166 | import logging
import os
import re
import sys
import errbot
from errbot.backends.base import Message
from errbot.backends.text import TextBackend # we use that as we emulate MUC there already
from errbot.rendering import xhtml
# Can't use __name__ because of Yapsy
log = logging.getLogger('errbot.backends.graphic')... | raphicBackend(TextBackend):
def __init__(self, config):
super().__init__(config)
self.bot_identifier = self.build_identifier('Err')
# create window and components
self.md = xhtml()
self.app = ChatApplication(self)
def connect_callback(self) | :
super().connect_callback()
self.app.update_commands(self.all_commands)
def send_command(self, text):
self.app.new_message(text, False)
msg = Message(text)
msg.frm = self.build_identifier(self.bot_config.BOT_ADMINS[0]) # assume this is the admin talking
msg.to = se... |
AeonGames/AeonEngine | tools/blender/addons/io_skeleton_skl/__init__.py | Python | apache-2.0 | 1,334 | 0.001499 | # Copyright | (C) 2017,2019 Rodrigo Jose Hernandez Cordoba
#
# Licensed unde | r the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distri... |
FireballDWF/cloud-custodian | tools/sandbox/c7n_autodoc/c7n-autodoc.py | Python | apache-2.0 | 6,289 | 0 | # Copyright 2019 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "Licen | se");
# 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 requi | red by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import yaml
import... |
DiptoDas8/Biponi | lib/python2.7/site-packages/braintree/payment_instrument_type.py | Python | mit | 263 | 0 |
class Payment | InstrumentType():
PayPalAccount = "paypal_account"
EuropeBankAccount = "europe_bank_account"
CreditCard = "credit_card"
CoinbaseAccount = "coinbase_account"
ApplePayCard = "apple_pay_card"
AndroidPayCard = "andro | id_pay_card"
|
Digilent/u-boot-digilent | tools/binman/etype/blob.py | Python | gpl-2.0 | 2,472 | 0.000809 | # SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Entry-type module for blobs, which are binary objects read from files
#
from binman.entry import Entry
from dtoc import fdt_util
from patman import tools
from patman import tout
class Entry_blob(Entry)... | bin'.
If compression is enabled, an ext | ra 'uncomp-size' property is written to
the node (if enabled with -u) which provides the uncompressed size of the
data.
"""
def __init__(self, section, etype, node):
super().__init__(section, etype, node)
self._filename = fdt_util.GetString(self._node, 'filename', self.etype)
def Ob... |
mktoni/anglerfish | tests/test_make_chainablefuture.py | Python | gpl-3.0 | 577 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test for anglerfish.ChainableFuture."""
import unittest
from angl | erfish import ChainableFuture
class TestName(unittest.TestCase):
maxDiff, __slots__ = None, ()
def test_ChainableFuture(self):
future1 = ChainableFut | ure()
future2 = future1.then(lambda arg: arg + "b")
future1.set_result("a")
self.assertEqual(future1.result(), "a") # a == b
self.assertEqual(future2.result(), "ab") # a == b
if __name__.__contains__("__main__"):
print(__doc__)
unittest.main()
|
duckinator/boreutils | util/ccomex.py | Python | isc | 791 | 0 | #!/usr/bin/env python3
from pathlib import Path
import sys
def extract(filename):
text = ""
lines = Path(filename).read_text().splitlines()
capture = False
for line in lines:
if | line.strip() == '/**':
capture = True
continue
if line.strip() == '*/':
capture = False
break
if not capture:
continue
# If we get to this point, we're in the first do | c comment.
if line.strip() == '*':
text += "\n"
continue
if line[0] == ' ':
line = line[1:]
if line[0] == '*':
line = line[1:]
if line[0] == ' ':
line = line[1:]
text += line + "\n"
return text
print(extract(s... |
kmike/psd-tools | tests/psd_tools/psd/test_effects_layer.py | Python | mit | 859 | 0 | from __future__ import absolute_import, unicode_literals
import pytest
import logging
from psd_tools.psd.effects_layer import (
CommonStateInfo,
ShadowInfo,
InnerGlowInfo,
OuterGlowInfo,
BevelInfo,
SolidFillInfo,
)
from ..utils import check_write_read, check_read_write
logger = logging.getLog... | ', [
(
b'\x00\x00\x00\x028BIMnorm\x0b\xf40262SC\x00\x00\xff\x01\x00\x00'
b'\xf0\x89\xa7s\x94\xd1\x00\x00'
),
]
)
def test_solid_fill_info(fixture):
check_read_write(SolidFillInfo, fixture) | |
davjohnst/fundamentals | fundamentals/dynamic_programming/num_ways_up_stairs.py | Python | apache-2.0 | 1,743 | 0.005164 | #!/usr/bin/env python
from fundamentals.adv_python.context_management.cm_examples import time_print
"""
Problem:
A child is running up a staircase with n steps, and can hop either 1 step, 2 steps or 3 steps
at a time. Implement a method to count mow many possible ways the child can run up the stairs.
"""
class NWa... | """
Phase 1: Build as a recursive problem
Base case: n < 0: 0
n = 0: 1
Recursive: n = 1: nways(0) then 1 step
n = 2: nways(0) then 2 steps, OR nways(1) then 1 step
nways(0) + nways(1)
n = 3: nways(0) then 3 steps, OR nways(1... | dynamic programming solution
"""
@staticmethod
def nways_rec(n):
if n < 0:
return 0
if n == 0:
return 1
else:
return NWaysUpStairs.nways_rec(n-3) + NWaysUpStairs.nways_rec(n-2) + NWaysUpStairs.nways_rec(n-1)
@staticmethod
def _nways_d... |
PsypherPunk/django-annotator | annotator/apps.py | Python | apache-2.0 | 93 | 0 | from django.apps import AppConfig
class AnnotatorConfig(AppConfig):
name = "annotat | or"
| |
dozzie/yumbootstrap | lib/yumbootstrap/__init__.py | Python | gpl-3.0 | 194 | 0.010309 | #!/ | usr/bin/python
#--------------------------------------------------------------------------- | --
#-----------------------------------------------------------------------------
# vim:ft=python
|
dajose/cookiecutter | tests/test_generate_files.py | Python | bsd-3-clause | 11,704 | 0 | # -*- coding: utf-8 -*-
"""
test_generate_files
-------------------
Tests formerly known from a unittest residing in test_generate.py named
TestGenerateFiles.test_generate_files_nontemplated_exception
TestGenerateFiles.test_generate_files
TestGenerateFiles.test_generate_files_with_trailing_newline
TestGenerateFiles.t... | h pytest.raises(exceptions.NonTemplatedInputDirException):
generate.generate_files(
context={
'cookiecutter': {'food': 'pizza'}
| },
repo_dir='tests/test-generate-files-nontemplated'
)
@pytest.mark.usefixtures('clean_system', 'remove_additional_folders')
def test_generate_files():
generate.generate_files(
context={
'cookiecutter': {'food': 'pizzä'}
},
repo_dir='tests/test-generate-... |
smarthimandrew/FantasyFRC | customMechanize/_opener.py | Python | gpl-2.0 | 14,890 | 0.001276 | """Integration with Python standard library module urllib2: OpenerDirector
class.
Copyright 2004-2006 John J Lee <jjl@pobox.com>
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the file
COPYING.txt included with the distribution).
"""
import o... | for lookup in [process_request, process_response]:
for scheme, handlers in lookup.iteritems():
lookup[scheme] = handlers
for scheme, lookup in handle_error.iteritems():
for code, handlers in lookup.iteritems():
handlers = list(handlers)
... | for scheme, handlers in handle_open.iteritems():
handlers = list(handlers)
handlers.sort()
handle_open[scheme] = handlers
# cache the indexes
self.handle_error = handle_error
self.handle_open = handle_open
self.process_request = process_request... |
beardypig/streamlink | src/streamlink/plugins/pluzz.py | Python | bsd-2-clause | 8,723 | 0.001834 | import logging
import re
import sys
import time
from streamlink.plugin import Plugin, PluginArgument, PluginArguments
from streamlink.plugin.api import validate
from streamlink.stream import DASHStream, HDSStream, HLSStream, HTTPStream
from streamlink.stream.ffmpegmux import MuxedStream
log = logging.getLogger(__name... | (.+\.)?francetvinfo\.fr)
''', re.VERBOSE)
_pluzz_video_id_re = re.compile(r'''(?P<q>["']*)videoId(?P=q):\s*["'](?P<video_id>[^"']+)["']''')
_jeunesse_video_id_re = re.compile(r'playlist: \[{.*?,"identity":"(?P<video_id>.+?)@(?P<catalogue>Ludo|Zouzous)"')
_sport_video_id_re = re.compile(r' | data-video="(?P<video_id>.+?)"')
_embed_video_id_re = re.compile(r'href="http://videos\.francetv\.fr/video/(?P<video_id>.+?)(?:@.+?)?"')
_hds_pv_data_re = re.compile(r"~data=.+?!")
_mp4_bitrate_re = re.compile(r'.*-(?P<bitrate>[0-9]+k)\.mp4')
_geo_schema = validate.Schema({
'reponse': {
... |
Ecotrust/forestplanner | lot/landmapper/migrations/0008_auto_20200810_2114.py | Python | bsd-3-clause | 3,163 | 0.002529 | # Generated by Django 2.2.12 on 2020-08-10 21:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('landmapper', '0007_property_scalebar_image'),
]
operations = [
migrations.AddField(
model_name='taxlot',
name='acre... | (blank=True, default=None, max_length=25, null=True),
),
migrations.AddField(
model_name='taxlot',
name='orzdesc',
field=models.CharField(blank=True, default=None, max_length=255, null=True),
),
migrations.AddField(
model_name='taxlot',
... | l=True),
),
migrations.AddField(
model_name='taxlot',
name='twnshpno',
field=models.CharField(blank=True, default=None, max_length=3, null=True),
),
]
|
qinggeng/ceShiGuanLiXiTong | site/ceShiGuanLiSite/apps/testManage/utils.py | Python | mit | 3,685 | 0.009498 | # -*- coding: utf-8 -*-
from openpyxl import load_workbook
from libs.xlsxInterface import getLevelTypes, travesalLevels
import models
from prettyprint import pp
from functools import partial
from django.db import transaction
def generateLevels(levelDict, levelTypes, cellAndValues):
currentDict = levelDict
pare... | ilter(parent = level)
rowSpan = len(children)
if rowSpan == 0:
return (1, u"<td>{title}</td></tr>\n".format(title = level.title))
rowSpan = 0
ret = u"<TD rowspan='{{rowspan}}'>{title}</ | TD>".format(title = level.title)
for i, child in zip(range(len(children)), children):
childRowCount, childRows = makeLevelsTable(child)
rowSpan += childRowCount
if i == 0:
ret += childRows
else:
ret += u"<tr>" + childRows
ret = ret.format(rowspan = rowSpan... |
KevinOConnor/klipper | klippy/extras/delayed_gcode.py | Python | gpl-3.0 | 2,248 | 0.002224 | # A simple timer for executing gcode templates
#
# Copyright (C) 2019 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
class DelayedGcode:
def __init__(self, config):
self.printer = config.get_printer()
self.reactor =... | self.timer_gcode = gcode_macro.load_template(config, 'gcode')
self.duration = config.getfloat('initial_duration', 0., minval=0.)
self.timer_handler = None
self.inside_timer = self.repeat = False
self.printer.register_event_handler("klippy:ready", self._handle_ready)
self.gcod... | PDATE_DELAYED_GCODE", "ID", self.name,
self.cmd_UPDATE_DELAYED_GCODE,
desc=self.cmd_UPDATE_DELAYED_GCODE_help)
def _handle_ready(self):
waketime = self.reactor.NEVER
if self.duration:
waketime = self.reactor.monotonic() + self.duration
self.timer_handler =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.