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 |
|---|---|---|---|---|---|---|---|---|
ChuanleiGuo/AlgorithmsPlayground | LeetCodeSolutions/python/211_Add_and_Search_Word_Data_structure_design.py | Python | mit | 1,004 | 0.000996 | class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root = {}
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.roo | t
for c in word:
if c not in node:
node[c] = {}
node = node[c]
node['#'] = '#'
def search(self, word):
"""
Returns if the word is in the data structure. A word could
contain the dot character '.' to represent any one letter.
:t... | ord = word[0], word[1:]
if c != '.':
return c in node and find(word, node[c])
return any(find(word, d) for d in node.values() if d != '#')
return find(word, self.root)
|
tiangolo/fastapi | tests/test_tutorial/test_metadata/test_tutorial001.py | Python | mit | 1,611 | 0.000622 | from fastapi.testclient import TestClient
from docs_src.metadata.tutorial001 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {
"title": "ChimichangApp",
"description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.... | me": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
"version": "0.0.1",
},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operatio | nId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
}
},
}
def test_openapi_s... |
nareshshah139/CocktailPartyAlgorithm1 | CocktailPartyAlgorithm.py | Python | mit | 2,277 | 0.039087 |
import sys
from numpy import *
from scipy import signal
import scipy.io.wavfile
from matplotlib import pyplot
import sklearn.decomposition
def main():
# First load the audio data, the audio data on this example is obtained from http://www.ism.ac.jp/~shiro/research/blindsep.html
rate, source = scipy.io.wavfile.re... | ight channels of the audio
source_1, source_2 = sour | ce[:, 0], source[:, 1]
data = c_[source_1, source_2]
# Normalize the audio from int16 range to [-1, 1]
data = data / 2.0 ** 15
# Perform Fast ICA on the data to obtained separated sources
fast_ica = sklearn.decomposition.FastICA( n_components=2 )
separated = fast_ica.fit_transform( data )
# Check, data = se... |
davislidaqing/Mcoderadius | toughradius/radiusd/plugins/acct_stop_process.py | Python | agpl-3.0 | 1,514 | 0.018494 | #!/usr/bin/env python
#coding=utf-8
from twisted.python import log
from toughradius.radiusd.settings import *
import logging
import datetime
def process(req=None,user=None,radiusd=None,** | kwargs):
if not req.get_acct_status_type() == STATUS_TYPE_STOP:
return
runstat=radiusd.runstat |
store = radiusd.store
runstat.acct_stop += 1
ticket = req.get_ticket()
if not ticket.nas_addr:
ticket.nas_addr = req.source[0]
_datetime = datetime.datetime.now()
online = store.get_online(ticket.nas_addr,ticket.acct_session_id)
if not online:
session_time = ti... |
EmanueleCannizzaro/scons | test/duplicate-sources.py | Python | mit | 2,021 | 0.000495 | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 us... | ERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "test/duplicate-sources.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Verify that specifying a source file more than once | works correctly
and dos not cause a rebuild.
"""
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """\
def cat(target, source, env):
t = open(str(target[0]), 'wb')
for s in source:
t.write(open(str(s), 'rb').read())
t.close()
env = Environment(BUILDERS = {'Cat' : Builder(ac... |
wevote/WebAppPublic | candidate/controllers.py | Python | bsd-3-clause | 29,893 | 0.003646 | # candidate/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .models import CandidateCampaignListManager, CandidateCampaignManager
from ballot.models import CANDIDATE
from config.base import get_environment_variable
from django.contrib import messages
from django.http import HttpRespon... | ive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_API_KEY = get_environment_variable("WE_VOTE_API_KEY")
CANDIDATES_SYNC_URL = get_environment_variable("CANDIDATES_SYNC_URL")
def candidates_import | _from_sample_file():
"""
Get the json data, and either create new entries or update existing
:return:
"""
# Load saved json from local file
logger.info("Loading CandidateCampaigns from local file")
with open("candidate/import_data/candidate_campaigns_sample.json") as json_data:
stru... |
Aerilius/eog_panorama | eog_panorama/eog_panorama.py | Python | gpl-3.0 | 15,642 | 0.007672 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Approach:
# - Listen for image load event and check the XMP tag GPano:UsePanoramaViewer
# https://developers.google.com/streetview/spherical-metadata
# - GExiv2 (in default Ubuntu install, but may not be robust enough to inconsistent/duplicate XMP tags)
# - ExifT... | f.panorama_view = None
self.panorama_viewer_active = False
self.panorama_viewer_loaded = False
def on_selection_changed(self, thumb_view):
"""An image has been selected."""
# Use the reference of thumb_view passed as parameter, not self | .thumb_view (did cause errors).
current_image = thumb_view.get_first_selected_image() # may be None
if current_image:
# Get file path
uri = current_image.get_uri_for_display()
filepath = urllib.parse.urlparse(uri).path
# If it is a panorama, s... |
OdatNurd/OverrideAudit | src/commands/package_report.py | Python | mit | 2,593 | 0.0027 | import sublime
import sublime_plugin
from ..core import oa_syntax, decorate_pkg_name
from ..core import ReportGenerationThread
from ...lib.packages import PackageList
###----------------------------------------------------------------------------
class PackageReportThread(ReportGenerationThread):
"""
Genera... | and(sublime_plugin.WindowCommand):
"""
Generate a tabular report of all installed packages and their state.
"""
def run(self, force_reuse=False):
PackageReportThread(self.window, "Generating Package Report",
self.window.active_view(),
force... | rce_reuse).start()
###----------------------------------------------------------------------------
# |
inuitwallet/nuberrypi | PKGBLD/nuberrypi-info/nuberrypi-info.py | Python | gpl-3.0 | 7,347 | 0.028039 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
#
# Copyright 2014 Peerchemist
#
# This file is part of NuBerryPi project.
#
# 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 Li... | ('-a', '--all', help='show everything', action='store_true')
parser.add_argument('-s','--system', help='show system information', action='store_true')
parser.add_argument('-p', '--nu', help='equal to "ppcoid getinfo"', action='store_true | ')
parser.add_argument('--public', help='hide private data [ip, balance, serial]', action='store_true')
parser.add_argument('-o', '--output', help='dump data to stdout, use to pipe to some other program',
action='store_true')
parser.add_argument('--health', help='compare local blockchain data with pe... |
chienlieu2017/it_management | odoo/odoo/addons/base/res/res_font.py | Python | gpl-3.0 | 6,052 | 0.003305 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from reportlab.pdfbase import ttfonts
from odoo import api, fields, models
from odoo.report.render.rml2pdf import customfonts
"""This module allows the mapping of some system-available TTF fonts to
the r... | ltin fonts (Helvetica, Times, Courier) to better alternatives
# if available, because they only support a very small subset of unicode
# (missing 'č' for example)
for builtin_font_family, mode, alts in BUILTIN_ALTERNATIVES:
if (builtin_font_family, mode) not in local_family_modes:
... | font_paths.get(altern_font):
altern_def = (builtin_font_family, altern_font,
local_font_paths[altern_font], mode)
customfonts.CustomTTFonts.append(altern_def)
_logger.debug("Builtin remapping %r", altern_def)
... |
JFDesigner/FBAlbumDownloader | browser_cookie/setup.py | Python | gpl-2.0 | 722 | 0.006925 | import sys
import os
from distutils.core import setup
if sys.version_info.major >= 3:
print 'Sorry, currently only supports Python 2. Patches welcome!'
sys.exit(1)
setup(
name='browser-cookie',
version='0.6',
packages=['browser_cookie'],
package_dir={'browser_cookie' : '.'}, # look for packag... | cookiejar object so can download with urllib and other libraries the same content you see in the web browser.',
url='https://bitbucket.org/richardpenman/browser_cookie',
install_requires=['pycrypto', 'keyring'],
license='lgpl'
) | |
geoaxis/ask-sweden | ask_sweden/lambda_function.py | Python | mit | 3,656 | 0.001094 | import logging
from ask import alexa
import car_accidents
import expected_population
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(request_obj, context=None):
return alexa.route_request(request_obj)
@alexa.default
def default_handler(request):
logger.info('default_handler')
... | ation.get_expected_population(year)),
end_session=True, is_ssml=True)
@alexa.intent('WaterUsage')
def water_usage_stockholm(request):
year = request.get_slot_value('year')
logger.info('water_usage_stockholm')
logger.info( | request.get_slot_map())
return alexa.respond(
'''
<speak>
the water consumption in Stockholm in <say-as interpret-as="date" format="y">%s</say-as>,
is <say-as interpret-as="cardinal">%s</say-as>
</speak>
''' % (year, car_accidents.get_water_usage_stock... |
Barmaley-exe/scikit-learn | sklearn/ensemble/tests/test_weight_boosting.py | Python | bsd-3-clause | 15,811 | 0 | """Testing for the boost module (sklearn.ensemble.boost)."""
import numpy as np
from sklearn.utils.testing import assert_array_equal, assert_array_less
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_raises, assert_rais... | shuffle=False,
random_state=1)
for alg in ['SAMME', 'SAMME.R']:
clf = AdaBoostClassifier(algo | rithm=alg)
clf.fit(X, y)
importances = clf.feature_importances_
assert_equal(importances.shape[0], 10)
assert_equal((importances[:3, np.newaxis] >= importances[3:]).all(),
True)
def test_error():
"""Test that it gives proper exception on deficient input."""
... |
xunxunzgq/open-hackathon-bak_01 | open-hackathon-server/src/hackathon/storage/local_storage.py | Python | mit | 7,616 | 0.003808 | # -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
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 res... | pe)
return context
| def __generate_url(self, physical_path, file_type):
"""Return the http URI of file
It's for local storage only and the uploaded images must be in dir /static
:type physical_path: str|unicode
:param physical_path: the absolute physical path of the file
:type file_type: str | u... |
7404N/deepnet | deepnet/tanh_layer.py | Python | bsd-3-clause | 1,606 | 0.010585 | from layer import *
class TanhLayer(Layer):
def __init__(self, *args, **kwargs):
super(TanhLayer, self).__init__(*args, **kwargs)
@classmethod
def IsLayerType(cls, proto):
return proto.hyperparams.activation == deepnet_pb2.Hyperparams.TANH
def ApplyActivation(self):
cm.tanh(self.state)
def Sam... | .mask)
def GetLoss(self, get_deriv=False, **kwargs):
"""Compu | tes loss.
Computes the loss function. Assumes target is in self.data and predictions
are in self.state.
Args:
get_deriv: If True, computes the derivative of the loss function w.r.t the
inputs to this layer and puts the result in self.deriv.
"""
perf = deepnet_pb2.Metrics()
perf.Merg... |
SUSE/kiwi | test/unit/solver/repository/rpm_md_test.py | Python | gpl-3.0 | 1,668 | 0 | from mock import patch, call
import mock
from lxml import etree
from kiwi.solver.repository.rpm_md import SolverRepositoryRpmMd
from kiwi.solver.repository.base import SolverRepositoryBase
class TestSolverRepositoryRpmMd:
def setup(self):
self.xml_data = etree.parse('../data/repomd.xml')
self.u... | @patch.object(SolverRepositoryBase, '_get_repomd_xml')
def test__setup_repository_metadata(
self, mock_xml, mock_mkdtemp, mock_create_solvables,
mock_download_from_reposi | tory
):
mock_mkdtemp.return_value = 'metadata_dir.XX'
mock_xml.return_value = self.xml_data
self.solver._setup_repository_metadata()
assert mock_download_from_repository.call_args_list == [
call(
'repodata/55f95a93-primary.xml.gz',
'metada... |
skosukhin/spack | var/spack/repos/builtin/packages/numdiff/package.py | Python | lgpl-2.1 | 2,791 | 0.000717 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | eneral Public
# License along with this program; if n | ot, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Numdiff(AutotoolsPackage):
"""Numdiff is a little program that can be used to compare putatively
sim... |
chitianhao/trafficserver | tests/gold_tests/pluginTest/sslheaders/sslheaders.test.py | Python | apache-2.0 | 3,767 | 0.004247 | '''
Test the sslheaders plugin.
'''
# 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, Ver... | er 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.
Test.S | ummary = '''
Test sslheaders plugin.
'''
Test.SkipUnless(
Condition.HasCurlFeature('http2'),
)
Test.Disk.File('sslheaders.log').Content = 'sslheaders.gold'
server = Test.MakeOriginServer("server", options={'--load': Test.TestDirectory + '/observer.py'})
request_header = {
"headers": "GET / HTTP/1.1\r\nHost:... |
kaplun/ops | modules/bibdocfile/lib/bibdocfile_webinterface.py | Python | gpl-2.0 | 26,790 | 0.005524 | ## This file is part of Invenio.
## Copyright (C) 2012, 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
... | ocname']
if not docformat:
docformat = args['format']
if args['subformat']:
docformat += ';%s' % args['subformat']
if not | version:
version = args['version']
## Download as attachment
is_download = False
if args['download']:
is_download = True
# version could be either empty, or all or an integer
try:
int(version)
excep... |
Nevtep/omniwallet | api/send.py | Python | agpl-3.0 | 10,105 | 0.017912 | import urlparse
import os, sys
tools_dir = os.environ.get('TOOLSDIR')
lib_path = os.path.abspath(tools_dir)
sys.path.append(lib_path)
from msc_utils_parsing import *
from blockchain_utils import *
from msc_apps import *
import random
def send_form_response(response_dict):
expected_fields=['from_address', 'to_addre... | oshi_amount=int( amount )
fee=int( btc_fee )
# differ bitcoin send and other currencies
if currency_id == 0: # bitcoin
# normal bitcoin send
required_value=satoshi_amount
# if marker is needed, allocate dust for the marker
if marker_address != None:
required_valu... | :
tx_type=0 # only simple send is supported
required_value=4*dust_limit
#------------------------------------------- New utxo calls
fee_total_satoshi=required_value+fee
dirty_txes = bc_getutxo( from_address, fee_total_satoshi )
if (dirty_txes['error'][:3]=='Con'):
raise Except... |
xiruibing/hae | src/trayicon.py | Python | mit | 1,695 | 0.040583 | from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
from PyQt5.Qt import QSy | stemTrayIcon, QIcon
class TrayIcon(QSystemTrayIcon):
ActivationReason = ['Unknown', 'Context', 'DoubleClick', 'Trigger', 'MiddleClick']
onactivate = pyqtSignal(int, str)
onmessageclick = pyqtSignal()
def __init__(self, parent, toolTip = '', icon = '') | :
super(TrayIcon, self).__init__(parent)
self.setObjectName('trayIcon')
self.setIcon(icon)
self.setToolTip(toolTip)
self.activated.connect(self.activateHandler)
self.messageClicked.connect(self.onmessageclick)
# Slots
# 设置工具提示
@pyqtSlot(str)
def setToolTip(self, toolTip):
super(TrayIcon... |
JensGrabner/mpmath | mpmath/function_docs.py | Python | bsd-3-clause | 280,518 | 0.000125 | """
Extended docstrings for functions.py
"""
pi = r"""
`\pi`, roughly equal to 3.141592654, represents the area of the unit
circle, the half-period of trigonometric functions, and many other
things in mathematics.
Mpmath can evaluate `\pi` to arbitrary precision::
>>> from mpmath import *
>>> mp.dps = 50; m... | 0.91596559417721901505460351493238411077414937428167
"""
khinchin = r"""
Khinchin's constant | `K` = 2.68542... is a number that
appears in the theory of continued fractions. Mpmath can evaluate
it to arbitrary precision::
>>> from mpmath import *
>>> mp.dps = 50; mp.pretty = True
>>> +khinchin
2.6854520010653064453097148354817956938203822939945
An integral representation is::
>>> I = qua... |
chunchih/article-matching | experiment/find_key_relation.py | Python | bsd-3-clause | 2,408 | 0.023671 | # -*- coding: utf-8 -*-
from gensim.models import word2vec
from gensim import models
import jieba
import codecs
import io
from collections import Counter
import operator
import numpy
f = codecs.open("target_article.txt",'r','utf8')
content = f.readlines()
article = []
jieba.set_dictionary('jieba_dict/dict.txt.big')... | st:
if friend_1 == friend_2:
continue
value += model.similarity(friend_1, friend_2)
leng = len(friend_list)
related_word[words[i]] = value/float(leng*leng)
s_imp_words = sorted(related_word | .items(), key=operator.itemgetter(1), reverse=True)
for i in s_imp_words[:20]:
print i[0]
print "-----------------------"
#print s_imp_words
# for value in output:
# if value[1] == 0.0:
# continue
# print value[0], value[1]
# print "-----------------------"
keywords = []
fg = numpy.zeros(len(s_imp_words))
for i... |
thuck/ppam | ui/tabs.py | Python | gpl-2.0 | 13,310 | 0.003681 | ###############################################################################
#PPAM is a pulseaudio interface.
#Copyright (C) 2013 Denis Doria (Thuck)
#
#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... | lor_pair(1))
else:
self.win.addstr(line_number + 1, 1, line)
self.max_item = line_number
if self.info_window_data:
draw_info_window(self.win, self.info_window_data)
self.win.refresh()
class Tab | Playback(GenericStream):
def __init__(self, win):
GenericStream.__init__(self, win, 'Playback', _('Playback'))
class TabRecord(GenericStream):
def __init__(self, win):
GenericStream.__init__(self, win, 'Record', _('Record'))
class GenericDevice(object):
def __init__(self, win, device_... |
aperigault/ansible | docs/docsite/rst/conf.py | Python | gpl-3.0 | 8,952 | 0.00067 | # -*- coding: utf-8 -*-
#
# documentation build configuration file, created by
# sphinx-quickstart on Sat Sep 27 13:23:22 2008-2009.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleab... | d HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
# html_style = 'solar.css'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = 'Ansible Documentation'
#... | le = None
# The name of an image file (within the static path) to place at the top of
# the sidebar.
# html_logo = None
# 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 = 'favicon.i... |
pytroll/satpy | satpy/readers/li_l2.py | Python | gpl-3.0 | 5,368 | 0.000373 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Satpy developers
#
# This file is part of satpy.
#
# satpy 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... | es/>.
# type: ignore
"""Interface to MTG-LI L2 product NetCDF files
The reader is based on preliminary test data provided by EUMETSAT.
The data description is described in the
"LI L2 Product User Guide [LIL2PUG] Draft version" documentation.
| """
import logging
from datetime import datetime
import h5netcdf
import numpy as np
from pyresample import geometry
# FIXME: This is not xarray/dask compatible
# TODO: Once migrated to xarray/dask, remove ignored path in setup.cfg
from satpy.dataset import Dataset
from satpy.readers.file_handlers import BaseFileHandl... |
kernsuite-debian/lofar | LCS/PyCommon/test/t_dbcredentials.py | Python | gpl-3.0 | 2,789 | 0.008964 | #!/usr/bin/env python3
import unittest
import tempfile
from lofar.common.dbcredentials import *
def setUpModule():
pass
def tearDownModule():
pass
class TestCredentials(unittest.TestCase):
def test_default_values(self):
c = Credentials()
self.assertEqual(c.type, "postgres")
self.assertEqual(c.hos... | dbc = DBCredentials(filepatterns=[f.name])
self.assertEqual(dbc.list(), ["DATABASE"])
# test if credentials match with what we've written
c_in = Credentials()
c_in.host = "example.com"
c_in.port = 1234
c_in.user = "root"
c_in.password = "secret"
c_in.database = "mydb"
c_out = dbc... | """
[database:DATABASE]
foo = bar
test = word word
""")
f.flush() # don't close since that will delete the TemporaryFile
# extract our config
dbc = DBCredentials(filepatterns=[f.name])
c_out = dbc.get("DATABASE")
# test if the free-form config options got through
self.assertEqual(c_out.config[... |
asedunov/intellij-community | python/testData/refactoring/introduceConstant/py1840.py | Python | apache-2.0 | 35 | 0.028571 | exec(open("t | mp<caret>.t | xt").read()) |
openstack/cinder | cinder/common/constants.py | Python | apache-2.0 | 1,167 | 0 | # Copyright 2016 Red Hat, 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... | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# The maximum value a signed INT type may have
DB_MAX_INT = 0x7FFFFFFF
# The cinder services binaries and topics' names
API_BINAR | Y = "cinder-api"
SCHEDULER_BINARY = "cinder-scheduler"
VOLUME_BINARY = "cinder-volume"
BACKUP_BINARY = "cinder-backup"
SCHEDULER_TOPIC = SCHEDULER_BINARY
VOLUME_TOPIC = VOLUME_BINARY
BACKUP_TOPIC = BACKUP_BINARY
LOG_BINARIES = (SCHEDULER_BINARY, VOLUME_BINARY, BACKUP_BINARY, API_BINARY)
# The encryption key ID used by... |
facebookexperimental/eden | eden/scm/tests/test-fb-hgext-diff-since-last-submit-t.py | Python | gpl-2.0 | 6,148 | 0.00244 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import
from testutil.dott import feature, sh, testtmp # noqa: F401
# Load extensions
(
sh % "cat"
<< r"""... | etermine previous changeset hash
[255]"""
sh % "'HG_ARC_CONDUIT_MOCK=$TESTTMP/mockduit' hg log -r 'lastsubmitted(.)' -T '{node} {desc}\\n'" == r"""
Error calling graphql: Unexpected graphql response format
abort: unable to determine previous changeset hash
[255]"""
sh % "cat" << r"""
[{"data": {"query... | ew",
"differential_diffs": {"count": 3},
"is_landing": false,
"land_job_status": "NO_LAND_RUNNING",
"needs_final_review_status": "NOT_NEEDED",
"created_time": 123,
"updated_time": 222
}]}}]}}]
""" > "$TESTTMP/mockduit"
sh % "'HG_ARC_CONDUIT_MOCK=$TESTTMP/mockduit' hg diff --since-last-submit" == r"""
ab... |
Architektor/PySnip | venv/lib/python2.7/site-packages/twisted/protocols/wire.py | Python | gpl-3.0 | 2,659 | 0.003009 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""Implement standard (and unused) TCP protocols.
These protocols are either provided by inetd, or are not provided at all.
"""
from __future__ import absolute_import, division
import time
import struct
from zope.interface import implementer
... | pass
@implementer(interfaces.IProducer)
class Charge | n(protocol.Protocol):
"""Generate repeating noise (RFC 864)"""
noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?'
def connectionMade(self):
self.transport.registerProducer(self, 0)
def resumeProducing(self):
self.transport.write(self.noise)
def paus... |
kamyu104/LeetCode | Python/kth-largest-element-in-an-array.py | Python | mit | 1,142 | 0.002627 | # Time: O(n) ~ O(n^2)
# Space: O(1)
from random import randint
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {integer}
def findKthLargest(self, nums, k):
left, right = 0, len(nums) - 1
while left <= right:
pivot_idx = randint(left, right)
... | 1
else: # new_pivot_idx < k - 1.
left = new_pivot_idx + 1
def PartitionAroundPivot(self, left, right, pivot_idx, nums):
pivot_value = nums[pivot_idx]
new_pivot_idx = left
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
for i in xrange(left, r... | ums[i] > pivot_value:
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
|
robocomp/robocomp-ursus-rockin | components/comprehension/comprehension.py | Python | gpl-3.0 | 4,066 | 0.029759 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, traceback, Ice, threading, time, os
import IceStorm
# Ctrl+c handling
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Qt interface
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtSvg import *
# Check that RoboComp has been ... | cribeAndGetPublisher(qos, proxyT)
adapterT.activate()
ASRPublishTopic_subscription = True
except IceStorm.NoSuchTopic:
print "Error! No topic found! Sleeping for a while..."
time.sleep(1)
print 'ASRPublishTopic subscription ok'
# Implement ASRComprehension
asrcomprehensionI = ASRCompr... | prehension')
adapterASRComprehension.add(asrcomprehensionI, self.communicator().stringToIdentity('asrcomprehension'))
adapterASRComprehension.activate()
self.communicator().waitForShutdown()
except:
traceback.print_exc()
status = 1
if self.communicator():
try:
self.communicator().destroy()... |
anand1712/cloudpulse | cloudpulse/openstack/api/cinder_api.py | Python | apache-2.0 | 1,489 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | f.cinderclient.volumes.create(volume_size,
name=volume_name)
except Exception as e:
return (404, e.message, [])
return (200, "success", cinder_ret)
def cinder_volume_delete(self, volume_id):
try:
cinder_re | t = self.cinderclient.volumes.delete(volume_id)
except Exception as e:
return (404, e.message, [])
return (200, "success", cinder_ret)
|
mateuszmidor/GumtreeOnMap | src/offerfetcher.py | Python | gpl-2.0 | 848 | 0.008255 | '''
Created on 30-07-2014
@author: mateusz
'''
from threading import Thread
import gumtreeofferparser as Parser
from injectdependency import Inject, InjectDependency
@InjectDependency('urlfetcher')
class OfferFetcher(Thread):
urlfetcher = Inject
def __init__(self, inQueue, outQueue):
... | l = self.inQueue.get()
offer = self.getOffer(url)
self.outQueue.put(offer)
self.inQueue.task_done()
def get | Offer(self, url):
html = self.urlfetcher.fetchDocument(url)
offer = Parser.extractOffer(html)
offer["url"] = url
return offer |
camerongray1515/Prophasis | application/prophasis_common/prophasis_common/alert_modules/syslog.py | Python | bsd-2-clause | 179 | 0.005587 | from sys | log import syslog
module_name = "Syslog"
config = {
"prefix": "Default Prefix"
}
def ha | ndle_alert(message):
syslog("{} - {}".format(config["prefix"], message))
|
Haellsigh/travaux-pratiques | TP/TP8-Exo2.py | Python | mit | 532 | 0.011278 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 20:42:20 2016
@author: haell
"""
def dicho(f, a, b, epsilon):
assert f(a) * f(b) <= 0 and | epsilon > 0
g, d = a, b
fg, fd = f(g), f(d)
n = 0
while d - g > 2 * epsilon:
n += 1
m = (g + d) / 2.
fm = f(m)
if fg | * fm <= 0:
d, fd = m, fm
else:
g, fg = m, fm
print(d, g, fd, fg)
return (g + d) / 2., n
print(dicho(lambda x : x*x*10**(-8) - 4*x / 5 + 10**(-8), 7*10**7, 9*10**7, 10**-8)) |
NonVolatileComputing/arrow | python/pyarrow/tests/test_types.py | Python | apache-2.0 | 4,240 | 0 | # 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 u... | pa.uint16(), pa.uint32(), pa.uint64()]
for t in signed_ints + unsigned_ints:
assert types.i | s_integer(t)
for t in signed_ints:
assert types.is_signed_integer(t)
assert not types.is_unsigned_integer(t)
for t in unsigned_ints:
assert types.is_unsigned_integer(t)
assert not types.is_signed_integer(t)
assert not types.is_integer(pa.float32())
assert not types.is_... |
harsimrans/word-treasure | word_treasure/test_wordt.py | Python | gpl-3.0 | 1,648 | 0.005461 | import unittest
from word_treasure import *
class WordTreasureTestCase(unittest.TestCase):
"""Test for functions in word treasure.
The major aim is to check if there is any
unexpected crash.
Doesnot check the validity of the response"""
def test_definition_call(self):
word1 = "hello"
... | def test_display_compact(self):
word1 = "hello"
word2 = "somenonexistantword"
| self.assertEqual(display_compact(word1), True)
self.assertEqual(display_compact(word2), None)
def test_help_display(self):
self.assertEqual(display_help(), True)
if __name__=='__main__':
unittest.main()
|
wolverineav/neutron | neutron/db/migration/alembic_migrations/brocade_init_ops.py | Python | apache-2.0 | 2,634 | 0 | # Copyright 2014 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 ... | imaryKeyConstraint('id'))
op.create_table(
'ml2_brocadeports',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('network_id', sa.String(length=36), nullable=False),
sa.Column('admin_state_up', sa.Boolean(), nullable=False),
sa.Column('physical_interface', sa.... | mn('tenant_id', sa.String(length=255), nullable=True,
index=True),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['network_id'], ['ml2_brocadenetworks.id']))
|
dlutxx/memo | python/daemon.py | Python | mit | 1,497 | 0 | # -*- encoding: utf8 -*-
# A daemon to keep SSH forwarding connected
from __future__ import print_function, absolute_import
import os
import sys
import time
import socket
import logging
class Daemon(object):
def __init__(self):
self.heartbeat = 50
def run(self):
logging.basicConfig(filename=... | if pid:
os.waitpid(pid, os.WNOHANG)
sys.exit(0)
return
def reconnect(self):
pid = os.fork()
if pid == 0: # child
err = os.execlp(' | /usr/bin/ssh', 'ssh', '-i',
'/home/xu/.ssh/id_rsa', '-L',
'3366:127.0.0.1:3306', '-p', '42022', 'xu@abc.com')
if err:
logging.error("error to execlp")
sys.exit(1)
elif pid > 0:
os.waitpid(pid, 0)
... |
patrick-brian-mooney/python-personal-library | run_subfolder_scripts.py | Python | gpl-3.0 | 1,560 | 0.005128 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Search through the subfolders of the current folder. For each subfolder found,
chdir() to it, then run all executable scri | pts ending in .SH in that folder.
Does not exhaustively search for subfolders of subfolders, o | r subfolders of
subfolders of subfolders, etc.; it only does exactly what was described in that
first sentence, without recursion.
Note that this calls scripts in an insecure way:
subprocess.call(script_name, shell=True)
so it should only be called on scripts that are trusted completely.
This script is copyrigh... |
eclee25/flu-SDI-exploratory-age | scripts/create_fluseverity_figs/F2_incid_time.py | Python | mit | 2,579 | 0.01551 | #!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 4/26/14
###Function: Incidence per 100,000 vs. week number for flu weeks (wks 40-20). Incidence is per 100,000 for the US population in the second calendar year of the flu season.
###Import data: SQL_... | d_time.png', transparent=False, bbox_inches='tight', pad_inches=0)
plt.close()
# plt.show()
# 7/28/14: does 'week' variable in SDI refer to week before or after referenced date? Thanksgiving week does not correpond with correct week nu | mber for dip in incidence plot
print [d_incid[wk] for wk in sorted(d_wk) if d_wk[wk]==2]
print [wk for wk in sorted(d_wk) if d_wk[wk]==2]
|
shaddyx/simpleDecorators | simpledecorators/Synchronized.py | Python | mit | 511 | 0.005871 | from functools import wraps
from threading import RLock
import traceback
def Synchronized(lock=None):
"""
:para | m lock: if None - global lock will used, unique for each function
:return:
"""
if not lock:
lock=RLock()
d | ef decorator(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
lock.acquire()
try:
return fn(*args, **kwargs)
finally:
lock.release()
return wrapped
return decorator
|
Code4SA/municipal-data | municipal_finance/templatetags/jsonify.py | Python | mit | 140 | 0 | import json
from django import template
regist | er = template.Library()
@register.filter
def jsonify(value):
return json.dumps(value) | |
zaibacu/DamnedQuest | sprite_creator.py | Python | mit | 1,532 | 0.00718 | from PIL import Image
from math import ceil, floor
def load_img(src):
return Image.open(src)
def create_master(width, height):
return Image.new("RGBA", (width, height))
def closest_power_two(num):
result = 2
while result < num:
result = result * 2
return result
def create_matrix(cols, ro... | eight: {1}".format(width, height))
offset_x = int((width - x) / 2)
offset_y = int((height - y) / 2)
master = create_master(width * cols, height * rows)
for i | ndex, img in enumerate(images):
row = floor(index / cols)
col = index % cols
master.paste(img, (width * col + offset_x, height * row - offset_y))
return master
def hero_sprites(name, action, frames):
from functools import reduce
def generator(name, action, position, frames):
... |
apache/incubator-airflow | airflow/operators/redshift_to_s3_operator.py | Python | apache-2.0 | 1,680 | 0.002381 | #
# 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... | less 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 License.
"""
T... | deprecated.
Please use :mod:`airflow.providers.amazon.aws.transfers.redshift_to_s3`.
"""
import warnings
from airflow.providers.amazon.aws.transfers.redshift_to_s3 import RedshiftToS3Operator
warnings.warn(
"This module is deprecated. Please use `airflow.providers.amazon.aws.transfers.redshift_to_s3`.",
Dep... |
BetterWorks/django-bleachfields | bleachfields/bleachchar.py | Python | mit | 409 | 0 | from django.db import models
from .bleachfield import BleachField
class BleachCharField(BleachField, models.CharField):
def pre_save(self, model_instance, add):
new_value = getattr(model_instance, self.attname)
clean_value = self.clean_text(new_value)
setattr(model_instance, self.attname... | return super(BleachCharField, self).pre_save(model_instance, add)
| |
tylertian/Openstack | openstack F/glance/glance/api/v2/image_tags.py | Python | apache-2.0 | 1,791 | 0 | # Copyright 2012 OpenStack, LLC
# 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 b... | db_api.image_tag_delete(req.context, image_id, tag_value)
except exception.NotFound:
raise webob.exc.HTTPN | otFound()
class ResponseSerializer(wsgi.JSONResponseSerializer):
def update(self, response, result):
response.status_int = 204
def delete(self, response, result):
response.status_int = 204
def create_resource():
"""Images resource factory method"""
serializer = ResponseSerializer()
... |
yosshy/osclient2 | osclient2/nova/v2/server.py | Python | apache-2.0 | 21,602 | 0 | # Copyright 2014-2017 by Akira Yoshiyama <akirayoshiyama@gmail.com>.
# 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... | e a server
@rtype: None
"""
self._http.post(self._url_resource_path, self._id, 'action',
data=utils.get_json_body("unpause"))
def suspend(self):
"""
Suspend a server (save to disk if server is a VM)
@rtype: None
"""
self._htt... | """
Resume a server
@rtype: None
"""
self._http.post(self._url_resource_path, self._id, 'action',
data=utils.get_json_body("resume"))
def reset_network(self):
"""
Reset networking of a server
@rtype: None
"""
self... |
skitoo/chac | chac/sensors/models.py | Python | gpl-3.0 | 251 | 0 | from dja | ngo.db import models
from jsonfield import JSONField
class Sensor(models.Model):
name = models.CharField(max_length=25)
activated = models.BooleanField( | default=False)
type = models.CharField(max_length=10)
meta = JSONField()
|
julka2010/games | games/tichu/cards.py | Python | mpl-2.0 | 2,702 | 0.002591 | import functools
from . import (
constants,
utils,
)
class Card():
def __init__(self, kind=None, strength=None, value=None, verbose=None, **kwargs):
if kind is None:
raise(TypeError("Missing required 'kind' argument."))
self.kind = kind
self.strength = strength
... | n(self, arg):
if super()._valid_comparision(arg):
if hasattr(arg, " | colour") and (arg.colour is not None):
if arg.strength is not None:
return True
return False
_valid_comparision = __valid_comparision
def __lt__(self, value):
if not self.__valid_comparision(value):
return super().__lt__(value)
if self.st... |
google-research/falken | service/learner/brains/specs.py | Python | apache-2.0 | 58,084 | 0.005113 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | eferenced by joysticks '
f'{joystick_names} has no rotation.')
class SpecBase:
"""Base class for an action or observation spec."""
def __init__(self, spec):
"""Parse and validate the provided spec proto.
Args:
spec: Spec protobuf to parse and validate.
"""
se... | def proto(self):
"""Return the underlying proto buffer."""
return self._spec_proto
@property
def proto_node(self):
"""Get the ProtobufNode referencing the underlying protocol buffer."""
return self._spec_proto_node
def __str__(self):
"""String representation of the proto owned by this object... |
dcsquared13/Diamond | src/collectors/network/network.py | Python | mit | 4,536 | 0.007496 | # coding=utf-8
"""
The NetworkCollector class collects metrics on network interface usage
using /proc/net/dev.
#### Dependencies
* /proc/net/dev
"""
import diamond.collector
from diamond.collector import str_to_bool
import diamond.convertor
import os
import re
try:
import psutil
except ImportError:
psuti... | stats.items():
# Get Metric Name
metric_name = '.'.join([device, s])
# Get Metric Value
metric_value = self.derivative(metric_name,
long | (v),
diamond.collector.MAX_COUNTER)
# Convert rx_bytes and tx_bytes
if s == 'rx_bytes' or s == 'tx_bytes':
convertor = diamond.convertor.binary(value=metric_value,
... |
brownharryb/erpnext | erpnext/manufacturing/doctype/work_order/work_order.py | Python | gpl-3.0 | 25,289 | 0.025031 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe.utils import flt, get_datetime, getdate, date_diff, cint, nowdate
from frappe.model.document ... | Manufacture", "produced_qty"),
("Material Transfer for Manufacture", "material_transferred_for_manufacturing")):
if (purpose == 'Material Transfer for Manufacture' and
self.ope | rations and self.transfer_material_against == 'Job Card'):
continue
qty = flt(frappe.db.sql("""select sum(fg_completed_qty)
from `tabStock Entry` where work_order=%s and docstatus=1
and purpose=%s""", (self.name, purpose))[0][0])
completed_qty = self.qty + (allowance_percentage/100 * self.qty)
if... |
rwl/PyCIM | CIM14/CPSM/Equipment/Core/GeographicalRegion.py | Python | mit | 2,316 | 0.000864 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | 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 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, ARISING
# FROM,... |
Quiphius/pdns-sync | pdnssync/main.py | Python | mit | 2,853 | 0.001052 | import argparse
from pdnssync.database import Database
from pdnssync.parse import Parser
from pdnssync.error import get_warn, get_err
parser = Parser()
def validate():
domains = parser.get_domains()
for d in sorted(domains):
domains[d].validate(domains)
def sync(db):
all_db_domains = db.get_dom... |
for j in records[i]:
print('%s %s' % (j.data, i[0]))
if i[1] == 'CNAME':
for j in records[i]:
print('C %s %s' % (i[0], | j.data))
if i[1] == 'SRV':
for j in records[i]:
print('S %s %s %s' % (i[0], j.prio, j.data))
if i[1] == 'TXT':
for j in records[i]:
print('X %s %s' % (i[0], j.data))
print()
def do_sync():
aparser = argparse.A... |
almet/whiskerboard | settings/epio.py | Python | mit | 751 | 0.001332 | from __future__ import absolute_import
from .base import *
from bundle_config import config
DATABASES = {
'default': {
'ENGINE': 'django.db.b | ackends.postgresql_psycopg2',
'NAME': config['postgres']['database'],
'USER': config['postgres']['username'],
'PASSWORD': config['postgres']['password'],
'HOST': config['postgres']['host'],
}
}
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATIO... |
'PASSWORD': config['redis']['password'],
},
'VERSION': config['core']['version'],
},
}
DEBUG = False
|
dan-stone/canal | canal/tests/test_from_json.py | Python | mit | 3,665 | 0 | import numpy as np
import canal as canal
from .util import NumpyTestCase
class FromJSONTestCase(NumpyTestCase):
class Measurement(canal.Measurement):
int_field = canal.IntegerField()
alternate_db_name = canal.IntegerField(db_name="something_else")
float_field = canal.FloatField()
... | self.assertndArrayEqual(
test_series.float_field,
np.array(5*[1.2, 2.3])
)
self.assertndArrayEqual(
tes | t_series.bool_field,
np.array(5*[True, False])
)
self.assertndArrayEqual(
test_series.string_field,
np.array(5*["some content", "some other content"])
)
self.assertndArrayEqual(
test_series.tag_1,
np.array(10*["1"])
)
... |
blakeohare/crayon | Scripts/project-diff.py | Python | mit | 5,511 | 0.020323 | import os
import sys
def main(args):
if len(args) != 2:
print("Usage: python project-diff.py [path-to-project-1] [path-to-project-2]")
return
dir1 = args[0]
dir2 = args[1]
project1 = collect_text_files(dir1)
project2 = collect_text_files(dir2)
files_only_in_1 = []
files_only_in_2 = []
files_... | ('/', os.sep), 'rt')
text = c.read()
c.close()
output[rel_file] = text
else:
output[rel_file] = '\n'.join([
"Binary file:",
"size X", # TODO: get file size
"first 20 bytes: ...", # TODO: this
"last 20 bytes: ...", # TODO: do this as well
... | Remove identical lines at the beginning and end of the file
while len(lines_1) > trimmed_front and len(lines_2) > trimmed_front and lines_1[trimmed_front] == lines_2[trimmed_front]:
trimmed_front += 1
lines_1 = lines_1[trimmed_front:]
lines_2 = lines_2[trimmed_front:]
while len(lines_1) > trimmed_back and ... |
zstars/weblabdeusto | server/src/experiments/ud_demo_xilinx/server.py | Python | bsd-2-clause | 2,623 | 0.006484 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# list... |
@caller_check(ServerType.Laboratory)
@logged("info")
def do_start_experiment(self, *args, **kwargs):
"""
Handles experiment startup, returning certain initial configuration parameters.
(Thus makes use of the API version 2).
"""
super(UdDemoXilinxExperiment, self).do_... | figuration" : """{ "webcam" : "%s", "expected_programming_time" : %s }""" % (self.webcam_url, self._programmer_time), "batch" : False })
@Override(UdXilinxExperiment.UdXilinxExperiment)
@caller_check(ServerType.Laboratory)
@logged("info")
def do_dispose(self):
super(UdDemoXilinxExperiment, self... |
suprotkin/atm | atm/card/middleware.py | Python | gpl-2.0 | 751 | 0.001332 | __author__ = 'roman'
from django.utils.functional import SimpleLazyObject
from . import get_card as _get_card
def get_card(request):
if | not hasattr(request, '_cached_card'):
request._cached_card = _get_card(request)
return request._cached_card
class CardAuthMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), (
| "The Card authentication middleware requires session middleware "
"to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
"'django.contrib.sessions.middleware.SessionMiddleware' before "
"'card.middleware.CardAuthMiddleware'."
)
request.card = SimpleLazyOb... |
SimonDevon/simple-python-shapes | square1.py | Python | mit | 236 | 0 | # Step 1: Make all the "turtle" commands a | vailable to us.
import turtle
# Step 2: create a new turtle, we'll call him simon
simon = turtle.Turtle()
|
# Lets draw a square!
for loop in range(4):
simon.forward(200)
simon.left(90)
|
iTALC/documentation | build-manuals.py | Python | gpl-3.0 | 1,538 | 0.046164 | #!/usr/bin/env python3
import os
import shutil
import subprocess
import gettext
version = '4.4.0'
builds = [
{ 'language': 'de', 'paper': 'a4paper', 'babel': 'ngerman' },
{ 'language': 'en', 'paper': 'letterpaper', 'babel': 'USenglish' },
{ 'language': 'es', 'paper': 'a4paper', 'babel': 'spanish' },
{ 'language'... | util.copyfile('_build/latex/veyon.pdf', 'veyon-%s-manual-%s_%s.pdf' % ( manual, langu | age, version ))
|
zstackio/zstack-woodpecker | integrationtest/vm/multihosts/vm_snapshots/paths/xc_path8.py | Python | apache-2.0 | 1,642 | 0.017052 | import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=8, path_list=[
[TestAction.create_vm, 'vm1', 'flag=ceph'],
[TestAction.create_volume, 'volume1', 'flag=ceph,scsi'],
[TestAction.attach_volume, 'vm1... | TestAction.start_vm, 'vm1'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot5'],
[TestAction.delete_vm_snapshot, 'vm1-snapshot1'],
[TestA | ction.create_vm_snapshot, 'vm2', 'vm2-snapshot9'],
[TestAction.clone_vm, 'vm1', 'vm3', 'full'],
[TestAction.delete_volume_snapshot, 'vm1-snapshot5'],
[TestAction.stop_vm, 'vm2'],
[TestAction.change_vm_image, 'vm2'],
[TestAction.delete_vm_snapshot, 'vm2-snapshot9'],
])
'''
The final status:
Running:['vm1', ... |
MSusik/invenio | invenio/testsuite/test_apps/first/views.py | Python | gpl-2.0 | 951 | 0.01367 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your optio | n) any later version.
##
## Invenio 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 Invenio; if not, write to ... |
meissnert/StarCluster-Plugins | STAR_2_4_0g1.py | Python | mit | 1,005 | 0.018905 | from starcluster.clustersetup import ClusterSetup
from starcluster.log | ger import log
class STARInstaller(ClusterSetup):
def run(self, nodes, master, user, user_shell, volumes):
for node in nodes:
log.info("Installing STAR 2.4.0g1 on %s" % (node.alias))
node.ssh.execute('wget -c -P /opt/software/star https://github.com/alexdobin/STAR/archive/STAR_2.4.0g1.tar.gz')
node.ssh.exe... | sh.execute('mkdir -p /usr/local/Modules/applications/star/;touch /usr/local/Modules/applications/star/2.4.0g1')
node.ssh.execute('echo "#%Module" >> /usr/local/Modules/applications/star/2.4.0g1')
node.ssh.execute('echo "set root /opt/software/star/STAR-STAR_2.4.0g1" >> /usr/local/Modules/applications/star/2.4.0g1... |
t-lou/JSudokuSolver | digit_generator/digit_gen.py | Python | apache-2.0 | 4,207 | 0.013311 | #! /bin/python2
import numpy
import cv2
import os
import struct
BLACK = (0,)
WHITE = (255,)
DIR_OUT = "./img/"
SIZE_CANVAS = 50
SIZE_FEATURE = 28
SIZE_BLOCK = 32
DIGITS = tuple([chr(ord("0") + i) for i in range(10)] + [""])
FONTS = (cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN,
cv2.FONT_HERSHEY_DUPLEX, c... | 2] = 0
copy[copy >= 192] = 255
copy = copy.astype(numpy.uint8)
ff.write(copy.data)
fl.write(numpy.uint8(id_digit))
if id_img % 1000 == 0:
print id_img, num_sample
fl.close()
ff.close()
create_dataset(DIR_OUT + "printed_feature_train", DIR_OUT + "printed_labe... | _valid", DIR_OUT + "printed_label_valid", 10000)
print "test data complete" |
jbarciauskas/slack-stats | openedxstats/urls.py | Python | bsd-3-clause | 319 | 0 | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers, serializers, viewsets
from .views import HomePageView
urlpatterns = [
url(r'^$', Hom | ePageView.as_view(), name='home'),
url(r'^admin/', admin.site.url | s),
url(r'^', include('slackdata.urls')),
]
|
DemocracyClub/UK-Polling-Stations | polling_stations/apps/bug_reports/apps.py | Python | bsd-3-clause | 96 | 0 | f | rom | django.apps import AppConfig
class BugReportsConfig(AppConfig):
name = "bug_reports"
|
CLVsol/oehealth | oehealth_prescription/oehealth_patient_medication.py | Python | agpl-3.0 | 2,721 | 0.009555 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | one('oehealth.patient', string='Patient',),
#'doctor': fields.many2one('oehealth.physician', string='Physician',
# help='Physician who prescribed the medicament'),
'adverse_reacti | on': fields.text(string='Adverse Reactions',
help='Side effects or adverse reactions that the patient experienced'),
'notes': fields.text(string='Extra Info'),
'is_active': fields.boolean(string='Active',
help='Check if the pat... |
r-rathi/error-control-coding | perf/perf_plots.py | Python | mit | 11,256 | 0.002221 | import argparse
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from perf.errsim import *
def plot_x_vs_pmf(params, show=True, fpath=None):
def plot(ax, x, param, **plotargs):
if param['pb'] is None:
param['pb'] = param['pe']
label = 'BSC pe={pe} m={m} n={n}... | l' not in plotargs:
plotargs['label'] = label
ax.plot(x, pndc[x], **plotargs)
| plt.close('all')
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=plt.figaspect(1/2))
t = np.arange(11)
for param in params:
plot(ax, t, param.copy(), lw=1.5)
ax.axhline(1e-15, color='black', linestyle='dashed')
ax.set_ylim(1e-25, 1e-1)
ax.set_ylabel('$P_{ndc}(t)$')
ax.set_yscale... |
rajrakeshdr/pychess | lib/pychess/widgets/ImageMenu.py | Python | gpl-3.0 | 4,643 | 0.0112 | from __future__ import print_function
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
class ImageMenu(Gtk.EventBox):
def __init__ (self, image, child):
GObject.GObject.__init__(self)
self.add(image)
self.subwindow = Gtk.Window()... | og):
parent = image.get_parent()
parent.remove(image)
imageMenu = ImageMenu(image, dialog)
parent.add(imageMenu)
imageMenu.show()
if __name__ == "__main__":
win = Gtk.Window()
vbox = Gtk.VBox()
vbox.add(Gtk.Label(label="Her er d | er en kat"))
image = Gtk.Image.new_from_icon_name("gtk-properties", Gtk.IconSize.BUTTON)
vbox.add(image)
vbox.add(Gtk.Label(label="Her er der ikke en kat"))
win.add(vbox)
table = Gtk.Table(2, 2)
table.attach(Gtk.Label(label="Minutes:"), 0, 1, 0, 1)
spin1 = Gtk.SpinButton(Gtk.Adjustment(... |
chrisjsewell/ipypublish | ipypublish/sphinx/tests/test_bibgloss.py | Python | bsd-3-clause | 3,453 | 0.002317 | # -*- coding: utf-8 -*-
"""
test_sphinx
~~~~~~~~~~~
General Sphinx test and check output.
"""
import sys
import pytest
import sphinx
from ipypublish.sphinx.tests import get_test_source_dir
from ipypublish.tests.utils import HTML2JSONParser
@pytest.mark.sphinx(buildername="html", srcdir=get_test_source_... | x_app_output(app, buildername="html")
parser = HTML2JSONParser()
parser.feed(output)
if sphinx.version_info >= (2,):
data_regression.check(parser.parsed, basename="test_basic_v2")
else:
data_regression.check(parser.parsed, basename="test_basic_v1")
@pyt | est.mark.sphinx(buildername="html", srcdir=get_test_source_dir("bibgloss_sortkeys"))
def test_sortkeys(app, status, warning, get_sphinx_app_output, data_regression):
app.build()
assert "build succeeded" in status.getvalue() # Build succeeded
warnings = warning.getvalue().strip()
assert warnings == ""... |
labase/eica | tests/testwebfunctionaldb.py | Python | gpl-2.0 | 5,489 | 0.00293 | #! /usr/bin/env python
# -*- coding: UTF8 -*-
# Este arquivo é parte do programa Carinhas
# Copyright 2013-2014 Carlo Oliveira <carlo@nce.ufrj.br>,
# `Labase <http://labase.selfip.org/>`__; `GPL <http://is.gd/3Udt>`__.
#
# Carinhas é um software livre; você pode redistribuí-lo e/ou
# modificá-lo dentro | dos termos da Licença Pública Geral GN | U como
# publicada pela Fundação do Software Livre (FSF); na versão 2 da
# Licença.
#
# Este programa é distribuído na esperança de que possa ser útil,
# mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO
# a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a
# Licença Pública Geral GNU para maiores d... |
leogregianin/pychess | lib/pychess/Utils/lutils/perft.py | Python | gpl-3.0 | 857 | 0 |
from time import time
from pychess.Utils.lutils | .lmovegen import genAllMoves
| from pychess.Utils.lutils.lmove import toLAN
def do_perft(board, depth, root):
nodes = 0
if depth == 0:
return 1
for move in genAllMoves(board):
board.applyMove(move)
if board.opIsChecked():
board.popMove()
continue
count = do_perft(board, depth - ... |
endlisnis/weather-records | testHourly.py | Python | gpl-3.0 | 159 | 0.018868 | #!/usr/bin/python
from __future__ import print_function
import weather, time
a = time.time(); weather.hourly.load("ottawa | "); print time.time() - a
r | aw_input()
|
wkschwartz/django | tests/model_indexes/tests.py | Python | bsd-3-clause | 13,530 | 0.0017 | from unittest import mock
from django.conf import settings
from django.db import connection, models
from django.db.models.functions import Lower, Upper
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.test.utils import isolate_apps
from .models import Book, ChildModel1, ChildModel2
... | Book)
@isolate_apps('model_indexes')
def test_name_auto_generation_with_quoted_db_table(self):
class QuotedDbTable(models.Model):
name = models.CharField(max_length=50)
class Meta:
db_table = '"t_quoted"'
index = models.Index(fields=['name'])
in... | uction(self):
index = models.Index(fields=['title'], db_tablespace='idx_tbls')
index.set_name_with_model(Book)
path, args, kwargs = index.deconstruct()
self.assertEqual(path, 'django.db.models.Index')
self.assertEqual(args, ())
self.assertEqual(
kwargs,
... |
stinebuu/nest-simulator | doc/userdoc/contribute/templates_styleguides/pynest_api_template.py | Python | gpl-2.0 | 4,742 | 0.001266 | # -*- coding: utf-8 -*-
#
# pynest_api_template.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 Lic... | o/en/latest/format.html>`_ and uses
reStructuredText markup. Please review the syntax rules if you are
unfamiliar with either reStructuredText or NumPy style docstrings.
Copy this file and replace the sample text with a description of the API.
The double bracketed sections [[ ]], which provide explanations... | pse_label=None):
"""Return a `SynapseCollection` representing the connection identifiers.
[[ In a single 'summary line', state what the function does ]]
[[ All functions should have a docstring with at least a summary line ]]
[[ Below summary line (separated by new line), there should be an extended
... |
openstack/vitrage | vitrage/evaluator/template_validation/content/v2/get_param_validator.py | Python | apache-2.0 | 1,505 | 0 | # Copyright 2019 - Nokia
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | ge.evaluator.template_functions import GET_PARAM
from vitrage.evaluator.template_functions.v2.functions import get_param
from vitrage.evaluator.template_validation.base import get_custom_fault_result
from vitrage.evalu | ator.template_validation.base import ValidationError
from vitrage.evaluator.template_validation.content.base import \
get_content_correct_result
class GetParamValidator(object):
@classmethod
def validate(cls, template, actual_params):
try:
function_resolver.validate_function(
... |
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/lldp/lldpparam.py | Python | apache-2.0 | 5,812 | 0.031142 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | y :
return self._mode
except Exception as e:
raise e
@mode.setter
def mode(self, mode) :
"""Global mode of Link Layer Discovery Protocol (LLDP) on the NetScaler ADC. The resultant LLDP mode of an interface depends on the LLDP mode configured at the global and the interface levels.<br/>Possible values = NON... | RANSMITTER, RECEIVER, TRANSCEIVER
"""
try :
self._mode = mode
except Exception as e:
raise e
def _get_nitro_response(self, service, response) :
""" converts nitro response into object and returns the object array in case of get request.
"""
try :
result = service.payload_formatter.string_to_resou... |
jkaberg/GakkGakk | manage.py | Python | mit | 1,062 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from flask_script import Manager, Shell, Server
from flask_migrate import MigrateCommand
from gakkgakk.app import create_app
from gakkgakk.models import User
from gakkgakk.settings import DevConfig, ProdConfig
from gakkgakk.database import db
reload(... | ort pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return ex | it_code
manager.add_command('server', Server(host='0.0.0.0', threaded=True))
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
|
cghr/cghr-chef-repository | cookbooks/trac/files/default/plugins-stock/public_wiki_policy.py | Python | apache-2.0 | 2,244 | 0.004902 | from fnmatch import fnmatchcase
from trac.config import Option
from trac.core import *
from trac.perm import IPermissionPolicy
revision = "$Rev: 11490 $"
url = "$URL: https://svn.edgewall.org/repos/trac/tags/trac-1.0.1/sample-plugins/permissions/public_wiki_policy.py $"
class PublicWikiPolicy(Component):
"""Allo... | realm == 'wiki': # wiki realm or resource
if resource.id: # ... it's a resource
if action == 'WIKI_VIEW': # (think 'VIEW' here)
pattern = self.view
else:
pattern = self.modify
if fnmatchca | se(resource.id, pattern):
return True
else: # ... it's a realm
return True
# this policy ''may'' grant permissions on some wiki pages
else: # coarse-grained permission check
#
# support for the legacy permiss... |
SteveAbb/Vestigo | Vestigo/vestigo.py | Python | mit | 405 | 0.081481 | #!/usr/bin/env python
from settings import Settings
from scan import Scanner
from logger import Logger
def main():
try:
#Read config | file
settings=Settings()
#Set up logger
logger=Logger(settings)
#Create sc | anner
scanner=Scanner(settings,logger)
#Begin scanning
scanner.StartScanning()
except KeyboardInterrupt:
scanner.StopScanning()
if __name__ == "__main__":
main()
|
andycasey/snob | snob/nips_search.py | Python | mit | 67,954 | 0.004709 |
"""
An estimator for modelling data from a mixture of Gaussians,
using an objective function based on minimum message length.
"""
__all__ = [
"GaussianMixture",
"kullback_leibler_for_multivariate_normals",
"responsibility_matrix",
"split_component", "merge_component", "delete_component",
]
import ... | larization must be a non-negative float")
if 0 >= threshold:
raise ValueError("threshold must be a positive value")
if 1 > max_em_iterations:
raise ValueError("max_em_iterations must b | e a positive integer")
self._threshold = threshold
self._mixture_probability = mixture_probability
self._percent_scatter = percent_scatter
self._predict_mixtures = predict_mixtures
self._max_em_iterations = max_em_iterations
self._covariance_type = covariance_type
... |
AntoDev96/GuidaSky | handlers/callback.py | Python | gpl-3.0 | 1,351 | 0.005181 | from constants import constants, callback_name_list
from controller import plan_controller, navigable_list_controller, navigable_inline_keyboard_controller, settings_controller
from telepot.namedtuple import ReplyKeyboardRemove
from bot import bot
from decorators.callback import callback_dict as callback_list
"""
call... | controller.set_settings,
}
"""
def handle_callback_data(msg, action_prefix):
callback_data = msg['data']
message = msg['message']['text'] if 'text' in msg['message'] else msg['message']['caption']
chat_id = msg['message']['chat']['id']
callback_query_id = msg['id']
inline_message_id = msg['message'... | callback_list[callback](callback_query_id, callback_data, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id)
if answer == None:
action_prefix[chat_id] = " "
else:
action_prefix[chat_id] = answer
break
else:
bot.sen... |
psychopy/versions | psychopy/app/coder/codeEditorBase.py | Python | gpl-3.0 | 19,323 | 0.001139 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provides class BaseCodeEditor; base class for
CodeEditor class in Coder
and CodeBox class in dlgCode (code component)
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd.
# Distributed under the term... | Item.Enable(self.CanRedo())
cutItem.Enable(self.CanCut())
copyItem.Enable(self.CanCopy())
pasteItem.Enable(self.CanPaste())
deleteItem.Enable(self.CanCopy())
# Append items to menu
menu.Append(undoItem)
menu.Append(redoItem)
menu.AppendSeparator()
... | nu.Append(copyItem)
menu.Append(pasteItem)
menu.AppendSeparator()
menu.Append(deleteItem)
menu.Append(selectItem)
self.PopupMenu(menu)
menu.Destroy()
def onUndo(self, event):
"""For context menu Undo"""
foc = self.FindFocus()
if hasattr(foc, ... |
iZehan/spatial-pbs | examples/simplerun.py | Python | bsd-3-clause | 7,287 | 0.004117 | """
Created on 05/12/13
@author: zw606
simple example
assumes images and labels files are named the same but in different folders
(one folder for images, one folder for labels)
"""
import glob
from os.path import join, basename
from spatch.image import spatialcontext
from spatch.image.mask import get_boundary_mask
f... | one,
spatialInfoType=spatialInfoType)
prevResults = open_image(join(prevResultsPath, targetFile))
refinementMask = get_boundary_mask(prevResults, boundaryRefinementSize)
queryMaskDict = {1: refinementMask}
# erosion of labels before calculating spatial context
if preDtErosion is No... | ts
spatialInfo = spatialcontext.get_dt_spatial_context_dict(prevResults, spatialInfoType=spatialInfoType,
spatialLabels=dtLabels, labelErosion=preDtErosion,
imageData=targetImage).values()
... |
dyn888/youtube-dl | youtube_dl/extractor/iprima.py | Python | unlicense | 3,713 | 0.00216 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from random import random
from math import floor
from .common import InfoExtractor
from ..utils import (
ExtractorError,
remove_end,
sanitized_Request,
)
class IPrimaIE(InfoExtractor):
_WORKING = False
_VALID_URL = r'https... | (self._VALID_URL, url)
video_id = mobj.group('id')
webpage = self._download_webpage(url, video_id)
if re.search(r'Nemáte oprávnění přistupovat na tuto stránku\.\s*</div>', webpage):
raise ExtractorError(
'%s said: You do not have permission to access this page' % se... | player_url = (
'http://embed.livebox.cz/iprimaplay/player-embed-v2.js?__tok%s__=%s' %
(floor(random() * 1073741824), floor(random() * 1073741824))
)
req = sanitized_Request(player_url)
req.add_header('Referer', url)
playerpage = self._download_webpage(req... |
smorand/dtol | src/core/controllers.py | Python | gpl-3.0 | 4,697 | 0.031935 | # -*- coding: utf-8 -*-
#
# This file is covered by the GNU Public Licence v3 licence. See http://www.gnu.org/licenses/gpl.txt
#
'''
List of controllers, with indirections to object loaded by Spring
'''
import springpython.context
from django.http import HttpResponse
from django.template import loader, Context
from o... | context={}):
name_i = name.split('.', 2)
tpl = self
while type(tpl) == TemplatesContainer:
try:
tpl = tpl.__getattr__(name_i.pop(0))
except:
LOGGER.error('I | nternal error: Template %s is missing' % (name))
raise Exception('Internal error: Template %s is missing' % (name))
return tpl.render(Context(context))
def content(self, content):
return HttpResponse(content=content, mimetype="text/html", status=200)
def response(self, name, context={}, status=200, mi... |
lantianlz/qiexing | www/sight/urls.py | Python | gpl-2.0 | 287 | 0 | # -*- coding: utf-8 -*-
from dj | ango.conf.urls import patterns, url
# from django.conf import settings
urlpatterns = patterns('www.sight.views',
url(r'^$', 'sight_map'),
| url(r'^(?P<sight_id>\d+)$', 'sight_detail'),
)
|
lino-framework/book | lino_book/projects/anna/lib/tickets/models.py | Python | bsd-2-clause | 1,862 | 0.001611 | # -*- coding: UTF-8 -*-
# Copyright 2016-2017 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
from lino_xl.lib.tickets.models import *
from lino.api import _
Ticket.hide_elements('closed')
# class Ticket(Ticket):
# class Meta(Ticket.Meta):
# app_label = 'tickets'
# verbose_name = _(... | al1 = """
summary:40 id:6 deadline
user:12 end_user:12 #faculty #topic
site workflow_buttons
"""
history_tab = dd.Panel("""
changes.ChangesByMaster:50 #stars.StarsByController:20
""", label=_("History"), required_roles=dd.login_required(Triager))
more = dd.Panel("""
more1:60 #skill... | pgrade_notes LinksByTicket skills.OffersByDemander
""", label=_("More"), required_roles=dd.login_required(Triager))
more1 = """
created modified ticket_type:10
state priority project
# standby feedback closed
"""
Tickets.detail_layout = TicketDetail()
|
Yagniksuchak/CodeParser | src/logChunk/dictUtil.py | Python | bsd-3-clause | 602 | 0.031561 | #Key, dictionary[key, int], int --> dictionary[key, int]
#Given a key, d | ictionary and increment, set the dictionary value at
#key to dictionary[key] + inc. If there is no old value, set to inc
def incrementDict(dictKey, dictionary, inc=1):
if(dictKey in dictionary):
dic | tionary[dictKey] += inc
else:
dictionary[dictKey] = inc
return dictionary
#dictionary[key, int] -> boolean
#Given a dictionary of counts return true if at least one is non zero
#and false otherwise
def nonZeroCount(dictionary):
for k,v in dictionary.iteritems():
assert(v >= 0)
if(v > 0):
return True
ret... |
brython-dev/brython | www/src/Lib/test/test_uu.py | Python | bsd-3-clause | 8,294 | 0.000844 | """
Tests for uu module.
Nick Mathewson
"""
import unittest
from test.support import os_helper
import os
import stat
import sys
import uu
import io
plaintext = b"The symbols on top of your keyboard are !@#$%^&*()_+|~\n"
encodedtext = b"""\
M5&AE('-Y;6)O;',@;VX@=&]P(&]F('EO=7(@:V5Y8F]A<F0@87)E("% (R0E
*7B8J*"E?*WQ^"... | lf.tmpin))
# in_file and out_file as filenames
uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644)
with open(self.tmpout, 'rb') as fout:
s = fout.read()
self.assertEqual(s, | encodedtextwrapped(0o644, self.tmpin))
def test_decode(self):
with open(self.tmpin, 'wb') as f:
f.write(encodedtextwrapped(0o644, self.tmpout))
with open(self.tmpin, 'rb') as f:
uu.decode(f)
with open(self.tmpout, 'rb') as f:
s = f.read()
self.... |
rwightman/pytorch-image-models | timm/models/layers/create_attn.py | Python | apache-2.0 | 3,526 | 0.002269 | """ Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Gl... | # Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network arc | hitecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ec... |
denever/discipline_terra | cover/urls.py | Python | gpl-2.0 | 198 | 0.005051 | from django.conf.urls import patte | rns, include, url
from cover.views import Cov | erView
urlpatterns = patterns('cover.views',
url(r'^$', CoverView.as_view(), name='cover'),
)
|
mitsei/dlkit | dlkit/abstract_osid/commenting/searches.py | Python | mit | 8,401 | 0.001309 | """Implementations of commenting abstract base class searches."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and inclu... | rty(fget=get_comment_query_inspector)
@abc.abstractmethod
def | get_comment_search_results_record(self, comment_search_record_type):
"""Gets the comment search results record corresponding to the given comment search record ``Type``.
This method is used to retrieve an object implementing the
requested record.
:param comment_search_record_type: a c... |
sanacl/GrimoireELK | grimoire/elk/github.py | Python | gpl-3.0 | 12,563 | 0.002468 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Github to Elastic class helper
#
# Copyright (C) 2015 Bitergia
#
# 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 3 of the License, o... | 'name']
return identity
def get_geo_point(self, location):
geo_point = geo_code = None
if location is None:
return geo_point
if location in self.geolocations:
geo_location = self.geolocations[location]
geo | _point = {
"lat": geo_location['lat'],
"lon": geo_location['lon']
}
elif location in self.location_not_found:
# Don't call the API.
pass
else:
url = 'https://maps.googleapis.com/maps/api/geocode/json'
p... |
datamade/yournextmp-popit | candidates/management/commands/candidates_parties_with_multiple_emblems.py | Python | agpl-3.0 | 834 | 0 | from django.core.management.base import BaseCommand
from candidates.models import OrganizationExtra
class Command(BaseCommand): |
def handle(self, *args, **options):
for party_extra in OrganizationExtra.objects \
.filter(base__classification='Party') \
.select_related('base') \
.prefetch_related('images'):
images = list(party_extra.images.all())
if len(images) ... | (images), party_extra.slug, party.name.encode('utf-8')
for image in images:
print ' --'
print ' ' + image.source.encode('utf-8')
print ' ' + image.image.url
|
lrq3000/pyFileFixity | pyFileFixity/lib/gooey/gui/windows/runtime_display_panel.py | Python | mit | 1,831 | 0.009285 | '''
Created on Dec 23, 2013
@author: Chris
'''
import sys
import wx
from gooey.gui.lang import i18n
from gooey.gui.message_event import EVT_MSG
class MessagePump(object):
def __init__(self):
# self.queue = queue
self.stdout = sys.stdout
# Overrides stdout's write method
def write(self, text):
... | | wx.BOTTOM | wx.EXPAND, 30)
sizer.AddSpacer(20)
self.SetSizer(sizer)
self.Bind(EVT_MSG, self.OnMsg)
def _HookStdout(self):
_stdout = sys.stdout
_stdout_write = _stdout.write
sys.stdout = MessagePump()
sys.stdout.write = self.WriteToDisplayBox
def AppendText(self, txt):
self.cmd_... | (self, evt):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.