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 |
|---|---|---|---|---|---|---|---|---|
ybak/myblog | app/pngcanvas.py | Python | mit | 9,000 | 0.037889 | #!/usr/bin/env python
"""Simple PNG Canvas for Python"""
__version__ = "0.8"
__author__ = "Rui Carmo (http://the.taoofmac.com)"
__copyright__ = "CC Attribution-NonCommercial-NoDerivs 2.0 Rui Carmo"
__contributors__ = ["http://collaboa.weed.rbse.com/repository/file/branches/pgsql/lib/spark_pr.rb"], ["Eli Bendersk... | width = width
self.height = height
if (bitdepth,colortype,compression, filter, interlace) != (8,2,0,0,0):
raise TypeError('Unsupported PNG format')
# we ignore tRNS because we use | pure white as alpha anyway
elif tag == 'IDAT':
raw_data = zlib.decompress(data)
rows = []
i = 0
for y in range(height):
filtertype = ord(raw_data[i])
i = i + 1
cur = [ord(x) for x in raw_data[i:i+width*3]]
if y == 0:
rgb... |
sunchuanleihit/vimrc | sources_non_forked/YouCompleteMe/install.py | Python | mit | 1,500 | 0.040667 | #!/usr/bin/env python
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import subprocess
import sys
import os.path as p
import glob
PY_MAJOR, PY_MINOR = sys.version_info[ 0 : 2 ]
if not ( ( PY_MAJOR == 2 and... | lledProcessError as error:
| sys.exit( error.returncode )
def Main():
build_file = p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' )
if not p.isfile( build_file ):
sys.exit(
'File {0} does not exist; you probably forgot to run:\n'
'\tgit submodule update --init --recursive\n'.format( build_file ) )
CheckCa... |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/dctp.py | Python | gpl-3.0 | 3,148 | 0.02987 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
float_or_none,
int_or_none,
unified_timestamp,
url_or_none,
)
class DctpTvIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?dctp\.tv/(?:#/)?filme/(?P<id>[^/?#&]+)'
... | },
'params': {
# rtmp download
'skip_download': True,
},
}, {
# 16x9
'url | ': 'http://www.dctp.tv/filme/sind-youtuber-die-besseren-lehrer/',
'only_matching': True,
}]
_BASE_URL = 'http://dctp-ivms2-restapi.s3.amazonaws.com'
def _real_extract(self, url):
display_id = self._match_id(url)
version = self._download_json(
'%s/version.json' % self._BASE_URL, display_id,
'Downloadin... |
aronsky/home-assistant | homeassistant/components/nut/config_flow.py | Python | apache-2.0 | 7,989 | 0.000876 | """Config flow for Network UPS Tools (NUT) integration."""
import logging
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import (
CONF_ALIAS,
CONF_BASE,
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_RESOURCES,
CONF_SCAN_INTERVAL,
... | except Exception: # pylint: disab | le=broad-except
_LOGGER.exception("Unexpected exception")
errors[CONF_BASE] = "unknown"
return info, errors
@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return OptionsFlowHandler(config_entry)
... |
lyw07/kolibri | kolibri/core/auth/test/test_roles_and_membership.py | Python | mit | 10,992 | 0.001638 | """
Tests of role and membership calculations.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.test import TestCase
from ..constants import role_kinds
from ..models import Classroom
from ..models import Facility
from ..models import ... | assroom1 = self.data["classrooms"][1]
self.assertFalse(coach0.has_role_for(role_kinds.COACH, classroom1))
self.assertNotIn(role_kinds.COACH, coach0.get_roles_for(classroom1))
def test_coach_has_coach_role_for_learner_from_own_classroom(self):
coach0 = self.data["classroom_coaches"][0]
... | sertTrue(coach0.has_role_for(role_kinds.COACH, learner0))
self.assertIn(role_kinds.COACH, coach0.get_roles_for(learner0))
def test_coach_has_no_coach_role_for_learner_from_other_classroom(self):
coach0 = self.data["classroom_coaches"][0]
learner1 = self.data["learners_one_group"][1][0]
... |
ep1cman/RFLED-Server | source/admin.py | Python | gpl-3.0 | 1,061 | 0.01131 | #!/usr/bin/env python
import socket
# Set admin server settings
UDP_IP = '' # Leave empty for Broadcast support
ADMIN_PORT = 48899
# Local settings of your Raspberry Pi, used for app discovery
INT_IP = '10.0.1.61'
INT_MAC = '111a02bf232b'
# Code Starts Here #
# Create UDP socket, bind to it
adminsock = socket.sock... | data, adminaddr = ad | minsock.recvfrom(64) # buffer size is 64 bytes
# Did we get a message?
if admindata is not None:
# print("admin command: ", str(admindata)) # Debugging
# If the client app is syncing to a unit
if str(admindata).find("Link_Wi-Fi") != -1:
RETURN = INT_IP + ',' + INT_MAC + ',' ... |
oskarm91/sis | apps/users/migrations/0005_parentrelation_signature.py | Python | bsd-3-clause | 488 | 0.002049 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20150428_2142'),
]
|
operations = [
migrations.AddField(
model_name='parentrelation',
name='signature',
| field=models.CharField(max_length=255, null=True, verbose_name='sig', blank=True),
preserve_default=True,
),
]
|
xrg/openerp-server | bin/addons/base/res/res_config.py | Python | agpl-3.0 | 18,280 | 0.002899 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | )
def _next(self, cr, uid, context=None):
next = self._next_action(cr, uid)
if next:
action = next.action_id
return {
'view_mode': action.view_mode,
'view_type': action.view_type,
'view_id': action.view_id and [action.view_id.i... | : {'active_action_todo': next.id},
}
self.logger.info('All configuration actions have been executed.')
current_user_menu = self.pool.get('res.users')\
.browse(cr, uid, uid).menu_id
# return the action associated with the menu
return self.pool.get(current_user_men... |
Freso/listenbrainz-server | listenbrainz_spark/utils/tests/test_init.py | Python | gpl-2.0 | 5,143 | 0.001556 | import os
import tempfile
from datetime import datetime
from listenbrainz_spark.tests import SparkTestCase
from listenbrainz_spark import utils, path, config
from pyspark.sql import Row
class UtilsTestCase(SparkTestCase):
# use path_ as prefix for all paths in this class.
path_ = "/test"
temp_path_ = "/... | a=None)
dest_path = self.path_ + '/{}/{}.parquet'.format(from_date.year, from_date.month)
utils.save_parquet(df, dest_path)
df = utils.create_dataframe([Row(column1=3, column2=4)], schema=None)
dest_pa | th = self.path_ + '/{}/{}.parquet'.format(to_date.year, to_date.month)
utils.save_parquet(df, dest_path)
received_df = utils.get_listens(from_date, to_date, self.path_)
self.assertEqual(received_df.count(), 2)
def test_path_exists(self):
utils.create_dir(self.path_)
status ... |
hsoft/musicguru | qt/fs_model.py | Python | bsd-3-clause | 7,759 | 0.006702 | # Created By: Virgil Dupras
# Created On: 2009-09-19
# Copyright 2010 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licens... | r()
def invalidate(self, with_subnodes=False):
if with_subnodes:
for node in self.subnodes:
node.invalidate(with_subnodes=True)
self._data = None
self._imageName = None
TreeNode.invalidate(self)
@property
def data(self):
if self._... | eName is None:
self._imageName = self._getImageName()
return self._imageName
class SongNode(FSNode):
def _getData(self):
song = self.ref
return [
song.name,
song.original.parent_volume.name,
0,
format_size(song.size, 2, 2, Fal... |
tiradoe/Giflocker | bin/pilfile.py | Python | lgpl-3.0 | 2,695 | 0.001113 | #!/Users/tiradoe/Projects/Giflocker/bin/python3
#
# The Python Imaging Library.
# $Id$
#
# a utility to identify image files
#
# this script identifies image files, extracting size and
# pixel mode information for known file formats. Note that
# you don't need the PIL C extension to use this module.
#
# History:
# 0.0... |
verbose = quiet = verify = 0
logging_level = "WARNING"
for o, a in opt:
if o == "-f":
Image.init()
id = sorted(Image.ID)
print("Supported for | mats:")
for i in id:
print(i, end=' ')
sys.exit(1)
elif o == "-i":
verbose = 1
elif o == "-q":
quiet = 1
elif o == "-v":
verify = 1
elif o == "-D":
logging_level = "DEBUG"
logging.basicConfig(level=logging_level)
def globfix(files):
# ex... |
larsbutler/swift | test/unit/account/test_server.py | Python | apache-2.0 | 99,400 | 0.00001 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | = Request.blank('/sda1/p/a', | environ={'REQUEST_METHOD': 'PUT',
'HTTP_X_TIMESTAMP': '0'})
req.get_response(self.controller)
req = Request.blank('/sda1/p/a/c1', environ={'REQUEST_METHOD': 'PUT'},
headers={'X-Put-Timestamp': '1',
... |
webpp-studio/codestyle | tests/test_system_wrappers.py | Python | gpl-3.0 | 4,814 | 0 | """Проверки модуля system_wrappers."""
from logging import INFO
from unittest import TestCase
from unittest.mock import Mock, call, patch
from codestyle import system_wrappers
from codestyle.system_wrappers import (
ExitCodes,
check_output,
interrupt_program_flow,
)
class Test(TestCase):
"""Проверка ... | k, mocked_sys: Mock
):
"""Проверка interrupt_program_flow."""
mock_log = Mock()
mocked_logger.log = mock_log
mock_exit = Mock()
mocked_sys.exit = mock_exit
interrupt_program_flow(log_message='Проверка | вызова функции.')
self.assertEqual(True, mock_log.called)
self.assertEqual(1, mock_log.call_count)
args, kwargs = mock_log.call_args
self.assertTupleEqual((INFO, 'Проверка вызова функции.'), args)
self.assertDictEqual({}, kwargs)
self.assertEqual(True, mock_exit.called)... |
maartenbreddels/ipyvolume | ipyvolume/hotreload.py | Python | mit | 1,466 | 0.000682 | from pathlib import Path
import logging
logger = logging.getLogger('ipyvolume')
HERE = Path(__file__).parent
_figures = []
_watching = set()
def _update_shaders(path=None, file_changed=None):
names = ['volr-fragment', 'volr-vertex', 'mesh-vertex', 'mesh-fragment', 'scatter-vertex', 'scatter-fragment', 'shadow-v... | for name in names:
shader_path = path / (name + ".glsl")
with shader_path.open() as f:
shaders[name] = f.read()
figure._sha | ders = shaders
def watch(figure, path=None):
_figures.append(figure)
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
if path is None:
# this assues a editable install (pip install -e .)
path = HERE / '../js/glsl/'
class ShaderEventHandle... |
csadorf/signac | examples/ideal_gas_project/project.py | Python | bsd-3-clause | 472 | 0.006356 | # project.py
import signac
def classify(job):
yield 'init'
if 'V' in job.document:
yield 'volume-computed'
def next_operation(job):
if 'volume-computed' not in classify(job):
return 'compute_volume'
if __name__ == | '__main__':
project = signac.get_project()
print(project)
for | job in project.find_jobs():
labels = ','.join(classify(job))
p = '{:04.1f}'.format(job.statepoint()['p'])
print(job, p, labels)
|
tensorflow/privacy | research/pate_2018/ICLR2018/rdp_cumulative.py | Python | apache-2.0 | 12,995 | 0.011081 | # Copyright 2017 The 'Scalable Private Learning with PATE' 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
#
# ... | Laplace mechanism.
eps_gnmax: The cumulative privacy costs of the Gaussian mechanism
answered_gnmax: The cumulative count of queries answered.
"""
xlim = 6000
x_axis = range(0, int(xlim), 10)
y_lap = np.zeros(len(x_axis), dtype=float)
y_gnmax = np.full(len(x_axis), np.nan, dtype=float)
for i in ran... | s_gnmax):
y_gnmax[i] = eps_gnmax[idx]
fig, ax = plt.subplots()
fig.set_figheight(4.5)
fig.set_figwidth(4.7)
ax.plot(
x_axis, y_lap, color='r', ls='--', label='LNMax', alpha=.5, linewidth=5)
ax.plot(
x_axis,
y_gnmax,
color='g',
ls='-',
label='Confident-GNMax',
a... |
nealedj/djangae | djangae/fields/iterable.py | Python | bsd-3-clause | 10,309 | 0.003104 | import copy
from django import forms
from django.db import models
from django.core.exceptions import ValidationError, ImproperlyConfigured
from django.db.models.fields.subclassing import Creator
from djangae.forms.fields import ListFormField
from django.utils.text import capfirst
class _FakeModel(object):
"""
... | lue_list:
if value not in valid_values:
# TODO: if there is more than 1 invalid value then this should show all of the invalid values
raise ValidationError(self.error_messages['invalid_choice'] % value)
# Validate null-ness
if value_list is None an... |
# apply the default items validation rules
for value in value_list:
self.item_field_type.clean(value, model_instance)
def formfield(self, **kwargs):
""" If this field has choices, then we can use a multiple choice field.
NB: The choices must be set on *this* field,... |
wonderful4228/qualitybots | src/appengine/handlers/base.py | Python | apache-2.0 | 5,928 | 0.003036 | #!/usr/bin/python2.4
#
# Copyright 2010 Google 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... | return int(str_value)
except ValueError:
raise InvalidIntValueError(parameter_name, str_value)
def RenderTemplate(self, name, template_args):
"""Renders the specified djan | go template.
Assumes the hander and templates are on different folders:
- root
- handlers
- templates
Args:
name: Str name of the file template.
template_args: Dict argument passed to the template.
"""
path = os.path.join(os.path.dirname(__file__), '..', 'templates', n... |
studentenportal/web | apps/documents/migrations/0004_remove_document_flattr_disabled.py | Python | agpl-3.0 | 342 | 0 | # Gen | erated by Django 2.2.11 on 2020-03-12 11:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("documents", "0003_auto_20200122_1624"),
]
operations = [
migrations.RemoveField(
model_name="document",
name="flattr_disabled",
... | ]
|
opendatakosovo/municipality-procurement-visualizer | gpv/views/json/procurementtype.py | Python | gpl-2.0 | 764 | 0.005236 | from flask import Response
from flask.views import View
from urllib2 import urlopen
from gpv import ut | ils
class ProcurementType(View):
def dispatch_request(self, komuna=None, year=None, company_slug=None):
api_base_url = utils.get_api_url()
url = "%s/procurement-type" % api_base_url
result = []
if komuna != None and year != None:
url = url + "/%s/%d" % (komuna, year)
... | d response object.
resp = Response(
response=result,
mimetype='application/json')
# Return response.
return resp
|
arrabito/DIRAC | docs/source/conf.py | Python | gpl-3.0 | 9,724 | 0.015014 | # -*- coding: utf-8 -*-
#
# DiracDocs documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 25 17:34:37 2010.
#
# 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.
#
# A... | se> documentation".
html_title = "DIRAC Documentation"
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The na | me of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = '_static/DIRAC-logo.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = '_static... |
AleksNeStu/ggrc-core | src/ggrc/fulltext/mixin.py | Python | apache-2.0 | 2,559 | 0.007816 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module contains Indexed mixin class"""
import itertools
from collections import namedtuple
from sqlalchemy import inspect, orm
from ggrc import db
from ggrc import fulltext
ReindexRule = namedtuple("... | .indexed_query().filter(cls.id.in_(ids))
indexer = fulltext.get_indexer()
keys | = inspect(indexer.record_type).c
records = (indexer.fts_record_for(i) for i in instances)
rows = itertools.chain(*[indexer.records_generator(i) for i in records])
values = [{c.name: getattr(r, a) for a, c in keys.items()} for r in rows]
if values:
return indexer.record_type.__table__.insert().val... |
alvin319/CarnotKE | jyhton/Lib/test/test_glob.py | Python | apache-2.0 | 7,373 | 0 | import glob
import os
import shutil
import sys
import unittest
import warnings
from test.test_support import run_unittest, TESTFN
def fsdecode(s):
return unicode(s, sys.getfilesystemencoding())
class GlobTests(unittest.TestCase):
def norm(self, *parts):
return os.path.normpath(os.path.join(self.te... | orm('aab') + os.sep)},
])
@unittest.skipUnless(hasattr(os, 'symlink'), "Requires symlink support")
def test_glob_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym3'), [self.norm('sym3')])
eq(self.glob('sym3', '*'), [self.norm('sym3', 'EF'),
... | .sep),
[[self.norm('sym3')], [self.norm('sym3') + os.sep]])
eq(self.glob('*', '*F'),
[self.norm('aaa', 'zzzF'), self.norm('aab', 'F'),
self.norm('sym3', 'EF')])
@unittest.skipUnless(hasattr(os, 'symlink'), "Requires symlink support")
def test_glob_broken_sym... |
Depado/starmato-admin | starmato/admin/templatetags/_fieldset_related.py | Python | mit | 976 | 0.008197 | # -*- coding: utf-8 -*-
de | f before_related(adminform):
adminform.fieldsets_before = adminform.fieldsets
adminform.fieldsets_after = []
try:
adminform.fieldsets_before = adminform.fieldsets[:adminform.fieldsets.index(('related_go_here', {'fields': []}))]
adminform.fieldsets_after = adminform.fieldsets[adminform.fields... | adminform
except:
return adminform
def after_related(adminform):
try:
adminform.fieldsets = adminform.fieldsets_after
adminform.fieldsets_before = adminform.fieldsets[:adminform.fieldsets.index(('related_go_here', {'fields': []}))]
adminform.fieldsets_after = adminform.fieldsets... |
AdL1398/PiCasso | source/modules/tester/testtermopi.py | Python | mit | 1,603 | 0.009981 | #!/usr/bin/python
"""
title : testtermopi.py
description : This program runs the termopi.py
: Displays the status of the resources (cpu load and memory usage) consumed by a Raspberry Pi
computer and the resources consumed by one or more containers instantiated in the Pi... | ce :
author : Carlos Molina-Jimenez (Carlos.Molina@cl.cam.ac.uk)
date | : 27 Mar 2017
institution : Computer Laboratory, University of Cambridge
version : 1.0
usage :
notes :
compile and run : % python termopi.py
: It imports pidict.py, dockerctl.py and picheck.py which are found in
: ./modules.
: ... |
jck/uhdl | setup.py | Python | bsd-3-clause | 1,201 | 0 | from setuptools import setup
reqs = [
'myhdl>=0.9.0',
'click',
'wrapt'
]
test_reqs = ['pytest', 'hypothesis']
requires = {
'setup_requires': ['setuptools_scm'],
'install_requires': reqs,
'tests_require': test_reqs,
'extras_require': {
'testing': test_reqs,
}
}
setup(
name... | OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
keywords='myhdl uhdl', |
**requires
)
|
PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/test_parallel_executor_seresnext_base_gpu.py | Python | apache-2.0 | 1,457 | 0 | # Copyright (c) 2019 PaddlePaddle 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 appli... | overning permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import seresnext_net
from seresnext_test_base import TestResnetBase, DeviceType
from functools import partial
class TestResnetGPU(TestResnetBase):
def test_seresnext_wi | th_learning_rate_decay(self):
# NOTE(zcd): This test is compare the result of use parallel_executor
# and executor, and the result of drop_out op and batch_norm op in
# this two executor have diff, so the two ops should be removed
# from the model.
check_func = partial(
... |
stefanklug/mapnik | scons/scons-local-2.3.6/SCons/Variables/PathVariable.py | Python | lgpl-2.1 | 5,646 | 0.000886 | """SCons.Variables.PathVariable
This file defines an option type for SCons implementing path settings.
To be used whenever a a user-specified path override should be allowed.
Arguments to PathVariable are:
option-name = name of this option on the command line (e.g. "prefix")
option-help = help string for optio... | "), to deal in the Software without restriction, including
# without limitation the rights 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 follo | wing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A ... |
texib/bitcoin-zoo | test/celeryconfig.py | Python | mit | 525 | 0.00381 | # List of modules to import when celery starts.
# CELERY_IMPORTS = ('libcloud_sandbox.tasks.code_execute', )
# Result store settings.
CELERY_RESULT_BACKEND = 'database'
CELERY_RESULT_DBURI = 'sqlite:///mydatabase.db'
# Broker settings.
BROKER_TRANSPORT = 'sqlalchemy'
BROKER_HOST = 'sqlite:///tasks.db'
BROKER_PORT = 5... | R_VHOST = '/'
BROKER_USER = 'guest'
BROKER_PASSWORD = 'guest'
## Worker settings
CELERYD_CONCURRENCY = 1
CELERYD_TASK_TIME_LIMIT = 20
# CELERYD_LOG_FILE = 'celeryd.log'
CELERYD_LOG_L | EVEL = 'INFO' |
TinyOS-Camp/DDEA-DEV | Archive/[14_10_11] Dr_Jung_Update/ddea_cli.py | Python | gpl-2.0 | 688 | 0.002907 | #!/adsc/DDEA_PROTO/bin/python
from df_data_analysis_ddea import ddea_analysis
from datetime | import datetime
import traceba | ck
import sys
if __name__ == '__main__':
try:
if 3 <= len(sys.argv):
###urls = open(sys.argv[1]).readlines()
start_time = sys.argv[1]
end_time = sys.argv[2]
stime = datetime.strptime(start_time, "%y-%m-%d")
etime = datetime.strptime(end_time, ... |
MSusik/invenio | invenio/ext/template/extensions.py | Python | gpl-2.0 | 1,614 | 0.008055 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 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 version 2 of the
## License, or (at yo... | filter_languages`."""
from invenio.modules.formatter.engine import filter_languages
return filter_la | nguages('<lang>' + caller() + '</lang>', g.ln)
|
tweemeterjop/thug | thug/DOM/W3C/HTML/HTMLFieldSetElement.py | Python | gpl-2.0 | 229 | 0 | #!/usr/bi | n/env python
from .HTMLElement import HTMLElement
class HTMLFieldSetElement(HTMLElement):
def __init__(self, doc, tag):
HTMLElement.__init__(self, doc, tag)
@property
def form(self):
pass
| |
fewu/gnuradio_drm | gr-drm/python/qa_drm_add_tailbits_vbvb.py | Python | gpl-3.0 | 1,583 | 0.025268 | #!/usr/bin/env python
#
# Copyright 2012 Communications Engineering Lab (CEL) / KIT (Karlsruhe Institute of Technology)
# Author: Felix Wunsch
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either... | . See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
#
from gnuradio import gr, gr_u... | gr.top_block ()
self.src = gr.vector_source_b((1,1,0,1), True, 4)
self.head = gr.head(4,3)
self.add_tailbits = drm.add_tailbits_vbvb(4,2)
self.snk = gr.vector_sink_b(6)
self.tb.connect(self.src, self.head, self.add_tailbits, self.snk)
def tearDown (self):
s... |
chromy/cmdtest | examples/echo.py | Python | mit | 198 | 0.010101 | from cmdtest import Program, a | ssert_hook
echo = Program('echo')
@e | cho.test
def echo_string_should_output_string():
assert echo('foo').out == 'foo\n'
if __name__ == '__main__':
echo.run()
|
chokribr/invenio | invenio/modules/collections/models.py | Python | gpl-2.0 | 28,007 | 0.000036 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2011, 2012, 2013, 2014, 2015 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 (a... | els for collections."""
# General imports.
import re
from operator import itemgetter
from flask import g, url_for
from intbitset import intbitset
from invenio.base.globals import cfg
from invenio.base.i18n import _, gettext_set_language
from invenio.ext.sqlalchemy import db
from invenio.ext.sqlalchemy.utils import... | e
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.orderinglist import ordering_list
from sqlalchemy.orm.collections import attribute_mapped_collection
from werkzeug.utils import cached_property
# Create your models here.
external_collection_mapper = attribute_multi_dict_collection(
... |
ebertti/django-admin-easy | test_project/settings.py | Python | mit | 2,792 | 0 | """
Django settings for sample_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ... | _processors.debug',
| 'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
|
brad-kaiser/spark | python/pyspark/sql/catalog.py | Python | apache-2.0 | 11,982 | 0.00192 | #
# 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... | the returned :class:`DataFrame` and
created external table.
:return: :class:`DataFrame`
"""
warnings.warn(
"createExternalTable is deprecated since Spark 2.2, please use createTable instead.",
DeprecationWarning)
return self.createTable(tableName, path, s... | ble(self, tableName, path=None, source=None, schema=None, **options):
"""Creates a table based on the dataset in a data source.
It returns the DataFrame associated with the table.
The data source is specified by the ``source`` and a set of ``options``.
If ``source`` is not specified, t... |
OCA/reporting-engine | report_py3o_fusion_server/tests/__init__.py | Python | agpl-3.0 | 158 | 0 | # Copyr | ight 2017 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import test_report_py3o_fusion_serve | r
|
nlamirault/python-freeboxclient | freeboxclient/client.py | Python | apache-2.0 | 3,447 | 0.00029 | #
# Copyright 2013 Nicolas Lamirault <nicolas.lamirault@gmail.com>.
#
# 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 ... | :
logger.info("[FreeboxOS] Check Authorization ")
self.app.freebox_client.check_authorization()
class FreeboxOpenSession(FreeboxCommand):
"""Open a new session to the FreeboxOS."""
def take_action(self, parsed_args):
logger.info("[FreeboxOS] Open sesion")
self.app.freebox_clie... | open_session()
class FreeboxCloseSession(FreeboxCommand):
"""Close the current session to the FreeboxOS."""
def take_action(self, parsed_args):
logger.info("[FreeboxOS] Close sesion")
self.app.freebox_client.close_session()
class FreeboxWifiStatus(FreeboxCommand):
"""Retrieve the WIFI s... |
Bartzi/LabShare | labshare/migrations/0013_initial_groups.py | Python | gpl-2.0 | 566 | 0.001767 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import Group
from django.db import migrations
def initial_data(apps, schema_editor):
staff = Group.objects.c | reate(name="Staff")
staff.save()
def delete_staff_group(apps, schema_editor):
staff = Group.objects.get(name="Staff")
staff.delete()
class Migration(migrations.Migration):
dependencies = [
('labshare', '0012_auto_20161026_1453'),
]
operations = [
migrations.RunPython(initia... | te_staff_group),
]
|
tinkerinestudio/Tinkerine-Suite | TinkerineSuite/Cura/cura_sf/skeinforge_application/skeinforge_plugins/craft_plugins/raft.py | Python | agpl-3.0 | 56,776 | 0.02251 | """
This page is in the table of contents.
Raft is a plugin to create a raft, elevate the nozzle and set the temperature. A raft is a flat base structure on top of which your object is being build and has a few different purposes. It fills irregularities like scratches and pits in your printbed and gives you a nice ba... | art II" at:
http://blog.thingiverse.com/2009/08/04/skeinforge-quicktip-the-raft-part-ii/
Nophead has written about rafts on his blog:
http://hydraraptor.blogspot.com/2009/07/thoughts-on-rafts.html
More pictures of rafting in action are available from the Metalab blog at:
http://reprap.soup.io/?search=rafting
==Opera... | the functions described below will work, when it is off, nothing will be done, so no temperatures will be set, nozzle will not be lifted..
==Settings==
===Add Raft, Elevate Nozzle, Orbit===
Default: On
When selected, the script will also create a raft, elevate the nozzle, orbit and set the altitude of the bottom of t... |
beobal/cassandra-dtest | upgrade_internal_auth_test.py | Python | apache-2.0 | 9,980 | 0.002405 | import time
import pytest
import logging
from cassandra import Unauthorized
from ccmlib.common import is_w | in
from ccmlib.node import Node
from dtest_setup_overrides import DTestSetupOverrides
from dtest import | Tester
from tools.assertions import assert_all, assert_invalid
from tools.misc import ImmutableMapping
since = pytest.mark.since
logger = logging.getLogger(__name__)
@pytest.mark.upgrade_test
@since('2.2')
class TestAuthUpgrade(Tester):
@pytest.fixture(scope='function', autouse=True)
def fixture_dtest_setu... |
mediawiki-utilities/python-mediawiki-utilities | doc/conf.py | Python | mit | 8,467 | 0.006023 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# mediawiki-utilities documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 10 17:31:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present ... | lt documents.
#
# The short X.Y version.
version = mw.__version__
# The full version, including alpha/beta/rc tags.
release = mw.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: e... | , %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cro... |
twitter-forks/bazel | tools/ctexplain/types_test.py | Python | apache-2.0 | 2,530 | 0.001581 | # Lint as: python3
# Copyright 2020 The Bazel 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 requir... | figuration(fragments=('F1'), options=options2)] = 4
self.assertEqual(len(d), 1)
options3 = frozendict({'o1': frozendict({'k1': 'v1'})})
d[Configuration(fragments=('F2'), options=options3)] = 4
self.assertEqual(len(d), 2)
options4 = frozendict({'o2': frozendict({'k1': 'v1'})})
d[Configuration(f... | 'v1'})})
d[Configuration(fragments=('F2'), options=options5)] = 4
self.assertEqual(len(d), 4)
options6 = frozendict({'o2': frozendict({'k2': 'v2'})})
d[Configuration(fragments=('F2'), options=options6)] = 4
self.assertEqual(len(d), 5)
def testConfigurationEquality(self):
c1 = Configuration(f... |
ego008/ijd8 | sae/setting.py | Python | mit | 1,814 | 0.024441 | # -*- coding: utf-8 -*-
import sae.const
DEBUG = False
SITE_TITLE = u"博客标题"
SITE_SUB_TITLE = u"博客副标题"
SITE_KEYWORDS = u"博客关键字"
SITE_DECRIPTION = u"博客描述"
AUTHOR_NAME = u"博客作者" #显示在RSS订阅里面
#CONACT_MAIL = "xxx@gmail.com" #暂未用到
THEMES = ['octopress','admin']
LINK_BROLL = [
{'text': u"爱简单吧", 'url': "http://www.... | 文章数
#######下面是保存附件的空间,可选SAE Storage 和 七牛(有免费配额),只选一个
## 1) 用SAE Storage 需要在SAE 控制面板开通
BUCKET = "" #Domain Name, 如 upload 。不用或用七牛请留空
## 2) 七牛 注册可获永久10G空间和每月10G流量,注册地址 http://t | .cn/z8h5lsg
QN_AK = "" #七牛 ACCESS_KEY
QN_SK = "" #七牛 SECRET_KEY
QN_BUCKET = "" #空间名称 , 如 upload
|
camradal/ansible | lib/ansible/modules/cloud/amazon/lambda_alias.py | Python | gpl-3.0 | 12,318 | 0.002598 | #!/usr/bin/python
# 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
# (at your option) any later version.
#
# Ansible is distributed... | name: "alias 'QA' for function {{ lambda_facts.FunctionName }} "
lambda_alias:
state: "{{ state | default('present') }}"
function_name: "{{ lambda_facts.FunctionName }}"
name: QA
version: "{{ lambda_facts.Version }}"
description: "QA is version {{ lambda_facts.Version }}"
when: lam... | ' for function {{ lambda_facts.FunctionName }} "
lambda_alias:
state: "{{ state | default('present') }}"
function_name: "{{ lambda_facts.FunctionName }}"
name: Prod
version: "{{ production_version }}"
description: "Production is version {{ production_version }}"
'''
RETURN = '''
---
a... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/ipware/utils.py | Python | agpl-3.0 | 794 | 0 |
import socket
def is_valid_ipv4(ip_str):
"""
Check the validity of an IPv4 address
"""
try:
socket.inet_pton(socket.AF_INET, ip_str)
except AttributeError:
try: # Fall-back on legacy API or False
socket.inet_aton(ip_str)
except (AttributeError, socket.error):
... | return False
return ip_str.count('.') == 3
except socket.error:
return False
return True
def is_valid_ipv6(ip_str):
"""
Check the validity of an IPv6 address
"""
try:
socket.inet_pton(socket.AF_INET6, ip_str)
except socket.error:
r | eturn False
return True
def is_valid_ip(ip_str):
"""
Check the validity of an IP address
"""
return is_valid_ipv4(ip_str) or is_valid_ipv6(ip_str)
|
onepercentclub/onepercentclub-site | apps/homepage/serializers.py | Python | bsd-3-clause | 794 | 0.001259 | from bluebottle.bb_projects.serializers import Pro | jectPreviewSerializer
from bluebottle.quotes.serializers import QuoteSerializer
from bluebottle.slides.serializers import SlideSerializer
|
from apps.campaigns.serializers import CampaignSerializer
from bluebottle.bb_fundraisers.serializers import BaseFundRaiserSerializer
from apps.statistics.serializers import StatisticSerializer
from rest_framework import serializers
class HomePageSerializer(serializers.Serializer):
quotes = QuoteSerializer(sou... |
ntt-sic/taskflow | taskflow/tests/unit/test_unordered_flow.py | Python | apache-2.0 | 2,294 | 0 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... | elf._make_engine(wf)
| e.run()
self.assertEquals(2, len(e.storage.fetch('context')))
|
fusionbox/satchless | satchless/order/app.py | Python | bsd-3-clause | 2,122 | 0.001414 | from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from ..core.app import SatchlessApp
from . import models
class ... | der_model)s/view.html'
]
order_list_templates = [
'satchless/order/my_orders.html',
'satchless/order/%(order_model)s/my_orders.html'
]
@method_decorator(login_required)
def index(self, request):
orders = self.order_model.objects.filter(user=request.user)
| context = self.get_context_data(request, orders=orders)
format_data = {
'order_model': self.order_model._meta.model_name
}
templates = [p % format_data for p in self.order_list_templates]
return TemplateResponse(request, templates, context)
def details(self, request... |
tbabej/freeipa | ipaserver/install/installutils.py | Python | gpl-3.0 | 48,113 | 0.00158 | # Authors: Simo Sorce <ssorce@redhat.com>
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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... | hostaddr = socket.getaddrinfo(host_name, None)
except Exception as e:
root_logger.debug('Search failed: %s', e)
raise HostForwardLookupError("Unable to resolve host name, check /etc/hosts or DNS name resolution") |
if len(hostaddr) == 0:
raise HostForwardLookupError("Unable to resolve host name, check /etc/hosts or DNS name resolution")
# Verify this is NOT a CNAME
try:
root_logger.debug('Check if %s is not a CNAME', host_name)
resolver.query(host_name, rdatatype.CNAME)
raise HostRev... |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/test/test_pyclbr.py | Python | mit | 7,874 | 0.002159 | '''
Test cases for pyclbr.py
Nick Mathewson
'''
from test.test_support import run_unittest, import_module
import sys
from types import ClassType, FunctionType, MethodType, BuiltinFunctionType
import pyclbr
from unittest import TestCase
StaticMethodType = type(staticmethod(lambda: None))
ClassMethodTyp... | Type):
ret | urn item.__module__ == module.__name__
if isinstance(item, FunctionType):
return item.func_globals is module.__dict__
return False
for name in dir(module):
item = getattr(module, name)
if isinstance(item, (ClassType, FunctionType)):
... |
illicitonion/givabit | src/givabit/backend/charity_repository_test.py | Python | apache-2.0 | 1,597 | 0.004383 | from givabit.backend.charity import Charity
from givabit.backend.errors import MissingValueException, MultipleValueException
from givabit.test_common import test_data
from givabit.test_common import test_utils
class CharityRepositoryTest(test_utils.TestCase):
def setUp(self):
super(CharityRepositoryTest, ... | rity_repo.get_charity('Shelter'), test_data.c1)
self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2)
with self.assertRaises(MissingValueException):
self.charity_repo.get_charity('Does not exist')
try:
self.charity_repo.get_charity('BHF')
except M... | al(e.values, [test_data.c3, test_data.c4])
def test_gets_charity_by_id(self):
self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1)
def test_getting_missing_charity_by_id_throws(self):
missing_id = 0
while missing_id in map(lambda charity: charity.k... |
VeNoMouS/Sick-Beard | lib/cherrypy/lib/cpstats.py | Python | gpl-3.0 | 22,932 | 0.000218 | """CPStats, a package for collecting and reporting on program statistics.
Overview
========
Statistics about program operation are an invaluable monitoring and debugging
tool. Unfortunately, the gathering and reporting of these critical values is
usually ad-hoc. This package aims to add a centralized place for gather... | mmended each namespace have an "Enabled" item which, if False,
stops collection (but not reporting) of statistical data. Applications
SHOULD provide controls to pause and resume collection by setting these
entries to False or True, if present.
Usage
== | ===
To collect statistics on CherryPy applications::
from cherrypy.lib import cpstats
appconfig['/']['tools.cpstats.on'] = True
To collect statistics on your own code::
import logging
# Initialize the repository
if not hasattr(logging, 'statistics'): logging.statistics = {}
# Initialize my n... |
lama7/blogtool | blogtool/xmlproxy/wp_proxy.py | Python | mit | 17,754 | 0.005633 | import proxybase
import xmlrpclib
import mimetypes
import os
import data
################################################################################
""" getInst
returns an instance of a wpproxy object
"""
def getInst(url, user, password):
wp = WordpressProxy(url, user, password)
return wp
##########... | return self.mt.getRecentPostTitles(blogid,
self._username,
| self._password,
number)
except (xmlrpclib.Fault, xmlrpclib.ProtocolError), error:
raise proxybase.ProxyError("wp.getRecentTitles", error)
############################################################################
"""publishPost
... |
mjirik/lisa | tests/texture_features_experiments_test.py | Python | bsd-3-clause | 3,114 | 0.003215 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# import funkcí z jiného adresáře
import sys
import os.path
from loguru import logger
path_to_script = os.path.dirname(os.path.abspath(__file__))
# sys.path.append(os.path.join(path_to_script, "../experiments/"))
# sys.path.append(os.path.join(path_to_script, "../extern/sed3... | s/20130919_liver_statistics.yaml')
# write_csv(fvall)
gf = tfeat.GaborFeatures()
glcmf = tfeat.GlcmFeatures()
haralick = tfeat.HaralickFeatures()
list_of_feature_fcn = [
[tls.feat_hist, []],
# [gf.feats_gabor, []],
# [glcmf.feats_glcm, []],
... | iers = [
# [GaussianNB, []],
# [svm.SVC, []],
[classification.GMMClassifier,
{'n_components': 2, 'covariance_type': 'full'}],
]
featrs_plus_classifs = tls.make_product_list(list_of_feature_fcn,
list_... |
Seldaiendil/meyeOS | devtools/qooxdoo-1.5-sdk/tool/pylib/ecmascript/frontend/Scanner.py | Python | agpl-3.0 | 8,958 | 0.008038 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2006-2010 1&1 Internet AG, Germany, http://www.1und1.de
#
# License:
# LGPL: http://www.gnu.org/li... | rs, and symbol names, but nothing that requires context
# awareness like strings or | comments.
##
import sys, os, re, types
from collections import deque
##
# IterObject -- abstract base class for iterators, making them resettable and
# providing an immediate .next() method
#
class IterObject(object):
def __init__(self, inData):
self.inData = inData
self.resetIte... |
mobolic/facebook-sdk | examples/get_posts.py | Python | apache-2.0 | 1,391 | 0 | """
A simple example script to get all posts on a user's timeline.
Originally created by Mitchell Stewart.
<https://gist.github.com/mylsb/10294040>
"""
import facebook
import requests
def some_action(post):
"""Here you might want to do something with each post. E.g. grab the
post's message (post['message']) o... | ost) for post in posts["data"]]
# Attempt to make a request to the next page of data, if it exists.
| posts = requests.get(posts["paging"]["next"]).json()
except KeyError:
# When there are no more pages (['paging']['next']), break from the
# loop and end the script.
break
|
fbradyirl/home-assistant | tests/components/input_boolean/__init__.py | Python | apache-2.0 | 45 | 0 | """Te | sts for the input_bo | olean component."""
|
aperigault/ansible | lib/ansible/module_utils/postgres.py | Python | gpl-3.0 | 7,961 | 0.004271 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | add_to_executed=True):
"""Execute SQL.
Auxiliary function for PostgreSQL user clas | ses.
Returns a query result if possible or True/False if ddl=True arg was passed.
It necessary for statements that don't return any result (like DDL queries).
Arguments:
obj (obj) -- must be an object of a user class.
The object must have module (AnsibleModule class object) and
... |
karrtikr/ete | ete3/clustering/stats.py | Python | gpl-3.0 | 159,124 | 0.014555 | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... | tstdev (for Numpy arrays only)
tsem (for Numpy arrays only)
descr | ibe
FREQUENCY STATS: itemfreq
scoreatpercentile
percentileofscore
histogram
cumfreq
relfreq
VARIABILITY: obrientransform
samplevar
samplestdev
signaltonoise (for Numpy arrays only)
... |
ecolitan/fatics | venv/lib/python2.7/site-packages/netaddr/ip/__init__.py | Python | agpl-3.0 | 66,411 | 0.001837 | #-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
"""Routines for IPv4 a... | :return: ``True`` if this IP is for internal/private use only
(i.e. non-public), ``False`` otherwi | se. Reference: RFCs 1918,
3330, 4193, 3879 and 2365.
"""
if self.version == 4:
for cidr in IPV4_PRIVATE:
if self in cidr:
return True
elif self.version == 6:
for cidr in IPV6_PRIVATE:
if self in cidr:
... |
pinax/django-waitinglist | waitinglist/stats.py | Python | mit | 842 | 0.002375 | import datetime
from django.conf import settings
from django.utils import timezone
from account.models import SignupCode
from waitinglist.models import WaitingListEntry
User = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
def stats():
waiting_list = WaitingListEntry.objects
return {
"waiting... | mezone.now() - datetime.timedelta(days=7)).count(),
"waitinglist_added_last_thirty_days":
waiting_list.filter(created__gt=timezone.now() - datetime.timedelta(days=30)).count(),
"waiting_list_entries_to_invi | te":
waiting_list.exclude(email__in=SignupCode.objects.values("email"))
.exclude(email__in=User.objects.values("email")).count()
}
|
brianjimenez/lightdock | bin/post/lgd_filter_membrane.py | Python | gpl-3.0 | 5,399 | 0.00463 | #!/usr/bin/env python
"""Filter LightDock final swarm results depending on the compatibility with the membrane"""
from __future__ import print_function
import sys
import os
import argparse
import shutil
import re
from prody.measure.contacts import Contacts
from prody import parsePDB, confProDy
from lightdock.util.log... | print("{:40s} {:5.3f}".format(pdb_file, perc))
except Exception, e:
log.error('Filtering has failed for structure {}. Please see error:'.format(pdb_file))
log.error(str(e))
filtered_ranking = os.path.join(filtered_folder, 'rank_filtered.list')
with open(filtered_ranking, ... | filter_passed and rank.id_glowworm in filter_passed[rank.id_cluster]:
handle.write('swarm_{}_{}.pdb {:5.3f} {:5.3f}'.format(rank.id_cluster,
rank.id_glowworm, rank.scoring, percentages[(rank.id_cluster, rank.id_glowworm)]) + os.linesep)
|
gdestuynder/MozDef | mozdef_util/mozdef_util/query_models/exists_match.py | Python | mpl-2.0 | 369 | 0 | # | !/usr/bin/env python
# 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/.
# Copyright (c) 2017 Mozilla Corporation
from elasticsearch_dsl import Q
def ExistsMatch(field_... | ts', field=field_name)
|
wonderbeyond/ezlog | pages/context_processors.py | Python | bsd-2-clause | 150 | 0.013333 | # coding=utf-8
from pages.models import Page
def nav_page | s(request):
return {'nav_pages': P | age.objects.filter(public=True, in_navigation=True),}
|
linostar/timeline-clone | test/specs/db/DbOpen.py | Python | gpl-3.0 | 5,595 | 0.000357 | # Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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... | /color>
<parent>Category 2</parent>
</category>
</categories>
<events>
<event>
<start>2009-11-4 22:52:0</start>
<end>2009-11-11 22:52:0</end>
<text>Event 1</text>
<category>Category 1</category>
<description>The first event.... | <end>2009-12-2 16:22:4</end>
</displayed_period>
<hidden_categories>
<name>Category 3</name>
</hidden_categories>
</view>
</timeline>
""".strip()
class DbOpenSpec(TmpDirTestCase):
def test_raises_error_when_reading_non_xml_file(self):
self.writeContentToTmpFile(CO... |
c0deforfun/LLL | ui/resources_rc.py | Python | mit | 138,528 | 0.000036 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Sun Feb 8 12:30:31 2015
# by: The Resource Compiler for PyQt (Qt v4.8.6)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x0f\x0a\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x4... | 6b\x02\
\x36\x3e\xe6\x07\x42\x20\xc3\x85\xf9\xc1\xcb\x10\x98\x87\x79\x31\
\x3f\x10\x02\x18\x19\xf3\x03\x21\x40\x61\x7e\x20\x04\x28\xcc\x0f\
\x84\x00\x85\xf9\x81\x10\xa0\x30\x3f\x10\x02\x98\x1f\xf3\x03\x21\
\x80\xf9\x01\x32\x13\x02\xf3\x31\x3f\xe6\ | x07\x42\x00\xf3\x03\x10\
\x02\x98\x1f\x80\x10\xc0\xfc\x00\x84\x00\xe6\x07\x20\x04\x30\x3f\
\x00\x21\xe0\x7d\x6d\xc2\xfc\x00\x35\x0f\x81\x1f\x05\x16\x00\xdb\
\x99\x59\x80\xe2\x82\xa0\x9f\xd4\x96\x40\x02\x60\x0f\x33\x0a\x50\
\x7c\x08\xc4\x52\xbf\x0d\x24\x04\x9a\x30\xa3\x00\xc5\x87\xc0\xec\
\x40\x02\xa0\x29\xb3\x09\x40\x0... |
faridborbar/01Tarea | Codigo.py | Python | mit | 4,518 | 0.016383 |
#Aqui resolveremos los puntos de la tarea
import | time
import matplotlib.pyplot as plt
import numpy as np
from astropy import c | onstants as const
from astropy import units as un
from scipy import integrate
#PRIMERA PARTE
#Cargamos los datos y definimos arreglos para la Longitud y el Flujo
Datos = np.loadtxt("sun_AM0.dat")
Longitud = Datos[:,0]
Flujo = Datos[:,1]
#declaramos las unidades y las convertimos
UniLongitud = Longitud*un.nm ... |
slarosa/QGIS | python/plugins/sextante/lidar/lastools/lassplit.py | Python | gpl-2.0 | 2,455 | 0.001222 | # -*- coding: utf-8 -*-
"""
***************************************************************************
lassplit.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
******************************... | *******************************
* | *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later... |
Staffjoy/client_python | staffjoy/resources/manager.py | Python | mit | 206 | 0.004854 | from staffjoy.resource import Resourc | e
class Manager(Resource):
"""Location managers"""
PATH = "organizations/{organization_id}/locations/{location_id}/managers/{user_id}"
| ID_NAME = "user_id"
|
Azure/azure-sdk-for-python | sdk/healthbot/azure-mgmt-healthbot/azure/mgmt/healthbot/__init__.py | Python | mit | 680 | 0.002941 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See L | icense.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# ------------------------ | --------------------------------------------------
from ._healthbot import Healthbot
from ._version import VERSION
__version__ = VERSION
__all__ = ['Healthbot']
try:
from ._patch import patch_sdk # type: ignore
patch_sdk()
except ImportError:
pass
|
loicseguin/grades | grades/__init__.py | Python | bsd-3-clause | 878 | 0.001142 | #-*- coding: utf-8 -*-
"""\
======
Grades
======
For managing student grades, most teachers use spreadsheet tools. With these
tools, it is hard to maintain grades in plain text files that are easily
readable by humans. The goa | l of **Grades** is to let teachers manage their
students's grade in plain text file while providing tools to parse the file and
calculate students and grou | p means.
The table format that **Grades** use is the one Emacs `org-mode
<http://orgmode.org/index.html>`_ uses. Using org-mode, grades tables can be
easily set up and then **Grades** will happily compute all the required values.
"""
from __future__ import print_function # For Python 2 compatibility.
__author__ ... |
txenoo/django-radio | radioco/apps/radioco/management/commands/create_example_data.py | Python | gpl-3.0 | 212 | 0 | from django.core | .management.base import BaseCommand
from radioco.apps.radioco.utils import create_example_data
class | Command(BaseCommand):
def handle(self, *args, **options):
create_example_data()
|
SOM-st/PySOM | tests/rtruffle_tests/test_node.py | Python | mit | 2,292 | 0 | import unittest
from rtruffle.node import Node
class NodeTest(unittest.TestCase):
def | test_adopt_child(self):
child = ChildNode()
parent = RootNode()
self.assertIsNone(child.parent)
parent.adopt_child(child)
self.assertIs(parent, child.parent)
def test_adopt_children(self):
chil | dren = [ChildNode() for _ in range(0, 10)]
parent = RootNode()
self.assertIsNot(children[0], children[1])
for child in children:
self.assertIsNone(child.parent)
parent.adopt_children(children)
for child in children:
self.assertIs(parent, child.parent)
... |
jpetto/olympia | src/olympia/access/tests.py | Python | bsd-3-clause | 9,223 | 0 | from django.http import HttpRequest
import mock
import pytest
from nose.tools import assert_false
from olympia import amo
from olympia.amo.tests import TestCase, req_factory_factory
from olympia.amo.urlresolvers import reverse
from olympia.addons.models import Addon, AddonUser
from olympia.users.models import UserPro... | UTHOR_ROLE_SUPPORT
self.au.save()
assert check_addon_ownership(self.request, self.addon, support=True)
class TestCheckReviewer(TestCase):
fixtures = ['base/addon_3615', 'addons/persona']
def setUp(self):
super(TestCheckReviewer, self).setUp()
self.user = UserProfile.objects.ge... | a = Addon.objects.get(pk=15663)
self.addon = Addon.objects.get(pk=3615)
def test_no_perm(self):
req = req_factory_factory('noop', user=self.user)
assert not check_addons_reviewer(req)
assert not check_unlisted_addons_reviewer(req)
assert not check_personas_reviewer(req)
... |
quattor/aquilon | lib/aquilon/worker/commands/compile_hostname.py | Python | apache-2.0 | 3,029 | 0.00033 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008-2013,2015-2016,2019 Contributor
#
# 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 t... | e.
"""Contains the logic for `aq compile`."""
from aquilon.worker.broker import BrokerCommand
from aquilon.worker.dbwrappers.host import hostname_to_host
from aquilon.worker.templates import Plenary, TemplateDomain
class CommandCompileHostname(BrokerCommand):
required_parameters = ["hostname"]
requires_read... | ):
dbhost = hostname_to_host(session, hostname)
if pancdebug:
pancinclude = r'.*'
pancexclude = r'components/spma/functions.*'
dom = TemplateDomain(dbhost.branch, dbhost.sandbox_author,
logger=logger)
plenary = Plenary.get_plenary(dbho... |
spacecoalmen/asteroid_scraper | asteroid_scraper/finder.py | Python | mit | 4,400 | 0.002273 | from numpy import NaN
from pandas import DataFrame
from asteroid_scraper.math.qfunction import Qfunction
from asteroid_scraper.math.tisserand import tisserand
from asteroid_scraper.utils.progress_bar import ProgressBarThread
class AsteroidFinder(object):
__shared_state = {}
client = None
def _borg_init(s... | )
asteroids_orbits = asteroids_orbits.to_dict(orient="records")
asteroids_orbits = self.filter_asteroids(asteroids_orbits)
results = []
for i, cycler_orbit in enumerate(cycler_orbits):
cycler_tisserand = cycler_orbit['tisserand']
cycler_q_function = cycler_orb... | orbit['tisserand'])
delta_q_function = self._q_function_delta(cycler_q_function,
orbit['q_function'])
results.append({'asteroid_id': orbit['id'],
'... |
matthewzhenggong/fiwt | XbeeZBS2Test/CommandWiFi.py | Python | lgpl-3.0 | 60,244 | 0.005577 | #!/bin/env python
# -*- coding: utf-8 -*-
""" @package XBee Zigbee API Test Programme
Funtions include:
1) AT command;
2) Remote AT command
3) Send single TX request with response in const frequency
4) Send continuous TX requests with/without response in const frequency
5) Flow rate predict/measurement in Pps(Packet p... | self.OnChar)
self.hexs = string.digits + 'abcdefABCDEF'
def Clone(self):
return MyValidator(self.flag)
def Validate(self, win):
tc = self.GetWindow()
val = tc.GetValue()
if self.flag == ALPHA_ONLY:
return all([i in string.letters for i in val])
eli... | ONLY:
return all([i in string.digits for i in val])
elif self.flag == HEX_ONLY:
return all([i in self.hexs for i in val])
return True
def OnChar(self, event):
key = event.GetKeyCode()
if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
... |
funkyeah/tiddlyweb | test/other/tiddlyweb/serializations/debug.py | Python | bsd-3-clause | 701 | 0.001427 |
"""
External serialization for testing remote module loading.
"""
from tiddlyweb.serializations import SerializationInterface
class Serialization(Serialization | Interface):
def list_recipes(self, recipes):
print recipes
def list_bags(self, bags):
print bags
def recipe_as(self, recipe | ):
print "r_as: %s" % recipe
def as_recipe(self, recipe, input):
print "as_r: %s" % input
def bag_as(self, bag):
print "b_as: %s" % bag
def as_bag(self, bag, input):
print "as_b: %s" % input
def tiddler_as(self, tiddler):
print "t_as: %s" % tiddler
def as... |
magic0704/oslo.db | oslo_db/tests/sqlalchemy/test_models.py | Python | apache-2.0 | 5,509 | 0 | # Copyright 2012 Cloudscaling Group, 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
#
# htt | p://www.apache.org/licenses/LICENSE-2.0
#
# | Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the Li... |
navcoindev/navcoin-core | qa/rpc-tests/walletbackup.py | Python | mit | 7,262 | 0.001515 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Exercise the wallet backup code. Ported from walletbackup.sh.
Test case is:
4 nodes. 1 2 and 3 send... | of all wallets should be 114 * 50 = 5700.
assert_equal(total, 5700)
##
# Test restoring spender wallets from backups
##
logging.info("Restoring using wallet.da | t")
self.stop_three()
self.erase_three()
# Start node2 with no chain
shutil.rmtree(self.options.tmpdir + "/node2/regtest/blocks")
shutil.rmtree(self.options.tmpdir + "/node2/regtest/chainstate")
# Restore wallets from backup
shutil.copyfile(tmpdir + "/node0/wall... |
brain-research/mirage-rl-bpttv | baselines/common/distributions.py | Python | mit | 10,920 | 0.009707 | import tensorflow as tf
import numpy as np
import baselines.common.tf_util as U
from tensorflow.python.ops import math_ops
class Pd(object):
"""
A particular probability distribution
"""
def flatparam(self):
raise NotImplementedError
def mode(self):
raise NotImplementedError
def... | return - self.neglogp(x)
class PdType(object):
"""
| Parametrized family of probability distributions
"""
def pdclass(self):
raise NotImplementedError
def pdfromflat(self, flat):
return self.pdclass()(flat)
def param_shape(self):
raise NotImplementedError
def sample_shape(self):
raise NotImplementedError
def sample... |
aacebedo/cloudflarednsupdater | environments/build/build.py | Python | lgpl-3.0 | 9,511 | 0.013984 | #!/usr/bin/env python3
# This file is part of CFDNSUpdater.
#
# CFDNSUpdater 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... | tput directory',
required=True, type=str)
deployDescParser.add_argument('--licenses', '-li', help='Software licences',
default=[], type=str, action='append')
deployDescParser.add_argument('--labels', '-la', help='Package labels',
... | ath = None
for x in range(0, 5):
tmp_dir_path = os.path.join(os.path.abspath(os.sep), "tmp", str(uuid.uuid4()))
if not os.path.exists(tmp_dir_path) :
os.makedirs(tmp_dir_path, exist_ok=True)
break
else:
tmp_dir_path = None
if tmp_dir_path == None:
raise Exception("Unable to generat... |
acsone/account-invoicing | account_invoice_rounding/__init__.py | Python | agpl-3.0 | 1,027 | 0 | # -*- coding: utf-8 -*-
################## | ############################################################
#
# Author: Yannick Vaucher
# Copyright 2013 Camptocamp SA
#
# This progr | am 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 distributed in the hope that it will be usefu... |
fyhtea/squeezeDet-hand | src/config/voc_squeezeDet_config.py | Python | bsd-2-clause | 1,990 | 0.037186 | """Model configuration for pascal dataset"""
import numpy as np
from config import base_model_config
def voc_squeezeDet_config():
"""Specify the parameters to tune below."""
mc = base_model_config('PASCAL_VOC')
mc.IMAGE_WIDTH = 320
mc.IMAGE_HEIGHT = 240
mc.BATCH_SI... | RID = 9
return mc
def set_anchors(m | c):
H, W, B = 14, 19, 9
anchor_shapes = np.reshape(
[np.array(
[[ 36., 37.], [ 366., 174.], [ 115., 59.],
[ 162., 87.], [ 38., 90.], [ 258., 173.],
[ 224., 108.], [ 78., 170.], [ 72., 43.]])] * H * W,
(H, W, B, 2)
)
center_x = np.reshape(
np.transpose(
... |
fearlessspider/python-social-auth | examples/webpy_example/app.py | Python | bsd-3-clause | 3,421 | 0.002631 | import sys
sys.path.append('../..')
import web
from web.contrib.template import render_jinja
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from social.utils import setting_name
from social.apps.webpy_app.utils import psa, backends
from social.apps.webpy_app import app ... | dOAuth2',
'social.backends.thisismyjam.ThisIsMyJamOAuth1',
'social.backends.stocktwits.StocktwitsOAuth2',
'social.backends.tripit.TripItOAuth',
'social.backends.clef.ClefOA | uth2',
'social.backends.twilio.TwilioAuth',
'social.backends.xing.XingOAuth',
'social.backends.yandex.YandexOAuth2',
'social.backends.podio.PodioOAuth2',
'social.backends.mineid.MineIDOAuth2',
'social.backends.wunderlist.WunderlistOAuth2',
'social.backends.upwork.UpworkOAuth',
)
web.config[s... |
wcmitchell/insights-core | insights/core/filters.py | Python | apache-2.0 | 2,205 | 0.000454 | import os
import pkgutil
import re
import six
import yaml as ser
from collections import defaultdict
import insights
from insights.core import dr
# TODO: consider case insensitive and regex
FILTERS = defaultdict(set)
def add_filter(name, patterns):
if isinstance(patterns, six.string_types):
FILTERS[nam... | = set(patterns)
elif isinstance(patterns, set):
FILTERS[name] |= patterns
else:
raise TypeError("patterns must be string, list, or set.")
def get_filters(component):
filters = set()
if component in FILTERS:
filters |= FILTERS[component]
alias = dr.get_alias(component)
... |
return filters
def apply_filters(target, lines):
results = []
for l in lines:
for f in FILTERS[target]:
if re.search(f, l):
results.append(l)
return results
_filename = ".".join(["filters", ser.__name__])
_dumps = ser.dump
_loads = ser.safe_load
def loads(strin... |
daumann/chronas-application | umap/templates/leaflet_storage/leaflet_storage_tags.py | Python | mit | 2,204 | 0.000907 | from django.utils import simplejson
from django import template
from django.conf import settings
from ..models import DataLayer, TileLayer
from ..views import _urls_for_js
register = template.Library()
@register.inclusion_tag('leaflet_storage/css2.html')
def leaflet_storage_css():
return {
"STATIC_URL":... | 'u | rls': _urls_for_js(),
'STATIC_URL': settings.STATIC_URL,
"allowEdit": False,
'hash': False,
'attributionControl': False,
'scrollWheelZoom': False,
'datalayersControl': False,
'zoomControl': False,
'storageAttributionControl': False,
'moreControl': ... |
gangadhar-kadam/sapphire_app | patches/july_2013/p01_remove_doctype_mappers.py | Python | agpl-3.0 | 516 | 0.017442 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# License: GNU General Public License v3. See license.txt
import webnotes
def execute():
webnotes.conn.sql("""drop table if exists `tabDocType Mapper`""")
webnotes.conn.sql("""drop table if exists `tabTable Mapper Detail`""")
webnotes.conn.sql("""drop table if ... | ists `tabField Mapper Detail`""")
webnotes.delete_doc("DocType", "DocType Map | per")
webnotes.delete_doc("DocType", "Table Mapper Detail")
webnotes.delete_doc("DocType", "Field Mapper Detail") |
sobi-wan/helmet | recipes-example/helmet-rootfs/helmet-rootfs-1.0.0/home/root/josh.py | Python | mit | 4,911 | 0.038689 | #!/usr/bin/python
import subprocess
import os
import time
import sys
import threading
import signal
from upload import ftp_open, upload
import gpio
from gpio import setup,mode,read,set,cleanup
led_red=91
led_amber=90
led_green=65
button_switch=95
def updateIndicators(stop_event):
blinker=0
while not stop_event.... | nter=0
while button() != (False,1):
time.sleep(0.5)
touch("trilobite")
try:
gstproc = subprocess.Popen(getGstCmd(), shell=True)
except ValueError as e:
print "value error:", e
except OSError as... |
print "OS error:", e
except subprocess.CalledProcessError as e:
print "called process error:", e
finally:
print "Popen finished."
while gstproc.poll() is None:
time.sleep(1)
if button()==(True,0):
break
#print ".",
... |
fedspendingtransparency/data-act-broker-backend | dataactcore/migrations/versions/d10d998b796b_remove_rule_description_from_rulesql_.py | Python | cc0-1.0 | 914 | 0.009847 | """Remove rule_description from RuleSql table
Revision ID: d10d998b796b
Revises: 5f1470603fa0
Create Date: 2018-03-20 13:46:14.180715
"""
# revision identifiers, used by Alembic.
revision = 'd10d998b796b'
down_revision = '5f1470603fa0'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy ... |
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
def upgrade_data_broker():
### commands auto generated by Alembic - please | adjust! ###
op.drop_column('rule_sql', 'rule_description')
### end Alembic commands ###
def downgrade_data_broker():
### commands auto generated by Alembic - please adjust! ###
op.add_column('rule_sql', sa.Column('rule_description', sa.TEXT(), autoincrement=False, server_default='N/A', nullable=False... |
regebro/doctrine.urwid | doctrine/urwid/layout.py | Python | mit | 10,162 | 0.001181 | # -*- coding: UTF-8 -*-
import urwid
from urwid.util import (move_prev_char, move_next_char, calc_width,
calc_text_pos, is_wide_char)
from urwid.text_layout import CanNotDisplayText, TextLayout
from urwid.compat import bytes, PYTHON3, B
ONECHAR_NEWLINES = (u'\n', b'\n', u'\r', b'\r')
TWOCHAR_N... | pported wrap mode."""
return wrap == urwid.SPACE
def layout(self, text, width, align, wrap):
"""Return a layout structure for text."""
try:
segs = self.calculate_text_segments(text, width, wrap)
return self.align_layout(text, width, se | gs, wrap, align)
except CanNotDisplayText:
return [[]]
def calculate_text_segments(self, text, width, wrap):
"""
Calculate the segments of text to display given width screen
columns to display them.
text - unicode text or byte string to display
width - n... |
pcecconi/mapground | layers/migrations/0007_auto_20180923_2151.py | Python | mit | 1,658 | 0.001206 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-09-23 21:51
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('layers', '0006_auto_20180811_1412'),
]
... | l=True),
),
migrations.AddField(
model_name='capa',
name='gdal_driver_longname',
field=models.CharField(blank=True, default='', max_length=100, verbose_name='Driver - Long Name'),
),
migrations.AddField(
model_name='capa',
name=... | ield(blank=True, default='', max_length=100, verbose_name='Driver - Short Name'),
),
migrations.AddField(
model_name='capa',
name='gdal_metadata',
field=django.contrib.postgres.fields.jsonb.JSONField(default={}),
),
migrations.AddField(
mod... |
enthought/etsproxy | enthought/chaco/overlays/simple_inspector_overlay.py | Python | bsd-3-clause | 108 | 0 | # proxy module
from __future__ import absolute_import
from chaco.overlays.si | mple_inspector_overla | y import *
|
hfinucane/ansible | lib/ansible/plugins/action/__init__.py | Python | gpl-3.0 | 32,910 | 0.003981 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | ent = self._templar.template(final_environment)
return self._connect | ion._shell.env_prefix(**final_environment)
def _early_needs_tmp_path(self):
'''
Determines if a temp path should be created before the action is executed.
'''
return getattr(self, 'TRANSFERS_FILES', False)
def _late_needs_tmp_path(self, tmp, module_style):
'''
... |
DebVortex/ariane-old- | ariane/apps/frontend/apps.py | Python | bsd-3-clause | 235 | 0 | from django.apps import AppConfig
from django.utils.translation i | mport ugettext_lazy as _
class FrontendConfig(AppConfig):
"""Configuration for frontend app."""
name = 'ariane.apps.frontend'
verbose_name = | _("Frontend")
|
Xarrow/pySimulatedDNS | dnsCat/__init__.py | Python | apache-2.0 | 139 | 0 | # -*- coding:utf-8 -*-
"""
Verion: 1.0
Author: zhangjian
Site: http://iliangqunru.com
File: | __init__.py.py
Time: 2 | 017/7/22 2:19
"""
|
bandienkhamgalan/flappyeagle | views/DraggableComponentButton.py | Python | gpl-3.0 | 549 | 0.018215 | #!/usr/bin/env python3
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap, QMouseEvent
from PyQt5.QtWidgets import QToolButton
from PyQt5.QtCore import Qt, | pyqtSignal
fro | m models.components import *
class DraggableComponentButton(QToolButton):
mousePress = pyqtSignal(ComponentType, QMouseEvent, name='mousePress')
def __init__(self, parent=None):
QToolButton.__init__(self, parent)
self.componentType = None
def mousePressEvent(self, event):
self.checked = False
self.mousePre... |
google-research/google-research | coltran/models/layers.py | Python | apache-2.0 | 24,446 | 0.006054 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.apa | che.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limi... | uture__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import math
import operator
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.compat.v2.keras import layers
from coltran.utils import att_utils
from coltran.utils import base_utils
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.