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 |
|---|---|---|---|---|---|---|---|---|
crisely09/horton | horton/meanfield/occ.py | Python | gpl-3.0 | 8,958 | 0.001786 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | Density matrices to be tested.
**Optional keyword argument | s:**
eps (default=1e-4)
The allowed deviation.
'''
raise NotImplementedError
class FixedOccModel(OccModel):
def __init__(self, *occ_arrays):
self.occ_arrays = occ_arrays
@doc_inherit(OccModel)
def assign(self, *exps):
if len(exps) != len(self.oc... |
hobinyoon/apache-cassandra-2.2.3-src | mtdb/process-log/calc-latency-multiple-runs/Latency.py | Python | apache-2.0 | 6,312 | 0.029943 | import os
import sys
sys.path.insert(0, "../../util/python")
import Cons
import Conf
def Load():
_LoadLogs()
sys.exit(0)
_WritePlotData()
_cass = None
_mutants = None
class LogEntry(object):
# simulation_time_dur_ms simulated_time OpW_per_sec running_behind_cnt read_latency_ms read_cnt
# ... | = e.write_latency_ms
r_min = e.read_latency_ms
r_max = e.read_latency_ms
first = False
else:
w_min = min(w_min, e.write_latency_ms)
w_max = max(w_max, e.write_latency_ms)
r | _min = min(r_min, e.read_latency_ms)
r_max = max(r_max, e.read_latency_ms)
time_intervals.append(e.simulation_time_dur_ms - time_prev)
w_sum += e.write_latency_ms
r_sum += e.read_latency_ms
time_prev = e.simulation_time_dur_ms
self.w_avg = float(w_sum) / len(self.entries)
self.r_avg = float(r_sum) ... |
disenone/zsync | test/parallel_task/ventilator.py | Python | mit | 694 | 0.005764 | # -*- coding: utf-8 -*-
import zmq
import random
import time
def run():
context = zmq.Context()
sender = context.socket(zmq.PUSH)
sender.bind('tcp://*:5557')
sink = context.socket(zmq | .PUSH)
sink.connect('tcp://localhost:5558')
print 'Press Enter when the workers are ready: '
_ = raw_input()
print('sending tasks to workders...')
sink.send(b'0')
random.seed()
total_msec = 0
for task_nbr in xrange(100):
workload = random.randint(1, 100)
total_msec +=... | __ == '__main__':
run() |
beeftornado/sentry | tests/snuba/api/endpoints/test_discover_saved_queries.py | Python | bsd-3-clause | 18,996 | 0.001263 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.discover.models import DiscoverSavedQuery
from sentry.testutils import APITestCase, SnubaTestCase
from sentry.testutils.helpers.datetime import before_now
class DiscoverSavedQueryBase(APITestCase, SnubaTestCase):
def... | onse = self.client.get(self.url, format="json", data={"query": "Test"})
assert response.status_code == 200, response.content
assert len(re | sponse.data) == 1
assert response.data[0]["name"] == "Test query"
with self.feature(self.feature_name):
# Also available as the name: filter.
response = self.client.get(self.url, format="json", data={"query": "name:Test"})
assert response.status_code == 200, response.co... |
KirillTim/crashsimilarity | crashsimilarity/cli/signatures_similarity.py | Python | mpl-2.0 | 1,820 | 0.002747 | import pprint
from crashsimilarity.downloader import SocorroDownloader
import argparse
import sys
from crashsimilarity.models.gensim_model_wrapper import Doc2vecModelWrapper
from crashsimilarity.models.similarity.doc2vec_similarity import Doc2VecSimilarity
from crashsimilarity.models.wmd_calcula | tor impo | rt WMDCalculator
from crashsimilarity.utils import StackTracesGetter
def parse_args(args):
parser = argparse.ArgumentParser(description='Test similarities between two signatures')
parser.add_argument('-1', '--one', required=True, help='First signature')
parser.add_argument('-2', '--two', required=True, he... |
irisdianauy/bioscripts | gbk_to_bed.py | Python | gpl-2.0 | 1,705 | 0 | #! /usr/bin/env python
"""
author @irisdianauy
The script converts a multi-genbank file into
a single bed file.
Feature: Specify features to extract (allows all).
"""
import pandas as pd
from os import path
from sys import argv, exit
from Bio import SeqIO
def get_id(ofeat):
sid = (ofeat.qualifiers.get("db_xr... | gb = SeqIO.parse(pgb, "genbank")
# Get all CDSs + info
lcds_all = get_all_cds(ogb, lfeats)
# Write locations in BED format
write_bed(lcds_all)
# """
if __name__ == "__main__":
try:
| pgb = path.abspath(argv[1])
pbed = path.abspath(argv[2])
lfeats = argv[3:]
except IndexError:
ppy = path.basename(path.abspath(__file__))
shelp = f"Usage:\n{ppy} <input.gbk> <output.bed> <type1 type2 typen>"
print(shelp)
exit()
main(pgb, pbed, lfeats)
# """
|
dimV36/webtests | webtests/auth.py | Python | gpl-2.0 | 486 | 0 | # coding=utf-8
__author__ = 'dimv | 36'
from flask_login import AnonymousUserMixin, LoginManager
from webtests.models import User
# Модуль инициализации менеджера входа пользователей
login_manager = LoginManager()
class AnonymousUser(AnonymousUserMixin):
id = None
login_manager.anonymous_user = Anonymou | sUser
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
|
Fjobbe/xbmc-swefilmer | navigation.py | Python | gpl-3.0 | 9,678 | 0.000723 | # -*- coding: utf-8 -*-
from mocks import Xbmc, Xbmcplugin, Xbmcgui, Xbmcaddon
import swefilmer
import sys
import urllib
ACTION_NEW = 'new'
ACTION_TOP = 'top'
ACTION_FAVORITES = 'favorites'
ACTION_CATEGORIES = 'categories'
ACTION_CATEGORY = 'category'
ACTION_SEARCH = 'search'
ACTION_VIDEO = 'video'
ACTION_NEXT_PAGE = ... | nswer][1]
return url
def add_menu_item(self, caption, action, total_items, logged_in, url=None):
li = self.xbmcgui.ListItem(caption)
infoLabels = {'Title': caption}
li.setInfo(type='Video', infoLabels=infoLabels)
params = {'action': action, 'logged_in': logged_in}
if... | ctoryItem(handle=self.handle, url=item_url,
listitem=li, isFolder=True,
totalItems=total_items)
def add_video_item(self, caption, url, image, action, total_items, logged_in):
li = self.xbmcgui.ListItem(caption)
li.set... |
aitgon/wopmars | wopmars/tests/resource/model/FooBaseH2.py | Python | mit | 192 | 0 | from | sqlalchemy | import Column, String
from FooBaseH import FooBaseH
class FooBaseH2(FooBaseH):
name2 = Column(String)
__mapper_args__ = {
'polymorphic_identity': "2"
}
|
Scalr/packages | pkgs/six/setup.py | Python | apache-2.0 | 274 | 0.00365 | import setuptools
version = '1.8.0'
setuptools.setup(
name='six',
version=version,
url='https://pypi.python.org/packages/source/s/six/six-%s | .tar.gz' % version,
license='MIT License',
author='Benjamin Peterson',
author_email='[email protected] | g'
)
|
dufferzafar/mitmproxy | mitmproxy/contrib/tnetstring.py | Python | mit | 8,799 | 0.000909 | """
tnetstring: data serialization using typed netstrings
======================================================
This is a custom Python 3 implementation of tnetstrings.
Compared to other implementations, the main difference
is that this implementation supports a custom unicode datatype.
An ordinary tnetstring is a ... | aise ValueError("not a tnetstring: invalid float literal: {}".format(data))
if data_type == ord(b'!'):
if data == b'true':
return True
elif data == b'false':
return False
else:
raise ValueError("not a tnetstring: invalid boolean literal: {}".format(data))
... | iteral")
return None
if data_type == ord(b']'):
l = []
while data:
item, data = pop(data)
l.append(item)
return l
if data_type == ord(b'}'):
d = {}
while data:
key, data = pop(data)
val, data = pop(data)
... |
eroicaleo/LearningPython | interview/leet/011_Container_With_Most_Water.py | Python | mit | 845 | 0.027219 | #!/usr/bin/env python
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i, j = 0, len(height)-1
l, r = height[i], height[j]
maxArea = (j - i) * min(l, r)
| while j > i:
if l < r:
while height[i] <= l:
i += 1
elif r < l:
while hei | ght[j] <= r:
j -= 1
else:
i, j = i+1, j-1
l, r = height[i], height[j]
print(i, j, l, r)
area = (j - i) * min(l, r)
if area > maxArea:
maxArea = area
return maxArea
sol = Solution()
height_list = [
[1... |
kaeawc/django-auth-example | test/controllers/info/test_authors.py | Python | mit | 425 | 0 | # -*- coding: utf-8 -*
from test import DjangoTestCase
class AuthorsSpec(DjangoTestCase):
def test_success(self):
"""
Anyone should be able | to view the authors page
"""
response = self.http_get(u"/authors")
assert response is not None
assert response.ok is True, response
assert response.controller == u"authors", response
| assert response.duration < 10
|
zaibacu/wutu | wutu/bench/compiler_bench.py | Python | mit | 535 | 0.001869 | from wutu.compiler.common import create_stream
from wutu.compiler.service import create_service_js
from wutu.compiler.controller import c | reate_controller_js
from wutu.util import *
def handle_creation(module, stream):
create_service_js(stream, module)
create_controller_js(stream, module)
def main():
mod = Module()
mod.__name__ = "test_module"
stream = create_stream()
fo | r i in range(0, 1000):
handle_creation(mod, stream)
if __name__ == "__main__":
import cProfile
cProfile.run("main()")
|
japaniel/CloudFerry | cloudferrylib/os/actions/deploy_snapshots.py | Python | apache-2.0 | 4,490 | 0 | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | ap) == 0:
act_snap_transfer = \
snap_transfer.SnapTransfer(
self.init,
ssh_ceph_to_ceph.SSHCephToCeph,
1)
else:
snap_num = snaps... | act_snap_transfer = \
snap_transfer.SnapTransfer(
self.init,
ssh_ceph_to_ceph.SSHCephToCeph,
2)
act_snap_transfer.run(volume=vol_info, snapshot_info=snap)
... |
mbiciunas/libnix | src/libnix/config/script/run_script.py | Python | gpl-3.0 | 1,491 | 0 | """
LibNix
Copyright (C) 2017 Mark Biciunas
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, or
(at your option) any later version.
This program is distributed in th... | received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from libnix.config.config import Config
class RunScript:
def __init__(self):
self._config = Config()
def run(self, name: str):
_script = self._config.get_scripts().fin... |
# print("Syntax Error: {}".format(e))
print("Syntax Error - filename: {}".format(e.filename))
print("Syntax Error - line: {}".format(e.lineno))
print("Syntax Error - msg: {}".format(e.msg))
print("Syntax Error - offset: {}".format(e.offset))
print... |
RaitoBezarius/mangaki | mangaki/mangaki/management/commands/lookup.py | Python | agpl-3.0 | 616 | 0.001623 | from django.core.management.base import BaseCommand, CommandError
from mangaki.models import Work, Rating
from django.db import connection
from django.db.models import Count
from collecti | ons import Counter
import sys
class Command(BaseCommand):
args = ''
help = 'Lookup some work'
def handle(self, *args, **options):
work = Work.objects.filter(title__icontains=args[0]).annotate(Count('rating')).order_by('-rating__count')[0]
print(work.title, work.id)
nb = Counter()
... | for rating in Rating.objects.filter(work=work):
nb[rating.choice] += 1
print(nb)
|
vpadillar/pventa | pventa/wsgi.py | Python | mit | 389 | 0 | """
WSGI config for pventa project.
It exposes the WSGI callable as a module-level variable named ``application``.
For | more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET | TINGS_MODULE", "pventa.settings")
application = get_wsgi_application()
|
jawilson/home-assistant | tests/components/tasmota/test_binary_sensor.py | Python | apache-2.0 | 13,393 | 0.000971 | """The tests for the Tasmota binary sensor platform."""
import copy
from datetime import timedelta
import json
from unittest.mock import patch
from hatasmota.utils import (
get_topic_stat_result,
get_topic_stat_status,
get_topic_tele_sensor,
get_topic_tele_will,
)
from homeassistant.components import ... | te via MQTT."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["swc"][0] = 1
config["swn"][0] = "Custom Name"
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
state = has... | attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online")
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.custom_name")
assert state.state == STATE_OFF
assert not state.attributes.get(ATTR_ASSUMED_STATE)
# Test normal state ... |
tobetter/linaro-image-tools_packaging | linaro_image_tools/testing.py | Python | gpl-3.0 | 2,121 | 0 | # Copyright (C) 2010, 2011 Linaro
#
# Author: James Westby <[email protected]>
#
# This file is part of Linaro Image Tools.
#
# Linaro Image Tools 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 v... | the fixture to use.
:type fixture: an object with setUp and tearDown methods.
:return: the fixture that was passed in.
"""
self.addCleanup(fixture.tearDown | )
fixture.setUp()
return fixture
def createTempFileAsFixture(self, prefix='tmp', dir=None):
"""Create a temp file and make sure it is removed on tearDown.
:return: The filename of the file created.
"""
_, filename = tempfile.mkstemp(prefix=prefix, dir=dir)
s... |
jeffery-do/Vizdoombot | doom/lib/python3.5/site-packages/dask/tests/test_async.py | Python | mit | 6,053 | 0.00033 | from __future__ import absolute_import, division, print_function
import dask
from dask.async import (start_state_from_dask, get_sync, finish_task, sortkey,
remote_exception)
from dask.order import order
from dask.utils_test import GetFunctionTestMixin, inc, add
fib_dask = {'f0': 0, 'f1': 1, ... | assert key == 'a' or key is None
assert d == dsk
assert isinstance(state, dict)
|
def end_callback(key, value, d, state, worker_id):
assert key == 'a' or key is None
assert value == 2 or value is None
assert d == dsk
assert isinstance(state, dict)
get(dsk, 'a', start_callback=start_callback, end_callback=end_callback)
def test_order_of_startstate():
ds... |
JustinTulloss/harmonize.fm | uploader/publish_win.py | Python | mit | 800 | 0.025 | import os, sys
import config
def notify_user(msg):
sys.stderr.write(msg+'\n')
raw_input('Press enter to exit ')
sys | .exit(1)
def run_cmd(cmd):
if os.system(cmd) != 0:
notify_user('Command "%s" failed!'%cmd)
def run_cmds(*cmds):
for cmd in cmds:
run_cmd(cmd)
if config.current != config.production:
notify_user('Change current configuration to production before running')
logo_dir = r'..\sandbox\logos\icons'
... | 48.png' % (logo_dir, logo_dir, logo_dir),
'python setup.py py2exe',
r'"C:\Program Files\Inno Setup 5\iscc" windows_installer.iss',
'pscp "Output\Harmonizer Setup.exe" harmonize.fm:/var/opt/uploaders')
raw_input('Publish completed successfully')
|
rkmaddox/mne-python | mne/io/meas_info.py | Python | bsd-3-clause | 97,239 | 0 | # -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <[email protected]>
# Matti Hämäläinen <[email protected]>
# Teon Brooks <[email protected]>
# Stefan Appelhoff <[email protected]>
#
# License: BSD (3-clause)
from collections import Counter, OrderedDict
im... | Hz', 'N', 'Pa', 'J', 'W', 'C', 'V', 'F', u'Ω', 'S',
'Wb', 'T', 'H', u'°C', 'lm', 'lx', 'Bq', 'Gy', 'Sv',
'kat']
# Valid units are all possible combinations of either prefix name or prefix
# symbol together with either unit name or unit symbol. E.g., nV for
... | ts = []
valid_units += ([''.join([prefix, unit]) for prefix in valid_prefix_names
for unit in valid_unit_names])
valid_units += ([''.join([prefix, unit]) for prefix in valid_prefix_names
for unit in valid_unit_symbols])
valid_units += ([''.join([prefix, unit]) for p... |
Wasper256/evo-departments | extentions.py | Python | gpl-3.0 | 103 | 0 | """Initialazation "db" sqlalchemy object."""
from flask_sqlalche | my import SQLAlchemy
db = SQLAl | chemy()
|
brburns/netdisco | setup.py | Python | apache-2.0 | 513 | 0 | from setuptools import setup, find_packages
setup(name='netdisco',
version='0.9.2',
description='Discover devices on your local network',
url='https://github.com/home-assistant/netdisco',
author='Paulus Schout | sen',
author_email='[email protected]',
license='Apache License 2.0',
install_requires=['ne | tifaces>=0.10.0', 'requests>=2.0',
'zeroconf==0.17.6'],
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False)
|
violine1101/MCEdit-Unified | albow/tree.py | Python | isc | 20,371 | 0.004124 | # -*- coding: utf-8 -*-
#
# tree.py
#
# (c) D.C.-G. 2014
#
# Tree widget for albow
#
from albow.widget import Widget
from albow.menu import Menu
from albow.fields import IntField, FloatField, TextFieldWrapped
from albow.controls import CheckBox, AttrRef, Label, Button
from albow.dialogs import ask, alert, input_text_bu... | ponses)
col = Column([title, self.w_type, Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=ok_action or self.dismiss)], margin=0)], margin=0, spacing=2)
Dialog.__init__(self, client=col)
def dismiss_ok(self):
self.dismiss(self.w_type.selectedChoice)
#-------... | :
if len(types) > 1:
choices = types.keys()
choices.sort()
result = SelectItemTypePanel("Choose item type", responses=choices, default=None).present()
else:
result = types.keys()[0]
if type(result) in (str, unicode):
return SetupNewItemPanel(result, types, ok_action).... |
sileht/gnocchi | gnocchi/cli/manage.py | Python | apache-2.0 | 3,776 | 0 | # Copyright (c) 2013 Mirantis Inc.
# | Copyright (c) 2015-2017 Red Hat
#
# 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... | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import os
import sys
import daiquiri
from oslo_config import cfg
from oslo_config import generator
import six
from gnocchi import archive_policy
from gnocchi import incoming
from gnocchi import... |
ozamiatin/oslo.messaging | oslo_messaging/tests/functional/test_functional.py | Python | apache-2.0 | 13,879 | 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
# ... | utils.RpcServerGroupFixture(self.conf, self.url,
use_fanout_ctrl=True))
group2 = self.useFixture(
utils.RpcServerGroupFixture(self.conf, self.url, exchange="a",
use_fanout_ctrl=True))
group3 = self.useFixture... | up1.client(1)
data1 = [c for c in 'abcdefghijklmn']
for i in data1:
client1.append(text=i)
client2 = group2.client()
data2 = [c for c in 'opqrstuvwxyz']
for i in data2:
client2.append(text=i)
actual1 = [[c for c in s.endpoint.sval] for s in group... |
clarammdantas/Online-Jugde-Problems | online_judge_solutions/python.py | Python | mit | 531 | 0.037665 | klein = raw_input()
gross = raw_input()
zahl = []
if gross[0] == '0':
zahl.append((1,0))
else:
zahl.append((0,1))
for i in range(1,len(gross)):
if gross[i] == '0':
zahl.append((zahl[i - 1][0] + 1, zahl[i - 1][1]))
else:
zahl.append((zahl[i - 1][0], zahl[i - 1][1] + 1))
plus = 0
for i in range(l | en(klein)):
if klein[i] == | '0':
plus += zahl[len(gross) - len(klein) + i][1]
if i > 0:
plus -= zahl[i - 1][1]
else:
plus += zahl[len(gross) - len(klein) + i][0]
if i > 0:
plus -= zahl[i - 1][0]
print plus
|
TheTimeTunnel/scout-camp | PROJECT/src/scoutcamp/database.py | Python | gpl-3.0 | 7,206 | 0.005291 | # -*- encoding: utf-8 -*-
import yaml
import sys
import os
import json
import sqlite3
from .exceptions import *
class DataList(object):
__data_list = None
def __init__(self, _path="", _list_file=""):
self.__data_list = list()
self.path = _path
self.listfile = _list_file
s... | ce('.'+self.extension, ''))
# Atribui à nova lista somente a primeira posição da list
self.__data_list = list_
def get_data_list(self):
"""Método público get_data_list
- Retorna a lista dos templates disponíveis.
| Argumentos:
- self (object): instância da própria classe
Retorno:
- self.__data_list (list): lista de templates
"""
return self.__data_list
class DataBase(object):
__id = None
__attributes = None
__relations = None
def __init__(s... |
ichi23de5/ichi_Repo | sale_order_line_edit/__openerp__.py | Python | gpl-3.0 | 342 | 0.04386 | # -*- coding: utf-8 -*-
{
"name": "Sale Order Line Edit",
"summary": "Edit Sale Order For | m",
"version": "9.0.0.1.1",
"category": "Sales",
"website": "http://www.toyo-kiki.co.jp",
"author": "ichi",
"license": "AGPL-3",
"application": Fal | se,
"installable": True,
"depends": [
"sale",
],
"data": [
"views/sale_view.xml",
],
}
|
mailund/CoaSim | Python/customMarkerTest.py | Python | gpl-2.0 | 2,572 | 0.018663 | #!/bin/env python
from CoaSim import *
cm = CustomMarker(0.1)
assert cm.position == 0.1
class MyMarker(CustomMarker):
def __init__(self,pos):
CustomMarker.__init__(self,pos)
def defaultValue(self):
return 1
def mutate(self, parentAllele, edgeLength):
return parentAllele+1
mm = My... | simulate([Uninitialized()],2)
assert False
except ValueError, e:
assert str(e) == 'arg #1 contains an un-initialized marker'
class Uninitialized(CustomMarker):
def __init__(self): pass
try:
simulate([Uninitialized()],2)
assert False
except ValueError, e:
assert str(e) == 'arg #1 contains an un-... | late([MissingDefaultValue()],2)
assert False
except AttributeError, e:
assert str(e) == 'defaultValue'
class IncorrectDefaultValue(CustomMarker):
def __init__(self):
CustomMarker.__init__(self,0.2)
def defaultValue(self, x):
return 3
try:
simulate([IncorrectDefaultValue()],2)
as... |
ChinaMassClouds/copenstack-server | openstack/src/nova-2014.2/nova/api/openstack/compute/plugins/v3/block_device_mapping_v1.py | Python | gpl-2.0 | 2,738 | 0 | # Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | License.
"""The legacy block device mappings extension."""
from webob import exc
from nova.api.openstack import e | xtensions
from nova import block_device
from nova import exception
from nova.i18n import _
from nova.openstack.common import strutils
ALIAS = "os-block-device-mapping-v1"
ATTRIBUTE_NAME = "block_device_mapping"
ATTRIBUTE_NAME_V2 = "block_device_mapping_v2"
class BlockDeviceMappingV1(extensions.V3APIExtensionBase):
... |
lorensen/VTKExamples | src/Python/Visualization/ViewFrog.py | Python | apache-2.0 | 5,808 | 0.001722 | #!/usr/bin/env python
"""
"""
import vtk
def view_frog(fileName, tissues):
colors = vtk.vtkNamedColors()
tissueMap = CreateTissueMap()
colorLut = CreateFrogLut()
# Setup render window, renderer, and interactor.
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWind... | eractor.Start()
def main():
fileName, tissues = get_program_parameters()
view_frog(fileName, tissues)
def get_program_parameters():
import argparse
description = 'The complete frog without skin.'
epilogue = '''
For Figure 12-9b in the VTK Book:
Specify these tissues as parameters after th... | parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('filename', help='frogtissue.mhd.')
parser.add_argument('tissues', nargs='+', help='List of one or more tissues.')
ar... |
nwjs/chromium.src | build/android/pylib/local/device/local_device_gtest_run_test.py | Python | bsd-3-clause | 2,907 | 0.005504 | #!/usr/bin/env vpython3
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for local_device_gtest_test_run."""
# pylint: disable=protected-access
import os
import tempfile
import unittest
from pyl... | .check_output')
def testMergeCoverageFiles(self, mock_sub):
with tempfile_ext.NamedTemporaryDirectory() as cov_tempd:
pro_tempd = os.path.join(cov_tempd, 'profraw')
os.mkdir(pro_tempd)
profdata = tempfile.NamedTemporaryFile(
dir=p | ro_tempd,
delete=False,
suffix=local_device_gtest_run._PROFRAW_FILE_EXTENSION)
local_device_gtest_run._MergeCoverageFiles(cov_tempd, pro_tempd)
# Merged file should be deleted.
self.assertFalse(os.path.exists(profdata.name))
self.assertTrue(mock_sub.called)
@mock.patch('py... |
ThreatConnect-Inc/tcex | tcex/api/tc/v2/threat_intelligence/mappings/group/group_types/campaign.py | Python | apache-2.0 | 1,625 | 0.004308 | """ThreatConnect TI Campaign"""
# standard | library
from typing import TYPE_CHECKING
# first-party
from tcex.api.tc.v2.threat_intelligence.mappings.group.group import Group
if TYPE_CHECKING:
# first-party
from tcex.api.tc.v2.threat_intelligence | .threat_intelligence import ThreatIntelligence
class Campaign(Group):
"""Unique API calls for Campaign API Endpoints
Args:
ti (ThreatIntelligence): An instance of the ThreatIntelligence Class.
name (str, kwargs): [Required for Create] The name for this Group.
owner (str, kwargs): The ... |
estnltk/suffix-lemmatizer | bootstrap.py | Python | gpl-2.0 | 7,459 | 0.00067 | ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if ... | ####
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', option... |
reyiyo/eventoL | eventol/manager/models.py | Python | gpl-3.0 | 40,847 | 0.001689 | # pylint: disable=arguments-differ
# pylint: disable=too-many-lines
import datetime
import itertools
import json
import logging
import re
from uuid import uuid4
from random import SystemRandom
from string import digits, ascii_lowercase, ascii_uppercase
from ckeditor.fields import RichTextField
from django.contrib im... | append({
'organizers': ','.join(full_names),
'email': event.email,
'id': event.id
})
return events
class EventTag(models.Model):
"""A Event grouper"""
name = models.CharField(_('EventTag Name'), max_length=50, unique=True,
... | .DateTimeField(_('Updated At'), auto_now=True)
background = models.ImageField(
null=True, blank=True,
help_text=_("A image to show in the background of"))
logo_header = models.ImageField(
null=True, blank=True,
help_text=_("This logo will be shown in the right corner of the page"... |
mitsuhiko/sentry | src/sentry/web/frontend/error_page_embed.py | Python | bsd-3-clause | 5,673 | 0.001234 | from __future__ import absolute_import
from django import forms
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.safestring import mark_saf... | name': request.GET.get('name'),
'email': request.GET.get('email'),
}
form = UserReportForm(request.POST if request.method == 'POST' else None,
initial=initial)
if form.is_valid():
| # TODO(dcramer): move this to post to the internal API
report = form.save(commit=False)
report.project = key.project
report.event_id = event_id
try:
mapping = EventMapping.objects.get(
event_id=report.event_id,
proje... |
srcc-msu/job_statistics | modules/job_analyzer/controllers.py | Python | mit | 1,969 | 0.028441 | from functools import partial
import time
from typing import List
from flask import Blueprint, Response, render_template, current_app, request
from core.job.helpers import expand_nodelist
from core.job.models import Job
from application.helpers import requires_auth
from core.monitoring.models import SENSOR_CLASS_MAP
... | , get_color=parti | al(get_color, thresholds=current_app.app_config.monitoring["thresholds"]))
|
srinivasanmit/all-in-all | puzzles/isprime.py | Python | gpl-3.0 | 548 | 0.018248 | '''
Check for primality for both decimal inputs and binary inputs
'''
lst = [2, 4, 6, 7, 9, 13, 17, 99, 127, 139]
print lst
prime = []
def is_composite(n) :
for i in range(2, n/2 + 1) :
if n % i == 0 :
return True
return False
for n in lst :
if is_composite(n) | :
continue
else :
prime.append(n)
print prime
print "Enter number to check for Primality : "
no = raw_input()
if not is_composite(int(no, 2)):
print "Entered number is prime"
else | :
print "Entered number is composite"
|
SurfasJones/djcmsrc3 | venv/lib/python2.7/site-packages/cms/tests/extensions.py | Python | mit | 13,596 | 0.003898 | from django.contrib.auth.models import Permission
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from cms.api import create_page
from cms.constants import PUBLISHER_STATE_DIRTY
from cms.models import Page
from cms.test_utils.project.extensionapp.models import MyPageExtension,... | delete_mypageextension', 'delete_mytitleextension',
]
)]
self.site = Site.objects.get(pk=1)
self.page = create_page(
'My Extension Page', 'nav_playground.html', 'en',
| site=self.site, created_by=self.admin)
self.page_title = self.page.get_title_obj()
self.page_extension = MyPageExtension.objects.create(
extended_object=self.page,
extra="page extension text")
self.title_extension = MyTitleExtension.objects.create(
... |
sebastianlach/zerows | zerows/__init__.py | Python | mit | 2,638 | 0.002658 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
usage: zerows [-h]
"""
__author__ = "Sebastian Łach"
__copyright__ = "Copyright 2015, Sebastian Łach"
__credits__ = ["Sebastian Łach", ]
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "Sebastian Łach"
__email__ = "[email protected]"
from json import loads
fro... | e
class ZeroMQHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
super(ZeroMQHandler, self).__init__(*args, **kwargs)
self.socket = None
self.stream = None
def open(self):
settings = self.application.settings
self.socket = settings['zero... | eromq']['url'])
self.stream = ZMQStream(self.socket, settings['ioloop'])
self.stream.on_recv(self.on_dispatch)
def on_message(self, message):
request = load_message(message)
if request:
data = message.encode('utf8')
self.stream.send(data)
else:
... |
IS-ENES-Data/esgf-pid | tests/testcases/rabbit/asyn/rabbit_asynchronous_tests.py | Python | apache-2.0 | 18,090 | 0.006578 | import unittest
import mock
import logging
import datetime
import time
import esgfpid.ra | bbit.asynch | ronous
from esgfpid.rabbit.asynchronous.exceptions import OperationNotAllowed
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(logging.NullHandler())
# Test resources:
from resources.TESTVALUES import *
import resources.TESTVALUES as TESTHELPERS
import globalvar
if globalvar.QUICK_ONLY:
print('Skipping slo... |
barche/k3d | share/k3d/scripts/MeshSourceScript/cubes.py | Python | gpl-2.0 | 771 | 0.001297 | #python
import k3d
k3d.check_node_environment(context, "MeshSourceScript")
# Construct a cube mesh primitive ...
cubes = context.output.primitives().create("cube")
matrices = cubes.topology().create("matrices", "k3d::matrix4")
materials = cubes.topology().create("materials", "k3d::imaterial*")
uniform = cubes.attribu... | uniform.create("Cs", "k3d::color")
# Add three cubes ...
matrices.append(k3d.translate3(k3d.vector3(-7, 0, 0)))
materials.append(None)
color.append(k3d.color(1, 0, 0))
matrices.append(k3d.translate3(k3d.vector3(0, 0, 0)))
materials.append(None)
color.append(k3d.color(0, 1, 0))
mat | rices.append(k3d.translate3(k3d.vector3(7, 0, 0)))
materials.append(None)
color.append(k3d.color(0, 0, 1))
print repr(context.output)
|
bhermansyah/DRR-datacenter | avatar/tests.py | Python | gpl-3.0 | 5,578 | 0.004661 | import os.path
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth import get_user_model
from avatar.settings import AVATAR_DEFAULT_URL, AVATAR_MAX_AVATARS_PER_USER
from avatar.util import get_primary_avatar
from avatar.models import... | primaries = Avatar.objects.filter(user=self.user, primary=True)
self.failUnlessEqual(len(primaries), 1)
self.failIf | Equal(oid, primaries[0].id)
avatars = Avatar.objects.filter(user=self.user)
self.failUnlessEqual(avatars[0].id, primaries[0].id)
def testTooManyAvatars(self):
for i in range(0, AVATAR_MAX_AVATARS_PER_USER):
self.testNormalImageUpload()
count_before = Avatar.objects.filte... |
adamhaney/airflow | airflow/contrib/operators/jenkins_job_trigger_operator.py | Python | apache-2.0 | 11,480 | 0.001394 | # -*- coding: utf-8 -*-
#
# 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
#... | d_crumb(req)
response = urlopen(req, timeout=jenkins_server.timeout)
response_body = response.read()
response_headers = response.info()
if response_body is None:
raise jenkins.EmptyResponseException(
"Error communicating with server[%s]: "
"emp... | .server)
return {'body': response_body.decode('utf-8'), 'headers': response_headers}
except HTTPError as e:
# Jenkins's funky authentication means its nigh impossible to
# distinguish errors.
if e.code in [401, 403, 500]:
# six.moves.urllib.error.HTTPError provides a 'rea... |
dminca/python-sandbox | udp_client.py | Python | gpl-3.0 | 285 | 0.003509 | # | !/usr/bin/env python2
# SIMPLE UDP CLI | ENT
import socket
host = '127.0.0.1'
port = 80
# create socket obj
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# send data
client.sendto("AAABBBCCC", (host, port))
# receive data
data, addr = client.recvfrom(4096)
print data
|
kvar/ansible | lib/ansible/utils/unsafe_proxy.py | Python | gpl-3.0 | 4,891 | 0.001022 | # PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
# --------------------------------------------
#
# 1. This LICENSE AGREEMENT is between the Python Software Foundation
# ("PSF"), and the Individual or Organization ("Licensee") accessing and
# otherwise using this software ("Python") in source or binary form and
# its ass... | rrogate_or_strict'))
return obj
def _wrap_dict(v):
for k in v.keys():
if v[k] is not None:
v[wrap_var(k)] = wrap_var(v[k])
return v
d | ef _wrap_list(v):
for idx, item in enumerate(v):
if item is not None:
v[idx] = wrap_var(item)
return v
def _wrap_set(v):
return set(item if item is None else wrap_var(item) for item in v)
def wrap_var(v):
if v is None or isinstance(v, AnsibleUnsafe):
return v
if isin... |
canvasnetworks/canvas | website/settings_drawquest.py | Python | bsd-3-clause | 8,754 | 0.001714 | from settings import *
PROJECT = 'drawquest'
CANVAS_SUB_SITE = '/admin/'
if PRODUCTION:
DOMAIN = "example.com"
SELF_PORT = 9000
SELF = 'localhost:9000'
UGC_HOST = 'i.canvasugc.com'
FACEBOOK_APP_ACCESS_TOKEN = "REDACTED"
FACEBOOK_APP_ID = "REDACTED"
FACEBOOK_APP_SECRET = "REDACTED"
FAC... | //stackoverflow.com/questions/11853141/foo-objects-getid-none-returns-foo-instance-sometimes
'init_command': 'SET SQL_AUTO_IS_NULL=0;',
},
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql | ', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'drawquest/db.sqlite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', ... |
Informatik-AG-KGN-2016/Dokumente | 2016-11-28/aufgabe-addierer.py | Python | gpl-3.0 | 587 | 0.001712 | # Addierer mit += 1
# Eingaben erhalten
a = input("Dies ist ein Addierer!\nGeben Sie a ein: ")
b = input("Geben Sie b ein: ")
# Zeichenketten in Zahlen umwandeln
a = int(a)
b = int(b)
# neue Variable verwenden, Eingaben nicht verändern
result = a
|
i = 0
if b > 0: # wenn b größer Null
while i < b: # dann Schleife positiv durchlaufen
result += 1
i += 1
elif b < 0: # wenn b kleiner Null
while i > b: | # dann Schleife negativ durchlaufen
result -= 1
i -= 1
print("\nDas Ergebnis ist: " + str(result))
|
maier/repo-mirror-mgr | Mirror/__init__.py | Python | mit | 52 | 0 | from Config im | port Config
from Distro import Distr | o
|
wlashell/lyrical_page | site_tracking/admin.py | Python | apache-2.0 | 493 | 0.014199 | from django.contrib.admin import site, ModelA | dmin
from site_tracking.models import VerificationCode, TrackingCode
class VerificationCodeAdmin(ModelAdmin):
list_display = ('site', 'verification_type', 'code',)
list_editable = ('code',)
site.register(VerificationCode, VerificationCodeAdmin)
class TrackingCodeAdmin(ModelAdmin):
list_display = ('s... | de')
site.register(TrackingCode, TrackingCodeAdmin) |
anistark/opiniohll | OpinioDelivery/constants.py | Python | mit | 522 | 0.001916 | # All | the constants
# Get keys
import config
# All the Base Endpoints
STAGING_URL_HOST = 'test.deliver.opinioapp.com'
PRODUCTION_URL_HOST = 'deliver.opinioapp.com'
ACCESS_KEY = config.ACCESS_KEY
SECRET_KEY = config.SECRET_KEY
# Api Endpoints
API_BASE_ENDPOINT = '/api'
API_VERSION = 'v1'
API_ENDPOINT = API_BASE_ENDPOINT ... | NDPOINT = API_BASE_ENDPOINT + '/' + API_VERSION + '/serviceability'
|
erinspace/osf.io | addons/base/utils.py | Python | apache-2.0 | 2,446 | 0.006132 | import markupsafe
from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
user_addon = user.get_addon(config.short_name)
ret = {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
... | # None is default
if error_type != 'FILE_SUSPENDED' and ((auth.user and node.is_contributor(auth.user)) or (auth.private_key and auth.private_key in node.private_link_keys_active)):
last_meta = file.last_known_metadata
last_seen = last_meta.get('last_seen', None)
hashes = last_meta.get('ha... | e else '',
"""last seen on {} UTC """.format(last_seen.strftime('%c')) if last_seen else '',
"""and found at path {} """.format(markupsafe.escape(path)) if last_seen and path else '',
"""last found at path {} """.format(markupsafe.escape(path)) if not last_seen and path else '',
... |
ktok07b6/polyphony | tests/if/if23.py | Python | mit | 439 | 0 | from polyphony import testbench
class C:
def __init__(self):
self.v1 = 0
self.v2 = 0
def set_v(self, i, v):
if i == 0:
pass
elif i == 1:
self.v1 = v
elif i == 2:
self.v2 = v
else:
return
def if23():
c = C()
... | return c.v1 + c.v2
@testbench
def test():
assert 30 == | if23()
test()
|
vrga/pyFanController | pyfc/common.py | Python | mit | 4,243 | 0.001414 | import logging
from abc import ABCMeta, abstractmethod
from collections import deque
from typing import List, Union, Iterable, Sequence
log = logging.getLogger(__name__)
class NoSensorsFoundException(RuntimeError):
pass
class Controller(metaclass=ABCMeta):
@abstractmethod
def run(self):
raise N... | edError
@abstractmethod
def enable(self):
raise NotImplementedError
@abstractmethod
def disable(self):
raise NotImplementedError
class PassthroughController(Controller):
def __init__(self, inputs=Sequence[InputDevice], outputs=Sequence[OutputDevice], speeds=None):
self.i... | r idx, input_reader in enumerate(self.inputs):
output = self.outputs[idx]
output.name = input_reader.name
output.values.name = input_reader.name
output.set_value(input_reader.get_value())
output.apply()
log.debug('ran loop')
def apply_candidates(s... |
beetbox/beets | beets/dbcore/query.py | Python | mit | 29,107 | 0 | # This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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, ... | null."""
def __init__(self, field, fast=True):
super().__init__(field, None, fast)
def col_clause(self):
return self.field + " IS NULL", ()
def match(self, item):
return item.get(self.field) is None
def __repr__(self):
return "{0.__class__.__name__}({0.field!r}, {0.f... | atch(cls, pattern, value):
"""Determine whether the value matches the pattern. The value
may have any type.
"""
return cls.string_match(pattern, util.as_string(value))
@classmethod
def string_match(cls, pattern, value):
"""Determine whether the value matches the pattern.... |
anubhav929/eden | modules/eden/doc.py | Python | mit | 14,543 | 0.010314 | # -*- coding: utf-8 -*-
""" Sahana Eden Document Library
@copyright: 2011-2012 (c) Sahana Software Foundation
@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 wi... | organisation_id(
widget = S3OrganisationAutocompleteWidget(default_from_profile=True)
),
s3_date(label = T("Date Published")),
location_id(),
s3_comments(),
... | writable=False),
*s3_meta_fields())
# Field configuration
table.file.represent = lambda file, table=table: \
self.doc_file_represent(file, table)
#table.location_id.readable = False
#table.location_id.writable = False
... |
acs3ss/austinsullivan.github.io | files/Gamebox/game.py | Python | unlicense | 28,200 | 0.002163 | # Grayson Gatti (gtg8cd) AND Austin Sullivan (acs3ss)
# CS 1110 - Spring 2017
# Monday, May 1st 2017
import pygame
import gamebox
import random
import math
# this code uses stop_loop to exit ticks() function. Then changes level, resets the screen, etc before re-entering ticks
def tick(keys):
global l... | = knight):
| enemies[room_num][index][1] = False
dead_enemy(enemy)
for sharp in arrows:
if sharp[0].touches(enemy) and alive:
enemies[room_num][index][1] = False
dead_enemy(enemy)
... |
ic-labs/django-icekit | icekit/page_types/layout_page/migrations/0008_auto_20170518_1629.py | Python | mit | 686 | 0.002915 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('layout_page', '0007_auto_20170509_1148'),
]
operations = [
migrations.AddField(
model_name='layoutpage',
... |
migrations.AddField(
model_name='layoutpage',
name='brief',
field=models.TextField(help_text=b'A document brief describing the p | urpose of this content', blank=True),
),
]
|
Arvedui/picuplib | setup.py | Python | lgpl-2.1 | 950 | 0.015789 | #!/usr/bin/env python
# -*- coding:utf8 -*-
from setuptools import setup
import picuplib
setup(
name = 'picuplib',
packages = ['picuplib'],
version = picuplib.__version__,
description = 'Picflash upload library',
author = 'Arvedui',
author_email = '[email protected]',
url =... | : Libraries',
'Intended Audience :: Developers',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'License :: OSI Approved :: GNU L | esser General Public License v2 (LGPLv2)',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
|
matham/cplcom | cplcom/moa/device/ftdi.py | Python | mit | 21,337 | 0.000047 | '''Barst FTDI Wrapper
=====================
'''
from pybarst.ftdi import FTDIChannel
from pybarst.ftdi.switch import SerializerSettings, PinSettings
from pybarst.ftdi.adc import ADCSettings
from kivy.properties import NumericProperty, DictProperty, StringProperty, \
ListProperty, ObjectProperty, BooleanPro... | vice.d | igital.ButtonViewPort` wrapper around a
:class:`pybarst.ftdi.switch.FTDISerializerIn` or
:class:`pybarst.ftdi.switch.FTDISerializerOut` instance
(depending on the value of :attr:`output`).
For this class, :class:`moa.device.digital.ButtonViewPort.dev_map` must be
provided upon creation and it... |
deployed/django | django/utils/text.py | Python | bsd-3-clause | 14,829 | 0.001416 | from __future__ import unicode_literals
import re
import unicodedata
from gzip import GzipFile
from io import BytesIO
from django.utils.encoding import force_text
from django.utils.functional import allow_lazy, SimpleLazyObject
from django.utils import six
from django.utils.six.moves import html_entities
from django.... | ied number
of characters.
Takes an optional argument of what should be used to notify that the
string has been truncated, defaulting to a translatable string of an
ellipsis (. | ..).
"""
length = int(num)
text = unicodedata.normalize('NFC', self._wrapped)
# Calculate the length to truncate to (max length - end_text length)
truncate_len = length
for char in self.add_truncation_text('', truncate):
if not unicodedata.combining(char):
... |
furbrain/tingbot-python | tests/button_test.py | Python | bsd-2-clause | 1,851 | 0.002161 | import unittest
from tingbot.button import Button
class ButtonTestCase(unittest.TestCase):
def setUp(self):
self.button = Button()
def assertActions(self, action_types):
| self.assertEqual(action_types, [a.type for a in self.button.actions])
| def testPress(self):
self.button.add_event('down', timestamp=1)
self.button.add_event('up', timestamp=1.5)
self.button.process_events(time=2)
self.assertActions(['down', 'up', 'press'])
def testHold(self):
self.button.add_event('down', timestamp=1)
self.button.add_ev... |
yelu/leetcode | ReverseWords.py | Python | gpl-2.0 | 295 | 0.020339 | class Solution:
def reverseWords(self, s) :
print 1 / 0
tks = s.split(' ');
tks = filter(None, tks)
| tks.reve | rse();
return ' '.join(tks).strip()
test = ["the sky is blue", " a b "]
sol = Solution();
for t in test :
print sol.reverseWords(t)
|
idcodeoverflow/SocialNetworkAnalyzer | DBLayout/FacebookPostControlDB.py | Python | mit | 3,492 | 0.002864 | from DBLayout.DBConnection import DBConnection, mysql
from EntitiesLayout.FacebookPostControl import FacebookPostControl
__author__ = 'David'
class FacebookPostControlDB:
def __init__(self):
self.db = DBConnection()
print('Create object to access table user in DB.')
def insertPostControl(sel... |
cursor.close()
self.db.closeConnection()
except mysql.connector.Error | as ex:
print(ex)
print('Error reading not Visited Facebook Posts Control in the DB.')
return postsControl
def readPostsControl(self):
postsControl = []
try:
cnx = self.db.openConnection()
cursor = cnx.cursor()
readFBPostControlQue... |
django-salesforce/django-salesforce | salesforce/testrunner/example/tests.py | Python | mit | 363 | 0 | # django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
"""
This | file de | monstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
# from django.test import TestCase
|
Macemann/Georgetown-Capstone | app/db/connect.py | Python | mit | 493 | 0.008114 | import pymongo
def connect ():
| '''
Create the connection to the MongoDB and create 3 collections needed
'''
try:
# Create the connection to the local host
conn = pymongo.MongoClient()
print 'MongoDB Connection Successful'
except pymongo.errors.ConnectionFailure, err:
print 'MongoDB Connection Unsu... | n False
# This is the name of the database -'GtownTwitter'
db = conn['GtownTwitter_PROD']
return db |
tombs/Water-Billing-System | waterbilling/tasks/models.py | Python | agpl-3.0 | 250 | 0.004 | from django.db import models
# Create your models here.
from core.models import BillingSchedule
f | rom core.models import Bill
from core.models import Account
from core.models | import FileRepo
from core.models import Config
from core.models import Task |
kervi/kervi | kervi-core/kervi/dashboards/__init__.py | Python | mit | 9,756 | 0.004818 | #Copyright 2016 Tim Wentlau.
#Distributed under the MIT License. See LICENSE in root of project.
"""
A dashboard is the main ui component in a kervi application.
"""
_DASHBOARDS = []
from kervi.core.utility.component import KerviComponent
import kervi.spine as spine
class DashboardPanelGroup(object):
r"""
... | "dashboard": self.dashboard.get_referenc | e(),
"panels": panels
}
class DashboardPanel(object):
r"""
Create a dashboard panel.
:param panel_id:
id of the panel.
This id is used in other components to reference this panel.
:type panel_id: str
:param \**kwargs:
... |
nstanke/mailinabox | management/status_checks.py | Python | cc0-1.0 | 41,760 | 0.024315 | #!/usr/bin/python3
#
# Checks that the upstream DNS has been set correctly and that
# TLS certificates have been signed, etc., and if not tells the user
# what to do next.
import sys, os, os.path, re, subprocess, datetime, multiprocessing.pool
import dns.reversename, dns.resolver
import dateutil.parser, dateutil.tz
i... | ")
elif len(pkgs) == 0:
output.print_ok("System software is up to date.")
else:
output.print_error("There are %d software packages that can be updated." % len(pkgs))
for p in pk | gs:
output.print_line("%s (%s)" % (p["package"], p["version"]))
def check_system_aliases(env, output):
# Check that the administrator alias e |
strugee/pumptweet | pumptweet/MLStripper.py | Python | mit | 831 | 0.038882 | # cod | ing=utf-8
from HTMLParser import HTMLParser
# Class for stripping HTML from text.
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self): |
return ''.join(self.fed)
# Replaces HTML entities with actual characters.
def replace_entities(html):
unifiable = [
('&', '&'),
(' ', ' '),
(''', "'"),
('"', "'"),
('–', '-'),
('—', u'–'),
('→', u'→'),
('←', u'←'),
('⇆', u'↔'),
('“', '"'),
... |
openrightsgroup/OrgProbe | test/test_result.py | Python | gpl-3.0 | 936 | 0.004296 | # coding: utf-8
from orgprobe.result import Result
import logging
def test_unicode():
title = u"Some text here with a \u00a3 sign"
r = Result('ok', 200, title=title)
assert isinstance(title, unicode)
assert r.title == "Some text here with a £ sign"
assert isinstance(r.title, str)
assert str(... | 0" """ \
"""ssl_verified="None" ssl_fingerprint="None" final_url="None" resolved_ip="None" title="Some text here with a £ sign">"""
logging.info("result: %s", r)
def test_utf8():
r = Result('ok', 200, title="£20")
assert r.title == "£20"
assert isinstance(r. | title, str)
assert str(r) == """<Result: status="ok" code="200" category="None" type="None" ip="None" body_length="0" """ \
"""ssl_verified="None" ssl_fingerprint="None" final_url="None" resolved_ip="None" title="£20">"""
|
bblacey/FreeCAD-MacOS-CI | src/Tools/embedded/PySide/mainwindow2.py | Python | lgpl-2.1 | 1,203 | 0.012469 | import sys
#sys.path.append("")
from PySide import QtCore, | QtGui
import FreeCADGui
class MainWindow(QtGui.QMainWindow):
def | __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
from PySide import QtNetwork
# Webkit is used to create icons from SVG files. This could cause a deadlock
# when setting up the internally used network interface. Doing this before
# creating the icons fixes ... |
whitegreyblack/Spaceship | spaceship/classes/dungeon.py | Python | mit | 25,031 | 0.004115 | # Dungeon.py
# builds a random dungeon of size MxN
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))+'/../')
from bearlibterminal import terminal as term
from copy import deepcopy
from random import choice, randint, shuffle
from collections import namedtuple
from tools import bresenhams... | liquid.append((i, j))
'' | '
# make sure any free spaces bordering changed cell turn into wall tiles
# for ii in range(-1, 2):
# for jj in range(-1, 2):
# within = point_oob_ext(i+ii, j+jj, (0, X_TEMP-1), (0, Y_TEMP-1))
# if within and decayed[j+jj][i+ii] == ' ':
... |
yilei0620/3D_Conditional_Gan | lib/ops.py | Python | mit | 4,533 | 0.015442 |
import theano
import theano.tensor as T
from theano.sandbox.cuda.basic_ops import (as_cuda_ndarray_variable,
host_from_gpu,
gpu_contiguous, HostFromGpu,
gpu_alloc_empty)
from theano. | sandbox.cuda.dnn import GpuDnnConvDesc, GpuDnnConv, GpuDnnConvGradI, dnn_conv, dnn_pool
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano.tensor.nnet.abstract_conv import conv3d_grad_wrt_inputs
from theano.tensor.nnet import conv3d
from rng import t_rng
t_rng = RandomStreams()
def | l2normalize(x, axis=1, e=1e-8, keepdims=True):
return x/l2norm(x, axis=axis, e=e, keepdims=keepdims)
def l2norm(x, axis=1, e=1e-8, keepdims=True):
return T.sqrt(T.sum(T.sqr(x), axis=axis, keepdims=keepdims) + e)
def cosine(x, y):
d = T.dot(x, y.T)
d /= l2norm(x).dimshuffle(0, 'x')
d /= l2norm(y).... |
henrykironde/deletedret | scripts/vertnet_amphibians.py | Python | mit | 10,575 | 0.000567 | # -*- coding: latin-1 -*-
#retriever
"""Retriever script for direct download of vertnet-amphibians data"""
import os
from builtins import str
from pkg_resources import parse_version
from retriever.lib.models import Table
from retriever.lib.templates import Script
try:
from retriever.lib.defaults import VERSION
... | resources/datatoolscode.html"
self.urls = {
'amphibians': 'https://de.iplantcollaborative.org/anon-files//iplant/home/shared/commons_repo/curated/Vertnet_Amph | ibia_Sep2016/VertNet_Amphibia_Sept2016.zip'
}
self.citation = "Bloom, D., Wieczorek J., Russell, L. (2016). VertNet_Amphibia_Sept. 2016. CyVerse Data Commons. http://datacommons.cyverse.org/browse/iplant/home/shared/commons_repo/curated/VertNet_Amphibia_Sep2016"
self.description = "Compilation ... |
TakayukiSakai/tensorflow | tensorflow/contrib/learn/python/learn/estimators/tensor_signature_test.py | Python | apache-2.0 | 5,029 | 0.000994 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | signatures))
inputs = {'a': placeholder_a}
signatures = tensor_signature.create_signatures(inputs) |
self.assertTrue(tensor_signature.tensors_compatible(inputs, signatures))
self.assertFalse(tensor_signature.tensors_compatible(placeholder_a,
signatures))
self.assertFalse(tensor_signature.tensors_compatible(placeholder_b,
... |
Juniper/nova | nova/tests/unit/virt/xenapi/test_vm_utils.py | Python | apache-2.0 | 98,282 | 0.000824 | # Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | vm_utils.lookup,
| self.session, self.name_label,
check_rescue=True)
class GenerateConfigDriveTestCase(VMUtilsTestBase):
@mock.patch.object(vm_utils, 'safe_find_sr')
@mock.patch.object(vm_utils, "create_vdi", return_value='vdi_ref')
@mock.patch.object(vm_utils.instance_met... |
aaronn/django-rest-framework-passwordless | tests/test_verification.py | Python | mit | 8,084 | 0.002474 | from rest_framework import status
from rest_framework.authtoken.models import Token
from django.utils.translation import ugettext_lazy as _
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from drfpasswordless.settings import api_settings, DEFAUL... | bile, 'token': callback}
callback_response = self.client.post(self.callback_url, callback_data)
self.assertEqual(callback_response.status_code, status.HTTP_200_OK)
# Verify we got the t | oken, then check and see that email_verified is now verified
token = callback_response.data['token']
self.assertEqual(token, Token.objects.get(user=user).key)
# Refresh and see that the endpoint is now verified as True
user.refresh_from_db()
self.assertEqual(getattr(user, self.m... |
bonzanini/luigi-slack | tests/test_api.py | Python | mit | 5,897 | 0.001696 | import sys
import unittest
from unittest import mock
import luigi
import luigi_slack.api
from luigi_slack.api import SlackBot
from luigi_slack.api import notify
from luigi_slack.events import *
class TestSlackBot(unittest.TestCase):
def setUp(self):
self.patcher = mock.patch('luigi_slack.api.SlackAPI')
... | rtRaises(ValueError):
bot.set_handlers()
class TestEvents(unittest.TestCase):
def test_event_label(self):
"""Test event labels for output"""
fixtures = {
'SUCCESS': 'Success',
'FAILURE': 'Failure',
'MISSING': 'Missing',
}
for event, ... | s TestHandlers(unittest.TestCase):
def setUp(self):
self.patcher = mock.patch('luigi_slack.api.SlackAPI')
self.mock_SlackAPI = self.patcher.start()
self.token = 'dummy-token'
self.channels = ['channel1']
def tearDown(self):
self.patcher.stop()
def test_success(sel... |
Relrin/aiorest-ws | examples/auth_token/settings.py | Python | bsd-3-clause | 187 | 0 | # -*- coding: utf-8 -*-
# store User and Token tables in the memory
DATABASES = {
'default': {
| 'backend': 'aiorest_ws.db.backends.sqlite3',
'nam | e': ':memory:'
}
}
|
Cadasta/django-jsonattrs | tests/test_mixins.py | Python | agpl-3.0 | 6,431 | 0 | from django.test import TestCase
from django.views.generic import TemplateView
from django.contrib.contenttypes.models import ContentType
from jsonattrs import models, mixins
from . import factories
class XLangLabelsTest(TestCase):
def test_dict(self):
res = mixins.template_xlang_labels({'en': 'Field 1'... | , 'three'],
'field_4': 'two'}
)
view = JsonAttrsView()
view.object = party
context = view.get_context_data()
assert len(context['attrs']) == 4
assert context['attrs'][0] == ('Field 1', 'Some value', '', '')
assert context['attrs'][1] == ('Fiel... | eld 3', 'Choice 1, Choice 3', '', '')
assert context['attrs'][3] == ('Field 4', 'Choice 2', '', '')
def test_get_context_xlang(self):
models.create_attribute_types()
org = factories.OrganizationFactory.create()
project = factories.ProjectFactory.create(organization=org)
cont... |
dakiri/splunk-app-twitter | twitter2/bin/twython/streaming/types.py | Python | apache-2.0 | 2,822 | 0.002126 | # -*- coding: utf-8 -*-
"""
twython.streaming.types
~~~~~~~~~~~~~~~~~~~~~~~
This module contains classes and methods for :class:`TwythonStreamer` to use.
"""
class TwythonStreamerTypes(object):
"""Class for different stream endpoints
Not all streaming endpoints have nested endpoints.
User Streams and S... | arams):
"""Stream statuses/filter
:param \*\*params: Paramters to send with your stream request
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/post/ | statuses/filter
"""
url = 'https://stream.twitter.com/%s/statuses/filter.json' \
% self.streamer.api_version
self.streamer._request(url, 'POST', params=params)
def sample(self, **params):
"""Stream statuses/sample
:param \*\*params: Paramters to send with your... |
chrisortman/CIS-121 | k0458928/assignment04.py | Python | mit | 914 | 0.014223 | #This line asks the user to input an integer that will be recorded as my age
my_age = input("Enter your age:")
#T | his line asks the user to input an integer that will be recorded as days_in_a_year
days_in_a_year = input("How many days are in a ye | ar?")
#This line states how many hours are in a day
hours_in_a_day = 24
#This line tells you how many seconds you've been alive based on the recorded integers
print "how many seconds have i been alive?", my_age * days_in_a_year * hours_in_a_day * 60 * 60
#This line says that there are 8 black cars
black_cars = 8
#This ... |
arunkgupta/gramps | gramps/gen/datehandler/_date_es.py | Python | gpl-2.0 | 6,538 | 0.017781 | # -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2004-2006 Donald N. Allingham
#
# 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 t... | _2 = [u'y']
self._span = re.compile("(%s)\s+(?P<start>.+)\s+(%s)\s+(?P<stop>.+)" %
('|'.join(_span_1), '|'.join(_span_2)),
re.IGNORECASE)
self._range = re.compile("(%s)\s+(?P<start>.+ | )\s+(%s)\s+(?P<stop>.+)" %
('|'.join(_range_1), '|'.join(_range_2)),
re.IGNORECASE)
#-------------------------------------------------------------------------
#
# Spanish display
#
#----------------------------------------------------------------------... |
jtwp470/my-programming-learning-book | nlp100/python/14.py | Python | unlicense | 278 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 14. 先頭からN行を出力
import sys
if len(sys.argv) != 3:
print("Usage: python | {} filename [num]".format(sys.argv[0]))
sys.exit()
with open(sys.argv[ | 1]) as f:
print("".join(f.readlines()[:int(sys.argv[2])]))
|
tbjoern/adventofcode | Twentyfour/script.py | Python | mit | 2,404 | 0.037022 | import Queue
import copy
laby = []
spots = []
de | f isInt(c):
try:
int(c)
return True
except:
return False
def shortestPath(map, start, dest):
height = len(map[0])
width = len(map)
dist = [[-1 for y in range(he | ight)] for x in range(width)]
prev = [[None for y in range(height)] for x in range(width)]
dist[start[0]][start[1]] = 0
shortestPath = []
Q = []
for i in range(width):
for j in range(height):
if map != "#":
Q.append((i,j))
while dest in Q:
min = 100000
minq = (-1,-1)
for q in Q:... |
tomkralidis/geonode | geonode/messaging/consumer.py | Python | gpl-3.0 | 9,159 | 0.001201 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# 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 ... | last_message = message
update_layer = True
last_workspace = message["source"]["workspace"] if "workspace" in message["source"] else None
last_store = message["source"]["store"] if "store" in message["source"] else None
last_filter = last_message["source"]["name"]
if (last_workspace, last_... | estamp_t1 = datetime.strptime(last_message["timestamp"], '%Y-%m-%dT%H:%MZ')
timestamp_t2 = datetime.strptime(message["timestamp"], '%Y-%m-%dT%H:%MZ')
timestamp_delta = timestamp_t2 - timestamp_t1
if timestamp_t2 > timestamp_t1 and timestamp_delta.seconds > 60:
update_layer = True
... |
ray-project/ray | ci/travis/py_dep_analysis.py | Python | apache-2.0 | 11,800 | 0.000508 | #!/usr/bin/env python
#
# This file contains utilities for understanding dependencies between python
# source files and tests.
#
# Utils are assumed to be used from top level ray/ folder, since that is how
# our tests are defined today.
#
# Example usage:
# To find all circular dependencies under ray/python/:
# ... | from py files to their immediate dependees."""
graph = DepGraph()
# Assuming we run from root /ray directory.
# Follow links since rllib is linked to /rllib.
for root, sub_dirs, files in os.walk("python", followlinks=True):
if _should_skip(root):
continue
module = _ | bazel_path_to_module_path(root)
# Process files first.
for f in files:
if not f.endswith(".py"):
continue
full = _full_module_path(module, f)
if full not in graph.ids:
graph.ids[full] = len(graph.ids)
# Process file:
... |
flexiant/xen | tools/python/xen/util/xmlrpcclient.py | Python | gpl-2.0 | 4,533 | 0.001985 | #============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope th... | ile 1:
try:
if sock:
response = sock.recv(1024)
else:
response = file.read(1024)
except socket.sslerror, exn:
if exn[0] == socket.SSL_ERROR_ZERO_RETURN:
break
raise
... | self.verbose:
print 'body:', repr(response)
p.feed(response)
file.close()
p.close()
return u.close()
# See xmlrpclib2.TCPXMLRPCServer._marshalled_dispatch.
def conv_string(x):
if isinstance(x, StringTypes):
s = string.replace(x, "'", r"\047... |
nirbheek/cerbero | cerbero/tools/osxrelocator.py | Python | lgpl-2.1 | 5,546 | 0.000721 | #!/usr/bin/env python3
# cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free S... |
from cerbero.utils import shell
INT_C | MD = 'install_name_tool'
OTOOL_CMD = 'otool'
class OSXRelocator(object):
'''
Wrapper for OS X's install_name_tool and otool commands to help
relocating shared libraries.
It parses lib/ /libexec and bin/ directories, changes the prefix path of
the shared libraries that an object file uses and chan... |
snailwalker/python | burness/0000/test.py | Python | mit | 607 | 0.07084 | from PIL import Image, ImageDraw, ImageFont
cla | ss Image_unread_message:
def open(self,path):
self.im=Image.open(path)
return True
def __init__(self):
self.fnt=None
self.im=None
def setFont(self,font_path,size):
self.fnt=ImageFont.truetype(font_path,size)
return True
def draw_text(self,position,str,colour,fnt):
draw=ImageDraw.Draw(self.im)
draw.... | lf.im.show()
self.im.save(str+'num'+'.jpg')
return True
test=Image_unread_message()
test.open('test.jpg')
test.setFont('ahronbd.ttf',80)
test.draw_text((160,-20),'4',(255,0,0),test.fnt)
|
scheib/chromium | tools/perf/core/services/luci_auth.py | Python | bsd-3-clause | 1,316 | 0.009878 | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
import subprocess
import sys
import six
_RE_INFO_USER_EMAIL = r'Logged in as (?P<email>\S+)\.$'
class AuthorizationError(Exception):
pass
d... | Token()
except AuthorizationError as exc:
sys.exit(str(exc))
def GetAccessToken():
"""Get an access token to make requests on behalf of the logged in user."""
return _RunCommand('token').rstrip()
def GetUserEmail():
"""Get the email address of the currently logged in user."""
output = _RunCommand('inf... | m = re.match(_RE_INFO_USER_EMAIL, output, re.MULTILINE)
assert m, 'Failed to parse luci-auth info output.'
return m.group('email')
|
GertBurger/pygame_cffi | pygame/compat.py | Python | lgpl-2.1 | 2,767 | 0.004698 | """Python 2.x/3.x compatibility tools | """
import sys
__all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_',
'unicode_', 'raw_input_', 'as_bytes', 'as_unicode']
def geterror (): |
return sys.exc_info()[1]
try:
long_ = long
except NameError:
long_ = int
try:
xrange_ = xrange
except NameError:
xrange_ = range
def get_BytesIO():
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
return BytesIO
def get_String... |
beni55/nixops | nixops/deployment.py | Python | lgpl-3.0 | 46,436 | 0.004427 | # -*- coding: utf-8 -*-
import sys
import os.path
import subprocess
import json
import string
import tempfile
import shutil
import threading
import exceptions
import errno
from collections import defaultdict
from xml.etree import ElementTree
import nixops.statefile
import nixops.backends
import nixops.logger
import ni... | ute("select name, value from DeploymentAttrs where deployment = ?", (self.uuid,))
rows = c.fetchall()
res = {row[0]: row[1] for row in rows}
res['resourc | es'] = {r.name: r.export() for r in self.resources.itervalues()}
return res
def import_(self, attrs):
with self._db:
for k, v in attrs.iteritems():
if k == 'resources': continue
self._set_attr(k, v)
for k, v in attrs['resources'].iteritem... |
ksmit799/Toontown-Source | toontown/estate/DistributedStatuary.py | Python | mit | 5,336 | 0.002436 | import DistributedLawnDecor
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.ShowBase import *
import GardenGlobals
from toontown.toonbase import TTLocalizer
from toontown.toonbase import ToontownGlobals
from toontown.toontowngui import TTDialog
from toontown.toonbase import TTLocalizer
from pand... | colNode = self.model.find('**/+CollisionNode')
if not colNode.isEmpty():
score, multiplier = ToontownGlobals.PinballScoring[ToontownGlobals.PinballStatuary]
if self.pinballScore:
score = self.pinballScore[0]
multiplier = self.pinballScore[1]
... | = NodePath('statuary-%d-%d' % (score, multiplier))
colNode.setName('statuaryCol')
scoreNodePath.reparentTo(colNode.getParent())
colNode.reparentTo(scoreNodePath)
self.model.setScale(self.worldScale)
self.model.reparentTo(self.rotateNode)
attrib = GardenGlobal... |
birdland/dlkit-doc | dlkit/mongo/repository/sessions.py | Python | mit | 237,798 | 0.001409 | """Mongodb implementations of repository sessions."""
# pylint: disable=no-init
# Numerous classes don't require __init__.
# pylint: disable=too-many-public-methods,too-few-public-methods
# Number of methods are defined in specification
# pylint: disable=protected-access
# Access to protected methods allow... | -1
ASCENDING = 1
CREATED = True
UPDATED = True
ENCLOSURE_RECORD_TYPE = Type(
identifier='enclosure',
namespace='osid-object',
authority='ODL.MIT.EDU')
CREATED = TrueUPDATED = True
COMPARATIVE = 0
PLENARY = 1
ACTIVE = 0
ANY_STATUS = 1
SEQUESTERED = 0
UNSEQUESTERED = 1
class AssetLookupSession(abc_reposit... | ry_sessions.AssetLookupSession, osid_sessions.OsidSession):
"""This session defines methods for retrieving assets.
An ``Asset`` represents an element of content stored in a
Repository.
This lookup session defines several views:
* comparative view: elements may be silently omitted or re-o... |
nizox/circuits | circuits/web/errors.py | Python | mit | 7,638 | 0.000262 | """Errors
This module implements a set of standard HTTP Errors.
"""
import json
import traceback
try:
from html import escape
except ImportError:
from cgi import escape # Deprecated since version 3.2
try:
from urllib.parse import urljoin as _urljoin
except ImportError:
from urlparse import urljoin a... | return json.dumps(dict((key, self.data[key]) for key in index))
if not self.request.print_debug:
self.data["traceback"] = ''
return DEFAULT_ERROR_MESSAGE % self.data
def __repr__(self):
return "<%s %d %s>" % (
self.__class__.__name__, self.code, HTTP_STATUS_CODE... |
self.code, "???"
)
)
class forbidden(httperror):
"""An event for signaling the HTTP Forbidden error"""
code = 403
class unauthorized(httperror):
"""An event for signaling the HTTP Unauthorized error"""
code = 401
class notfound(httperror):
"""An event ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.