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 |
|---|---|---|---|---|---|---|---|---|
gzamboni/sdnResilience | loxi/of10/message.py | Python | gpl-2.0 | 248,179 | 0.006455 | # Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
# Copyright (c) 2011, 2012 Open Networking Foundation
# Copyright (c) 2012, 2013 Big Switch Networks, Inc.
# See the file LICENSE.pyloxi which should have been included in the source distribution
# Automatically generated by LOXI from ... | self.packet_count = packet_count
else:
self.packet_count = 0
if byte_count != None:
self.byte_count = byte_count
else:
self.byte_count = 0
if flow_count != None:
self.flow_count = flow_count
else:
self.flow_cou... | .append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(struct.pack("!Q", ... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/NV/texture_expand_normal.py | Python | lgpl-3.0 | 591 | 0.021997 | ''' | Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXT... | exture_expand_normal',error_checker=_errors._error_checker)
GL_TEXTURE_UNSIGNED_REMAP_MODE_NV=_C('GL_TEXTURE_UNSIGNED_REMAP_MODE_NV',0x888F)
|
the0forge/sp | frontend/migrations/0038_auto__add_unique_spuser_username.py | Python | gpl-3.0 | 22,106 | 0.008097 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'SPUser', fields ['username']
db.create_uni... | h': '25'}),
u'i | d': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'logo_height': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
'logo_img': ('django.db.models.fields.files.ImageField', [], {'max_length': '255', 'null': 'True'}),
'logo_width': ('dja... |
EvanK/ansible | lib/ansible/modules/cloud/azure/azure_rm_managed_disk.py | Python | gpl-3.0 | 14,499 | 0.002 | #!/usr/bin/python
#
# Copyright (c) 2017 Bruno Medina Bolanos Cacho <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version':... | ices=['linux', 'windows']
),
disk_size_gb=dict(
type='int'
),
| managed_by=dict(
type='str'
)
)
required_if = [
('create_option', 'import', ['source_uri']),
('create_option', 'copy', ['source_uri']),
('create_option', 'empty', ['disk_size_gb'])
]
self.results = dict(
c... |
pombredanne/pushmanager | tests/test_servlet_newpush.py | Python | apache-2.0 | 6,300 | 0.00381 | from contextlib import nested
from contextlib import contextmanager
import mock
import testing as T
import types
from core import db
from core.settings import Settings
from core.mail import MailQueue
from core.util import get_servlet_urlspec
from core.xmppclient import XMPPQueue
import servlets.newpush
from servlets.... | s.newpush.subprocess.call.call_count, 1)
# Verify that we have a valid call to
# subprocess.call. Getting the arguments involves ugly
# mock magic
mocked_call.assert_called_once_with([
'/nail/sys/bin/nodebot',
'-i',... | NY, # msg
])
def call_on_db_complete(self, urgent=False):
mocked_self = mock.Mock()
mocked_self.check_db_results = mock.Mock(return_value=None)
mocked_self.redirect = mock.Mock(return_value=None)
mocked_self.pushtype = 'normal'
mocked_self.on_db_complete =... |
Kaezon/allianceauth | allianceauth/services/modules/mumble/tasks.py | Python | gpl-2.0 | 1,857 | 0.002154 | import logging
from django.contrib.auth.models import User
from | django.core.exceptions import ObjectDoesNotExist
from celery import shared_task
from allianceauth.services.tasks import QueueOnce
from .models import MumbleUser
logger = logging.getLogger(__name__)
cla | ss MumbleTasks:
def __init__(self):
pass
@staticmethod
def has_account(user):
try:
return user.mumble.username != ''
except ObjectDoesNotExist:
return False
@staticmethod
def disable_mumble():
logger.info("Deleting all MumbleUser models")
... |
kevintom/django-bloom | bloom/image/templatetags/__init__.py | Python | gpl-3.0 | 89 | 0 | # Bloom | Framework
#
# John Boxall
# Copyright 2008 Handi Mobility
# www.handimo | bility.ca
|
nwjs/chromium.src | third_party/crashpad/crashpad/build/install_linux_sysroot.py | Python | bsd-3-clause | 2,174 | 0 | #!/usr/bin/env python3
# Copyright 2018 The Crashpad 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
#
# Unle... | sysroot/toolchain'
REVISION = '43a87bbebccad99325fdcf34166295b121ee15c7'
FILENAME = 'debian_sid_amd64_sysroot.tar.xz'
def main():
url = '%s/%s/%s/%s' % (SERVER, PATH, REVISION, FILENAME)
sysroot = os.path.join(SCRIPT_DIR, os.pardir, 'third_party', 'linux',
'sysroot')
stamp = o... | oot image from %s' % url)
if os.path.isdir(sysroot):
shutil.rmtree(sysroot)
os.mkdir(sysroot)
tarball = os.path.join(sysroot, FILENAME)
print('Downloading %s' % url)
for _ in range(3):
response = urllib.request.urlopen(url)
with open(tarball, 'wb') as f:
f.write... |
mliudev/sassafras | sassafras/settings.py | Python | mit | 3,364 | 0 | """
Django settings for sassafras project.
Generated by 'django-admin startproject' using Django 1.8.13.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build p... | rib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'sassafras | .urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request... |
NarlikarLab/DIVERSITY | weblogoMod/corebio/utils/deoptparse.py | Python | gpl-3.0 | 9,010 | 0.016426 | # Copyright (c) 2004 Gavin E. Crooks <[email protected]>
#
# This software is distributed under the MIT Open Source License.
# <http://www.opensource.org/licenses/mit-license.html>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentati... | for type 'dict'")
elif not isinstance(self.choices, dict):
raise OptionValueError(
"choices must be a dictionary ('%s' supplied)"
% str(type(self.choices)).split("'")[1])
return
self._check_choice()
# Have to override _check_... | at we can parse
# a dict through to check_dict
CHECK_METHODS = Option.CHECK_METHODS
CHECK_METHODS[2] = _new_check_choice
class DeOptionParser(OptionParser) :
def __init__(self,
usage=None,
option_list=None,
option_class=DeOption,
v... |
katakumpo/niceredis | niceredis/client/zset.py | Python | mit | 11,593 | 0.000086 | # -*- coding: utf-8 *-*
from redis._compat import iteritems, iterkeys, itervalues
from redis.connection import Token
from redis.exceptions import RedisError
from .base import RedisBase
class ZsetCommands(RedisBase):
# SORTED SET COMMANDS
def zadd(self, name, *args, **kwargs):
"""
Set any numb... | ")
pieces = ['ZRANGEBYLEX', name, min, max]
if start is not None and num is not N | one:
pieces.extend([Token('LIMIT'), start, num])
return self.execute_command(*pieces)
def zrangebyscore(self, name, min, max, start=None, num=None,
withscores=False, score_cast_func=float):
"""
Return a range of values from the sorted set ``name`` with scor... |
Onirik79/aaritmud | src/connection.py | Python | gpl-2.0 | 8,524 | 0.005397 | # -*- coding: utf-8 -*-
"""
Modulo per la gestione generica di una connessione al sito.
"""
#= IMPORT ======================================================================
import datetime
from twisted.internet import protocol
from src.config import config
from src.enums import LOG, OPTION, TRUST
from src.log ... | to! Devo inserire questi attributi nella Twisted Session al sito
class Connection(protocol.Protocol):
"""
Questa classe serve a gestire le connessioni, e le relative sessioni, dei
differenti Client al Mud.
"""
def __init__(self):
self.account = None # Account utili | zzato
self.new_player = None # Personaggio che si sta creando
self.player = None # Personaggio in gioco
self.session = None # Twisted Session
self.request = None # Twisted Request
self.ip = "None" # Ip de... |
paul99/clank | tools/grit/grit/gather/tr_html_unittest.py | Python | bsd-3-clause | 17,175 | 0.004134 | #!/usr/bin/python2.4
# Copyright (c) 2011 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.
'''Unit tests for grit.gather.tr_html'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.di... | desktop.google.com/privacypolicy.html?hl=[LA | NG_CODE]'>Privacy Policy</A>
and <A HREF='http://desktop.google.com/privacyfaq.html?hl=[LANG_CODE]'>Privacy FAQ</A> online.''')
pres = msg.GetPresentableContent()
self.failUnless(pres == '''You c |
snakeleon/YouCompleteMe-x64 | third_party/ycmd/third_party/jedi_deps/parso/parso/python/parser.py | Python | gpl-3.0 | 8,227 | 0.000851 | from parso.python import tree
from parso.python.token import PythonTokenTypes
from parso.parser import BaseParser
NAME = PythonTokenTypes.NAME
INDENT = PythonTokenTypes.INDENT
DEDENT = PythonTokenTypes.DEDENT
class Parser(BaseParser):
"""
This class is used to parse a Python file, it then divides them into ... | try:
plan = self.stack[-1].dfa.transitions[PythonTokenTypes.NEWLINE]
except KeyError:
pass
else:
if plan.next_dfa.is_final and not plan.dfa_pushes:
| # We are ignoring here that the newline would be
# required for a simple_stmt.
self.stack[-1].dfa = plan.next_dfa
self._add_token(token)
return
if not self._error_recovery:
return... |
cr0hn/openvas_to_report | openvas_to_report/examples/__init__.py | Python | bsd-3-clause | 1,761 | 0.007382 | # -*- coding: utf-8 -*-
#
#
# Project name: OpenVAS2Report: A set of tools to manager OpenVAS XML report files.
# Project URL: https://github.com/cr0hn/openvas_to_report
#
# Copyright (c) 2015, cr0hn<-AT->cr0hn.com
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modificatio... | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
__author__ = 'cr0hn - cr0hn<-at->cr0hn.com (@ggdaniel)'
| |
soulfx/gmusic-playlist | ExportLists.py | Python | mit | 3,890 | 0.004627 | # Author: John Elkins <[email protected]>
# License: MIT <LICENSE>
from common import *
if len(sys.argv) < 2:
log('ERROR output directory is required')
time.sleep(3)
exit()
# setup the output directory, create it if needed
output_dir = sys.argv[1]
if not os.path.exists(output_dir):
os.makedirs(ou... | _dir,playlist_name+u'.log'))
outfile = codecs.open(os.path.join(output_dir,playlist_name+u'.csv'),
encoding='utf-8',mode='w')
# keep track of stats
stats = create_stats()
export_skipped = 0
# keep track of songids incase we need to skip duplicates
| song_ids = []
log('')
log('============================================================')
log(u'Exporting '+ unicode(len(playlist_tracks)) +u' tracks from '
+playlist_name)
log('============================================================')
# add the playlist description as a "comment"
... |
eri-trabiccolo/exaile | plugins/playlistanalyzer/__init__.py | Python | gpl-2.0 | 6,185 | 0.008892 | # Copyright (C) 2014 Dustin Spicuzza
#
# 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, or (at your option)
# any later version.
#
# This program is distributed in the hope that... | *kwargs):
'''
Opens a template file, performs substitution, writes it to the
| output URI, and also writes d3.min.js to the output directory.
:param tmpl: Local pathname to template file
:param uri: URI of output file suitable for passing to gio.File
:param kwargs: Named parameters to substitute in template
'''
# read... |
pneerincx/easybuild-framework | easybuild/tools/parallelbuild.py | Python | gpl-2.0 | 8,870 | 0.003157 | # #
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (ht... | st of command line options (in 'longopt=value' form)
"""
curdir = os.getcwd()
# the options to ignore (help options can't reach here)
ignore_opts = ['robot', 'job']
# generate_cmd_line returns the options in form --longopt=value
opts = [x for x in cmd_line_opts if not x.split('=')[0] in ['--%s... | command = "unset TMPDIR && cd %s && eb %%(spec)s %s --testoutput=%%(output_dir)s" % (curdir, opts_str)
_log.info("Command template for jobs: %s" % command)
job_info_lines = []
if testing:
_log.debug("Skipping actual submission of jobs since testing mode is enabled")
else:
jobs = buil... |
drewhutchison/coolerofdoom | data.py | Python | mit | 3,415 | 0.009663 | import sqlite3
TWITTER_CONSUMER_KEY = 'twitter_consumer_key'
TWITTER_CONSUMER_SECRET = 'twitter_consumer_secret'
TWITTER_ACCESS_TOKEN = 'twitter_access_token'
TWITTER_ACCESS_TOKEN_SECRET = 'twitter_access_token_secret'
LAST_LATITUDE = 'last_latitude'
LAST_LONGITUDE = 'last_longitude'
UPC_DATABASE_KEY = 'upc_database_k... | WHERE user_id=?''',
(user_id,))
def log(self, upc): |
self.c.execute('''INSERT INTO log(upc, timestamp)
VALUES (?, datetime('now'))''',
(upc,))
def get_current_user(self):
self.c.execute('''SELECT *
FROM users
WHERE last_seen BETWEEN datet... |
alriddoch/cyphesis | rulesets/mason/world/tasks/Repairing.py | Python | gpl-2.0 | 3,147 | 0.013028 | #This file is distributed under the terms of the GNU General Public license.
#Copyright (C) 2011 Jekin Trivedi <[email protected]> (See the file COPYING for details).
from atlas import *
from physics import *
from physics import Quaternion
from physics import Vector3D
import server
class Repairing(server.Task):... | cter.lo | cation, self.target().location) > self.target().location.bbox.square_bounding_radius():
self.progress = current_status
self.rate = 0
return self.next_tick(1.75)
# Some entity do not have status defined. If not present we assume that the entity is unharmed & stop the task
... |
wakatime/komodo-wakatime | components/wakatime/compat.py | Python | bsd-3-clause | 3,553 | 0.001689 | # -*- coding: utf-8 -*-
"""
wakatime.compat
~~~~~~~~~~~~~~~
For working with Python2 and Python3.
:copyright: (c) 2014 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import codecs
import os
import platform
import subprocess
import sys
is_py2 = (sys.version_info[0] == 2)
is_py3 ... | level += 1
name = _resolve_name(name[level:], package, level)
__import__(name)
return sys.modules[name]
try:
from .packages import simplejson as json
except (ImportError, SyntaxError): # pragma: nocover
import json
class Popen(subprocess.Popen):
"""Patched Popen... | startupinfo = kwargs.get('startupinfo')
if is_win or True:
try:
startupinfo = startupinfo or subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
except AttributeError:
pass
kwargs['startupinfo'] =... |
swastvedt/dailygraphics | fabfile/utils.py | Python | mit | 813 | 0.00369 | #!/usr/bin/env python
import boto
from boto.s3.connection import OrdinaryCallingFormat
from fabric.api import prompt
def confirm(message):
"""
Verify a users | intentions.
"""
answer = prompt(message, default="Not at all")
if answer.lower() not in ('y', 'yes', 'buzz off', 'screw you'):
exit()
def replace_in_file(filena | me, find, replace):
with open(filename, 'r') as f:
contents = f.read()
contents = contents.replace(find, replace)
with open(filename, 'w') as f:
f.write(contents)
def get_bucket(bucket_name):
"""
Established a connection and gets s3 bucket
"""
if '.' in bucket_name:
... |
82Flex/DCRM | WEIPDCRM/views/admin/help/about.py | Python | agpl-3.0 | 1,308 | 0 | # coding=utf-8
"""
DCRM - Darwin Cydia Repository Manager
Copyright (C) 2017 WU Zheng <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at yo... | jango.contrib import admin
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render
from django.utils.translation import ugettext as _
@staff_ | member_required
def about_view(request):
"""
:param request: Django Request
:return: Django HttpResponse
:rtype: HttpResponse
"""
context = admin.site.each_context(request)
context.update({
'title': _('About'),
'version': "4.1",
})
template = 'admin/help/about.html'
... |
google/active-qa | px/nmt/model_test.py | Python | apache-2.0 | 70,985 | 0.005776 | # Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | context_bilstm_pool/ctx_resizer/sum':
-0.64984130,
'ContextModel_bilstm_last_decoder_hidden_state/last_dec_weight/shape':
(10, 20),
'ContextModel_bilstm_last_decoder_hidden_state/last_dec_weight/sum':
0.058056116,
'ContextModel_bilstm_last_decoder_hidden_state... | Model_bilstm_pool_encoder_output/last_dec_weight/shape': (10,
20),
'ContextModel_bilstm_pool_encoder_output/last_dec_weight/sum':
0.058035135,
'ContextModel_bilstm_pool_encoder_output/last_enc_weight/shape': (10,
... |
dbentley/pants | src/python/pants/goal/goal.py | Python | apache-2.0 | 8,127 | 0.010336 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.goal.erro... | types used by tasks in this goal, in no particular order."""
ret = set()
for task_type in self.task_types():
ret.update([dep.subsystem_cls for dep in task_type.subsystem_dependencies_iter()])
return ret
def ordered_task_names(self):
"""The task names in this goal, in registration | order."""
return self._ordered_task_names
def task_type_by_name(self, name):
"""The task type registered under the given name."""
return self._task_type_by_name[name]
def task_types(self):
"""Returns the task types in this goal, unordered."""
return self._task_type_by_name.values()
def task... |
UFCGProjects/sig | src/tests/FugaRotaTest.py | Python | mit | 1,680 | 0.008333 | import psycopg2
import unittest
import sys
import os
class GFugaRotaTest(unittest.TestCase):
def setUp(self):
self.table = open(os.path.abspath('../') + '/sql/createsTable/FugaRota.sql', 'r')
self.constraints = open(os.path.abspath('../') + '/sql/createsTable/FugaRota_const.sql', 'r')
sel... | nstraints(self):
self.cur.execute(self.cons)
self.assertEqual(self.cur.st | atusmessage, "ALTER TABLE")
def testDInsertTable(self):
for self.dados in self.inserts:
self.cur.execute(self.dados)
self.assertEqual(self.cur.statusmessage, "INSERT 0 1")
def testEInsertTableFalhos(self):
for self.dadosFalhos in self.falhos:
try:
... |
uclouvain/osis | infrastructure/tests/shared_kernel/academic_year/repository/in_memory/test_academic_year.py | Python | agpl-3.0 | 2,533 | 0.001975 | #
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, progr... | domain.model.academic_year import AcademicYear, AcademicYearIdentity
from infrastructure.shared_kernel.academic_year.repository.in_memory.academic_year import AcademicYearInMemoryRepository
class TestAcademicYearInMemory | Repository(SimpleTestCase):
def setUp(self):
self.academic_year_repository = AcademicYearInMemoryRepository()
for annee in range(2016, 2021):
self.academic_year_repository.save(AcademicYear(
entity_id=AcademicYearIdentity(year=annee),
start_date=datetime.... |
NeCTAR-RC/horizon | openstack_dashboard/test/integration_tests/tests/test_defaults.py | Python | apache-2.0 | 3,108 | 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
# d... | ertGreater(len(default_quota_values), 0)
for quota_name in default_quota_values:
self.assertTrue(
self.defaults_p | age.is_volume_quota_a_match(
quota_name,
default_quota_values[quota_name] + self.add_up
))
|
mcmaxwell/idea_digital_agency | idea/feincms/module/page/migrations/0010_auto_20180124_1945.py | Python | mit | 612 | 0.001634 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2018-01-24 19:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('page', '0009_auto_20180124_0105'),
| ]
operations = [
migrations.AlterField(
model_name='page',
name='template_key',
field=models.CharField(choices=[(b'content/pages/page.html', 'Pa | ge'), (b'content/pages/index_page.html', 'Index Page')], default=b'content/pages/page.html', max_length=255, verbose_name='template'),
),
]
|
yephper/django | django/views/generic/base.py | Python | bsd-3-clause | 7,898 | 0.001013 | from __future__ import unicode_literals
import logging
from functools import update_wrapper
from django import http
from django.core.exceptions import ImproperlyConfigured
from django.template.response import TemplateResponse
from django.urls import NoReverseMatch, reverse
from django.utils import six
from ... | rendered w | ith the given context.
If any keyword arguments are provided, they will be
passed to the constructor of the response class.
"""
response_kwargs.setdefault('content_type', self.content_type)
return self.response_class(
request=self.request,
templat... |
gh0std4ncer/doit | doc/tutorial/uptodate_callable.py | Python | mit | 279 | 0.003584 |
def fake_get_value_from_db():
| return 5
def check_outdated():
total = fake_get_value_from_db()
return total > 10
def task_put_more_stuff_in_db():
def put_stuff(): pass
return {'actions': [put_stuff],
'uptodate': [check | _outdated],
}
|
MSFTOSSMgmt/WPSDSCLinux | Providers/Scripts/2.6x-2.7x/Scripts/nxIPAddress.py | Python | mit | 30,909 | 0.027727 | #!/usr/bin/env python
#============================================================================
# Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.
#============================================================================
from __future__ import print_function
fro... | Exception is ' +str(e),file=sys.stderr)
try:
os.rename(temp,filepath)
except IOError, e:
print('ReplaceFileContentsAtomic','Removing '+ filepath + ' Exception is ' +str(e),file=sys.stderr)
return 1
return 0
def GetMyDistro(dist_class_name= | ''):
"""
Return MyDistro object.
NOTE: Logging is not initialized at this point.
"""
if dist_class_name == '':
|
PetePriority/home-assistant | homeassistant/components/wink/fan.py | Python | apache-2.0 | 3,231 | 0 | """
Support for Wink fans.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/fan.wink/
"""
import logging
from homeassistant.components.fan import (
SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM, SUPPORT_DIRECTION,
SUPPORT_SET_SPEED, FanEntity)
from homeassi... | if SPEED_LOWEST == current_wink_speed:
return SPEED_LOWEST
if SPEED_LOW == current_wink_speed:
return SPEED_LOW
if SPEED_MEDIUM == current_wink_speed:
return SPEED_MEDIUM
if SPEED_HIGH == current_wink_speed:
return SPEED_HIGH
| return None
@property
def current_direction(self):
"""Return direction of the fan [forward, reverse]."""
return self.wink.current_fan_direction()
@property
def speed_list(self) -> list:
"""Get the list of available speeds."""
wink_supported_speeds = self.wink.fa... |
google-research/sound-separation | models/train/data_meeting_io.py | Python | apache-2.0 | 23,738 | 0.007162 | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Returns:
Feature specifications suitable to pass to tf.parse_example.
"""
spec = {}
spec[Features.RECEIVER_AUDIO] = tf.FixedLenFeature(
[num_receivers, num_samples], tf.float32)
spec[Features.SOURCE_IMAGES] = tf.FixedLenFeature(
[num_sources, num_receivers, num_samples], tf.float32)
return s... | ible with a given feature spec."""
placeholders = {}
for key, feature in feature_spec.items():
placeholders[key] = tf.placeholder(dtype=feature.dtype,
shape=[1] + feature.shape,
name=key)
return placeholders
def _read_meeting_list... |
ganow/gq | gq/missing.py | Python | mit | 788 | 0.002538 | class MethodMissing(object):
def __getattr__(self, name):
try:
return self.__getattribute__(name)
except AttributeError:
def method(*args, **kw):
return self.method_missing(name, *args, **kw)
return method
def method_missing(self, name, *args,... | attr__(self, name):
try:
return self.__getattribute__(name)
except AttributeError:
| return self.val_missing(name)
def val_missing(self, name):
raise AttributeError("%r object has no attribute %r" %
(self.__class__, name))
|
ilathid/ilathidEngine | engine/music.py | Python | epl-1.0 | 6,871 | 0.015282 | #Music Class and support functions
import pygame
import parameters
from filemanager import filemanager
from pygame.locals import *
from pygame import *
from pygame.mixer import *
#Pygame Module for Music and Sound
pigmusic = None
currentStdMusic=None
currentMenuMusic=None
currentType = None
def initmusic():
globa... |
return
else:
print " music std, not the same we change, cu | rrentStdMusic=",self._file
currentStdMusic=self
else:
print " music std, current type is menu isn't it :", currentType ," so we change it to std\n"
#we change menu slide to standard slide
currentTy... |
jwilder/nginx-proxy | test/test_multiple-hosts.py | Python | mit | 562 | 0.003559 | import pytest
def test_unknown_virtual_host_is_503(docker_compose, nginxproxy | ):
r = nginxproxy.get("http://unknown.nginx-proxy.tld/port")
assert r.status_code == 503
def test_webA_is_forwarded(docker_compose, nginxproxy):
r = nginxproxy.get("http://webA.nginx-proxy.tld/port")
assert r.status_code == 200
assert r.text == "answer from port 81\n"
def test_webB_is_forwarded(do... | tus_code == 200
assert r.text == "answer from port 81\n"
|
andreas-kowasch/DomainSearch | DomainSearchViewer/additional/Scheduler.py | Python | bsd-2-clause | 3,767 | 0.003186 | # -*- coding: utf-8 -*-
"""
The scheduler is responsible for the module handling.
"""
import modules
from importlib import import_module
from additional.Logging import Logging
################################################################################
class Scheduler():
"""
This class instantiates the... | module_name, result[0][0], module_version))
############################################################################
def get_mod | ule_select_queries(self):
"""
Returns the module's search queries.
"""
queries = {}
for module_name, module in self._instantiated_modules.items():
queries[module_name] = module.get_queries('select')
return queries
##########################################... |
anythingrandom/eclcli | eclcli/dh/v2/usage.py | Python | apache-2.0 | 2,651 | 0.010562 | import copy
import six
from eclcli.common import command
from eclcli.common import utils
class ListUsage(command.Lister):
def get_parser(self, prog_name):
parser = super(ListUsage, self).get_parser(prog_name)
parser.add_argument(
"--From",
help="Date to list usage fr... | debug('search options: %s',search_opts)
columns = [
'ID', 'Type', 'Value', 'Unit', 'Name', 'Has License Key', 'Resource ID'
]
column_headers = columns
data = dh_client.usages.list(search_opts=search_opts)
return (column_headers,
(utils.g... | owUsageHistory, self).get_parser(prog_name)
parser.add_argument(
"usage",
help="Usage id whose history to be shown",
metavar='<usage>'
)
parser.add_argument(
"--From",
help="Date to list usage from",
metavar='<from>'
... |
Annubis45/PhotoDisplayer | cgi-bin/index.py | Python | gpl-2.0 | 2,228 | 0.04623 | #!/usr/bin/python3
# -*- coding: utf-8 -*
import cgi
import base64
import random
import requests, json
def getCurrentPhoto(currentPhotoMD5):
response = requests.get("http://localhost:9200/photodisplayer/photo/"+currentPhotoMD5)
jsonPhoto = json.loads(response.text)
return jsonPhoto
def add_note(currentPhotoMD5,a... | 1", data=query)
results = json.loads(response.text)
photoMD5=results["hits"]["hits"][0]["_id"]
return photoMD5
form = cgi.FieldStorage()
print("Content-type: text/html; charset=utf-8\n")
#I | nit
var = 0;
html = ""
#Get the action
action = form.getvalue("action")
idcurrent = form.getvalue("idcurrent")
idprevious = form.getvalue("previous")
#Switch "action"
if action=="ban":
ban(idcurrent)
html="ok"
if action=="next":
html=getRandom();
if action=="like":
add_note(idcurrent,1)
html="ok"
if action=="... |
yehialicious/pyrf | pyrf.py | Python | gpl-3.0 | 5,240 | 0.033206 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 distr... | along with this program. If not, see <http://www.gnu.org/licenses/>.
#rapidshare config
USER = ''
PASS = ''
USSL = False
import sys
import os
import urllib
import time
import re
import argparse
import md5
def say(message):
print message
def error(message):
print 'ERROR: ' + message
def progress(done, ind_size,... | ne * ind_size) / float(time.time() - starttime)) / 1024
sys.stdout.write('Progress: %.0f%%, Complete: %.2fKb, Speed: %.3fkb/s\r' % (total, progress, speed))
sys.stdout.flush()
def download(src, dest):
global starttime
starttime = time.time()
filename, headers = urllib.urlretrieve(src, dest, progress)
sys.stdout.... |
will-hart/django-citations | citations/migrations/0006_auto__add_field_reference_year.py | Python | mit | 2,201 | 0.008178 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Reference.year'
db.add_column(u'citations_reference', 'year',
self.gf(... | '}),
'slug': ('django.db.models.fields.CharField', [], {'unique': 'T | rue', 'max_length': '128'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'True'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'BK'", 'max_length': '3'}),
'url': ('django.db.models.fields.URLField', [], {'max_le... |
WmHHooper/aima-python | submissions/aardvark/myNN.py | Python | mit | 8,182 | 0.004033 | # References:
#
# https://www.tensorflow.org/guide/low_level_intro
#
# only needed for python 2.7
# from __future__ import absolute_import
# from __future__ import division
# from __future__ import print_function
import numpy as np
from numpy import array
from numpy import float32
# a complete input set on 7 bits
# ... | 0],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[0, 1, 0],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[0, 1, 0],
[1, 0, 0],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 0],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[0, 1, 0],
[0, 0, 1],
... | 0],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[0, 1, 0],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 1, 0],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[0, 1, 0],
[1, 0, 0],
[0, 1, 0],
... |
reclosedev/requests-cache | requests_cache/backends/gridfs.py | Python | bsd-2-clause | 3,582 | 0.002792 | """
.. image::
../_static/mongodb.png
`GridFS <https://docs.mongodb.com/manual/core/gridfs/>`_ is a specification for storing large files
(>16 MB) in MongoDB. See :py:mod:`~requests_cache.backends.mongodb` for more general info on MongoDB.
API Reference
^^^^^^^^^^^^^
.. automodsumm:: requests_cache.backends.gridf... | ad of creating a new one
kwargs: Additional keyword arguments for :py:class:`pymongo.MongoClient`
"""
def __init__(self, db_name: str, **kwargs):
super().__init__(**kwargs)
self.respo | nses = GridFSPickleDict(db_name, **kwargs)
self.redirects = MongoDict(
db_name, collection_name='redirects', connection=self.responses.connection, **kwargs
)
def remove_expired_responses(self, *args, **kwargs):
with self.responses._lock:
return super().remove_expired... |
Thraxis/pymedusa | sickbeard/name_parser/regexes.py | Python | gpl-3.0 | 23,532 | 0.0034 | # coding=utf-8
# Author: Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 ... | 01.Sourc | e.Quality.Etc-Group
r"""
^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator
s(eason[. _-])? # S01/Season 01
(?P<season_num>\d+)[. _-]* # S01 and optional separator
[. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-
... |
Gastove/blogric | new_post.py | Python | epl-1.0 | 3,746 | 0.004271 | import os
from time import localtime, strftime
import re
import sys
from fabric.api import local, lcd, settings, task
from fabric.utils import puts
from blog_config import INPUT_PATH, OUTPUT_PATH
SETTINGS_FILE = 'blog_config'
# Load paths
ABS_DIR_PATH = os.path.dirname(os.path.abspath(__file__))
ABS_SETTINGS_FILE = ... | s.path.isfile(candidate_path) else True
def _post_path():
""" Generate the c | orrect post path and make sure it exists """
abs_path = os.path.join(ABS_INPUT_PATH, 'posts')
if not os.path.exists(abs_path):
local("mkdir -p %s" % abs_path)
return abs_path
def _post_name(input_string):
""" Generate a valid post name """
def is_not_empty(entry): return True if entry el... |
shakamunyi/beam | sdks/python/apache_beam/utils/annotations_test.py | Python | apache-2.0 | 6,739 | 0.007716 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | heck_a | nnotation(warning=[w[1]], warning_size=1,
warning_type=FutureWarning,
fnc_name='fnc2_test_annotate_frequency',
annotation_type='experimental',
label_check_list=[])
# helper function
def check_annotation(... |
Distrotech/qtcreator | share/qtcreator/debugger/qttypes.py | Python | lgpl-2.1 | 90,089 | 0.003519 | ############################################################################
#
# Copyright (C) 2015 The Qt Company Ltd.
# Contact: http://www.qt.io/licensing
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the comm... | if displayFormat == AutomaticFormat or displayFormat == Latin1StringFormat:
d.putValue(p, Hex2EncodedLatin1, elided=elided)
elif displayFormat == SeparateLatin1StringFormat:
d.putValue(p, Hex2EncodedLatin1, elided=elided)
d.putField("editformat", DisplayLatin1String)
d.putField("ed... | elif displayFormat == Utf8StringFormat:
d.putValue(p, Hex2EncodedUtf8, elided=elided)
elif displayFormat == SeparateUtf8StringFormat:
d.putValue(p, Hex2EncodedUtf8, elided=elided)
d.putField("editformat", DisplayUtf8String)
d.putField("editvalue", d.encodeByteArray(value, limit=10000... |
alwaysrookie/superlists | superlists/settings.py | Python | apache-2.0 | 2,067 | 0 | """
Django settings for superlists project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... | 'lists',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMidd... | ngo.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'superlists.urls'
WSGI_APPLICATION = 'superlists.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path... |
DarioGT/OMS-PluginXML | org.modelsphere.sms/lib/jython-2.2.1/Lib/keyword.py | Python | gpl-3.0 | 2,162 | 0.004625 | #! /usr/bin/env python
"""Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
python Lib/keyword.py
"""
__all__ = ["iskeyword", "kw... | lass',
'continue',
'def',
'del',
'elif',
'else',
'except',
'exec',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'not',
'or',
... | 'return',
'try',
'while',
'yield',
#--end keywords--
]
kwdict = {}
for keyword in kwlist:
kwdict[keyword] = 1
iskeyword = kwdict.has_key
def main():
import sys, re
args = sys.argv[1:]
iptfile = args and args[0] or "Python/graminit.c"
if len(args... |
jefftc/changlab | Betsy/Betsy/modules/run_loocv_random_forest.py | Python | mit | 4,207 | 0.002615 | from Module import Abstract | Module
class Module(AbstractModule):
de | f __init__(self):
AbstractModule.__init__(self)
def run(
self, network, antecedents, out_attributes, user_options, num_cores,
outfile):
import os
import arrayio
from genomicode import filelib
from Betsy import bie3
from Betsy import rulebase
f... |
idiap/cbrec | data.py | Python | gpl-3.0 | 2,541 | 0.023219 | # Copyright (c) 2014 Idiap Research Institute, http://www.idiap.ch/
# Written by Nikolaos Pappas <[email protected]>,
#
# This file is part of CBRec.
#
# | CBRec is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# CBRec 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 CBRec. If not, see <ht... |
cbare/Etudes | python/quick_sort.py | Python | apache-2.0 | 572 | 0.001748 | import random
def pivot(items, a, b):
p = items[b]
i = a
for j in range(a,b):
| if items[j] <= p:
items[i], items[j] = items[j], items[i]
i += 1
items[i], items[b] = items[b], items[i]
return i
def quicksort(items, i, j):
"""
inplace quicksort
"""
if i < j:
p = pivot(items, i, j)
quicksort(items, i, p-1)
quicksort(items,... | sort(letters, 0, len(letters)-1)
print(''.join(letter for letter in letters))
|
pgiri/asyncoro | py3/asyncoro/discoronode.py | Python | mit | 55,226 | 0.00344 | #!/usr/bin/python3
"""This file is part of asyncoro; see http://asyncoro.sourceforge.net for
details.
This program can be used to start discoro server processes so discoro scheduler
(see 'discoro.py') can send computations to these server processes for executing
distributed communicating proceses (coroutines). All co... |
See 'discoro_client*.py' files for example use cases.
"""
__author__ = "Giridhar Pemmasani ([email protected])"
__copyright | __ = "Copyright (c) 2014 Giridhar Pemmasani"
__license__ = "MIT"
__url__ = "http://asyncoro.sourceforge.net"
def _discoro_server_coro_proc():
# coroutine
"""Server process receives computations and runs coroutines for it.
"""
import os
import shutil
import traceback
import sys
import ... |
hasgeek/lastuser | migrations/versions/07f975f81f03_remove_team_domain.py | Python | bsd-2-clause | 655 | 0.001527 | # -*- coding: utf-8 -*-
"""Remove team domain
Revision ID: 07f975f81f03
Revises: 4e206c5ddabd
Create Date: 2017-08-04 15:12:11.992856
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers | , used by Alembic.
revision = '07f975f81f03'
down_revision = '4e206c5ddabd'
branch_labels = None
depends_on = None
def upgrade():
op.drop_index('ix_team_domain', table_name='team')
op.drop_column('team', 'domain')
def downgrade():
op.add_column(
'team',
sa.Column('domain', sa.VARCHAR(len... | ,
)
op.create_index('ix_team_domain', 'team', ['domain'], unique=False)
|
axinging/chromium-crosswalk | tools/perf/measurements/skpicture_printer_unittest.py | Python | bsd-3-clause | 1,305 | 0.004598 | # Copyright 2014 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 shutil
import tempfile
from telemetry import decorators
from telemetry.testing import options_for_unittests
from telemetry.testing import page_test_t... | outdir)
@decorators.Disabled('android')
def testSkpicturePrinter(self):
| ps = self.CreateStorySetFromFileInUnittestDataDir('blank.html')
measurement = skpicture_printer.SkpicturePrinter(self._skp_outdir)
results = self.RunMeasurement(measurement, ps, options=self._options)
# Picture printing is not supported on all platforms.
if results.failures:
assert 'not suppo... |
janekg89/flutype_webapp | flutype/gal-file.py | Python | lgpl-3.0 | 5,034 | 0.0147 | import pandas as pd
import os
# -*- coding: utf-8 -*-
from flutype.data_management.fill_master import Master
import numpy as np
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
def extract_peptide_batch(ma):
gal_lig_fix = ma.read_gal_ligand("170... | # print_full(peptide_batch)
#fp = os.path.join(ma.collections_path,"170725_N13","peptides_batch.csv")
# peptide_batch.to_csv(fp)
ma_path_standard = "../master/"
ma_standard = Master(ma_path_standard)
gal_lig_fix = gal_reformat(ma)
#subset = peptide_batches_not_in_master(ma_standard,gal_lig_fix)... | l_lig_fix)
gal_lig_fix = gal_lig_fix.reset_index(drop=True)
fp = os.path.join(ma.collections_path,"170725_P7","lig_fix_012.txt")
gal_lig_fix.to_csv(fp, sep='\t',index=True , index_label="ID")
#gal_lig_fix = three_viruses_gal(gal_lig_fix)
gal_lig_fix["Name"] = "Ach1"
fp2 = os.path.join(ma.collec... |
LamCiuLoeng/vat | vatsystem/util/common.py | Python | mit | 7,482 | 0.014969 | # -*- coding: utf-8 -*-
import datetime
from datetime import date, datetime as dt
from email import Encoders
from email.header import Header
import os
import pickle
import random
import smtplib
import traceback
import calendar
from decimal import Decimal
from email.MIMEBase import MIMEBase
from email.MIMEMultipart im... | n(f.readlines())
f.close()
return content
def defaultIfNone(blackList=[None, ], default=""):
def returnFun(value):
defaultValue=default() if callable(default) else default
if value in blackList:
return defaultValue
else:
try:
return str(v | alue)
except:
try:
return repr(value)
except:
pass
return defaultValue
return returnFun
def _get_params_from_args_and_obj(keys, obj, ** args):
params = {}
for i in keys:
if type(i) == dict:
par... |
Valloric/YouCompleteMe | python/ycm/tests/mock_utils.py | Python | gpl-3.0 | 4,496 | 0.013568 | # Copyright (C) 2017 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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) ... | ure:
"""A fake version of a future response object, just about suitable for
mocking a server response as generated by PostDataToHandlerAsync.
Not usually used directly. See MockAsyncServerResponse* methods"""
def __init__( self, done, response = None, exception = None ):
self._done = done
if not done:
... | ._done
def result( self ):
return self._result
def MockAsyncServerResponseDone( response ):
"""Return a MessagePoll containing a fake future object that is complete with
the supplied response message. Suitable for mocking a response future within
a client request. For example:
with MockVimBuffers( [ ... |
callowayproject/django-tweeter | django_oauth_twitter/__init__.py | Python | mit | 149 | 0 | ACCESS_KEY = 'tw | itter | _access_token'
REQUEST_KEY = 'twitter_request_token'
SUCCESS_URL_KEY = 'twitter_success_url'
USERINFO_KEY = 'twitter_user_info'
|
z0rr0/eshop | shop/sales/migrations/0001_initial.py | Python | mit | 4,179 | 0.004786 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-13 15:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0001_initial'),
]
o... | ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.Customer', verbose_name='customer')),
],
options={
'verbose_name': 'Order',
'ordering': | ['-modified', '-created'],
'verbose_name_plural': 'Orders',
},
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nam... |
georgemarshall/django | django/db/backends/mysql/compiler.py | Python | bsd-3-clause | 1,599 | 0.001251 | from django.db.models.sql import compiler
class SQLCompiler(compiler.SQLCompiler):
def as_subquery_condition(self, alias, columns, compiler):
qn = compiler.quote_name_unless_alias
qn2 = self.connection.ops.quote_name
sql, params = self.as_sql()
return '(%s) IN (%s)' % (', '.join('%... | SQLCompiler):
pass
class SQLDeleteCompiler(compiler.SQLDel | eteCompiler, SQLCompiler):
def as_sql(self):
if self.connection.features.update_can_self_select or self.single_alias:
return super().as_sql()
# MySQL and MariaDB < 10.3.2 doesn't support deletion with a subquery
# which is what the default implementation of SQLDeleteCompiler uses... |
catapult-project/catapult | tracing/tracing_build/vulcanize_histograms_viewer.py | Python | bsd-3-clause | 912 | 0.006579 | # Copyright 2017 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 tracing_project
from py_vulcanize import generate
from tracing_build import render_histograms_viewer
def VulcanizeHistogramsViewer():
"""Vulcaniz... | ld.histograms_viewer'])
return generate.GenerateStandaloneHTMLAsString(load_sequence)
def VulcanizeAndRenderHistogramsViewer(
histogram_dicts, output_stream, reset_results=False):
render_histograms_viewer.RenderHistogramsViewer(
histogram_dicts, output_stream, reset_ | results,
VulcanizeHistogramsViewer())
|
rockwolf/python | cece/app/views.py | Python | bsd-3-clause | 4,840 | 0.022727 | """
See LICENSE file for copyright and license details.
"""
from app import app
from flask import render_template, flash, redirect
#from app.forms import LoginForm
from app.modules.constant import *
@app.route("/")
@app.route("/index")
@app.route("/index/")
@app.route("/<app_profile>/index")
@app.route... | eturn render_template("trading_journal.html",
title = 'Trading Journal',
user = user,
app_profile = app_profile.lower())
else:
return render_template("404.html",
title = '404')
@app.route("/contact")
@app.route("/contact/")
@app.route("/<app_pro... | t(app_profile = AppProfile.PERSONAL):
"""
Address book.
"""
# Try to sync this with abook? Can abook export them?
return('TBD');
@app.route("/task")
@app.route("/task/")
@app.route("/<app_profile>/task")
@app.route("/<app_profile>/task/")
def task(app_profile = AppProfile.PERSONAL):
... |
hip-odoo/odoo | addons/l10n_nl/__init__.py | Python | agpl-3.0 | 158 | 0 | # | -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2016 Onestein (<htt | p://www.onestein.eu>).
|
rvswift/BlastNFilter | build/lib/BlastNFilter/Utilities/Run.py | Python | bsd-3-clause | 827 | 0.001209 | __author__ = 'robswift'
__project__ = 'blastnfilter'
import os
from BlastNFilter.PreRelease import ParsePreRelease
from BlastNF | ilter.Blast import ParseAlignment
import OutPut
def run(options):
non_polymer = options.non_polymer
polymer = options.polymer
out = options.o | ut
blast_dir = os.path.abspath(options.blast_db)
pdb_db = os.path.join(blast_dir, 'pdb_db')
fasta = os.path.join(blast_dir, 'pdb_seqres.txt')
target_list = ParsePreRelease.add_ligands(non_polymer)
target_list = ParsePreRelease.add_sequences(polymer, target_list)
#new = [x for x in target_list i... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractBijinsans.py | Python | bsd-3-clause | 387 | 0.023256 | def extractB | ijinsans(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Benkyou no Kamisama wa Hitomishiri' | in item['tags']:
return buildReleaseMessageWithType(item, 'Benkyou no Kamisama wa Hitomishiri', vol, chp, frag=frag, postfix=postfix)
return False
|
arcticshores/kivy | kivy/__init__.py | Python | mit | 14,620 | 0.000547 | '''
Kivy framework
==============
Kivy is an open source library for developing multi-touch applications. It is
completely cross-platform (Linux/OSX/Win) and released under the terms of the
MIT License.
It comes with native support for many multi-touch input devices, a growing
library of multi-touch aware widgets and... | kivy_options[option] = environ[key].split(',')
else:
kivy_options[option] = environ[key].lower() in \
( | 'true', '1', 'yes', 'yup')
except Exception:
Logger.warning('Core: Wrong value for %s environment key' % key)
Logger.exception('')
# Extract all needed path in kivy
#: Kivy directory
kivy_base_dir = dirname(sys.modules[__name__].__file__)
#: Kivy modules directory
kivy_modules_dir = en... |
derekjchow/models | research/object_detection/utils/config_util.py | Python | apache-2.0 | 36,470 | 0.006581 | # Copyright 2017 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... | model_config.ssd.image_resizer
raise ValueError("Unknown model type: {}".format(meta_architecture))
def get_spatial_image_size(image_resizer_config):
"""Returns expected spatial size of the output image from a given config.
Args:
image_resizer_config: An image_resizer_pb2.ImageResizer.
Returns:
A l... | of two integers of the form [height, width]. `height` and `width` are
set -1 if they cannot be determined during graph construction.
Raises:
ValueError: If the model type is not recognized.
"""
if image_resizer_config.HasField("fixed_shape_resizer"):
return [
image_resizer_config.fixed_shap... |
steve-ord/daliuge | daliuge-engine/dlg/manager/__init__.py | Python | lgpl-2.1 | 1,112 | 0 | #
# ICRAR - International Centre for Radio Astronomy Research
# (c) UWA - The University of Western Australia, 2015
# Copyright by UWA (in the framework of the ICRAR)
# All rights reserved
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser G... | ption) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warrant | y of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite ... |
sagittarian/personal-sort | sort.py | Python | mit | 4,539 | 0.003745 | #!/usr/bin/env python3
'''A simple implementation of a sorting algorithm, meant to allow
people to manually rank a list of items using whatever subjective or
objective criteria they want.
This program can be called as a script and used interactively. You
can provide the list of things to sort as command line argument... | srcidx > dstidx:
seq[srcidx], seq[srcidx - 1] = seq[srcidx - 1], seq[srcidx]
srcidx -= 1
i = 1
while i < len(seq):
lower = 0; upper = i
while lower < upper:
j = (upper + lower) // 2
key1, key2 = keyfunc(seq[i]), keyfunc(seq[j])
if key... | XX this is not stable
i += 1
break
if key1 < key2:
upper = j
else: # >
lower = j + 1
else:
mv(i, upper)
i += 1
class SortableWithHeuristic:
def __init__(self, val, heur):
self.val = val
... |
mldbai/mldb | testing/MLDB-1594-aggregator-empty-row.py | Python | apache-2.0 | 1,755 | 0.005698 | #
# MLDB-1594-aggregator-empty-row.py
# mldb.ai inc, 2016
# this file is part of mldb. copyright 2016 mldb.ai inc. all rights reserved.
#
import unittest
from mldb import mldb, MldbUnitTest, ResponseException
class Mldb1594(MldbUnitTest):
def test_simple(self):
res1 = mldb.query("select {}")
r... | mldb.query("""
select sum({*}) as *
named 'pwet'
from (
SELECT tokenize(lower(txt), {splitChars: ' ,.!;:"?', minTokenLength: 2}) as *
from toy
whe | re rowName() != 'rowB'
)
"""),
expected)
# passing the empty row (rowB) to sum
self.assertTableResultEquals(
mldb.query("""
select sum({*}) as *
named 'pwet'
from (
SELECT tokenize(lower(txt), ... |
sysadminmatmoz/odoo-clearcorp | TODO-7.0/sneldev_magento/wizard/sneldev_magento_categories_import.py | Python | agpl-3.0 | 1,660 | 0.00241 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | your option) any later version.
#
# This program 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 Affero General Public Lic | ense for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import pooler
import os
from export_tools import *
from osv... |
pirata-cat/agora-ciudadana | actstream/actions.py | Python | agpl-3.0 | 3,984 | 0.003012 |
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from actstream.exceptions import check_actionable_model
def follow(user, obj, send_action=True, actor_only=False, request=None):
"""
Creates a relationship al... | t geolocate_ip
action.send(user, verb=_('started following'), target=obj,
ipaddr=request.META.get('REMOTE_ADDR'),
geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))
e | lse:
action.send(user, verb=_('started following'), target=obj)
return follow
def unfollow(user, obj, send_action=False, request=None):
"""
Removes a "follow" relationship.
Set ``send_action`` to ``True`` (``False is default) to also send a
``<user> stopped following <object>`` action... |
davidegalletti/koa-proof-of-concept | kag/application/urls.py | Python | agpl-3.0 | 305 | 0.009836 | from django.conf.urls import patterns, url
from application import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<application_id>\d+)/$', views.detail, name='detail'),
url(r'^klogin/(?P<user | name>\w+)/(?P<passwo | rd>\w+)/$', views.klogin, name='klogin'),
)
|
MiltosD/CEF-ELRC | metashare/storage/models.py | Python | bsd-3-clause | 28,959 | 0.007321 | from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.db import models
# pylint: disable-msg=E0611
from hashlib import md5
from metashare.settings import LOG_HANDLER
from metashare import settings
from os import mkdir
from os.path import exists
import os.path
from uuid import uuid1... | = INGESTED
published = property(_get_published, _set_published)
publication_status = models.CharField(default=INTERNAL, max_length=1, choices=STATU | S_CHOICES,
help_text="Generalized publication status flag for this " \
"storage object instance.")
source_node = models.CharField(blank=True, null=True, max_length=32, editable=False,
help_text="(Read-only) id of source node from which the resource " \
"originally stems as ... |
gnmerritt/casino | casino/handlers.py | Python | mit | 1,275 | 0.000784 | from twisted.internet import reactor
from twisted.python import log
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
agent = Agent(reactor)
class LoginHandler(object):
def __init__(self, api_url):
self.api_url = api_url
def handle(self, handler, args):
game, ... | try:
handler.parent.login_success( | game, bot)
except:
log.err()
elif response.code == 401:
failed(response, "Invalid bot key")
elif response.code == 404:
failed(response, "Invalid game")
elif response.code == 410:
failed(response, "Gam... |
pybursa/homeworks | a_karnauh/hw1/6.py | Python | gpl-2.0 | 354 | 0.04644 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from types import *
def typer(x,y):
if type(x) is StringType or type(y) is StringType :
print u'получена строка'
else:
if x > y:
print u'б | ольше'
elif x < y:
print u'меньше'
else:
print u'равно'
typer("12", 4)
typer("12", | "4")
typer(12, 4)
typer(4, 45)
typer(4, 4) |
snowfed/Chessology | run_locally.py | Python | gpl-3.0 | 92 | 0 | from bottle import run
from bottle_app i | mport application
run(host='local | host', port=8080)
|
andaluri/rootio_web | alembic/versions/1cb4253a8bc6_station_analytics_up.py | Python | agpl-3.0 | 472 | 0.006356 | """station | _analytics_update
Revision ID: 1cb4253a8bc6
Revises: 2972360b9a6f
Create Date: 2014-04-27 13:01:26.309272
"""
# revision identifiers, used by Alembic.
revision = '1cb4253a8bc6'
down_revision = '2972360b9 | a6f'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('radio_station', sa.Column('analytic_update_frequency', sa.Float(), nullable=True))
def downgrade():
op.drop_column('radio_station', 'analytic_update_frequency')
|
rizsotto/Ente | setup.py | Python | bsd-3-clause | 383 | 0 | #!/usr/bin/env python
# -*- coding: | utf-8 -*-
from setuptools import setup
setup(
name="Ente",
version="0.1",
description="place finder on commoncrawl dataset",
author="László Nagy",
author_email="[email protected]",
license='LICENSE',
url='https://github.com/rizsotto/Ente',
long_description=open('README.md').read( | ),
scripts=['bin/ente']
)
|
moble/scri | scri/LVC/__init__.py | Python | mit | 242 | 0.004132 | # Copyright (c) 2 | 018, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/scri/blob/master/LICENSE>
"""Submodule for operating on LVC-format wa | veform files"""
from .. import __version__
from .file_io import read_from_h5
|
shaggytwodope/qutebrowser | qutebrowser/misc/__init__.py | Python | gpl-3.0 | 820 | 0 | # vim: | ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser 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... | rsion 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 shou... |
dwgill/dspell | dspell/corpus.py | Python | mit | 1,947 | 0.007704 | # Copyright (c) 2013 Daniel Gill
#
# 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,
# in | cluding without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# su | bject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTAB... |
wichovw/tca-gt | server/tca/cellaut.py | Python | mit | 2,703 | 0.009989 | # Based on cage v1.1.4
# http://www.alcyone.com/software/cage/
# Copyright (C) 2002-20 | 06 Erik Max Francis <[email protected]>
# GPL License
class Topology:
"""Encaptulation of the | shape and dimentionality of a cellular automata"""
def get(self, address):
raise NotImplementedError
def set(self, address, state):
raise NotImplementedError
def normalize(self, address):
raise NotImplementedError
class Neighborhood:
"""Abstrac... |
globocom/database-as-a-service | dbaas/physical/tests/test_disk_offering.py | Python | bsd-3-clause | 9,097 | 0.00033 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
from django.core.cache import cache
from django.test import TestCase
from django.contrib import admin
from physical.tests.factory import DiskOfferingFactory, EnvironmentFactory
from physical.errors import NoDiskOfferingGreat... | )
disk_offering = DiskOffering.objects.get(name='disk_offering_small')
self.assertEqual(disk_offe | ring.size_gb(), 0.5)
self.assertEqual(disk_offering.size_kb, 524288)
def test_editing_gb_to_kb(self):
disk_factory = DiskOfferingFactory()
disk_offering = DiskOffering.objects.get(pk=disk_factory.pk)
self.assertEqual(disk_offering.size_gb(), 1)
self.assertEqual(disk_offering... |
rapodaca/Terasology | blender_addons/io_mesh_terasology/__init__.py | Python | apache-2.0 | 3,098 | 0.037121 | #!BPY
"""
Name: 'TerasologyBlockShapeExport'
Blender: 260
Group: 'Export'
Tooltip: 'Export a Terasology Block Shape'
"""
bl_info = {
"name": "Terasology Block Shape Export",
"description": "Exporter for producing Terasology Block Shape files",
"author": "Immortius",
"version": (1, 1),
"blender": (2, ... | operty, BoolProperty
class ExportBlockShape(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
bl_idname = "export_mesh.terasology_block_shape"
bl_label = "Export Terasology Block Shape"
filename_ext = ".groovy"
filter_glob = StringPrope | rty(default="*.groovy", options={'HIDDEN'})
apply_modifiers = BoolProperty(
name="Apply Modifiers",
description="Apply Modifiers to the exported mesh",
default=True)
for_embed = BoolProperty(
name="For Embed in Jar",
description="Adds the default package to the groovy file",
default=False)
... |
davidbrazdil/nacl | toolchain_build/toolchain_build.py | Python | bsd-3-clause | 39,585 | 0.004825 | #!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Recipes for NativeClient toolchain packages.
The real entry plumbing is in toolchain_main.py.
"""
import collections
import f... | mand.path.join('%(abs_top_srcdir)s',
'..', 'third_party',
tar_file)],
| cwd='%(output)s'),
],
}
patch_packages = []
patch_commands = []
for package, info in GIT_REVISIONS.iteritems():
sources[package] = {
'type': 'source',
'commands': command.SyncGitRepoCmds(GitUrl(package), '%(output)s',
... |
CoderHito/wx_demo | app/util/component_access_token.py | Python | mit | 772 | 0.001319 | impo | rt redis
from app.config import get_config_obj
from app.util.httputil import Http_util
class Component_access_token():
def __init__(self):
self.component_appid = get_config_obj().component_appid
self.component_app | secret = get_config_obj().component_secret
self.r = redis.Redis(host='localhost', port=6379, db=0)
def get_component_verify_ticket(self):
# TODO 读取保存的ticket
component_verify_ticket = self.r.get('component_verify_ticket')
return component_verify_ticket
def get_commponent_access_... |
rwl/PyCIM | CIM15/CDPSM/Balanced/IEC61970/Wires/EnergyConsumer.py | Python | mit | 4,290 | 0.005128 | # 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... | roup fixed active po | wer. Load sign convention is used, i.e. positive sign means flow out from a node.
self.pfixedPct = pfixedPct
#: Fixed reactive power as per cent of load group fixed reactive power. Load sign convention is used, i.e. positive sign means flow out from a node.
self.qfixedPct = qfixedPct
#... |
mansweet/GaussianLDA | FastGaussianLDA2.py | Python | apache-2.0 | 27,002 | 0.004037 | from __future__ import division
import random
import time
from collections import defaultdict, Counter
import gensim
import numpy as np
from numpy import log, pi
from scipy import linalg
from scipy.special import gammaln
import copy
from sklearn.cluster import KMeans
from numba import jit
import cholesky
__author__... | useable_vocab = 0
unusable_vocab = 0
self.word_vec_size = self.wvmodel.vector_size
for word in self.vocab:
try:
self.word_vecs[word] = self.wvmodel[word]
useable_vocab += 1
except KeyError:
... | re {0} words that could be converted to word vectors in your corpus \n" \
"There are {1} words that could NOT be converted to word vectors".format(useable_vocab,
unusable_vocab)
# ==============================... |
GreenDelta/olca-updates | update-src/001_db_schema_update_v6_f0..b7/script.py | Python | mpl-2.0 | 1,555 | 0.036656 | import org.openlca.core.database.CategoryDao as CategoryDao
dbUtil.createTable("tbl_dq_systems",
"CREATE TABLE tbl_dq_systems ( "
+ "id BIGINT NOT NULL, "
+ "name VARCHAR(255), "
+ "ref_id VARCHAR(36), "
+ "version BIGINT, "
+ "last_change BIGINT, "
+ "f_category BIGINT, "
+ "f_source BIG... | HAR(255), "
+ "position INTEGER NOT NULL, "
+ "f_dq_system BIGINT, "
+ "PRIMARY KEY (id)) ")
dbUtil.createTable(" | tbl_dq_scores", "CREATE TABLE tbl_dq_scores ( "
+ "id BIGINT NOT NULL, "
+ "position INTEGER NOT NULL, "
+ "description CLOB(64 K), "
+ "label VARCHAR(255), "
+ "uncertainty DOUBLE default 0, "
+ "f_dq_indicator BIGINT, "
+ "PRIMARY KEY (id)) ")
dbUtil.createColumn("tbl_processes", "dq_entry", "dq_entr... |
ryanmcgrath/drinkkitcom | urls.py | Python | mit | 1,223 | 0.023712 | from django.conf.urls.defaults import *
from django.contrib import admin
# Set up the admin shit
admin.autodiscover()
urlpatterns = patterns('',
(r'^knux/', include(admin.site.urls)),
# Viewing and adding tips/locations
(r'^locations/add/$', 'drinkkit.redditors.views.add_location'),
(r'^locations/search/$', '... | inkkit.redditors.views.checkin_location'),
(r'^locations/(?P<location_id>[a-zA-Z0-9_.-]+)/$', 'drinkkit.redditors.views.view_location'),
# Query and see who's getting into what
(r'^redditor/(?P<redditor_name>[a-zA-Z0-9_.-]+)/$', 'drinkkit.redditors.views.view_redditor'),
# Registration
(r'^register/$', 'drinkki... | .logout_then_login'),
(r'^auth/$', 'django.contrib.auth.views.login'),
(r'^/*', 'drinkkit.redditors.views.home'),
)
|
ActiveState/code | recipes/Python/496703_importonce/recipe-496703.py | Python | mit | 1,231 | 0.02762 | def import_once(modulenames, silent=1):
## import_once
## Fedmich Last modified: 3:38 PM 5/15/2006
## version 1.1
## Usage:
## import_once('os')
## import_once( ["os", 'sys'] )
if type(modulenames) is list:
pass
elif type(modulenames) is tuple:
pass
else:
mod... | ulenam | e
return (imported == len(modulenames) ) #return true if every modules are successfuly imported
print import_once( ("os", "sys") )
import_once( "sys")
import_once("oyster")
import_once("psyco", silent=0) #silent is used for debugging...
print os
print sys
print os.path.basename(r"c:\WINNT")
|
dhaase-de/dh-python-dh | dh/image/pipeline.py | Python | mit | 13,563 | 0.007299 | """
Image pipeline viewer.
Note: currently under heavy construction.
"""
import tkinter
import tkinter.ttk
import dh.gui.tk
import dh.image
##
## basic classes
##
class Viewer():
def __init__(self):
self.images = []
self.n = None
self.pipeline = Pipeline()
self.pipeline.add("c... | .viewer.applyPipeline()
self.imageCanvas.setImage(I)
self.updateStatusBar("{shape}, {dtype}, {time}ms".format(
shape=I.shape,
dtype=I.dtype,
time=dh.utils.around(t() * 1 | 000.0),
))
def updateStatusBar(self, text):
self.statusBar.setText(text)
##
## pipeline framework
##
class Pipeline():
def __init__(self):
# nodes
self.nodes = []
self.add("core.source")
def __call__(self, I):
J = I.copy()
for node in self.nodes:... |
Dob3r/python_seleniumwebdriver | Tests/test_Browser_logs.py | Python | apache-2.0 | 819 | 0.004884 | from termcolor import colored
def test_Browser_logs(app):
wd = app.wd
sidebar = wd.find_element_by_xpath("//td[@id='sidebar']")
sidebar.find_element_by_xpath(".//span[normalize-space(.)='Catalog']").click()
wd.find_element_by_xpath("//i[@class='fa fa-folder']/../a").click()
products_qty = len(wd.f... | tains(@name,'products')]/../..")))
wd.get_log("browser")
for i in range(1, products_qty + 1):
wd.find_element_by_xpath("//inp | ut[contains(@name,'products[%s]')]/../..//a[not(contains(@title,'Edit'))]" % i).click()
log = wd.get_log("browser")
if len(log) != 0:
print(colored("WARNING! LOG EXIST(S)", "red"))
for entry in log:
print(entry)
wd.find_element_by_name("cancel").click()
... |
obulpathi/cdn1 | cdn/manager/default/v1.py | Python | apache-2.0 | 1,291 | 0 | # C | opyright (c) 2014 Rackspace, 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 writi... | # implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from cdn.manager import base
JSON_HOME = {
"resources": {
"rel/cdn": {
"href-template": "services{?marker,limit}",
"href-vars": {
"marker": "param/marke... |
neocogent/electrum | electrum/plugins/digitalbitbox/digitalbitbox.py | Python | mit | 32,370 | 0.004541 | # ----------------------------------------------------------------------------------
# Electrum plugin for the Digital Bitbox hardware wallet by Shift Devices AG
# digitalbitbox.com
#
import base64
import binascii
import hashlib
import hmac
import json
import math
import os
import re
import struct
import sys
import ti... | msg = _("Password must have at least 4 characters.") \
+ "\n\n" + _("Enter password:")
elif len(password) > 64:
msg = _("Password must have less than 64 characters.") \
+ "\n\n" + _("Enter password:")
else:
return passw... | password = self.handler.get_passphrase(msg, False)
if password is None:
return False
if len(password) < 4:
msg = _("Password must have at least 4 characters.") + \
"\n\n" + _("Enter password:")
elif len(password) > 64:
... |
Arcanewinds/FDL-LunarResources | DataPreparation/LOLA_DEM/img_split.py | Python | gpl-3.0 | 3,075 | 0.014634 | #Written by Timothy Seabrook
#[email protected]
#This script is used to split the LOLA_DEM South Pole Large Tiles into smaller tiles f | or ingestion.
import glob, os
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from osgeo import gdal
full_size = [30400, 30400]
p_size = [3800, 3800]
cut_size = [32,32]
stride = np.divide(cut_size, 2)
thisDir = os.path.dirname(os.path.abspath(__file__))
rootDir = os.pa... | os.path.join(DEMDir, 'Large_Tiles')
DEMSmallDir = os.path.join(DEMDir, 'Small_Tiles')
base_filename = "hs-45-45_lola20sp"
#https://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio
v_pieces = np.floor_divide(full_size[0], p_size[0]) #Number of vertical divisions for ... |
quaddra/engage | install_extension.py | Python | apache-2.0 | 7,602 | 0.002894 | #!/usr/bin/env python
"""This utility installs an engage extension into a deployment home.
"""
import os
import os.path
import sys
from optparse import OptionParser
import shutil
import re
import logging
logger = logging.getLogger(__name__)
# enable importing from the python_pkg sub-directory
base_src_dir=os.path.ab... | _version = vf.read().rstrip()
ext = EngageExtension(extension_path, extension_name,
extension_version, options.update)
return (ext, options)
def main(argv=sys.argv[1:]):
(ext, opts) = process_args(argv)
ext.install(dist_root, dry_run=opts.dry_run)
return 0
i... | s] %(message)s")
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
#console_handler.setFormatter(formatter)
root_logger.addHandler(console_handler)
logger.setLevel(logging.INFO)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.