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 |
|---|---|---|---|---|---|---|---|---|
robscetury/gibson | lib/netaddr/eui/__init__.py | Python | gpl-3.0 | 21,545 | 0.0013 | #-----------------------------------------------------------------------------
# Copyright (c) 2008-2010, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
"""
Classes and functi... | :
"""@return: integer value of this identifier"""
return self._value
def __long__(self):
"""@return: integer value of this identifier"""
return self._val | ue
def __oct__(self):
"""@return: octal string representation of this identifier."""
# Python 2.x only.
if self._value == 0:
return '0'
return '0%o' % self._value
def __hex__(self):
"""@return: hexadecimal string representation of this identifier."""
... |
areedtomlinson/django-crud-filters | CRUDFilters/models.py | Python | mit | 5,473 | 0.005116 | from django.db import models
from .managers import CRUDManager, CRUDException
class CRUDFilterModel(models.Model):
class Meta:
abstract = True
@classmethod
def verify_user_has_role(cls, user, role, request):
"""
Call user-defined auth function to determine if this user can | use this role.
"""
if role in ['anonymous', 'authenticated']:
return True
elif role == "admin":
return user.is_superuser
if CRUDManager.auth_function is None:
raise CRUDException("You must define an auth_function for CRUDManagerMixin", 500)
t... | e CRUDException("Your auth_function in CRUDManager threw an exception: " + str(exc), 500)
if not value:
raise CRUDException("This user is not authorized to use this role", 403)
return True
@classmethod
def role_can_perform_operation_with_filter(cls, role, operation, filter_str):
... |
michae1/django-geonames | geonames/management/commands/download_geonames.py | Python | bsd-3-clause | 2,894 | 0.004147 | from optparse import make_option
import datetime, os, sys
import urllib, urllib2, urlparse
import re
from django.db import connection, models
from django.core.management import call_command, sql, color
from django.core.management.base import NoArgsCommand
from django.conf import settings
from compress_geonames import ... | ize of files
web_file_size = web_file.info().getheaders("Content-Length")[0]
if os.path.isfile(filepath):
existing_file = open(filepath, "r")
existing_file_size = len(existing_file.read())
print existing_file | _size, web_file_size
if existing_file_size == web_file_size:
existing_file_size.close()
return
local_file = open(filepath, 'w')
local_file.write(web_file.read())
web_file.close()
local_file.close()
class Command(NoArgsCommand):
help = 'Download all data files from g... |
seongahjo/Mosaicer | mosaicer/file_util.py | Python | mit | 1,185 | 0.001688 | import os
import unicodedata
from keras.applications import InceptionV3, VGG16, MobileNet
image_type = ['.jpg']
def check_img(file_name):
"""To check image
Args:
file_name : file name
Returns:
if this file is image
"""
file_name, file_ext = os.path.splitext(file_name)
if fil... | ype from file name
Args:
file_name : face img name
delimiter : delimiter
Returns:
type: type of face
"""
file_name, ext = os.path.splitext(file_name)
type = file_name |
if delimiter in type:
type = type.split(delimiter)[0]
type = unicodedata.normalize('NFC', type)
return type
def make_model(model, image_size):
if model == "inceptionv3":
base_model = InceptionV3(include_top=False, input_shape=image_size + (3,))
elif model == "vgg16" or model is No... |
mapa17/Eruliaf | nodes/Node.py | Python | gpl-3.0 | 1,182 | 0.005076 | '''
Created on Feb 2, 2012
@author: Pasieka Manuel , mapa17@posgrado.upv.es
Copyright (C) 2012 Pasieka Manuel , mapa17@posgrado.upv.es
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 Foundatio... | Id()
def __str__(self, *args, **kwargs):
| return "Node (0)".format(self.nid)
def getNodeId(self):
return self.nid
|
flyapen/UgFlu | flumotion/component/misc/httpserver/cachedprovider.py | Python | gpl-2.0 | 42,643 | 0.000915 | # -*- Mode: Python; test-case-name: -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
| # This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fitness for a particular purpose.
# See "LICENSE.GPL" in... | or holding a valid Flumotion Advanced
# Streaming Server license may use this file in accordance with the
# Flumotion Advanced Streaming Server Commercial License Agreement.
# See "LICENSE.Flumotion" in the source distribution for more information.
# Headers in this file shall remain intact.
import errno
import os
i... |
hfp/tensorflow-xsmm | tensorflow/contrib/distributions/python/ops/autoregressive.py | Python | apache-2.0 | 8,448 | 0.00367 | # 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... | lt constructable.
num_steps: Number of times `distribution_fn` is composed from samples,
e.g., `num_steps=2` implies
`distribution_fn(distribution_fn(sample0).sample(n)).sample()`.
valida | te_args: Python `bool`. Whether to validate input with asserts.
If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
(e.g., mean, mode, variance) use the value "`NaN`" to indi... |
ioram7/keystone-federado-pgid2013 | tests/test_cert_setup.py | Python | apache-2.0 | 3,259 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | rtfile='invalid')
user = {
'id': 'fake1',
| 'name': 'fake1',
'password': 'fake1',
'domain_id': DEFAULT_DOMAIN_ID
}
body_dict = {
'passwordCredentials': {
'userId': user['id'],
'password': user['password'],
},
}
self.identity_api.create_user(... |
HybridF5/tempest_debug | tempest/api/identity/admin/v3/test_domains_negative.py | Python | apache-2.0 | 3,018 | 0 | # Copyright 2015 Red Hat Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.identi... | stJSON(base.BaseIdentityV3AdminTest):
_interface = 'json'
@test.attr(type=['negative', 'gate'])
@test.idempotent_id('1f3fbff5-4e44-400d-9ca1-d953f05f609b')
def test_delete_active_domain(self):
d_name = data_utils.rand_name('domain')
d_desc = data_utils.rand_name('domain-desc')
d... |
samuelmaudo/yepes | yepes/contrib/newsletters/abstract_models.py | Python | bsd-3-clause | 24,266 | 0.000206 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator
from django.db import models
from django.db.models import F, Q
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
f... | lf.message_id is not None):
self.newsletter_id = self.message.newsletter_id
super(AbstractDelivery, self).save(**kwargs)
# PROPERTIES
@described_property(_('Response Time'))
def response_time(self):
if self.process_date is None or self.open_date is None:
return ... | ompatible
class AbstractDomain(models.Model):
name = fields.CharField(
editable=False,
max_length=63,
unique=True,
validators=[RegexValidator(DOMAIN_RE)],
verbose_name=_('Domain'))
is_trusted = fields.BooleanField(
default=False,
... |
SimenB/thefuck | thefuck/rules/git_checkout.py | Python | mit | 1,635 | 0.001835 | import re
import subprocess
from thefuck import utils
from thefuck.utils import replace_argument
from thefuck.specific.git import git_support
from thefuck.shells import shell
@git_support
def match(command):
return ('did not match any file(s) known to git' in command.output
and "Did you forget to 'git... | _branches(),
fallback_to_first=False)
new_commands = []
if closest_branch:
new_commands.append(replace_argument(command.script, missing_file, closest_branch))
if command.script_parts[1] == 'checkout':
new_commands.append(replace_argument(command.scrip... | ))
return new_commands
|
kunz07/fyp2017 | GUI/lockscreen_rc.py | Python | mit | 22,062 | 0.000227 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.8.0)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x04\x31\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x0... | a\xd5\x78\xfa\xd6\
\x76\xfb\xd7\x79\xfb\xd3\x78\xfb\xd5\x78\xed\xc4\x6f\xed\xc5\x6d\
\xfc\xd6\x79\xeb\xc2\x6d\xec\xc6\x70\xfc\xd5\x76\xfc\xd6\x78\xfd\
\xd6\x77\xfd\xd4\x77\xfd\xd6\x77\xfd\xd5\x76\xfb\xd5\x78\xfb\xd4\
\x77\xfc\xd5\x78\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\x78\
\xfc\xd5\x77\xfc\xd5\x77\xfb\xd5\x77\... | \xcd\x72\xfc\xd5\x77\xf3\xcb\x72\xfc\
\xd5\x77\xfc\xd5\x77\xf |
ikeikeikeike/celery-tracker | tracker/configs/celeryconfig.py | Python | mit | 1,416 | 0.004237 | """
Global Settings
"""
settings = {}
# | try:
# conf = __import__("django.conf")
# settings = conf.conf.settings
# except ImportError:
# settings = {}
# Broker - amqp,
BROKER_URL = getattr(settings, "BROKER_URL", "amqp://guest@127.0.0.1//")
# file storage path (default: memory), e.g. /tmp/tracker.db
CELE | RY_TRACKER_STORAGE = getattr(settings, "CELERY_TRACKER_STORAGE", "")
# Log level
CELERY_TRACKER_LOG_LEVEL = getattr(settings, "CELERY_TRACKER_LOG_LEVEL", "INFO")
# plugins
CELERY_TRACKER_PLUGINS = getattr(settings, "CELERY_TRACKER_PLUGINS", {
"fluent": {
"class": "tracker.plugins.fluent.FluentPlugin",
... |
thiezn/morTimmy | raspberrypi/morTimmy/morTimmy.py | Python | mit | 5,132 | 0.002338 | #!/usr/bin/env python3
# imports
import logging
from hardware_controller import *
from time import sleep, time
import queue
class Robot:
""" Main class for controlling our robot morTimmy
The brain of the robot is a raspberry Pi and the low level
electronic are handled by an Arduino. The Arduino provides... | Robot moving forward")
# Stop robot if running for 5sec
elif self.currentState == self.state.running and (currentTime - self.runningTime) >= 5:
self.arduino.sendMessage(MODULE_MOTOR, CMD_MOTOR_STOP)
self.runningTime = currentTime
self.currentState = self.state.stopped... | rduino.recvMessage()
# Process all received messages in the queue
while not self.arduino.recvMessageQueue.empty():
recvMessage = self.arduino.recvMessageQueue.get_nowait()
if recvMessage is None:
# Why does the queue always return a None object?
... |
zinglax/SPA-BoilerPlate2017 | app/stock/spa/fabfile.py | Python | mit | 2,980 | 0.001007 | from fabric.colors import *
from fabric.contrib.console import confirm
from contextlib import contextmanager
from fabric.api import *
from fabric.contrib.project import rsync_project
from fabric.contrib.files import exists
import os
env.user = "root"
env.hosts = ['__var_pooled_server_ip__']
env.key_filename = '__var_s... | % os.path.join(path_to_project, project_name))
# Enable the site
run('a2ensite %s' % apache_conf_file)
# Enable the mods
run('a2enmod wsgi')
run('a2enmod ssl')
# Lets Encrypt
run('letsencrypt -n --apache -d ' + domain + '.zinglax.com')
# Restart the apache server
run('service apa... | omain="__var_production_subdomain__")
def deploy_dev():
deploy(domain="__var_development_subdomain__")
def deploy_on_local_apache():
print("dylanRules")
env.user = "root"
env.hosts = ['zinglax']
deploy()
|
Valloric/ycmd | ycmd/responses.py | Python | gpl-3.0 | 12,247 | 0.025394 | # Copyright (C) 2013-2020 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd 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.
#
#... |
"""
class Kind:
"""These are LSP kinds that we use outside of LSP completers."""
REFACTOR = 'refactor'
def __init__( self, location, chunks, text = '', kind = None ):
"""location of type Location, chunks of type list<FixItChunk>" | ""
self.location = location
self.chunks = chunks
self.text = text
self.kind = kind
class FixItChunk:
"""An individual replacement within a FixIt (aka Refactor)"""
def __init__( self, replacement_text, range ):
"""replacement_text of type string, range of type Range"""
self.replacement_tex... |
1adrianb/face-alignment | face_alignment/detection/folder/folder_detector.py | Python | bsd-3-clause | 1,643 | 0.001217 | import os
import numpy as np
import torch
from ..core import FaceDetector
class FolderDetector(FaceDetector):
'''This is a simple helper module that assumes the faces were detected already
(either previously or are provide | d as ground truth).
The class expects to find the bound | ing boxes in the same format used by
the rest of face detectors, mainly ``list[(x1,y1,x2,y2),...]``.
For each image the detector will search for a file with the same name and with one of the
following extensions: .npy, .t7 or .pth
'''
def __init__(self, device, path_to_detector=... |
viraintel/OWASP-Nettacker | lib/scan/port/engine.py | Python | apache-2.0 | 24,604 | 0.006015 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import socks
import time
import json
import threading
import string
import random
import os
import logging
from core.alert import *
from core.targets import target_type
from core.targets import target_to_host
from core.load_modules import load_file_path
from ... | 15, 5922, 5925, 5950, 5952, 5959, 5960,
5961, 5962, 5963, 5987, 5988, 5989, 5998, 5999, 6000, 6001, 6002, 6003, 6004,
6005, 6006, 6007, 6009, 6025, | 6059, 6100, 6101, 6106, 6112, 6123, 6129, 6156,
6346, 6389, 6502, 6510, 6543, 6547, 6565, 6566, 6567, 6580, 6646, 6666, 6667,
6668, 6669, 6689, 6692, 6699, 6779, 6788, 6789, 6792, 6839, 6881, 6901, 6969,
7000, 7001, 7002, 7004, 7007, 70... |
devoid/nova | nova/tests/scheduler/test_host_filters.py | Python | apache-2.0 | 80,600 | 0.001179 | # Copyright 2011 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 req... | lf._do_extra_ | specs_ops_test(
value='2',
req='s< 12',
matches=False)
def test_extra_specs_fails_with_op_sg(self):
self._do_extra_specs_ops_test(
value='12',
req='s> 2',
matches=False)
def test_extra_specs_matches_with_op_in(self):
self.... |
kisna72/django | tests/migrations/test_migrations_no_changes/0003_third.py | Python | bsd-3-clause | 960 | 0.002083 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('migrations', '0002_second'),
]
operations = [
migrations.CreateModel(
name='ModelWithCustomBase',
fi... | ID', serialize=False, auto_created=True, primary_key=True)),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='UnmigratedModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_crea... | migrations.DeleteModel(
name='Book',
),
]
|
DRL/blobtools | lib/view.py | Python | gpl-3.0 | 5,130 | 0.004288 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""usage: blobtools view -i <BLOBDB> [-x <TAXRULE>] [--rank <TAXRANK>...] [--hits]
[--list <LIST>] [--out <OUT>] [--notable]
[--concoct] [--cov] [--experimental <META>]
[--h|--help]
... | tCore as BtCore
import lib.BtLog as BtLog
import lib.BtIO as BtIO
import lib.interface as interface
TAXRULES = ['bestsum', 'bestsumorder']
RANKS = ['species', 'genus', 'family', 'order', 'phylum', 'superkingdom', 'all']
def main():
#print(data_dir)
args = docopt(__doc__)
blobdb_f = args['--input']
pref... | e = args['--taxrule']
hits_flag = args['--hits']
seq_list_f = args['--list']
concoct = args['--concoct']
cov = args['--cov']
notable = args['--notable']
experimental = args['--experimental']
# Does blobdb_f exist ?
if not isfile(blobdb_f):
BtLog.error('0', blobdb_f)
out_f = ... |
munhyunsu/Hobby | Pickle/pickle_example.py | Python | gpl-3.0 | 242 | 0.008264 | #!/usr/bin/env python3
import sys
import subprocess
import urllib.request
import copy
def main(argv):
cooki | e = urllib.request.HTTPCookieProcessor()
oc = copy.deepcopy(cookie)
if __name__ == '__main__':
sys.e | xit(main(sys.argv))
|
gandalfar/django-brainstorm | brainstorm/feeds.py | Python | bsd-3-clause | 914 | 0.002188 | from django.contrib.syndication.feeds import Feed, FeedDoesNotExist
from brainstorm.models import Subsite
class SubsiteFeed(Feed):
title_template = 'brainstorm/feed_title.html'
description_template = 'brainstorm/feed_description.h | tml'
def get_object(self, bits):
return Subsite.objects.get(slug__exact=bits[0])
def title(self, obj):
return 'Latest ideas submitted for %s' % obj.name
def description(self, obj):
return 'Latest ideas submitted for %s' % obj.name
def link(self, obj):
if not obj:
... | s(self, obj):
return obj.ideas.order_by('-submit_date')[:30]
def item_link(self, item):
return item.get_absolute_url()
def item_author_name(self, item):
return item.user
def item_pubdate(self, item):
return item.submit_date
|
renatopp/liac-chess | chess/__init__.py | Python | mit | 3,617 | 0.005806 | # =============================================================================
# Federal University of Rio Grande do Sul (UFRGS)
# Connectionist Artificial Intelligence Laboratory (LIAC)
# Renato de Pontes Pereira - rppereira@inf.ufrgs.br
# =============================================================================
... | ess import models
from chess import gui
from chess.app import *
from chess.resources import *
from chess.events import *
from chess.logger import Logger
def load_themes():
'''Loads the themes file.'''
global themes
log.debug('INIT', 'Loading themes file.')
themes = json.load(open('data/themes.json'), ... | load_configs():
'''Loads the configuration file.'''
global config
log.debug('INIT', 'Loading configuration file.')
config = json.load(open('data/config.json'), object_pairs_hook=collections.OrderedDict)
log.debug('INIT', 'Configurations loaded successfully.')
def load_levels():
'''Loads the l... |
realsobek/freeipa | ipaserver/dnssec/odsmgr.py | Python | gpl-3.0 | 7,447 | 0 | #!/usr/bin/python2
#
# Copyright (C) 2014 FreeIPA Contributors see COPYING for license
#
import dns.name
try:
from xml.etree import cElementTree as etree
except ImportError:
from xml.etree import ElementTree as etree
from ipapython import ipa_log_manager, ipautil
# hack: zone object UUID is stored as path t... | Reader, self).__init__()
def process_ipa_zone(self, op, uuid, zone_ldap):
assert (op == 'add' or op == 'del'), 'unsupported op %s' % op
assert uuid is not None
assert 'idnsname' in zone_ldap, \
'LDAP zone UUID %s without i | dnsName' % uuid
assert len(zone_ldap['idnsname']) == 1, \
'LDAP zone UUID %s with len(idnsname) != 1' % uuid
if op == 'add':
self._add_zone(zone_ldap['idnsname'][0], uuid)
elif op == 'del':
self._del_zone(zone_ldap['idnsname'][0], uuid)
class ODSMgr(object)... |
CoderBotOrg/coderbot | stub/picamera/__init__.py | Python | gpl-2.0 | 77 | 0.012987 | from picamera.exc imp | ort PiCameraError
from picamera.camera import PiCamera
| |
huntxu/fuel-web | nailgun/nailgun/test/unit/test_version_handler.py | Python | apache-2.0 | 1,730 | 0 | # -*- coding: utf-8 -*-
# Copyright 2013 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 requi... | headers=self.default_headers
)
self.assertEqual(200, resp.status_code)
self.assertEqual(
resp.json_body,
{
"release": "0.1b",
"feature_groups": [],
| "auth_required": True,
}
)
|
antoinecarme/pyaf | tests/basic_checks/test_temporal_demo_hourly_D_H_ErrorMessage.py | Python | bsd-3-clause | 1,208 | 0.018212 | # %matplotlib inline
import pyaf
import numpy as np
import pandas as pd
DATA_FREQ = 'H'
PERIODS = ["D" , "H"]
H = 365
N = H * 10
lDateColumn = "Date"
lSignalVar = "Signal";
START_TIME = "2001-01-25"
# generate a daily signal covering one year 2016 in a pandas dataframe
np.random.seed(seed=1960)
df_train = pd.DataFra... | U" , 'TD' , 'MO' , 'OC'];
lFailed = None
try:
lSignalHierarchy = lEngine.train(df_train , lDateColumn, lSignalVar, H, lHierarchy, None);
lFailed = False
except Exception as lEx:
print("ERROR" , lEx.__class__, lEx)
lFailed = True
if(not lFailed) | :
raise Exception("NORMAL_BEHAVIOR_NOT_EXPECTED_SHOULD_HAVE_FAILED")
|
OCA/account-financial-tools | account_asset_management/tests/__init__.py | Python | agpl-3.0 | 84 | 0 | from . import test_ac | count_asset_m | anagement
from . import test_asset_management_xls
|
kev40293/timeball | src/tests/configtest.py | Python | gpl-2.0 | 1,218 | 0.031199 | #!/u | sr/bin/python
import sys
sys.path.insert(0, '../src')
from timeball_utils.configparser import backup_ | parser, config_parser, arg_parser
def backup():
cparse = backup_parser(sys.argv[2])
backups = dict()
while not cparse.empty():
date = cparse.parseString()
if date is None:
break
backup_list = cparse.parseBlock()
if backup_list is None:
break
backups[date] = back... |
palcu/rotopcoder | telina/teste/generator.py | Python | mit | 361 | 0.00554 | import sys
from random import randint
def generate_tests(N, P):
for i in range(N):
MAX_M = 10**exponent
MIN_SHIT = 5
m = randint(10**(exponent-1), MAX_M)
b = randint(5, m-2)
print("{0} {1}".format(m, b))
if len(sys.argv) < 2:
print("Ai uitat de numarul de exponent")
else:
gen | erate_tests(int(sys.argv[1]), int(sys.argv[2 | ]))
|
mrnamingo/vix4-core | src/ImageManager.py | Python | gpl-2.0 | 37,839 | 0.025978 | # for localized messages
from boxbranding import getBoxType, getImageType, getImageDistro, getImageVersion, getImageBuild, getImageFolder, getImageFileSystem, getBrandOEM, getMachineBrand, getMachineName, getMachineBuild, getMachineMake, getMachineMtdRoot, getMachineRootFile, getMachineMtdKernel, getMachineKernelFile, ... | return PluginBrowserSummary
def selectionChanged(self):
item = self["list"].getCurrent()
desc = self["backupstatus"].text
| if item:
name = item
else:
name = ""
for cb in self.onChangedEntry:
cb(name, desc)
def backupRunning(self):
self.populate_List()
self.BackupRunning = False
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Image Manager")):
self.BackupRunning = False
if get... |
mattupstate/flask-stache | example/__init__.py | Python | mit | 806 | 0 | from flask import Flask
from flask_stache import render_view, rend | er_template
from example.admin import cr | eate_blueprint
class Home(object):
def msg(self):
return "Home"
def msg2(self):
return "Partial Content"
class About(object):
def msg(self):
return "About"
def create_app():
app = Flask(__name__)
app.debug = True
@app.route('/')
def home():
return rend... |
sonicrules1234/sonicbot | oldplugins/on_PRIVMSG.py | Python | bsd-3-clause | 10,821 | 0.011274 | import shelve, time, random
def main(connection, info) :
"""This is the old plugin"""
#"""Run every time a message is seen"""
if info["message"].startswith("\x01ACTION") and info["message"].endswith("\x01") :
on_ACTION(connection, info)
return None
# if info["sender"] == "OperServ" :
... |
# connection.rawsend("JOIN %s\n" % (newchannel))
# connection.rawsend("MODE %s +o %s\n" % (newchannel, conf.nick))
# connection.msg(newchannel, "Hello %s, I am sonicbot and I am here to help you with IRC." % (registeree))
seendb = shelve.open("seen.db", writeback=True)
if ... | key("users") :
seendb["users"] = {}
seendb.sync()
seendb["users"][info["sender"].lower()] = [time.time(), info["message"]]
seendb.sync()
seendb.close()
badwords = shelve.open("badwords.db", writeback=True)
if badwords.has_key(connection.host) :
if badwords[connection.... |
rafaelang/django-rest-framework | tests/test_versioning.py | Python | bsd-2-clause | 11,173 | 0.000716 | import pytest
from django.conf.urls import include, url
from rest_framework import serializers, status, versioning
from rest_framework.decorators import APIView
from rest_framework.relations import PKOnlyObject
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.... | /'}
d | ef test_reverse_query_param_versioning(self):
scheme = versioning.QueryParameterVersioning
view = ReverseView.as_view(versioning_class=scheme)
request = factory.get('/endpoint/?version=v1')
response = view(request)
assert response.data == {'url': 'http://testserver/another/?vers... |
django-wiki/django-wiki | src/wiki/core/markdown/mdx/codehilite.py | Python | gpl-3.0 | 4,523 | 0.001327 | import logging
import re
from markdown.extensions.codehilite import CodeHilite
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
logger = logging.getLogger(__na... | kdown(self, md):
"""Add HilitePostprocessor to Markdown instance."""
hiliter = HiliteTreeprocessor(md)
hiliter.config = self.getConfigs()
if "hilite" in md.treeprocessors:
logger.warning(
"Replacing existing 'hilite' extension - please remove "
| "'codehilite' from WIKI_MARKDOWN_KWARGS"
)
del md.treeprocessors["hilite"]
add_to_registry(md.treeprocessors, "hilite", hiliter, "<inline")
if "fenced_code_block" in md.preprocessors:
logger.warning(
"Replacing existing 'fenced_code_block' extensi... |
radiasoft/optics | optics/magnetic_structures/wiggler.py | Python | apache-2.0 | 292 | 0.006849 | __author__ = 'labx'
"""
Implements a wiggler.
"""
from optics.magnetic_structures.inserti | on_device import InsertionDevice
cl | ass Wiggler(InsertionDevice):
def __init__(self, K, period_length, periods_number):
InsertionDevice.__init__(self, K, 0.0, period_length, periods_number) |
Stanford-Legal-Tech-Design/legaltech-rapidpro | temba/flows/stats.py | Python | agpl-3.0 | 2,713 | 0.006635 |
def get_jenks_breaks(dataList, numClass):
dataList.sort()
mat1 = []
for i in range(0,len(dataList)+1):
temp = []
for j in range(0,numClass+1):
temp.append(0)
mat1.append(temp)
mat2 = []
for i in range(0,len(dataList)+1):
temp = []
for j in range... | ay mean (SDAM) and the squared deviations from the
class means (SDCM), and dividing by the SDAM
"""
breaks = get_jenks_breaks(dataList, numClass)
dataList.sort()
listMean = sum(dataList)/len(dataList)
print listMean
SDAM = 0.0
for i in range( | 0,len(dataList)):
sqDev = (dataList[i] - listMean)**2
SDAM += sqDev
SDCM = 0.0
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
classEnd = dataList.index(breaks[... |
Sorsly/subtle | google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_lex.py | Python | mit | 29,128 | 0.006248 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | input is OK here.
break
# There were some characters in the input that did not form a valid key.
raise resource_exceptions.ExpressionSyntaxError(
'key expected [{0}].'.format(lex.Annot | ate(here)))
# Check if the key is a function call.
if lex.IsCharacter('('):
# Collect the actual args and convert numeric args to float or int.
args = lex.Args(convert=True)
else:
args = None
# Skip an isspace() characters. End of input will fail with an
# 'Operator expected [...]'... |
gregplaysguitar/glamkit | glamkit/incubated/imageutil/imagemagick_util.py | Python | bsd-3-clause | 6,569 | 0.011874 | from django.conf import settings
from django.http import Http404
import os
import shutil
import time
import re
import urlparse
import urllib
from subprocess import call
from exceptions import ImageMagickException, ImageMagickConversionError, ImageMagickOSFileError
from cache_util import file_hash
from django.db.mode... | CACHE_PATH)
def convert(original_image_path, arg):
"""
Takes the file name (relative to MEDIA_ROOT), and a specification of the conversion.
Returns a URL to retrieve the converted file.
See http://www.i | magemagick.org/script/command-line-options.php for the possible options.
Does the conversion, if it's not cached, and caches it in MEDIA_ROOT/IMAGEUTIL_CACHE.
Pseudocode for filter:
1. generate the result filename.
2. does it exist? Yes = return it. No = create it.
3. do the conversion; save the ... |
anhstudios/swganh | data/scripts/templates/object/tangible/ship/interior_components/shared_droid_interface_interior.py | Python | mit | 495 | 0.044444 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/interior_components/shared_droid_interface_interior.iff"
resul... | me("space/space_item","droid_interface_interior_n")
#### BEGIN MODIFIC | ATIONS ####
#### END MODIFICATIONS ####
return result |
stevearc/dynamo3 | setup.py | Python | mit | 1,819 | 0.00055 | """ Setup file """
import os
from setuptools import find_packages, setup
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.rst")) as f:
README = f.read()
with open(os.path.join(HERE, "CHANGES.rst")) as f:
CHANGES = f.read()
REQUIREMENTS_TEST = open(os.path.join(HERE, "r... | ges(exclude=("tests",)),
license="MIT",
entry_points={
"console_scripts": [
"dynamodb-local = dynamo3.testing:run_dynamo_local",
],
"nose.plugins": [
"dynamolocal=dynamo3.testing:DynamoLocalPlugin",
],
},
pyt... | res=">=3.6",
install_requires=REQUIREMENTS,
tests_require=REQUIREMENTS + REQUIREMENTS_TEST,
)
|
Funtazoid/helium | bin/rd_core.py | Python | isc | 291 | 0.013746 | # == Dependencies ==
import os
# == ~~~~~~~~~~~~ ==
def CommandExecution( | argument):
try:
if os.path.exists(argument) == True:
os.rmdir(argument)
else:
print("ERROR: Directory isn't empty")
except:
print( | "ERROR: Directory isn't empty") |
toenuff/treadmill | tests/api/server_test.py | Python | apache-2.0 | 2,316 | 0 | """Server API tests."""
import unittest
# Disable W0611: Unused import
import tests.treadmill_test_deps # pylint: disable=W0611
import mock
from treadmill impo | rt admin
from treadmill.api import server
class ApiServerTest(unittest.TestCase):
"""treadmill.api.server tests."""
def setUp(self):
self.svr = server.API()
def tearDown(self):
pass
@mock.patch('treadmill.context.AdminContext.conn',
mock.Mock(return_value=admin.Admin... | @mock.patch('treadmill.admin.Server.list', mock.Mock(return_value=[]))
def test_list(self):
"""Dummy test for treadmill.api.server._list()"""
self.svr.list(None, None)
svr_admin = admin.Server(None)
self.assertTrue(svr_admin.list.called)
self.svr.list('some-cell', None)
... |
benosment/daily-exercises | easy-249.py | Python | gpl-2.0 | 1,302 | 0.001536 | #! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''... | max_se | ll = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])
|
clipo/idss-seriation | analysis/optimize-filtersolutions/filtertest.py | Python | apache-2.0 | 11,443 | 0.004894 | #!/usr/bin/env python
# Copyright (c) 2015. Mark E. Madsen <mark@madsenlab.org>
#
# This work is licensed under the terms of the Apache Software License, Version 2.0. See the file LICENSE for details.
"""
Description here
"""
import pickle
import logging
import networkx as nx
import pprint as pp
import argparse
im... | ce these are trivial (e.g., A->B->C->D already covers
# A->C->D.) That should then leave all the unique maximum solutions (or so it seems)
################################################# FILTERING ####################################
filteredarray = []
num_comparisons = 0
node_cache = dict()
... |
newOne = 0
for tnetwork in reversed(all_solutions):
log.trace("trying tnetwork: %s of length %s", tnetwork, len(tnetwork.nodes()))
tnetwork_nodeset = _get_cached_nodes(node_cache, tnetwork)
log.trace("Testing tnetworkArray: %s against accepted solutions", tnetwork_nodeset)
exist... |
hortonworks-spark/spark-llap | python/pyspark_llap/sql/__init__.py | Python | apache-2.0 | 879 | 0 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# | this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compl | iance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express ... |
UnrememberMe/pants | contrib/jax_ws/src/python/pants/contrib/jax_ws/targets/jax_ws_library.py | Python | apache-2.0 | 1,170 | 0.004274 | # coding=utf-8
# Copyright 2017 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.backend.j... | les."""
def __init__(self,
payload=None,
xjc_args=None,
extra_args=None,
**kwargs):
"""Generates a Java library from WSDL files using JAX-WS.
:param list xjc_args: Additional arguments to xjc.
:param list extra_args: Additional arguments for th... | f.assert_list(xjc_args, key_arg='xjc_args')),
'extra_args': PrimitiveField(self.assert_list(extra_args, key_arg='extra_args')),
})
super(JaxWsLibrary, self).__init__(payload=payload, **kwargs)
|
NECDisplaySolutions/necpdsdk | nec_pd_sdk/nec_pd_sdk.py | Python | mit | 193,013 | 0.003523 | # -*- coding: utf-8 -*-
"""nec_pd_sdk.py - High level functions for communicating via LAN or RS232 with NEC large-screen displays.
"""
#
#
# Copyright (C) 2016-18 NEC Display Solutions, Ltd
# written by Will Hollingworth <whollingworth at necdisplay.com>
# See LICENSE.rst for details.
# TODO == Helper Functions ==
# ... | 'input',
'signal_h_resolution',
'signal_v_resolution',
| 'audio_input',
'audio_input_status',
'picture_status',
... |
Orav/kbengine | kbe/src/lib/python/Lib/unittest/case.py | Python | lgpl-3.0 | 56,919 | 0.001195 | """Test case implementation"""
import sys
import functools
import difflib
import logging
import pprint
import re
import warnings
import collections
import contextlib
import traceback
from . import result
from .util import (strclass, safe_repr, _count_diff_all_purpose,
| _count_diff_hashable, _common_shorten_repr)
__unittest = True
DIFF_OMITTED = ('\nDiff is %s characters long. '
'Set self.maxDiff to None to see it.')
class SkipTest(Exception):
"""
Raise this exception in a test to skip it.
|
Usually you can use TestCase.skipTest() or one of the skipping decorators
instead of raising this directly.
"""
class _ShouldStop(Exception):
"""
The test should stop.
"""
class _UnexpectedSuccess(Exception):
"""
The test was supposed to fail, but it didn't!
"""
... |
elfnor/sverchok | nodes/analyzer/kd_tree_edges_mk2.py | Python | gpl-3.0 | 4,347 | 0.00069 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | uts[s].is_linked:
sock_input = dtype(inputs[s].sv_get()[0][0])
else:
sock_input = s_default_value
socket_inputs.append(sock_input)
self.run_kdtr | ee(verts, socket_inputs)
def run_kdtree(self, verts, socket_inputs):
mindist, maxdist, maxNum, skip = socket_inputs
# make kdtree
# documentation/blender_python_api_2_78_release/mathutils.kdtree.html
size = len(verts)
kd = mathutils.kdtree.KDTree(size)
for i, xyz i... |
alexa-infra/negine | thirdparty/boost-python/libs/python/test/voidptr.py | Python | mit | 1,168 | 0.009418 | # Copyright Niall Douglas 2005.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
>>> from voidptr_ext import *
Check for correct conversion
>>> use(get())
Check that None is conver... | oid pointer
>>> useany(get())
1
>>> useany(None)
0
Check that we don't lose type information by converting NULL
opaque pointers to None
>>> assert getnull() is None
>>> useany(getnull())
0
Check that there is no conversi | on from integers ...
>>> try: use(0)
... except TypeError: pass
... else: print 'expected a TypeError'
... and from strings to opaque objects
>>> try: use("")
... except TypeError: pass
... else: print 'expected a TypeError'
"""
def run(args = None):
import sys
import doctest
if... |
vicky2135/lucious | tests/functional/dashboard/test_catalogue.py | Python | bsd-3-clause | 11,171 | 0 | from django.core.urlresolvers import reverse
from django.utils.six.moves import http_client
from o | scar.core.loading import get_model
from oscar.test.testcases import WebTestCase, add_permissions
from oscar.test.factories import create_product
from oscar.test.factor | ies import (
CategoryFactory, PartnerFactory, ProductFactory, ProductAttributeFactory)
Product = get_model('catalogue', 'Product')
ProductClass = get_model('catalogue', 'ProductClass')
ProductCategory = get_model('catalogue', 'ProductCategory')
Category = get_model('catalogue', 'Category')
StockRecord = get_model(... |
cmusatyalab/gabriel | server/setup.py | Python | apache-2.0 | 996 | 0 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="gabriel-server",
version="2.0.2",
author="Roger Iyengar",
| author_email="ri@rogeriyengar.com",
description="Server for Wearable Cognitive Assistance Applications",
long_description=long_description,
long_description_content_type="text/markdown",
url="http://gabriel.cs.cmu.edu",
| packages=setuptools.find_packages("src"),
package_dir={"": "src"},
license="Apache",
classifiers=[
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Lic... |
ShadowKyogre/mypaint | setup.py | Python | gpl-2.0 | 12,625 | 0 | # This file is part of MyPaint.
# Imports:
from __future__ import print_function
import subprocess
import glob
import os
import os.path
import sys
import textwrap
from distutils.command.build import build
from distutils.command.clean import clean
from setuptools import setup
from setuptools import Extension
from se... | pass
def finalize_options(self):
pass
def run(self):
build = self.get_finalized_command("build")
for src in glob.glob("po/*.po"):
data_files = self._compile_message_catalog(src, build.build_temp)
if not self.dry_run:
self.distribution.data_file... | g, "LC_MESSAGES")
targ = os.path.join(targ_dir, "mypaint.mo")
install_dir = os.path.join("locale", lang, "LC_MESSAGES")
needs_update = True
if os.path.exists(targ):
if os.stat(targ).st_mtime >= os.stat(src).st_mtime:
needs_update = False
if needs_upd... |
nka11/store-fr | setup.py | Python | gpl-3.0 | 1,116 | 0 | #!/usr/bin/env python
from setu | ptools import setup, find_packages
from store import VERSION
setup(
name='store_fr',
version=VERSION,
url='https://github.com/tangentlabs/django-oscar-paypal',
author="Nicolas Karageuzian",
author_email="nicolas@karageuzian.com",
description=(
"Integrated webstore french legal complia... | long_description=open('README.rst').read(),
keywords="Store, PayPal, Oscar",
license=open('LICENSE').read(),
platforms=['linux'],
packages=find_packages(exclude=['sandbox*', 'tests*']),
include_package_data=True,
install_requires=['requests>=1.0'],
extras_require={
'oscar': ["djang... |
maysara/pandora_image | pandora/place/managers.py | Python | gpl-3.0 | 3,668 | 0.002726 | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
import unicodedata
from django.db.models import Q, Manager
from ox.django.query import QuerySet
from item.utils import decode_id
def parseCondition(condition, user):
'''
condition: {
value: "war"
}
or
condition: {
key: "y... | ag
key = k
elif k in ('lat', 'lng', 'area', 'south', 'west', 'north', 'east', 'matches', 'id'):
key = '%s | %s' % (k, {
'>': '__gt',
'>=': '__gte',
'<': '__lt',
'<=': '__lte',
}.get(op,''))
else:
key = '%s%s' % (k, {
'==': '__iexact',
'^': '__istartswith',
'$': '__iendswith',
}.get(op,'__icontains'))
key = str... |
abhiatgithub/shogun-toolbox | applications/easysvm/scripts/easysvm.py | Python | gpl-3.0 | 2,446 | 0.009403 | #!/usr/bin/env python
#############################################################################################
# #
# This program is free software; you can redistribute it and/or modify #
# it under t... | modelsel
if __name__ == '__main__':
if len(sys.argv)<2:
sys.stderr.write("usage: %s [cv|pred|modelsel|eval|poim] parameters | \n" % sys.argv[0])
sys.exit(-1)
random.seed()
topmode = sys.argv[1]
if topmode == 'cv':
svm_cv(sys.argv)
elif topmode == 'pred':
svm_pred(sys.argv)
elif topmode == 'poim':
svm_poim(sys.argv)
elif topmode == 'eval':
svm_eval(sys.argv)
elif topmode ==... |
Mafarricos/Mafarricos-xbmc-addons | plugin.video.moviereleases/main.py | Python | gpl-2.0 | 19,311 | 0.064892 | # -*- coding: UTF-8 -*-
# by Mafarricos
# email: MafaStudios@gmail.com
# This program is free software: GNU General Public License
import xbmcplugin,xbmcgui,xbmc,xbmcaddon,os,threading,re,urllib,json,time
from BeautifulSoup import BeautifulSoup
from resources.libs import links,tmdb,imdb,trakt,rottentomatoes,youtube,b... | 17,'',False,9,'',0,'','','')
addDir(language(30011),'boxoffice',17,'',True,9,'',1,'','','')
addDir(language(30009),'theaters',17,'',True,9,'',1,'','','')
addDir(language(30075),'opening',17,'',True,9,'',1,'','','')
addDir(language(30010),'upcoming',17,'',True,9,'',1,'','','')
addDir('[COLOR green]%s[/COLOR]' % lan... | t_releases',17,'',True,9,'',1,'','','')
addDir(language(30079),'dvdnew_releases',17,'',True,9,'',1,'','','')
#addDir('dvdupcoming','dvdupcoming',17,'',True,1,'',1,'','','')
menus_view()
def rottenlist(index,url):
listdirs = []
if url == 'boxoffice': listdirs = rottentomatoes.listmovies(links.link().rotten_boxoffi... |
xlevus/python-diana | tests/test_context.py | Python | mit | 1,257 | 0.000796 | import typing as t
import contextlib
import pytest
import diana
State = t.NewType("State", dict)
AsyncState = t.NewType("AsyncState", dict)
async def no_op():
pass
@pytest.fixture
def module():
class ContextModule(diana.Module):
def __init__(self):
self.state: State = {"count": 0}
... | await no_op()
yield self.state
self.state["count"] -= 1
| return ContextModule()
@pytest.fixture
def injector(module):
injector = diana.Injector()
injector.load(module)
return injector
def test_within_context(injector):
@injector
def uses_state(*, state: State):
assert state["count"] != 0
uses_state()
@pytest.mark.asyncio
async def t... |
veltzer/scrapers | pyscrapers/workers/getpocket.py | Python | gpl-3.0 | 679 | 0.001473 | from logging import Logger
from requests.sessions import Session
def getpocket_download(session: Session, _logger: Logger):
"""
This does the heavy lifting
:param session:
:param _logger:
:return:
"""
headers = {
"Origin": "https://app.getpocket.com", # checked that this is needed... | r_key": "78809-9423d8c743a58f62b23ee85c", # checked that this is needed
}
url = "https://getpocket.com/v3/get"
response = session.post(url=url, headers=headers, params=params)
response.raise_for_status()
obj = response.json()
print(ob | j)
|
axinging/chromium-crosswalk | third_party/WebKit/Tools/Scripts/webkitpy/tool/webkit_patch.py | Python | bsd-3-clause | 3,181 | 0.001886 | # Copyright (c) 2010 Google Inc. All rights reserved.
# Copyright (c) 2009 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above... | options to all commands during execute() as well.
def handle_global_options(self, options):
self.initialize_scm(options.patch_directories)
def should_execute_command(self, command):
if command.requires_local_commits and not self.scm().supports_local_ | commits():
failure_reason = "%s requires local commits using %s in %s." % (
command.name, self.scm().display_name(), self.scm().checkout_root)
return (False, failure_reason)
return (True, None)
|
TooAngel/democratic-collaboration | tests/test_routes_githubWebHook_push.py | Python | agpl-3.0 | 761 | 0 | import server
import unittest
import json
from datetime import datetime, timedelta
from mock import patch, MagicMock
class GithubHookTestCase(unittest.TestCase):
def setUp(self):
server.app.testing = True
self.app = server.app.test_client()
def test_push(self) | :
headers = {
'Content-Type': 'application/json',
'X-GitHub-Event': 'push'
}
data = {}
rv = self.app.post(
'/github/',
data=json.dumps(data),
headers=headers,
base_url='https://localhost'
)
response... | ssertEqual('All fine, thanks', response['info'])
if __name__ == '__main__':
unittest.main()
|
mupi/escolamupi | core/templatetags/timtec_markdown.py | Python | agpl-3.0 | 574 | 0 | import markdown
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(is_safe=True)
@stringfilter
def timtec_markdown(value):
ex | tensions = ["nl2br", "attr_list"]
return mark_safe(markdown.markdown(force_unicode(value),
| extensions,
safe_mode=True,
enable_attributes=False))
|
dennybaa/st2 | st2common/st2common/exceptions/auth.py | Python | apache-2.0 | 1,754 | 0 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... | pass
class TokenNotFoundError(StackStormDBObjectNotFoundError):
pass
class TokenExpiredError(StackStormBaseException):
pass
class TTLTooLargeException(StackStormBaseException):
pass
class ApiKeyNotProvidedError(StackStormBaseException):
pass
class ApiKeyNotFoundError(StackStormDBObjectNotFo... | isabledError(StackStormDBObjectNotFoundError):
pass
class MultipleAuthSourcesError(StackStormBaseException):
pass
class NoAuthSourceProvidedError(StackStormBaseException):
pass
|
arpitar/osf.io | api/base/exceptions.py | Python | apache-2.0 | 1,838 | 0.002176 |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_fr... | errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in m... | response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystrin... |
adamRogerson/Hours | speed_test.py | Python | gpl-3.0 | 1,066 | 0.00469 | from timer import Timer
from back.application_mgmt import Application,Data_saver,View_control
view_control = View_control()
data_saver = Data_saver()
with Timer() as t:
view_control.top_6_background_today()
print "=> elasped top 6 today: %s s" % t.secs
with Timer() as t:
view_control.new_top_6_background_... | get_file (meata): %s s" % t.secs |
with Timer() as t:
data_saver.get_file("saved_background_data")
print "=> elasped get_file (background): %s s" % t.secs
with Timer() as t:
data_saver.get_file("saved_ignore_data")
print "=> elasped get_file (ignore): %s s" % t.secs
|
jolyonb/edx-platform | lms/djangoapps/notes/models.py | Python | agpl-3.0 | 3,401 | 0.000294 | import json
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.db import models
from django.utils.html import strip_tags
from opaque_keys.edx.django.models import CourseKeyField
from six import text_type
class Note(models.Model):... | rt_offset = ranges[0]['startOffset']
self.range_end = ranges[0]['end']
self.range_end_offset = ranges[0]['endOffset']
self.tags = ""
tags = [strip_tags(tag) for tag in body.get('tags', [])]
if len(tags) > 0:
self.tags = ",".join(tags)
def get_absolute_url(self):... | the note object.
"""
kwargs = {'course_id': text_type(self.course_id), 'note_id': str(self.pk)}
return reverse('notes_api_note', kwargs=kwargs)
def as_dict(self):
"""
Returns the note object as a dictionary.
"""
return {
'id': self.pk,
... |
toastdriven/eliteracing | courses/views.py | Python | bsd-3-clause | 1,639 | 0 | from django.core.paginator import Paginator, EmptyPage
from django.db.models import | Q
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from .models import Course
def list(request):
qs = Course.approved.all()
course_types = [ct[0] for ct in Course.COURSE_TYPES]
search = request.GET.get('q', None)
vehicle_type = request.GET.get('vehicle_type', 'a... | m__icontains=search) |
Q(notes__icontains=search) |
Q(created_by__name__icontains=search)
)
if vehicle_type == 'ship':
qs = qs.filter(
Q(course_type='zerogravity') |
Q(course_type='surface') |
Q(course_type='stadium')
)
elif ve... |
openstack/horizon | openstack_dashboard/dashboards/admin/overview/tests.py | Python | apache-2.0 | 8,099 | 0 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | =False, overview_days_range=None)
@test.create_mocks({api.nova: ('usage_list',),
api.keystone: ('tenant_list',)})
def _test_usage_csv(self, nova_stu_enabled=True, overview_days_range=1):
self.mock_tenant_list.return_value = [self.tenants.list(), False]
usage_obj = [api.n... | _obj
csv_url = reverse('horizon:admin:overview:index') + "?format=csv"
res = self.client.get(csv_url)
self.assertTemplateUsed(res, 'admin/overview/usage.csv')
self.assertIsInstance(res.context['usage'], usage.GlobalUsage)
hdr = '"Project Name","VCPUs","RAM (MB)","Disk (GB)","Usa... |
nitely/Spirit | spirit/topic/admin/urls.py | Python | mit | 342 | 0 | # -*- coding: utf-8 -*-
from django.c | onf.urls import re_path
from . import views
app_name = 'topic'
urlpatterns = [
re_path(r'^$', views.deleted, name='index'),
re_p | ath(r'^deleted/$', views.deleted, name='deleted'),
re_path(r'^closed/$', views.closed, name='closed'),
re_path(r'^pinned/$', views.pinned, name='pinned'),
]
|
CajetanP/coding-exercises | Exercism/python/beer-song/beer_song.py | Python | mit | 808 | 0.002475 | def verse(x):
if x == 0:
return [
"No more bottles of beer on the wall, no more bottles of beer.",
"Go to the store and buy some more, 99 bottles of beer on the wall.",
]
if x == 1:
return [
"1 bottle of beer on the wall, 1 bottle of beer.",
... | er.".format(x),
"Take one down and pass it around, {0} bottle{1} of beer on the wall."
.format(x-1, "" if x == 2 else "s")
]
def recite(start, take=1):
result = []
while take > 0:
result += ver | se(start)
result.append("")
start -= 1
take -= 1
return result[:-1]
|
kickstandproject/python-payloadclient | payloadclient/shell/v1/agent.py | Python | apache-2.0 | 1,641 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2013 PolyBeacon, 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 applica... | ""List agents."""
list_columns = [
'uuid',
'user_id',
'project_id',
'created_at',
'updated_at',
]
log = logging.getLogger(__name__ + '.ListAgent')
resource = 'agents'
class ShowAgent(base.ShowCommand):
"""Show information of a given agent."""
log = log... | ts'
|
lizardsystem/lizard5-apps | lizard_rainapp/forms.py | Python | lgpl-3.0 | 5,053 | 0.000198 | # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst.
# -*- coding: utf-8 -*-
"""Forms for RainApp. Currently only one, for uploading shapefiles to
fill the GeoObject model."""
# Python 3 is coming
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import... | "Shapefile heeft geen veld '{}'.".format(shape_field))
return
def clean(self):
super(UploadShapefileForm, self).clean()
self.cleaned_data['temporary_directory'] = self.temporary_directory
self.save_file('shp_file')
self.save_file('dbf_file')
self.save_fi... | ile_path'):
self.check_fields_exist()
return self.cleaned_data
def clean_temporary_directory(self):
if os.path.exists(self.temporary_directory):
shutil.rmtree(self.temporary_directory)
|
Ebag333/Pyfa | eos/effects/rolebonuscdlinkspgreduction.py | Python | gpl-3.0 | 325 | 0.003077 | # roleBonusCDLinksPGReduction
#
# Used by:
# Ships from group: Command Destroyer (4 of 4)
# Ship: Porpoise
type = "passive"
|
def handler(fit, src, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Leadership"), "power",
| src.getModifiedItemAttr("roleBonusCD"))
|
MoroGasper/client | tests/test_recaptcha.py | Python | gpl-3.0 | 1,831 | 0.006011 | # -*- coding: utf-8 -*-
"""Copyright (C) 2013 COLDWELL AG
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 dist... | You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import loader
loader.init()
import gevent
import requests
fr | om client import interface, event
from client.captcha import recaptcha
def send_input(e, input):
gevent.spawn_later(0.1, interface.call, 'input', 'answer', id=input.id, answer={'captcha': 'invalid test recaptcha answer'})
def test_recaptcha():
browser = requests.session()
resp = browser.get("http://www.go... |
rombie/contrail-controller | src/config/api-server/vnc_cfg_api_server/vnc_rbac.py | Python | apache-2.0 | 12,746 | 0.003138 | #
# Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
#
import sys
import json
import uuid
import string
import re
import ConfigParser
from provision_defaults import *
from cfgm_common.exceptions import *
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from vnc_api.gen.vnc_api_client_gen import al... | rules = self.get_rbac_rules_object('global_system_config', config_uuid)
rule_list.extend(rules)
# get domain rbac group
rules = self.get_rbac_rules_object('domain', domain_id)
rule_list.extend(rules)
# get project rbac group
if project_id is not None:
rules ... | s)
# [{u'rule_object': u'*', u'rule_perms': [{u'role_crud': u'CRUD', u'role_name': u'admin'}], u'rule_field': None}]
# collapse of rules might be needed as same object/field might be present in
# domain as well project rules
rule_dict = {}
for rule in rule_list:
o =... |
datalogics/scons | test/TEX/auxiliaries.py | Python | mit | 3,930 | 0 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... | ary sections to be excluded from the output.
That was fixed (courtesy Joel B. Mohler) by making all the relevant
auxiliary files Precious().
Test configuration courtesy Dmitry Mikhin.
"""
import TestSCons
test = TestSCons.TestSCons()
dvips = test.where_is('dvips')
latex = test.where_is('latex')
if not dvips or not... | tex:
test.skip_test("Could not find dvips or latex; skipping test(s).\n")
test.subdir(['docs'])
test.write(['SConstruct'], """\
env = Environment(tools = ['pdftex', 'dvipdf', 'dvips', 'tex', 'latex'],
ENV = {},
BUILD_DIR = '#build/docs')
# Use 'duplicate=1' because LaTeX tool... |
darkopevec/kivy | kivy/animation.py | Python | mit | 24,358 | 0.000082 | '''
Animation
=========
:class:`Animation` and :class:`AnimationTransition` are used to animate
:class:`~kivy.uix.widget.Widget` properties. You must specify at least a
property name and target value. To use an Animation, follow these steps:
* Setup an Animation object
* Use the Animation object on a Widget
... | the '&' operator. The following example
will animate the position to (80, 10) over 1 second, whilst in parallel
animating the size to (800, 800)::
anim = Animation(pos=(80, 10))
anim &= Animation(size=(800, 800), duration=2.)
anim.start(widget)
Keep in mind that creating overlapping animations on the sam... | f you want to apply multiple animations to the same
property, you should either schedule them sequentially (via the '+' operator or
using the *on_complete* callback) or cancel previous animations using the
:attr:`~Animation.cancel_all` method.
Repeating animation
-------------------
.. versionadded:: 1.8.0
.. note::... |
GiovanniCardamone/tg-client_2 | lib/bot/Bot.py | Python | gpl-3.0 | 789 | 0.029151 | import threading
import time
from lib.Message import Message
class Bot(threading.Thread):
controller = None
username = None
| message = None
status = False
event = None |
counter = 0
def __init__ (self, controller, username):
"""
"""
self.controller = controller
self.username = username
self.event = threading.Condition()
super().__init__(group=None)
#
#
#
def getUsername(... |
kinow-io/kinow-python-sdk | kinow_client/models/video_access_info_response.py | Python | apache-2.0 | 8,913 | 0.000561 | # coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 2.0.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class VideoAccessInfoResponse(object):
"""
NOTE: This cl... | streaming of this VideoAccessInfoResponse.
:rtype: bool
"""
return self._streaming
@streaming.setter
def streaming(self, streaming):
"""
Sets the streaming of this VideoAccessInfoResponse.
:param streaming: The streaming of this VideoAccessInfoResponse.
... | = streaming
@property
def download(self):
"""
Gets the download of this VideoAccessInfoResponse.
:return: The download of this VideoAccessInfoResponse.
:rtype: bool
"""
return self._download
@download.setter
def download(self, download):
"""
... |
lokeshjindal15/gem5_transform | configs/common/Simulation.py | Python | bsd-3-clause | 21,327 | 0.002485 | # Copyright (c) 2012-2013 ARM Limited
# All rights reserved
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functiona... | ype, options)
return cls, cls.memory_mode()
def setCPUClass(options):
"""Returns two cpu classes and the initial mode of operation.
Restoring from a checkpoint or fast forwarding through a benchmark
can be done using one type of cpu, and then the actual
simulation can be carried out using... | Class, test_mem_mode = getCPUClass(options.cpu_type, options)
CPUClass = None
if TmpClass.require_caches() and \
not options.caches and not options.ruby:
fatal("%s must be used with caches" % options.cpu_type)
if options.checkpoint_restore != None:
if options.restore_with_cpu !=... |
timm/timmnix | pypy3-v5.5.0-linux64/lib-python/3/test/test_pyclbr.py | Python | mit | 7,018 | 0.00228 | '''
Test cases for pyclbr.py
Nick Mathewson
'''
from test.support import run_unittest
import sys
from types import FunctionType, MethodType, BuiltinFunctionType
import pyclbr
from unittest import TestCase
StaticMethodType = type(staticmethod(lambda: None))
ClassMethodType = type(classmethod(lambda c: None))
# H... | thods, actualMethods, ignore)
self.assertEqual(py_item.__module__, value.module)
self.assertEqualsOrIgnored(py_item.__name__, value.name,
ignore)
# can't check file or line | no
except:
print("class=%s" % py_item, file=sys.stderr)
raise
# Now check for missing stuff.
def defined_in(item, module):
if isinstance(item, type):
return item.__module__ == module.__name__
if isinstance(i... |
xiaonanln/myleetcode-python | src/659. Split Array into Consecutive Subsequences.py | Python | apache-2.0 | 1,119 | 0.051832 | from heapq import *
class Solution(object):
def isPossible(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums: return False
seqs0 = [] #seqs ends with the current num
seqs1 = [] #seqs ends with the current num - 1
pn = None
for n in nums:
if pn is not None:
# print pn, n, s... | == pn:
pass
elif n == pn+1:
for seqlen in seqs1:
if seqlen < 3: return False
seqs1, seqs0 = seqs0, []
else:
for seqlen in seqs0:
if seqlen < 3: return False
for seqlen in seqs1:
if seqlen < 3: return False
seqs0, seqs1 = [], []
# print pn, n, seqs1, seqs0
... | heappush(seqs0, 1)
# print pn, n, seqs1, seqs0
pn = n
# print seqs1, seqs0
for seqlen in seqs0:
if seqlen < 3: return False
for seqlen in seqs1:
if seqlen < 3: return False
return True
# print Solution().isPossible([1,2,3,3,4,5])
print Solution().isPossible([1,2,3,3,4,4,5,5])
# print Solutio... |
aliyun/oss-ftp | python36/unix/lib/pyftpdlib/test/test_ioloop.py | Python | mit | 19,088 | 0.000419 | #!/usr/bin/env python
# Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>.
# Use of this source code is governed by MIT license that can be
# found in the LICENSE file.
import contextlib
import errno
import select
import socket
import sys
import time
from pyftpdlib._compat import PY3
from pyftpdlib.ioloop im... | ==============
# select()
# ===================================================================
class SelectIOLoopTestCase(unittest.TestCase, BaseIOLoopTestCase):
ioloop_class = pyftpdlib.ioloop.Select
def test_select_eintr(self):
# EINTR is supposed to be ignored
| with mock.patch('pyftpdlib.ioloop.select.select',
side_effect=select.error()) as m:
m.side_effect.errno = errno.EINTR
s, rd, wr = self.test_register()
s.poll(0)
# ...but just that
with mock.patch('pyftpdlib.ioloop.select.select',
... |
dmacvicar/spacewalk | backend/server/test/test_rhnSession.py | Python | gpl-2.0 | 965 | 0 | #
# Copyright (c) 2008--2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version | 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat tradem... | ranted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
from spacewalk.common.rhnConfig import initCFG
from spacewalk.server import rhnSQL, rhnUser
rhnSQL.initDB("rhnuser/rhnuser@webdev")
initCFG('server.xmlrpc')
u = rhnUser.search("mibanescu-channel-admin")
ses... |
adaussy/eclipse-monkey-revival | plugins/python/org.eclipse.eclipsemonkey.lang.python/Lib/distutils/tests/test_sdist.py | Python | epl-1.0 | 16,944 | 0.000354 | """Tests for distutils.command.sdist."""
import os
import tarfile
import unittest
import warnings
import zipfile
from os.path import join
from textwrap import dedent
from test.test_support import captured_stdout, check_warnings, run_unittest
# zlib is not used here, but if it's not available
# the tests that use zipfi... | mp_dir, 'somecode', '.svn', 'ok.py'), 'xxx')
os.mkdir(join(self.tmp_dir, 'somecode', '.hg'))
self.write_file((self.tmp_dir, 'somecode', '.hg',
'ok'), 'xxx')
os.mkdir(join | (self.tmp_dir, 'somecode', '.git'))
self.write_file((self.tmp_dir, 'somecode', '.git',
'ok'), 'xxx')
# now building a sdist
dist, cmd = self.get_cmd()
# zip is available universally
# (tar might not be installed under win32)
cmd.formats = ['zip'... |
Kinnay/NintendoClients | tests/test_dauth.py | Python | mit | 2,095 | 0.015274 |
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n... | 83f90ee845")
keys["master_key_0a"] = byte | s.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
|
x75/mavlink | pymavlink/examples/mavmission.py | Python | lgpl-3.0 | 1,070 | 0.005607 | #!/usr/bin/env python
'''
extract mavlink mission from log
'''
import sys, time, os
# allow import from the parent directory, | where mavlink.py is
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
from optparse import OptionParser
parser = OptionParser("mavmission.py [options]")
parser.add_option("--output", default='mission.txt', help="output file")
(opts, args) = parser.parse_args()
import mavutil, mavwp... | ns] <LOGFILE...>")
sys.exit(1)
parms = {}
def mavmission(logfile):
'''extract mavlink mission'''
mlog = mavutil.mavlink_connection(filename)
wp = mavwp.MAVWPLoader()
while True:
if mlog.mavlink10():
m = mlog.recv_match(type='MISSION_ITEM')
else:
m = mlog.r... |
SumiTomohiko/corgi | tests/test_charset080.py | Python | mit | 344 | 0 | # -* | - coding: utf-8 -*-
from os import environ
from subprocess import PIPE, Popen
from sys import exit
args = [environ["CORGI"], "match", "[ \\t\\n\\r]", "\n"]
proc = Popen(args, stdout=PIPE)
stdout = proc.stdout.read().decode("UTF-8")
proc.wait()
if stdout != "\n":
exit(1)
exit(0)
# vim: tabstop=4 shiftwidth=4 expa... | b softtabstop=4
|
ntymtsiv/tempest | tempest/services/compute/v3/json/aggregates_client.py | Python | apache-2.0 | 3,750 | 0 | # Copyright 2013 NEC Corporation.
# 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... | n writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
from tempest.common.rest_cli... | port exceptions
CONF = config.CONF
class AggregatesV3ClientJSON(RestClient):
def __init__(self, auth_provider):
super(AggregatesV3ClientJSON, self).__init__(auth_provider)
self.service = CONF.compute.catalog_v3_type
def list_aggregates(self):
"""Get aggregate list."""
resp, ... |
marvoey/live-web | sites/all/libraries/fckeditor/editor/filemanager/connectors/py/upload.py | Python | gpl-2.0 | 6,011 | 0.028614 | <<<<<<< HEAD
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http... | ebUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.... | userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFi... |
maurizi/otm-core | opentreemap/treemap/migrations/0032_add_udfs_to_web_detail_fields.py | Python | agpl-3.0 | 1,638 | 0.003053 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from copy import deepcopy
from django.db import migrations, models
from treemap.util import to_object_name
from treemap.search_fields import DEFAULT_WEB_DETAIL_FIELDS
|
def add_udfs_to_web_detail_fields(apps, schema_editor):
Instance = apps.get_mod | el("treemap", "Instance")
UserDefinedFieldDefinition = apps.get_model("treemap", "UserDefinedFieldDefinition")
for instance in Instance.objects.all():
scalar_udfs = UserDefinedFieldDefinition.objects \
.filter(iscollection=False, instance=instance) \
.order_by('name')
#... |
puras/moobo | moobo/settings.py | Python | mit | 2,175 | 0.00046 | """
Django settings for moobo project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
impo... | ware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'moobo | .urls'
WSGI_APPLICATION = 'moobo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproj... |
bsurfer/CryptPass | start.py | Python | gpl-3.0 | 3,177 | 0.005351 | #!/usr/bin/python
import os
import getpass
from Shadow import *
class Password():
def __init__(self, passwd):
self.data = Shadow(passwd)
def list(self):
info = self.data.getInfo()
for row in info:
#print row['id'] ,row['name'],row['user'],row['password']
print... |
while True:
self.options()
value = raw_input("Make a selection> ")
if '1' in value:
self.imp()
#self.runSetMenu()
#os.system('clear')
os.ch
elif '2' in value:
... | elif '3' in value:
self.ins()
#self.deleteSetMenu()
#os.system('clear')
elif '4' in value:
#self.createSetMenu()
self.search()
#os.system('clear')
elif '5' in value:
... |
tripmode/pxlcoin | share/qt/clean_mac_info_plist.py | Python | mit | 894 | 0.017897 | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Pxlcoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
inF... | e = bitcoinDir+"/share/qt/Info.plist"
outFile = "Pxlcoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrab | bingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)
fOut = open(outFile, "w");
fOut.wr... |
MaryanMorel/utopical-brotherhood | __init__.py | Python | mit | 251 | 0.003984 | #! /usr/bin/python2
# -*- coding: utf8 -*-
# utopical_brotherhood/
# __init__.py
# actors/
# Big_brother.py
# Manager.py
# Fetcher.py
# Parser.py
# Learner.py
from actors import | *
__all_ | _ = ["actors"] |
reisalex/test-sfm | setup.py | Python | gpl-3.0 | 588 | 0.005102 | """
Python-packaging for synbiomts
Copyright 2017 Alexander C. Reis, Howard M. Salis, all rights reserved.
"""
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='synbiomts',
version='1.0',
description='Test suit | e for DNA sequence | -function models',
url='http://github.com/reisalex/SynBioMTS',
author='Alexander C. Reis',
author_email='alex.reis@psu.edu',
license='MIT',
packages=['synbiomts'],
# install_requires=['numpy','scipy','pandas','biopython'],
zip_safe=False) |
eresearchrmit/hpctardis | tardis/tardis_portal/management/commands/dumpschemas.py | Python | bsd-3-clause | 1,683 | 0.000594 | """
Command for dumping soft schema definitions
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
from django.core import serializers
from optparse import make_option
from tardis.tardis_portal import models
class Command(BaseCommand):
help... | get('traceback', False)
format = options.get('format', 'json')
if format not in serializers.get_public_serializer_formats():
raise CommandError("Unknown serialization format: %s" % format)
try:
serializers.get_serializer(format)
| except KeyError:
raise CommandError("Unknown serialization format: %s" % format)
objects = []
objects.extend(models.Schema.objects.all())
objects.extend(models.ParameterName.objects.all())
try:
return serializers.serialize(format, objects, indent=4,
... |
telefonicaid/fiware-sdc | automatization_scripts/get_software_catalogue.py | Python | apache-2.0 | 4,111 | 0.009976 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Telefonica | Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# 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... | HOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For those usages not covered by the Apache version 2.0 License please
# contact with opensource@tid.es
'''
Created on 16/04/2013
@author:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.