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 |
|---|---|---|---|---|---|---|---|---|
openai/baselines | baselines/ppo2/microbatched_model.py | Python | mit | 3,241 | 0.007097 | import tensorflow as tf
import numpy as np
from baselines.ppo2.model import Model
class MicrobatchedModel(Model):
"""
Model that does training one microbatch at a time - when gradient computation
on the entire minibatch causes some overflow
"""
def __init__(self, *, policy, ob_space, ac_space, nbat... | self.train_model.X: obs[_sli],
self.A:actions[_sli],
self.ADV:advs[_sli],
self.R:returns[_sli],
self.CLIPRANGE:cliprange,
self.OLDNEGLOGPAC:neglogpacs[_sli],
self.OLDVPRED:values[_sli]
| }
# Compute gradient on a microbatch (note that variables do not change here) ...
grad_v, stats_v = self.sess.run([self.grads, self.stats_list], td_map)
if microbatch_idx == 0:
sum_grad_v = grad_v
else:
# .. and add to the total of... |
slackhq/python-rtmbot | setup.py | Python | mit | 521 | 0 | #!/usr | /bin/env python
from setuptools import setup, find_packages
setup(
name='rtmbot',
version='0.4.1',
description='A Slack bot written in python that connects via the RTM API.',
author='Ryan Huber and Jeff Ammons',
author_email='developers@slack.com',
url='https://github.com/slackhq/python-rtmbot'... | scripts': ['rtmbot=rtmbot.bin.run_rtmbot:main']},
install_requires=[
'pyyaml>=3, <4',
'slackclient>=1, <2'
]
)
|
g-weatherill/oq-risklib | openquake/calculators/calc.py | Python | agpl-3.0 | 9,525 | 0.000105 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014, GEM Foundation
# OpenQuake 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 Licen... | map goes automatically to zero
hmap_val.append(0)
else:
# exp-log interpolation, to reduce numerical errors
# see https://bugs.launchpad.net/oq-engine/+bug/1252770
val = num | py.exp(
numpy.interp(
numpy.log(poe), numpy.log(curve_cutoff), imls))
hmap_val.append(val)
result.append(hmap_val)
return numpy.array(result)
# ######################### GMF->curves #################################### #
# NB (MS): the approac... |
InfoSec-CSUSB/club-websystem | src/events/urls.py | Python | mit | 675 | 0.002963 | from django.conf.urls import url
from views import calendarpage, jsonsearch, fcdragmodify, Even | tManager, event_view
event_manager = EventManager.as_view()
urlpatterns = [
url(r'^$', calendarpage, name='events'),
url(r'^json/', jsonsearch, name='jsonsearch'),
url(r'^modify/', fcdragmodify, name='fcdragmodify'),
url(r'^new/', event_manager, name='newevent'),
url(r'^(?P<eventid>\d+)/edit/', event_manage... | nt': False}, name='editrecurringevent'),
# Must be last...
url(r'^(?P<eventid>\d+)/', event_view, name='viewevent'),
]
|
swimmadude66/RestEasy | python/get_pin.py | Python | apache-2.0 | 3,367 | 0.00594 | import os
import sys
from subprocess import check_output
class pin_power:
async = 'disabled'
control = 'auto'
runtime_enabled = 'disabled'
runtime_status = 'Unsupported'
runtime_active_kids = 0
runtime_active_time = 0
runtime_suspended_time = 0
runtime_usage = 0
def __str__(self):... | _info(pin_id):
if not (os.path.isdir('/sys/class/gpio/gpio'+str(pin_id))):
print('{\n\tsuccess: false, \n\tmessage: "pin ' + pin_id +' does not exist"\n}')
| exit(-1)
pin_obj = pin(pin_id)
pin_path = '/sys/class/gpio/gpio'+str(pin_id)+'/'
pin.active_low = open(pin_path+'active_low', 'r').read().strip()
pin.direction = open(pin_path+'direction', 'r').read().strip()
pin.edge = open(pin_path+'edge', 'r').read().strip()
pin.value = open(pin_path+'value',... |
mvaled/sentry | src/sentry/utils/settings.py | Python | bsd-3-clause | 2,420 | 0.001653 | from __future__ import absolute_import
import inspect
import six
import sys
from sentry.utils.imports import import_string
PACKAGES = {
"django.db.backends.postgresql_psycopg2": "psycopg2.extensions",
"sentry.db.postgres": "psycopg2.extensions",
"django.core.cache.backends.memcached.MemcachedCache": "mem... |
>>> do_something_crazy()
>>> except Exception:
>>> reraise_as(UnhandledException)
"""
__traceback_hide__ = True # NOQA
e_type, e_value, e_traceback = sys.exc_info()
if inspect.isclass(new_exception_or_type):
new_type = new_exception_or_type
new_exception = new_exc... | .reraise(new_type, new_exception, e_traceback)
finally:
del e_traceback
def validate_settings(settings):
for key, engine_key, engine_type in [
("DATABASES", "ENGINE", "database engine"),
("CACHES", "BACKEND", "caching backend"),
]:
value = getattr(settings, key, {})
... |
shendric/pyoval | tests_resample_uofa_orbits.py | Python | gpl-3.0 | 9,128 | 0.006792 | # -*- coding: utf-8 -*-
import os
import glob
# Import Data Resampling Class from user library
from lib.pyoval import CS2RefOrbit
from lib.pyoval import CS2OrbitResData
from lib.data import read_embird_dat
from lib.data import read_OIB
from lib.helpers import EmptyObject
class PathInfo():
""" Definition of path... | ldenDays/'
self.dir.SampleDat | a = os.path.join(self.dir.workspace,'20130424')
self.dir.RefOrbit = self.dir.SampleData
self.dir.RefCCOrbit = self.dir.SampleData
self.dir.SampleFigures = self.dir.SampleData
# Files
self.file = EmptyObject()
#self.file.example_orbit = r'Location_file_21011_20140326T09000... |
snewell/wlint | lib/wlint/punctuation/colon.py | Python | bsd-2-clause | 973 | 0 | #!/usr/bin/python3
|
"""Punctuation rules around colons and semi-colons."""
import wlint.punctuation
def _colon_rule(name, colon):
rules = []
# a colon might be followed by a digit if it's time
if name == "colon":
rules.append(("{}.missing-space".format(name),
wlint.punctuation.make_pair_regex_... | "[^\\s\\d]")))
elif name == "semicolon":
rules.append(("{}.missing-space".format(name),
wlint.punctuation.make_pair_regex_rule(colon,
"\\S")))
rules.append(("{}.preceeding-space".format(name),
... |
litecoinz-project/litecoinz | qa/rpc-tests/keypool.py | Python | mit | 4,852 | 0.004534 | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2017-2018 The LitecoinZ developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet ... | # put three new keys in the keypool
nodes[0].walletpassphrase('test', 12000)
nod | es[0].keypoolrefill(3)
nodes[0].walletlock()
# drain the keys
addr = set()
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
# assert that four unique addresses were returne... |
Edraak/edraak-platform | openedx/core/djangoapps/user_api/accounts/serializers.py | Python | agpl-3.0 | 19,240 | 0.003119 | """
Django REST Framework serializers for the User API Accounts sub-application
"""
import json
import logging
from rest_framework import serializers
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from s... | _links = SocialLinkSerializer(many=True, required=False)
name_en = serializers.CharField(required=False)
class Meta(object):
model = UserProfile
field | s = (
"name", "name_en", "gender", "goals", "year_of_birth", "level_of_education", "country", "social_links",
|
mapequation/infomap | utils/create-python-package-meta.py | Python | agpl-3.0 | 1,125 | 0.001778 | import json
def creat | e_package_meta(package_json, meta_file):
with open(package_json, 'r') as fp:
pkg = json.load(fp)
lines = (
f"__name__ = \"infomap\"\n",
f"__version__ = \"{pkg.get('version')}\"\n",
f"__description__ = \"{pkg.get('description')}\"\n",
f"__author__ = \"{pkg.get('author... |
f"__license__ = \"{pkg.get('license')}\"\n",
f"__homepage__ = \"{pkg.get('homepage')}\"\n",
f"__url__ = \"{pkg.get('python')['homepage']}\"\n",
f"__repo__ = \"{pkg.get('repository')['url']}\"\n",
f"__issues__ = \"{pkg.get('bugs')['url']}\"\n",
f"__keywords__ = \"{' '.joi... |
onebit0fme/django-pgMemento | pg_memento/management/commands/_sql.py | Python | lgpl-3.0 | 1,024 | 0.001953 | from django.db import connection
INIT_PG_MOMENTO = """
-- 'Create event trigger to log schema changes ...'
SELECT pgmemento.create_schema_event_trigger(0);
-- 'Creating triggers for tables in ':schema_name' schema ...'
SELECT pgmemento.create_schema_log_trigger('public', string_to_array('%s',','));
-- 'Creating aud... | T_PG_MOMENTO % (','.join(ignore_tables), ','.join(ignore_tables)))
def uninit(ignore_tables=None):
cursor = connection.cursor()
if ignore_tables is None:
cursor.execute(DROP_SCHEMA_LOG)
else:
cursor.execute(DROP_SCHEMA_LOG_IGNORE % (','.join(ignore_tables), | ))
|
carlwgeorge/pnc | pnc.cli/pnc/cli/__init__.py | Python | apache-2.0 | 850 | 0.007059 | import click
def incomplete(package):
click.echo('{} packages not yet implemented'.format(package))
@click.group()
def run():
'''Build packages inside Docker containers.'''
pass
@click.command()
@click.option('--image', '-i', help='imag | e to build in', required=True)
def rpm(image):
package = click.style('RPM', fg='red', bo | ld=True)
incomplete(package)
@click.command()
@click.option('--image', '-i', help='image to build in', required=True)
def deb(image):
package = click.style('Debian', fg='magenta', bold=True)
incomplete(package)
@click.command()
@click.option('--image', '-i', help='image to build in', required=True)
def ar... |
mhrivnak/pulp | server/test/unit/server/managers/content/test_query.py | Python | gpl-2.0 | 5,319 | 0.00282 | import inspect
import unittest
import mock
from pulp.server.db.connection import PulpCollection
from pulp.server.db.model.criteria import Criteria
from pulp.server.managers.content.query import ContentQueryManager
from test_cud import PulpContentTests, TYPE_1_DEF, TYPE_1_UNITS, TYPE_2_DEF, TYPE_2_UNITS
class PulpCo... | the correct collection
mock_get_collection.assert_called_once_with('deb')
# make sure the query call itself was correct
mock_query = mock_get_collection.return_value.query
self.assertEqual(mock_query.call_count, 1)
self.assertEqual(mock_query.call_args[0][0], criteria)
... | E_1_DEF.id)
self.assertEqual(len(TYPE_1_UNITS), len(units))
units = self.query_manager.list_content_units(TYPE_2_DEF.id)
self.assertEqual(len(TYPE_2_UNITS), len(units))
def test_get_by_id(self):
unit = self.query_manager.get_content_unit_by_id(TYPE_1_DEF.id, self.type_1_ids[0])
... |
Ecpy/ecpy_hqc_legacy | exopy_hqc_legacy/instruments/drivers/visa/anritsu_signal_source.py | Python | bsd-3-clause | 5,187 | 0.000193 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by ExopyHqcLegacy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ------... | super(AnritsuMG3694, self).__init__(connection_info,
caching_allowed,
caching_permissions,
auto_open)
self.frequency_unit = 'GHz'
def open_connection(self, **para):
"... | super(AnritsuMG3694, self).open_connection(**para)
self.write_termination = '\n'
self.read_termination = '\n'
self.write("DSPL 4")
self.write("EBW3") # if the external reference is very stable in phase
# the largest EBW must be chosen
self.write("LO0"... |
frouty/odoogoeen | extra-addons/oph/oph/custom/oph_res_users.py | Python | agpl-3.0 | 773 | 0.01423 | # -*- coding: utf-8 -*-
#===============================================================================
# Custom res_users object
# Add an CAFAT ID for use in New Caledonia
#===============================================================================
from openerp.osv import fields, osv, orm
from openerp.tools.trans... | .users"
_columns = {
'cafat_id':fields.char('CAFAT ID', size = 16, help = 'CAFAT ID of | the doctor = convention number. This is not the CAFAT Number as for a patient'),
}
|
akchinSTC/rtc2git | tests/test_migration.py | Python | mit | 1,445 | 0.002076 | import unittest
import os
from unittest.mock import patch
import migration
from configura | tion import Builder
import configuration
from tests import testhelper
class MigrationTestCase(unittest.TestCase):
def | setUp(self):
self.rootfolder = os.path.dirname(os.path.realpath(__file__))
@patch('migration.Commiter')
@patch('migration.Initializer')
@patch('migration.RTCInitializer')
@patch('migration.os')
@patch('configuration.shutil')
def testDeletionOfLogFolderOnInitalization(self, shutil_mock, ... |
l3enny/lasana | parse.py | Python | mit | 4,091 | 0.010761 | """
Processes the data from whatever format it was captured in and renders
it in a usable form to whoever's knocking.
"""
# Standard modules
import ConfigParser
import os
from os import path
import sys
# Third party
import numpy as N
def config(top_dir='.', debug=False):
# Parse the settings file, check for pro... | .zeros((samples, points))
v_r = N.ze | ros((samples, points))
i_r = N.zeros((samples, points))
pd_s = N.zeros((samples, points))
ref_s = N.zeros((samples, points))
v_s = N.zeros((samples, points))
i_s = N.zeros((samples, points))
# Loop over all acquired files
for i in range(samples):
if obsolete:
referen... |
riceissa/static-site-generator | tags.py | Python | unlicense | 7,669 | 0.001565 | # This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or distribute
# this software, either in source code form or as a compiled binary, for any
# purpose, commercial or non-commercial, and by any means.
#
# In jurisdictions that recog... | children: '[TagNode]'):
"""
"""
pass
def is_descendant(self, tag_one, tag_two):
"""
(TagNode, TagNode) -> bool
Check if tag_one is a descendant of tag_two.
"""
is_des = False
def implies(self, tag_one, tag_two):
"""
(TagNode, Ta... | bool
Check if tag_one implies tag_two. Same as is_descendant.
"""
return self.is_descendant(tag_one, tag_two)
def write(self):
pass
def size(self):
return len(self.data)
if __name__ == "__main__":
main()
|
mistermatti/plugz | setup.py | Python | bsd-3-clause | 1,412 | 0.001416 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
f | rom setuptools.command.test import test as TestC | ommand
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import plugz
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
]
setup(
n... |
kidchang/compassv2-api | compass/actions/health_check/check_package_installer.py | Python | apache-2.0 | 4,679 | 0 | # Copyright 2014 Huawei Technologies Co. Ltd
#
# 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... | chef_data_map[data_type]))
print "[Done]"
missing = False
for item in total_missing:
if item[1] != []:
missing = True
break
if missing is True:
messages = []
for item in total_missing:
... | issed for missed in item[1])))
self._set_status(
0,
"[%s]Error: Missing modules on chef server: "
"%s." % (
self.NAME,
' ;'.join(message for message in messages)))
self.check_chef_config_dir()
print "[Do... |
mayankjohri/LetsExplorePython | Section 2 - Advance Python/Chapter S2.11 Multiprocessing and Threading/code/multi_2.py | Python | gpl-3.0 | 1,045 | 0 | from urllib.request import urlopen
from multiprocessing.dummy import Pool as ThreadPool
import time
from datetime import timedelta
urls = ['http://www.python.org',
'http://www.python.org/about/',
'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
'http://www.python.org/doc/',
... | he results
results = pool.map(urlopen, urls)
# close the pool and wait for the work to finish
pool.close()
pool.join()
end_time = time.monotonic()
print(tim | edelta(seconds=end_time - start_time))
|
wy36101299/NCKU_Machine-Learning-and-Bioinformatics | hw4_predictData/creatPredictdata.py | Python | mit | 2,986 | 0.015405 | import glob
import os
import pandas as pd
class CTD(object):
"""docstring for CTD"""
def __init__(self):
self.format_l = []
self.td_l = []
self.iternum = 0
self.formatname = ""
def feature(self,index):
format_l = self.format_l
feature = ((float(format_l[inde... | format_l = self.format_l
classify = (float(format_l[index][3])-float(format_l[index+1][3]))/float(format_l[index+1][3])*100
feature = self.feature(index)
a = ['0']+format_l[index+1]+format_l[in | dex+2]+format_l[index+3]+[feature]
self.td_l.append(a)
except:
pass
def storage_csv(self):
rowname=['classify','feature','1-open','1-high','1-low','1-close','1-volume','1-adj close','2-open','2-high','2-low','2-close','2-volume','2-adj close','3-open','3-high','3... |
jpadilla/feedleap | feedleap/config.py | Python | mit | 527 | 0 | impor | t base64
from django.conf import settings
class SubHubConfig(object):
def get_extra_hub_headers(self, feed_url, hub_url): |
headers = {}
if hub_url == settings.SUPERFEEDR_HUB:
headers['Authorization'] = \
'Basic %s' % base64.b64encode('%s:%s' % (
settings.SUPERFEEDR_USER,
settings.SUPERFEEDR_PASS,
))
return headers
def get_defau... |
diogo149/simbo | webapp/demo/binary.py | Python | mit | 1,214 | 0.004942 | import json
import random
from uuid import uuid1
from collections import defaultdict
import requests
schema_url = "http://localhost:5000/api/schema/"
experiment_url = "http://localhost:5000/api/sample/"
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
binary_schema = {
"default": 0,
"di... | return str(uuid1())
def gen_schema(keys):
return {key: binary_schema for key in keys}
def objective_function(a, b, **kwargs):
return (0.5
+ random.uniform(0, 1)
+ 3 * a
+ 2 * b
- 5 * (a * b))
keys = ['a', 'b']
experiment = "binary" # uuid()
e | xperiment_url += experiment
schema_url += experiment
schema = gen_schema(keys)
requests.post(schema_url, data=json.dumps(schema), headers=headers)
distribution = defaultdict(lambda: 0)
while True:
r = requests.get(experiment_url)
in_data = r.json()
distribution[(in_data["a"], in_data["b"])] += 1
prin... |
czpython/aldryn-newsblog | aldryn_newsblog/views.py | Python | bsd-3-clause | 13,366 | 0.000075 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
try:
from django.contrib.sites.shortcuts import get_current_site
except ImportError:
# Django 1.6
from django.contrib.sites.models import get_current_site
f... | __gt=object.publishing_date
).order_by(
'publishing_date'
)[:1]
if next_objs:
return next_objs[0]
else:
return None
class ArticleListBase(AppConfigMixin, AppHookChe | ckMixin, TemplatePrefixMixin,
PreviewModeMixin, ViewUrlMixin, ListView):
model = Article
show_header = False
def get_paginate_by(self, queryset):
if self.paginate_by is not None:
return self.paginate_by
else:
try:
return self.con... |
cloudControl/cctrl | cctrl/user.py | Python | apache-2.0 | 8,933 | 0.000448 | # -*- coding: utf-8 -*-
"""
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
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
... | 'Type "Yes" without the quotes to remove: ')
else:
question = 'Yes'
if question.lower() == 'yes':
self.api.delete_user_key(users[0]['username'], args.id[0])
else:
rais | e InputErrorException('SecurityQuestionDenied')
def logout(self, args):
"""
Logout a user by deleting the token.json file.
"""
self.api.set_token(None)
def registerAddon(self, args):
file_content = readContentOf(args.manifest)
email, password = get_email_and... |
Plenglin/math-game | src/sprites.py | Python | gpl-2.0 | 1,911 | 0.002616 | import time
import pygame
import colors
class Spritesheet():
surface = None
size = (0, 0)
def __init__(self, surface, size):
self.surface = surface
self.size = size
def get(self, x, y):
surf = pygame.Surface(self.size, pygame.SRCALPHA, 32)
croparea = (x * self.size[... | - 1]
def isFinished(self):
return self.getFrame() >= self.getFrames() and self.hasStarted
def getRect(self):
return self.frames[0].get_rect()
def spriteAnimation(surf, fps):
w, h = surf.get_size()
sheet = Spritesheet(surf, (h, h))
frames = []
for x in range(0, int(w / h)):
... | pygame.init()
d = pygame.display.set_mode((640, 480))
explosionAnimation = spriteAnimation(assets.explosionEnd1, 30)
explosionAnimation.start()
while True:
d.fill(colors.white)
d.blit(explosionAnimation.getSurface(), (0, 0))
pygame.display.update()
if __name__ == '__main__':... |
unbracketed/tipi | tipi/commands/base.py | Python | mit | 12,932 | 0.004021 | """
Base classes for writing management commands (named commands which can
be executed through ``tipi.py``).
"""
import os
import sys
from ConfigParser import ConfigParser
from optparse import make_option, OptionParser
from virtualenv import resolve_interpreter
class CommandError(Exception):
"""
Exception cl... | ement command which takes one or more installed application
# names as arguments, and does something with each of them.
#
# Rather than implementing ``handle()``, subclasses must implement
# ``handle_app()``, which will be called once for each application.
#
# """
# args = '<appname appname ...>'
#
#... | ')
# try:
# app_list = [models.get_app(app_label) for app_label in app_labels]
# except (ImproperlyConfigured, ImportError), e:
# raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
# output = []
# for app in app_list:
# app_out... |
ondoheer/GOT-english | holdings.py | Python | gpl-2.0 | 7,657 | 0.000131 | from libraries import JSONDictionary
holdingsData = {
'defense': {
'superiorCastle': 50,
'castle': 40,
'smallCastle': 30,
'hall': 20,
'tower': 10
},
'influence': {
'firstBorn': 20,
'secondBorn': 10,
'otherChildren': 5
},
'lands': {
... | Holdings.append('First Born')
influenceTotal -= influenceDict['firstBorn']
if influenceTotal < influenceDict['secondBorn']:
houseDict['influenceHoldings'] = self.influenceHoldings
houseDict['remainingInfluence'] = influenceTotal
return houseDict
... | influenceTotal -= influenceDict['secondBorn']
while influenceTotal > influenceDict['otherChildren']:
self.influenceHoldings.append('Other child')
influenceTotal -= influenceDict['otherChildren']
houseDict['influenceHoldings'] = self.influenceHold... |
xwb1989/hackerrank-go | alternatestring/rand.py | Python | mit | 189 | 0.015873 | import rand | om
import sys
print(1 | )
for i in range(0,100000):
if random.randint(0,1) == 0:
sys.stdout.write('A')
else:
sys.stdout.write('B')
sys.stdout.write('\n')
|
TumblrCommunity/PowerPortfolio | portfolio/models/base.py | Python | mit | 101 | 0 | # /mod | els/base.py
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_bas | e()
|
justanr/owa | owa/api/album.py | Python | gpl-3.0 | 358 | 0 | from ..models im | port Album
from ..resource import SingleResource, ListResource
from ..schemas import AlbumSc | hema
class SingleAlbum(SingleResource):
schema = AlbumSchema()
routes = ('/album/<int:id>/',)
model = Album
class ListAlbums(ListResource):
schema = AlbumSchema(many=True)
routes = ('/album/', '/tracklist/')
model = Album
|
ExCiteS/geokey-webresources | geokey_webresources/forms.py | Python | mit | 321 | 0 | """All forms for the extension."""
from django.forms import ModelForm
from .models i | mport WebResource
class WebResourceForm(ModelForm):
"""Form for a single web resource."""
| class Meta:
"""Form meta."""
model = WebResource
fields = ('name', 'description', 'url', 'colour', 'symbol')
|
mahim97/zulip | zerver/lib/user_groups.py | Python | apache-2.0 | 3,491 | 0.00487 | from __future__ import absolute_import
from collections import defaultdict
from django.db import transaction
from django.utils.translation import ugettext as _
from zerver.lib.exceptions import JsonableError
from zerver.models import UserProfile, Realm, UserGroupMembership, UserGroup
from typing import Dict, Iterable,... | user_profile=user_profile)
return created
def remove_user_from_user_group(user_profile: UserProfile, user_group: UserGroup) -> int:
num_deleted, _ = UserGroupMembership.objects. | filter(
user_profile=user_profile, user_group=user_group).delete()
return num_deleted
def check_remove_user_from_user_group(user_profile: UserProfile, user_group: UserGroup) -> bool:
try:
num_deleted = remove_user_from_user_group(user_profile, user_group)
return bool(num_deleted)
ex... |
dtudares/hello-world | yardstick/yardstick/vTC/apexlake/experimental_framework/benchmarks/instantiation_validation_noisy_neighbors_benchmark.py | Python | apache-2.0 | 3,974 | 0 | # Copyright (c) 2015 Intel Research and Development Ireland Ltd.
#
# 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 app... | perimental_framework import common
NUM_OF_NEIGHBORS = 'num_of_neighbours'
AMOUNT_OF_RAM = 'amount_of_ram'
NUMBER_OF_CORES = 'number_of_cores'
NETWORK_NAME = 'network'
SUBNET_NAME = 'subnet'
class InstantiationValidationNoisyNeighborsBenchmark(
base.InstantiationValidationBenchmark):
def __init__(self, ... | mp_name = 'stress_workload_liberty.yaml'
else:
temp_name = 'stress_workload.yaml'
self.template_file = common.get_template_dir() + \
temp_name
self.stack_name = 'neighbour'
self.neighbor_stack_names = list()
def get_features(self):
features = super(I... |
BD2KGenomics/slugflow | src/toil/leader.py | Python | apache-2.0 | 63,884 | 0.004931 | # Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... | super().__init__()
self.jobStoreLocator = jobStoreLocator
self.numberOfFailedJobs = len(failedJobs)
def __str__(self):
"""
Stringify the exception, including the message.
"""
return self.msg
####################################################
##Following class re... | self, config, batchSystem, provisioner: AbstractProvisioner, jobStore, rootJob, jobCache=None):
"""
:param toil.common.Config config:
:param toil.batchSystems.abstractBatchSystem.AbstractBatchSystem batchSystem:
:param toil.provisioners.abstractProvisioner.AbstractProvisioner provisioner... |
flacjacket/qtile | libqtile/widget/battery.py | Python | mit | 16,807 | 0.000833 | # Copyright (c) 2011 matt
# Copyright (c) 2011 Paul Colomiets
# Copyright (c) 2011-2014 Tycho Andersen
# Copyright (c) 2012 dmpayton
# Copyright (c) 2012 hbc
# Copyright (c) 2012 Tim Neumann
# Copyright (c) 2012 uberj
# Copyright (c) 2012-2013 Craig Barnes
# Copyright (c) 2013 Tao Sauvage
# Copyright (c) 2014 Sean Vig
... | return f.read().strip(), value_type
except Exception:
logger.exception("Failed to get %s" % name)
return None
def _get_param(self, name) -> Tuple[str, str]:
if name in self.filenames and self.filenames[name]:
result = self._load_file(self.filenames[name])
| if result is not None:
return result
# Don't have the file name cached, figure it out
# Don't modify the global list! Copy with [:]
file_list = self.BATTERY_INFO_FILES.get(name, [])[:]
user_file_name = getattr(self, name, None)
if user_file_name is not... |
bramfoo/legosorted | camera/camera.py | Python | mit | 494 | 0.002024 | from gpiozero import LED
from picamera imp | ort PiCamera
led = LED(18) # Add some ambient light for crispier picture :-)
camera = PiCamera()
camera.resolution = (600, 400)
def make_picture(file_name):
try:
toggle_light(True)
camera.capture(file_name)
toggle_light(False)
return True
except Exception:
return Fal... | oggle_light(status):
led.on() if status else led.off()
if __name__ == "__main__":
make_picture('test-image.png')
|
xmendez/wfuzz | src/wfuzz/plugins/printers/printers.py | Python | gpl-2.0 | 13,472 | 0.00141 | import socket
import csv as csvmod
import json as jjson
from xml.dom import minidom
from wfuzz.externals.moduleman.plugin import moduleman_plugin
from wfuzz.plugin_api.base import BasePrinter
from wfuzz.exception import FuzzExceptPluginBadParams
@moduleman_plugin
class magictree(BasePrinter):
name = "magictree"
... | ds,
}
self.json_res.append(res_entry)
def footer(self, summary):
self.f.write(jjson.dumps(self.json_res))
@modu | leman_plugin
class raw(BasePrinter):
name = "raw"
author = ("Xavi Mendez (@xmendez)",)
version = "0.1"
summary = "Raw output format"
category = ["default"]
priority = 99
def __init__(self, output):
BasePrinter.__init__(self, output)
def header(self, summary):
self.f.wri... |
pycket/pycket | pycket/prims/vector.py | Python | mit | 11,249 | 0.006401 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from pycket import impersonators as imp
from pycket import values
from pycket import vector as values_vector
from pycket.cont import continuation, label, loop_label
from pycket.error import SchemeException
from pycket.prims.expose import unsafe, default, expose, subclass_... | terpreter import return_value
return return_value(values.w_true, env, cont)
@continuation
def vector_cas_bang_cont(vec, pos_idx, old_val, new_val, env, cont, _vals):
from pycket.interpreter import check_one_val, return_value
current_vec_val = check_one_val(_vals)
if equal.eqp_logic(current_vec_val,old_... | _idx, new_val, env, vector_cas_success(env, cont))
return return_value(values.w_false, env, cont)
# FIXME: Chaperones
@expose("vector-cas!", [values.W_MVector, values.W_Fixnum, values.W_Object, values.W_Object], simple=False)
def vector_cas_bang(vec, pos, old_val, new_val, env, cont):
if isinstance(vec, imp.W_... |
khakhleva/khakhleva.github.io | Ana_photoweb/aino-galleria-fc65989/docs/conf.py | Python | mit | 6,973 | 0.007027 | # -*- coding: utf-8 -*-
#
# Galleria documentation build configuration file, created by
# sphinx-quickstart on Sun Aug 22 04:00:02 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | rue, "(C) Copyright ..." is s | hown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the fi... |
clchiou/garage | py/g1/databases/setup.py | Python | mit | 283 | 0 | from setuptools import setup
setup(
| name='g1.databases',
packages=[
'g1.databases',
],
install_requires=[
'SQLAlchemy',
'g1.bases',
],
extras_require={
'parts': [
'g1.apps' | ,
],
},
zip_safe=False,
)
|
looker/sentry | src/sentry/integrations/slack/event_endpoint.py | Python | bsd-3-clause | 3,448 | 0.00029 | from __future__ import absolute_import
import json
import re
import six
from sentry import http
from sentry.api.base import Endpoint
from sentry.models import G | roup, Project
from .utils import build_attachment, logger
from .requests import SlackEventRequest, SlackRequestError
# XXX(dcramer): this could be more tightly bound to our configured domain,
# but slack limits what we can unfurl anyways so its probably safe
_link_regexp = re.compile(r | '^https?\://[^/]+/[^/]+/[^/]+/issues/(\d+)')
# XXX(dcramer): a lot of this is copied from sentry-plugins right now, and will
# need refactored
class SlackEventEndpoint(Endpoint):
authentication_classes = ()
permission_classes = ()
def _parse_issue_id_from_url(self, link):
match = _link_regexp.mat... |
unlessbamboo/grocery-shop | algorithm/search/stringHandlePy.py | Python | gpl-3.0 | 2,790 | 0.000432 | #!/usr/bin/env python
#coding:utf-8
##
# @file longestPalindrome.py
# @brief Find longest palindrome string
# @author unlessbamboo
# @version 1.0
# @date 2016-02-15
def secondHelper(str1, left, right):
"""secondHelper:Find a palindrome string from one point
:param str1:source string
:param left:
:... | return res
def lengthOfLongestSubstring(str1):
"""lengthOfLongestSubstring:
find the length of the longest substring without repeating characters
| 分析:(完全归纳法)
1,使用hash,对每一个character进行index记录,从而保证
不存在repeating characters
2,假设l[i] = s[m...i],其中m-i没有任何重复元素,最大长度为i-m+1
3,判断s[i+1]:
if s[i+1] not in Hashmap:
L[i+1] = s[m...i+1]
else
m = max(m, ... |
Brown-University-Library/vivo-data-management | vdm/context.py | Python | mit | 1,141 | 0.003506 | """
JSON-LD contexts.
"""
from .namespaces import ns_mgr, D
base = {
"@base": str(D),
"a": "@type",
"uri": "@id",
"label": "rdfs:label",
}
#set namespaces from the ns_mgr
for prefix, iri in ns_mgr.namespaces():
base[prefix] = iri.toPython()
#BCITE publications
publication = {
"title": "rdfs:l... | "eissn": "bcite:eissn",
"book": "bcite:book",
"published_in": "bcite:publishedIn",
"date": {
"@id": "bcite:date",
"@type": "http: | //www.w3.org/2001/XMLSchema#date"
},
"url": "bcite:url",
"pages": "bcite:pages",
"venue": {
"@id": "bcite:hasVenue",
"@type": "@id",
},
"contributor": {
"@id": "bcite:hasContributor",
"@type": "@id",
}
}
#Brown delegate editors
delegate = {
"first": "foaf... |
dholm/simpleguitk | simpleplot/__init___flymake.py | Python | bsd-3-clause | 207 | 0 | # Copyright (c) 2013 David Holm <dholmster@gmail.com>
# This fil | e is part of SimpleGUITk - https://github.com/dholm/simpleguitk
# See the file | 'COPYING' for copying permission.
from .plot import plot_lines
|
genzgd/lampost_lib | lampost/server/session.py | Python | mit | 9,077 | 0.000992 | import time
from datetime import datetime, timedelta
from os import urandom
from base64 import b64encode
from lampost.di.app import on_app_start
from lampost.di.resource import Injected, module_inject
from lampost.di.config import on_config_change, config_value
from lampost.event.zone import Attachable
from lampost.se... | return session
def _start_player(session, player_id):
old_session = player_session(player_id)
if old_session and old_session != session:
player = old_session.player
old_session.player = None
| old_session.user = None
old_session.append({'other_location': player_id})
_connect_session(session, player, '-- Existing Session Logged Out --')
player.parse('look')
else:
player = um.find_player(player_id)
if not player:
session.append('logout')
... |
openstack/keystone | keystone/api/system.py | Python | apache-2.0 | 7,273 | 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... | '] = PROVIDERS.identity_api.get_user(
flask.request.view_args['user_id'])
except exception.UserNotFound:
if not allow_non_existing:
raise
else:
try:
target['group'] = PROVIDERS.identity_api.get_group(
... | raise
return target
class SystemUsersListResource(flask_restful.Resource):
def get(self, user_id):
"""List all system grants for a specific user.
GET/HEAD /system/users/{user_id}/roles
"""
ENFORCER.enforce_call(action='identity:list_system_grants_for_user',
... |
nschloe/seacas | packages/seacas/libraries/ioss/src/visualization/ParaViewCatalystIossAdapter/python/PhactoriScript.py | Python | bsd-3-clause | 26,602 | 0.018006 | # Copyright(C) 1999-2017 National Technology & Engineering Solutions
# of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
# NTESS, the U.S. Government retains certain rights in this software.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provid... | import glob
jsonFilelist = glob.glob('*.j | son.correct')
phactori.myDebugPrint2("about to open json file\n")
phactori.myDebugPrint2("json file name: " + jsonFilelist[0] + "\n")
jff = open(jsonFilelist[0], 'rb')
phactori.myDebugPrint2("about to read json file\n")
testJsonString = jff.read()
phactori.myDebugPrint2("test json string: " + te... |
snahelou/awx | awx/main/tests/functional/utils/test_common.py | Python | apache-2.0 | 2,126 | 0.001411 | import pytest
import copy
import json
from awx.main.utils.common import (
model_instance_diff,
model_to_dict,
)
@pytest.mark.django_db
def test_model_to_dict_user(alice):
username = copy.copy(alice.username)
password = copy.copy(alice.password)
output_dict = model_to_dict(alice)
assert outpu... | model_to_dict(credential)
assert output_dict['name'] == name
assert output_dict['inputs'] == 'hidden'
assert credential.name == name
assert credential.inputs == inputs
@pytest.mark.django_db
def test_model_to_dict_notification_template(notification_template_with_encrypt):
old_configuration = copy.... | utput_dict = model_to_dict(notification_template_with_encrypt)
new_configuration = json.loads(output_dict['notification_configuration'])
assert notification_template_with_encrypt.notification_configuration == old_configuration
assert new_configuration['token'] == '$encrypted$'
assert new_configuration['... |
arielbro/attractor_learning | testing/test_attractors.py | Python | mit | 179,258 | 0.010649 | import numpy as np
import logic
from unittest import TestCase
import graphs
import sympy
from collections import namedtuple
import random
from attractors import find_num_attractors_onestage, \
vertex_model_impact_scores, stochastic_vertex_model_impact_scores, find_num_steady_states, \
find_attractors_dubrova, f... | etwork(vertex_names=["A", "B"], edges=[("A", "A")],
vertex_functions=[logic.SymmetricThresholdFunction(signs=[1], threshold=1),
| None])
experiments.append(ILPAttractorExperimentParameters(G=G, T=1, P=5, n_attractors=4))
experiments.append(ILPAttractorExperimentParameters(G=G, T=2, P=5, n_attractors=4))
# 8, 9
G = graphs.Network(vertex_names=["A", "B"], edges=[("A", "A")],
vertex_... |
alextreme/Django-Bingo | ping/admin.py | Python | bsd-3-clause | 133 | 0 | from django.cont | rib import admin
from models import *
import datetime
admin.site.register(PingHost)
admin.site.register(PingResul | t)
|
0sw4l/villas-de-san-pablo | apps/empleabilidad/forms.py | Python | mit | 1,944 | 0.000514 | from django import forms
from . import models
from apps.utils import forms as utils, constants
from django.forms import models as models_form
from apps.personas import models as persona_models
class VacanteForm(utils.BaseFormAllFields):
title = 'Vacante'
fecha = forms.DateField(input_formats=constants.INPUT_F... | rsona,
models.VacantePersona,
form,
formset,
**kwargs
)
class FormacionTrabajoForm(utils.BaseForm | AllFields):
title = 'Formacion para el trabajo'
fecha_creacion = forms.DateField(input_formats=constants.INPUT_FORMATS)
class Meta(utils.BaseFormAllFields.Meta):
model = models.FormacionTrabajo
class FormacionTrabajoPersonasForm(utils.BaseFormAllFields):
title = 'Formacion Trabajo Persona'
... |
pacoqueen/bbinn | PyChart-1.39/demos/bgtest.py | Python | gpl-2.0 | 1,171 | 0.017933 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("..")
#
# Copyright (C) 2000-2005 by Yasushi Saito (yasushi.saito@gmail.com)
#
# Pychart 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 Foundati... | HANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
from pychart import *
data = [(10, 20, 5, 5), (20, 65, 5, 5),
(30, 55, 4, 4), (40, 45, 2, 2), (50, 25, 3, 3)]
ar = area.T(x_axis = axis.X(label = "X label"),
y_axis = axis.Y(label = "Y label... | abel="foo", data = data,
fill_style = fill_style.gray90,
error_bar = error_bar.bar3,
error_minus_col = 2,
error_plus_col = 3))
canvas.default_canvas().set_background(fill_style.diag, -100, -100, 300, 300)
ar.draw()
|
osma/annif | create_corpus_yso_finna.py | Python | cc0-1.0 | 4,644 | 0.007106 | #!/usr/bin/env python3
from SPARQLWrapper import SPARQLWrapper, JSON
import requests
import re
import os
import os.path
import time
import sys
FINTO_ENDPOINT='http://api.dev.finto.fi/sparql'
FINNA_API_SEARCH='https://api.finna.fi/v1/search'
lang = sys.argv[1]
# map ISO 639-1 language codes into the ISO 639-2 codes ... | bels.append(concept['al | larspref'])
if 'alts' in concept:
labels.append(concept['alts'])
labels = ' '.join(labels)
# look for more text in Finna API
texts = []
fields = ['title','summary']
finnaterms = (concept['ysapref'], concept['allarspref'])
finnalang = LANGMAP[lang]
# Search type 1: exact ma... |
unodba/cloudstack-docs-install | source/conf.py | Python | apache-2.0 | 14,051 | 0.005622 | # 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 ... | erulean
# * cosmo
# * cyborg
# * cupid (v3 only)
# * flatly
# * journal
# * lumen (v3 only)
# * readable
# * simplex
# * slate
# * spacelab
# * spruce (v2 only)
# * superhero
# * united
# * yeti (v3 only)
'bootswatch_theme': "spacelab",
# Choose Bootstrap... | this directory.
# ``get_html_theme_path`` returns a list, so you can concatenate with
# any other theme directories you would like.
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available ... |
ctgk/BayesianNetwork | test/math/test_add.py | Python | mit | 561 | 0 | import unittest
import numpy as np
import bayesnet as bn
class TestAdd(unittest.TestCase):
def test_add(self):
x = bn.Parameter(2)
z = x + 5
self.assertEqual(z.value, 7)
z.ba | ckward()
self.assertEqual(x.grad, 1)
x = np.random.rand(5, 4)
y = np.random.rand(4)
| p = bn.Parameter(y)
z = x + p
self.assertTrue((z.value == x + y).all())
z.backward(np.ones((5, 4)))
self.assertTrue((p.grad == np.ones(4) * 5).all())
if __name__ == '__main__':
unittest.main()
|
UNICT-DMI/Telegram-DMI-Bot | module/gitlab.py | Python | gpl-3.0 | 12,856 | 0.003044 | # -*- coding: utf-8 -*-
# Telegram
from telegram.ext import run_async, CallbackContext
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
#Modules
from module.shared import config_map, check_log
# System libraries
from urllib.parse import quote
import requests
import sqlite3
import logging
impor... | l, pathname, parent_id = db_result
| blob_info = get_blob_file(parent_id, blob_id)
download_url = "%s/raw/master/%s" % (web_url, quote(pathname))
if int(blob_info['size']) < 4.5e+7:
file_name = "%s_%s" % (time.time(), blob_name)
with open('file/%s' % file_name, 'wb') as file_handle:
with sessi... |
wilthewolf/rssso2015schedule | rssso2015schedule.py | Python | gpl-3.0 | 24,594 | 0.010614 | #!/usr/local/lib/python2.7.10/bin/python
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 09 13:15:13 2015
@author: Vedran
Fetching a schedule from Google Docs, extracting information, converting to
pdf and sending via e-mail.
Copyright (C) 2015 Vedran Vukovic <wilheru@gmail.com>
This program is free softw... | ,
# using zero-based indexing.
"""
def cutHtml(html):
allDays = [] # the list which will be populated with locations of all
# strings that match the case-insensitive regex "day \d"
for i in range(len(html)):
if html[i:i+4] | .lower() == "day ":
if html[i+4:i+5].lower() in ([str(x) for x in range(10)]):
allDays.append(i)
allTDs = [] # the list which will be populated with locations of all
# strings that match "<td "
for i in range(len(html)):
if html[i:i+4].lower() == "<td ":
... |
daskol/ml-cipher-cracker | sgt.py | Python | mit | 7,861 | 0.002926 | # Copyright 2009-2011 by Max Bane
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in ... | rc('text', usetex=True)
rc('text', dvipnghack=True) # for OSX
rc('font', family='serif')
rc('font', serif=['Computer Modern'])
def plotFreqVsGoodTuring(counts, confidence=1.96, loglog=False):
"""
Draws a scatterplot of the empirical frequencies of the counted | species
versus their Simple Good Turing smoothed values, in rank order. Depends on
pylab and matplotlib.
"""
import pylab
from matplotlib import rc
tot = float(sum(counts.values()))
freqs = dict([(species, cnt/tot) for species, cnt in counts.iteritems()])
sgt, p0 = simpleGoodTuringProb... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/rest_framework/utils/field_mapping.py | Python | agpl-3.0 | 9,402 | 0.000425 | """
Helper functions for mapping model fields to a dictionary of default
keyword arguments that should be used for their equivelent serializer fields.
"""
import inspect
from django.core import validators
from django.db import models
from django.utils.text import capfirst
from rest_framework.compat import clean_manyt... | or raises a KeyError if nothing matches.
"""
def __init__(self, mapping):
self.mapping = mapping
def __getitem__(self, key):
if hasattr(key, '_proxy_class'):
# Deal with proxy classes. Ie. BoundField behaves as if it
# is a Field instance when using ClassLookupDict.
... | ):
if cls in self.mapping:
return self.mapping[cls]
raise KeyError('Class %s not found in lookup.' % base_class.__name__)
def __setitem__(self, key, value):
self.mapping[key] = value
def needs_label(model_field, field_name):
"""
Returns `True` if the label base... |
nicolasbrailo/IMGeotaggerV2 | imgeotagger.py | Python | lgpl-2.1 | 3,219 | 0.004039 | from img_list import Img_List
from image_control import Image_Control
from browser import *
class Wnd(gtk.Window):
def __init__(self):
super(Wnd, self).__init__(gtk.WINDOW_TOPLEVEL)
self.set_size_request(width=1200, height=768)
self.set_title('IMGeotagger revived')
self.realize()
... | t understand it. Unknown URL: {0}".format(map_path)
exit(1)
print "Setting selection to " + str(coords)
for img in self.img_list.get_current_selection():
img.set_position(coords)
self.img_list.notify_elements_updated()
def maybe_update_coords(self, url):
if... | self.current_pos.set_markup('Position: ' + str(coords))
return
self.current_pos.set_markup('Position: ???')
def on_image_selection(self, widget, data=None):
self.img_ctrl.on_images_selected(self.img_list.get_current_selection())
@staticmethod
def hack_coords_... |
jasonkeene/python-ubersmith | ubersmith/api.py | Python | mit | 21,356 | 0.00014 | """Lower level API, configuration, and HTTP stuff."""
import six
import time
from ubersmith.compat import total_ordering, file_type
import requests
from ubersmith.exceptions import (
RequestError,
ResponseError,
UpdatingTokenResponse,
MaintenanceResponse,
)
from ubersmith.utils import (
append_qs,... | w Contact',
u'client.contact_ | delete': u'Delete a Contact',
u'client.contact_get': u'Get Contact Details',
u'client.contact_list': u"List a Client's Contacts",
u'client.contact_metadata_get': u"Get a Contact's Metadata",
u'client.contact_metadata_single': u"Get a Contact's Metadata Value",
u'client.contact_update': u'Update a Co... |
wking/thumbor | vows/healthcheck_vows.py | Python | mit | 1,666 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
from pyvows import Vows, expect
from tornado_pyvows.context import To... | ServiceApp(ctx)
return application
class WhenRunning(TornadoHTTPContext): |
def topic(self):
response = self.get('/healthcheck')
return (response.code, response.body)
class StatusCode(TornadoHTTPContext):
def topic(self, response):
return response[0]
def should_not_be_an_error(self, topic):
expec... |
dcarrot2/DjangoSunstreet | events/admin.py | Python | gpl-2.0 | 254 | 0.019685 | from django.contrib import | admin
from events.models import Event
# Register your models here.
class EventAdmin(admin.ModelAdmin):
list_display = ['title', 'date', 'youTube_link','des | cription', 'link_to_event']
admin.site.register(Event, EventAdmin) |
UrduWikipedia/DB_reports | EditCounterNoBots.py | Python | mit | 2,518 | 0.025492 | #!/usr/bin/python
# Abbas (Ar:User:Elph), 2012
# -*- coding: utf-8 -*-
import catlib ,pagegenera | tors
import wikipedia,urllib,g | zip,codecs,re
import MySQLdb as mysqldb
import config
pagetop=u"'''تاریخ آخری تجدید:''''': ~~~~~ '''بذریعہ:''' [[user:{{subst:Currentuser}}|{{subst:Currentuser}}]]''\n\n"
pagetop+=u'\nفہرست 100 بلند پایہ صارفین بلحاظ شراکت بدون روبہ جات۔\n'
pagetop+=u'\nمزید دیکھیں: [[ویکیپیڈیا:رودادہائے ڈیٹابیس/فہرست ویکیپیڈیا صارفین ... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/GL/SGIX/sprite.py | Python | lgpl-3.0 | 3,385 | 0.027179 | '''OpenGL extension SGIX.sprite
This module customises the behaviour of the
OpenGL.raw.GL.SGIX.sprite to provide a more
Python-friendly API
Overview (from the spec)
This extension provides support for viewpoint dependent alignment
of geometry, in particular geometry that rotates about a point or
a ... | Primitives are first transformed by a rotation, depending on the
sprite mode:
SPRITE_AXIAL_SGIX: The front of the object is rotated about
an axis so that it faces the eye as much as the | axis
constraint allows. This is used for roughly rendering cylindrical
objects such as trees in visual simulation.
SPRITE_OBJECT_ALIGNED_SGIX: The front of the object is
rotated about a point to face the eye with the remaining
rotational degree of freedom specified by aligning the top
of the object with... |
ShySec/scrimmage-scoreboard | web2py/gluon/shell.py | Python | gpl-2.0 | 15,657 | 0.000575 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file | is part of the web2py Web Framework
| Developed by Massimo Di Pierro <mdipierro@cs.d | epaul.edu>,
| limodou <limodou@gmail.com> and srackham <srackham@gmail.com>.
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Web2py environment in the shell
--------------------------------
"""
import os
import sys
import code
import logging
import types
import re
import optparse
import glob
import tracebac... |
josecolella/Dynatrace-Resources | portal/Portal.py | Python | mit | 17,063 | 0.002403 | #!/usr/bin/env python3
from __future__ import print_function
import datetime
import calendar
import logging
import time
import re
import os
import os.path
from abc import ABCMeta
from abc import abstractmethod
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui ... | gScreenshot("Home")
usernameInput = self.driver.find_element_by_name(
self.usernameInputIdentifier)
passwordInput = self.driver.find_element_by_name(
self.passwordInputIdentifier)
logging.debug("Sending username credentials")
usernameInput.send_keys(self.username)... | nd_keys(self.password)
submitButton = self.driver.find_element_by_id(
self.submitButtonIdentifier)
logging.debug("Sending button click")
submitButton.click()
logging.debug("Waiting for page to load")
def close(self):
"""Closes the driver session and the phantomjs... |
AlvaroRQ/prototipo | install.py | Python | gpl-3.0 | 14,799 | 0.063003 | import os
import cv2
import sys
import math
import time
import json
import argparse
import numpy as np
from ownLibraries.pathsandnames import PathsAndNames
debug = False
nuevaLocalizacion = ''
# We get the current working git branch
gitBranches = os.popen('git branch').read().replace(' ','').split('\n')
gitVersion = [... | ange(24):
for i in range(8):
indices.append((punto0+i*pasoHorizontal+j*pasoVertical).tolist())
#print('len of indices', len(indices))
#print('single index', indices[0])
#indices = [[round(x[0]),round(x[1])] for x in indices]
return indices
###########Calculate new Points############
def transformIma(lista):
... | n((y2-y3)/distancia)
anguloInicialGrados=anguloInicial*180/(math.pi)
anguloGrados=180-90-anguloInicialGrados
anguloRadians=anguloGrados*(math.pi)/180
y=altura*math.sin(anguloRadians)
x=altura*math.cos(anguloRadians)
x1=int(x2-x)
y1_0=int(y2-y)
y1=int(y1_0-altura)
x4=int(x3-x)
y4_0=int(y3-y)
y4=int... |
EricSchles/python-route53 | route53/resource_record_set.py | Python | mit | 10,055 | 0.002685 | from route53.change_set import ChangeSet
from route53.exceptions import Route53Error
class ResourceRecordSet(object):
"""
A Resource Record Set is an entry within a Hosted Zone. These can be
anything from TXT entries, to A entries, to CNAMEs.
.. warning:: Do not instantiate this directly yourself. Go ... | this record set. We use this
# to detect changes that need saving.
self._initial_vals = dict(
connection=connection,
zone_id=zone_id,
name=name,
ttl=ttl,
records=r | ecords,
region=region,
weight=weight,
set_identifier=set_identifier,
)
def __str__(self):
return '<%s: %s>' % (self.__class__.__name__, self.name)
@property
def hosted_zone(self):
"""
Queries for this record set's HostedZone.
.. ... |
rcsanchez97/mongo-c-driver | build/evergreen_config_lib/functions.py | Python | apache-2.0 | 26,392 | 0.002236 | # Copyright 2018-present MongoDB, 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 w... | e='${build_id}.tar.gz', bucket='mciuploads',
permissions='public-read',
content_type='${content_type|application/x-gzip}'),
)),
('release archive', Function(
shell_mongoc(r'''
# Need modern Sphinx for :caption: in literal includes.
python -m virtualenv venv
... | IMEOUT_MS=30000
export MONGOC_TEST_SKIP_LIVE=on
export MONGOC_TEST_SKIP_SLOW=on
sh .evergreen/check-release-archive.sh
'''),
)),
('install ssl', Function(
shell_mongoc(r'SSL=${SSL} sh .evergreen/install-ssl.sh', test=False),
)),
('fetch build', Function(
s... |
dc3-plaso/plaso | tests/formatters/ganalytics.py | Python | apache-2.0 | 3,320 | 0.006325 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Analytics cookie event formatters."""
import unittest
from plaso.formatters import ganalytics
from tests.formatters import test_lib
class AnalyticsUtmaCookieFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the UTMA Google Analytics coo... | t_lib.EventFormatterTestCase):
"""Tests for | the UTMB Google Analytics cookie event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = ganalytics.AnalyticsUtmbCookieFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNam... |
jonas-eberle/pyEOM | pyEOM/datasets/Landsat.py | Python | mit | 1,358 | 0.002946 | __author__ = 'Jonas Eberle <jonas.eberle@eberle-mail.de>'
from pyEOM.sources import *
class GEE(GEESource):
dataset = None
start = '1900-01-01'
end = '2100-01-01'
epsg = 'EPSG:4326'
scale = 30
def __init__(self, task):
self.task = task
if 'dataset' not in task:
rais... | ['publishPath']
self.connect()
self.geom = self.processGeometry(task['geom'])
def setPublishPath( | self, path):
self.publishPath = path
def run(self):
# dataset bands geom start end epsg scale crsTransform
data = self.getData(self.dataset, None, self.geom, self.start, self.end, self.epsg, self.scale, None)
return data
def... |
detiber/openshift-ansible | roles/openshift_health_checker/test/docker_image_availability_test.py | Python | apache-2.0 | 9,879 | 0.001316 | import pytest
from openshift_checks.docker_image_availability import DockerImageAvailability
@pytest.fixture()
def task_vars():
return dict(
openshift=dict(
common=dict(
service_type='origin',
is_containerized=False,
is_atomic=False,
... | g", failed=connection_test_failed)
elif module_name == "command":
return dict(msg="msg", failed=skopeo_failed)
| check = DockerImageAvailability(execute_module, task_vars())
check._module_retry_interval = 0
available = check.is_available_skopeo_image(image, registries)
assert available == expect_success
assert expect_registries_reached == check.reachable_registries
@pytest.mark.parametrize("deployment_type, i... |
Anatoscope/sofa | applications/plugins/Compliant/examples/using_types.py | Python | lgpl-2.1 | 485 | 0.018557 |
from Compliant import types
import numpy as np
def createScene(node):
obj = node.createObject('MechanicalObject',
template = 'Rigid',
position = '0 0 0 0 0 0 1',
name = 'dofs')
# a | rigid view on position vector
pos = np.array(obj.position).view(dtype = types.Rigid3)
print type(pos[0])
# now we have all kinds of fancy accessors
| pos[0].center = np.ones(3)
print pos
|
mixcloud/django-celery-haystack-SearchIndex | celery_haystack_index/queued_indexer.py | Python | mit | 1,487 | 0.004035 | from django.db.models import signals
from django.db.models.loading import get_model
from haystack import indexes
from haystack import site
from tasks import SearchIndexUpdateTask
def remove_instance_from_index(instance):
model_class = get_model(instance._meta.app_label, instance._meta.module_name)
search_ind... | ost_save.connect(self.enqueue_save, sender=model)
def _setup_delete(self, model):
signals.post_delete.connect(self.enqueue_delete, sender=model)
def _teardown_save(self, model):
signals.post_save.disconnect(self.enqueue_save, sender=model)
def _teardown_delete(self, model):
signal... | teTask.delay(instance._meta.app_label, instance._meta.module_name, instance._get_pk_val())
def enqueue_delete(self, instance, **kwargs):
remove_instance_from_index(instance)
|
lexdene/drape | drape/_default_configs.py | Python | gpl-3.0 | 525 | 0 | SYSTEM_IS_DEBUG = True
NOTFOUND_PAGE = 'notfo | und/Index'
DEFAULT_MOD = 'index'
DEFAULT_CONTROLLER = 'Index'
DB_DRIVER = 'mysql'
DB_NAME = ''
DB_USER = ''
DB_PASSWORD = ''
DB_HOST = 'localhost'
DB_PORT = 3306
DB_CHARSET = 'utf8'
DB_TABLE_PREFIX = ''
DB_LOG_SQL = True
DEFAULT_TEMPLATOR = 'jinja2'
SESSION_STORE_ENGINE = 'file'
SESSION_FILE_DIRECTORY = 'data/sessio... | ATE_DIR = 'template'
|
plaid/plaid-python | plaid/model/transfer_user_in_request.py | Python | mit | 7,582 | 0.000659 | """
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | zing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
... | .
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petTyp... |
ygol/odoo | addons/website_event_track_online/controllers/community.py | Python | agpl-3.0 | 653 | 0.004594 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
from odoo.addons.website_event.controllers.main import WebsiteEventController
from odoo import fields, http, modules, tools
from odoo.http import request
class WebsiteEventCommunityController(http.Controller):
@http.route('/event/<model("event.event"):event>/community', type="http", auth="public", website=True)
... | route will be overriden in website_event_track_quiz, website_event_meet and website_event_meet_quiz. """
return request.render('website.page_404')
|
Jay-Jay-D/LeanSTP | Algorithm.Python/StandardDeviationExecutionModelRegressionAlgorithm.py | Python | apache-2.0 | 3,090 | 0.01101 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | hm.Framework.Selection import *
from Alphas.RsiAlphaModel import RsiAlphaModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from E | xecution.StandardDeviationExecutionModel import StandardDeviationExecutionModel
from datetime import timedelta
### <summary>
### Regression algorithm for the StandardDeviationExecutionModel.
### This algorithm shows how the execution model works to split up orders and submit them
### only when the price is 2 standard ... |
destijl/grr-workshop-setup | cleanup.py | Python | apache-2.0 | 602 | 0.009967 | """Cleanup script."""
fr | om grr.lib import export_utils
# After you do this the UI complains a little, but creating a new hunt fixes it.
hunts = aff4.FACTORY.Open("aff4:/hunts/")
for hunt in hunts.ListChildren():
aff4.FACTORY.Delete(hunt)
# Delete clients that haven't polled in for 2hours
for fd in aff4.FACTORY.MultiOpen(export_utils.GetAl... | .Delete(fd.urn)
# Delete all flows
for client in export_utils.GetAllClients():
aff4.FACTORY.Delete(client.Add("flows"))
|
cylc/cylc | tests/unit/parsec/test_ordered_dict.py | Python | gpl-3.0 | 4,516 | 0 | # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# 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 Licen... | d['key'] = 'Birds'
d.defaults_ = {
'value': '10'
}
self.assertTrue('key' in d)
self.assertTrue('value' in d)
self.assertFalse('test' in d)
def test_nonzero(self):
d = OrderedDictWithDefaul | ts()
self.assertFalse(d)
d['value'] = 10
self.assertTrue(d)
def test_prepend(self):
d = OrderedDictWithDefaults()
d['key'] = 'Birds'
d.prepend('year', 1980)
d.prepend('key', 2000)
iterator = iter(d.keys())
self.assertEqual('key', next(iterat... |
facebook/fbthrift | thrift/lib/py/async_common.py | Python | apache-2.0 | 14,364 | 0.000278 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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 o... | self.recvd = b""
async def message_received(self, frame):
raise NotImplementedError
def data_received(self, data):
" | ""Implements asyncio.Protocol.data_received."""
self.recvd = self.recvd + data
while len(self.recvd) >= 4:
(length,) = struct.unpack("!I", self.recvd[:4])
if length > MAX_FRAME_SIZE:
logger.error(
"Frame size %d too large for THeaderProtocol",
... |
anton-pershin/pyleeds | postproc/chflow/timeintegration.py | Python | mit | 3,367 | 0.008019 | # What do I need?
# 1) Read file ReD.asc and return a function D(Re) from it.
# It is probably better to return an object which links corresponding D, Re and u-field together
# 2) Launch continuation -- both from scratch and proceeding previous continuation
# 3) All of these should be configurated such that I could use... | _builder.set_command('couette -T0 {} -T1 {} -dt {} -R {} -dT {} -dPT {} -ke {} -o data-{} {}'.format(T_start, T_end, \
dt, Re, dT_fields, dT_data, max_ke_threshold, Re, os.path.basename(init_field)), sid=str(Re))
task_builder.set_program(self.__execution_host.get_path... | task_builder.set_inputs((init_field,))
task_builder.set_sge_properties(16, '24:00:00')
return task_builder.build_task()
def create_perturbed_field_task(self, Re, T_start, T_end, dt, seed, init_field, smoothness=0.4, magnitude=0.2):
# both smoothness and magnitude are defined on [0, 1]
... |
plotly/python-api | packages/python/plotly/plotly/validators/sankey/node/hoverlabel/_bgcolor.py | Python | mit | 521 | 0.001919 | import _plotly_utils.basevalidators
class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="bgcolor", parent_name="sankey.node.hoverlabel", **kwargs
):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_... | edit_ty | pe=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "style"),
**kwargs
)
|
zstackio/zstack-woodpecker | integrationtest/vm/multihosts/migrate/test_migrate_vm_with_iso2.py | Python | apache-2.0 | 4,045 | 0.003956 | '''
New Integration test for testing running vm migration between hosts when attach ISO.
@author: Chenyuan.xu
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.operations.resource_ope... | m_host(vm)
vm.check()
host_ip = test_lib.lib_find_host_by_vm(vm.get_vm()).managementIp
cmd = "umount /mnt"
if not test_lib.lib_ssh_vm_cmd_by_agent_with_retry(host_ip, vm_ip, 'root', 'password', cmd):
test_lib.SSH_TIMEOUT = ssh_timeout
test_util.test_fail("Failed to umount /mnt.")
i... | ib.lib_ssh_vm_cmd_by_agent_with_retry(host_ip, vm_ip, 'root', 'password', cmd):
test_lib.SSH_TIMEOUT = ssh_timeout
test_util.test_fail("Failed to mount /dev/sr0 /mnt.")
cmd = "cat /mnt/Licenses.txt"
if not test_lib.lib_ssh_vm_cmd_by_agent_with_retry(host_ip, vm_ip, 'root', 'password', cmd):
... |
mindw/numpy | numpy/lib/index_tricks.py | Python | bsd-3-clause | 26,049 | 0.000537 | from __future__ import division, absolute_import, print_function
import sys
import math
import numpy.core.numeric as _nx
from numpy.core.numeric import (
asarray, ScalarType, array, alltrue, cumprod, arange
)
from numpy.core.numerictypes import find_common_type
from . import function_base
import numpy.matrix... | (step, c | omplex):
size.append(int(abs(step)))
typ = float
else:
size.append(
int(math.ceil((key[k].stop - start)/(step*1.0))))
if (isinstance(step, float) or
isinstance(start, float) or
... |
alexandru/django-asynctasks | src/django_asynctasks/admin.py | Python | bsd-2-clause | 983 | 0.008138 | from django.contrib import admin
from django_asynctasks.models import AsyncTask, AsyncTaskError
class AsyncTaskAdmin(admin.ModelAdmin):
list_display = ('name', 'function', 'bucket', 'task_type', 'formatted_status',
'started_at', 'duration', 'created_at',)
list_filter = ('created_at'... | sk.status in ['new', 'running']:
return "<span style='color: blue'><b>" + task.status + "</b></span>"
if task.status == 'done':
return "<span style='color: green'><b>DONE</b></span>"
if task.status in ['failed', 'stopped']:
return "<span style='co | lor: red'><b>%s</b></span>" % task.status.upper()
formatted_status.allow_tags = True
formatted_status.short_description = 'Status'
admin.site.register(AsyncTask, AsyncTaskAdmin)
admin.site.register(AsyncTaskError)
|
chiangf/rallycaster | rallycaster/users/service.py | Python | apache-2.0 | 1,171 | 0.000854 | from datetime import datetime
from rallycaster import helpers
from rallycaster import mongo
class UserService(object):
def get_user_by_id(self, user_id):
user = mongo.db.users.find_one({'_id': user_id})
ret | urn user
def get_user_by_oauth_id(self, oauth_id):
user = mongo.db.users.find_one({'oauth_id': oauth_id})
return user
def add_user(self, user_info):
user_id = mongo.db.users.insert(user_info)
return user_id
def update_user(self, user_info):
mongo.db.users.update({'... | _user(self, user, session_token):
session_info = {
'user_id': user['_id'],
'token': session_token,
'created': datetime.utcnow()
}
mongo.db.sessions.insert(session_info)
session_token = helpers.session.generate_guid()
return session_token
... |
okuta/chainer | tests/chainer_tests/functions_tests/rnn_tests/test_function_lstm.py | Python | mit | 7,898 | 0 | import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.functions.rnn import lstm
from chainer.testing import backend
def _sigmoid(x):
half = x.dtype.type(0.5)
return numpy.tanh(x ... | rad_outputs,
**self.check_backward_options)
def test_backward(self, backend_c | onfig):
self.check_backward(self.inputs, self.grad_outputs, backend_config)
testing.run_module(__name__, __file__)
|
matejcik/osc | osclib-tests/test_api.py | Python | gpl-2.0 | 3,172 | 0.003468 | import osclib.api
import osc.conf
import os
import os.path
import vcr
import pytest
import requests
TESTROOT = os.path.join(pytest.config.rootdir, "osclib-tests")
OSCRC = os.path.join(TESTROOT, "oscrc", "oscrc_test_api")
VCRROOT = os.path.join(TESTROOT, "fixtures", "vcr")
def test_default_api(monkeypatch):
""... | assert not r.ok
@vcr.use_cassette(os.path.join(VCRROOT, "test_request.yaml"), filter_headers=['authorization'])
def test_get_xml():
"""
get_xml() should return a xml document, or raise an exception
TODO maybe get_xml should always return xml document?
This test assumes that the user running it has ... | first clear out osc.conf settings
osc.conf.get_config()
api = osclib.api.Api("https://api.opensuse.org")
root = api.get_xml(["source", "openSUSE:Factory", "osc"])
assert root is not None
assert root.tag == "directory"
assert root.get("name") == "osc"
with pytest.raises(requests.exceptions.... |
kastnerkyle/discrete-opt | week1/solver.py | Python | bsd-3-clause | 225 | 0.008889 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def solve_it(input_data):
# return a positive integer, as a string
return '10'
if __name__ == '__main__':
print('This scrip | t submits the integer: %s\n' % | solve_it(''))
|
silverfix/django-accio | accio/async_logging.py | Python | bsd-3-clause | 1,005 | 0.00199 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, absolute_import
import logging
from datetime import timedelta
from accio import celery_app
from redis import Redis
class RedisHandler(logging.Handler):
def __init__(self, task_name, task_id, level):
logging.Handler.__init__(self, ... | def emit(self, record):
k = 'logs:%s:%s' % (self.task_name, self.task_id)
self.redis_db.rpush(k, | self.format(record))
self.redis_db.expire(k, timedelta(weeks=1))
def getLogger(task_request):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
if hasattr(task_request, 'task'):
logger.addHandler(RedisHandler(task_request.task, task_request.id, level=logging.INFO))
return log... |
yeming233/rally | tests/unit/plugins/common/sla/test_iteration_time.py | Python | apache-2.0 | 3,062 | 0 | # Copyright 2014: Mirantis 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 b... | self.assertFalse(sla_inst.add_iteration({"duration": 4.5}))
self.assertFalse(sla_inst.add_iteration({"duration": 3.8}))
@ddt.data([[1.0, 2.0, 1.5, 4.3],
[2.1, 3.4, 1.2, 6.3, 7.2, 7.0, 1.],
[1.1, 1.1, 2.2, 2.2, 3.3, 4.3]])
def test_merge(self, durations):
single_sl... | : d})
slas = [iteration_time.IterationTime(4.0) for _ in durations]
for idx, sla_inst in enumerate(slas):
for duration in durations[idx]:
sla_inst.add_iteration({"duration": duration})
merged_sla = slas[0]
for sla_inst in slas[1:]:
merged_sla.me... |
zorroz/microblog | flask/lib/python2.7/site-packages/sqlparse/utils.py | Python | bsd-3-clause | 3,484 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com
#
# This module is part of python-sqlparse and is released under
# the BSD License: https://opensource.org/licenses/BSD-3-Clause
import itertools
import re
from collections import deque
from contextlib import contextmanager
from sqlp... | if not isinstance(sgroup, cls):
wrapped_f(sgroup)
| f(tlist)
return wrapped_f
return wrap
def imt(token, i=None, m=None, t=None):
"""Helper function to simplify comparisons Instance, Match and TokenType
:param token:
:param i: Class or Tuple/List of Classes
:param m: Tuple of TokenType & Value. Can be list of Tuple for multiple
:param... |
zzeleznick/zDjango | venv/lib/python2.7/site-packages/pystache/tests/test_context.py | Python | mit | 14,750 | 0.001898 | # coding: utf-8
"""
Unit tests of context.py.
"""
from datetime import datetime
import unittest
from pystache.context import _NOT_FOUND, _get_value, KeyNotFoundError, ContextStack
from pystache.tests.common import AssertIsMixin, AssertStringMixin, AssertExceptionMixin, Attachable
class SimpleObject(object):
"... |
"""
Test passing None.
"""
context = ContextStack.create({'foo': 'b | ar'}, None)
self.assertEqual(context.get('foo'), 'bar')
def test_create__object(self):
"""
Test passing an object.
"""
class Foo(object):
foo = 'bar'
context = ContextStack.create(Foo())
self.assertEqual(context.get('foo'), 'bar')
def test_c... |
pkimber/block | example_block/tests/test_view_link_wizard.py | Python | apache-2.0 | 13,494 | 0 | # -*- encoding: utf-8 -*-
import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.urlresolvers import reverse
from block.models import (
BlockError,
Document,
Url,
)
from block.tests.factories import (
DocumentFactory,
LinkCategoryFactory,
LinkFactory,
... | url = url_link_single(content, 'block.wizard.link.external')
# create a document ready to upload
data = {
'add_to_library': True,
# 'category': category.pk,
'url_external': 'https://www.pkimber.net',
'title': 'Rugby',
}
response = client.post(url, data)
# check
... | ssert 302 == response.status_code
assert expect in response['Location']
assert 'Rugby' == content.link.title
assert content.link is not None
assert 'https://www.pkimber.net' == content.link.url_external
# assert content.link.category == category
# assert content.link.document.deleted is False
... |
coldfix/pystif | pystif/minimize.py | Python | gpl-3.0 | 1,297 | 0.000771 | """
Minimize a system of inequalities.
Usage:
minimize INPUT [-o OUTPUT] [-e] [-q]... [-v]... [-p]
Options:
-o OUTPUT, --output OUTPUT Write final (minimized) system to this file
-a, --append Open output file in append mode
-e, --el-ineqs Extend system with ele... |
def cb_start(self, rows):
self.num_orig = len(rows)
def cb_step(self, idx, rows):
self.info("Minimizing: {} -> {} (i={})"
.format(self.num_orig, len(rows), idx))
def cb_stop(self, rows):
self.info("Minimizing: {} -> {} (DONE)"
.format(self.nu... | ow in m.minimize(app.system.matrix):
app.output(row)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.