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
nens/timeseries
setup.py
Python
gpl-3.0
1,079
0.00278
from setuptools import setup version = 'y.dev0' long_description = '\n\n'.join([ open('README.rst').
read(), open('TODO.rst').read(), open('CREDITS.rst').read(), open('CHANGES.rst'
).read(), ]) install_requires = [ 'pkginfo', 'setuptools', 'nens', ], tests_require = [ ] setup(name='timeseries', version=version, description="Package to implement time series and generic operations on time series.", long_description=long_description, # Get strings f...
ghostsquad/seasalt
src/tests/unit/test_container.py
Python
mit
5,504
0.001272
import pytest from seasalt import container from assertpy import assert_that from os import path def get_minimum_seasalt_kwargs(): return { 'image': 'test-image:latest' } def get_minimum_container(docker_fixture): kwargs = get_minimum_seasalt_kwargs() return container(docker_cli=docker_fixtu...
kwargs): pass # assert that the host_config was created in order to create the container expected_salt_path = '/path/on/host/salt' expected_pillar_path = '/path/on/host/pillar' expected_test_path = '/path/on/host/tests' expected_salt_bind = '{}:/srv/salt:ro'.format(expected_salt_path) ...
at(expected_test_path) actual_kwargs = assert_single_call_get_kwargs(create_host_config_mock) assert_that(actual_kwargs).contains_key('binds') (assert_that(actual_kwargs['binds']) .contains(expected_salt_bind) .contains(expected_pillar_bind) .contains(expected_test_bind)) # a...
yleo77/leetcode
Unique_Email_Addresses/answer.py
Python
mit
550
0
class Solution(object): def numUniqueEmails(self, emails): ret = set() for email in emails: local, rest = email.split("@") pos = local.find("+") if pos >= 0: local = local[0: pos] local = local.replace(".", "") ret.add(lo...
.e.mail+bob.cathy@leetcode.com", "testemail+david@
lee.tcode.com"] sol = Solution() print(sol.numUniqueEmails(emails))
drbean/ultisnips
test/test_Plugin.py
Python
gpl-3.0
935
0.00107
import sys from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Plugin_SuperTab_SimpleTest(_VimTest): plugins = ["ervandew/supertab"] snippets = ("long", "Hello", "", "w") keys = ( "l
ongtextlongtext\n" + "longt" + EX + "\n" + "long" + EX # Should complete word ) # Should expand wanted = "longtextlongtext\nlongtextlongtext\nHello" def _before_test(self): # Make sure that UltiSnips has the keymap self.vim.send_to_vim(":call UltiSnips#map_keys#MapKeys()\n") def _ext...
.append('let g:SuperTabDefaultCompletionType = "<c-p>"') vim_config.append('let g:SuperTabRetainCompletionDuration = "insert"') vim_config.append("let g:SuperTabLongestHighlight = 1") vim_config.append("let g:SuperTabCrMapping = 0")
vitorio/pygrow
grow/client/client.py
Python
mit
1,209
0.008271
from apiclient import errors import httplib2 import json import requests HOST = '' root_url_format = '{}://{}/_ah/api' api = 'grow' version = 'v0.1' class Client(object): def __init__(self, host=None): self.host = host def rpc(self, path, body=None): if body is None: body = {} headers = { ...
resp.status_code >= 200 and resp.status_code < 205): raise Exception(resp.text) print 'Uploaded: {}'.format(signed_url['
pod_path'])
DinoCow/airflow
airflow/providers/microsoft/azure/example_dags/example_local_to_adls.py
Python
apache-2.0
1,492
0.00067
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
al=None, tags=['example'], ) as dag: # [START howto_operator_local_to_adls] upload_file = LocalToAzureDataLakeStorageOperator( task_id='upload_task', local_path=LOCAL_FILE_PATH, remote_path=REMOTE_FILE_P
ATH, ) # [END howto_operator_local_to_adls]
jrafa/hotshot
settings_default.py
Python
mit
110
0
# -
*- coding: utf-8 -*- HOST = 'localhost' PORT
_REDIS = 6379 PORT_APP = 6500 PASSWORD = '' DEBUG = False
iulian787/spack
var/spack/repos/builtin/packages/r-cli/package.py
Python
lgpl-2.1
1,307
0.003826
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RCli(RPackage): """A suite of tools designed to build attractive command line interfaces ...
5ee4') version('1.0.0', sha256='8fa3dbfc954ca61b8510f767ede9e8a365dac2ef95fe87c715a0f37d721b5a1d') depends_on('r@2.10:', type=('build', 'run')) depends_on('r-assertthat', type=('build',
'run')) depends_on('r-crayon@1.3.4:', type=('build', 'run')) depends_on('r-glue', when='@2:', type=('build', 'run')) depends_on('r-fansi', when='@2:', type=('build', 'run'))
DEVSENSE/PTVS
Python/Tests/TestData/WFastCgi/BadHeaders/myapp.py
Python
apache-2.0
1,130
0.007965
import sys import traceback def test_1(environment, start_response): try: start_response('200', []) raise Exception yield b'200 OK' except: # We get to start again as long as no data has been yielded start_response('500', [], sys.exc_info()) yield b'500 Error' d...
a generic 500 error start_response('500', [], sys.exc_info()) def test_3(environment, start_response): start_response('200', []) try: start_response('200', []) yield b'Should have thrown when setting headers again' except: start_response('500'
, [], sys.exc_info()) yield traceback.format_exc() def test_4(environment, start_response): yield b'Should throw because we have not set headers' def handler(environment, start_response): return globals()[environment['PATH_INFO'].strip('/')](environment, start_response)
technologiescollege/Blockly-rduino-communication
scripts_XP/Lib/site-packages/autobahn/wamp/test/test_protocol_peer.py
Python
gpl-3.0
4,497
0.001557
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
ED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNEC...
############################## from __future__ import absolute_import import os # we need to select a txaio subsystem because we're importing the base # protocol classes here for testing purposes. "normally" you'd import # from autobahn.twisted.wamp or autobahn.asyncio.wamp explicitly. import txaio if os.environ.get(...
pedro2d10/SickRage-FR
sickbeard/providers/elitetorrent.py
Python
gpl-3.0
6,480
0.003086
# coding=utf-8 # Author: CristianBB # # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
h %s seeders and %s leechers" % (title, seeders, leechers), logger.DEBUG) items.append(item) except Exception: logger.log(u"Failed parsing provider. Traceback: %s" % traceback.format_exc(), logger.WARNING) # For each search mode sort all the...
items.sort(key=lambda tup: tup[3], reverse=True) results += items return results @staticmethod def _processTitle(title): # Quality, if no literal is defined it's HDTV if 'calidad' not in title: title += ' HDTV x264' title = title.replace('(calidad...
Hossein-Noroozpour/PyHGEE
core/HGEApplication.py
Python
mit
168
0
#!/usr/bin/pytho
n3.3 __author__ = 'Hossein Noroozpour Thany Abady' class Application(): def __init__(self): pass def render_loop(self): pass
fnp/prawokultury
prawokultury/settings.d/35-search.py
Python
agpl-3.0
277
0.00361
HAYSTACK_C
ONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr/prawokultury' }, } HAYSTACK_DOCUMENT_FIELD = "text" #HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals
.RealtimeSignalProcessor'
WoLpH/EventGhost
eg/Classes/ActionBase.py
Python
gpl-2.0
6,104
0.000328
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2016 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
anel.dialog.buttonRow.applyButton.Enable(False) label = p
anel.StaticText( eg.text.General.noOptionsAction, style=wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE ) panel.sizer.Add((0, 0), 1, wx.EXPAND) panel.sizer.Add(label, 0, wx.ALIGN_CENTRE) panel.sizer.Add((0, 0), 1, wx.EXPAND) while panel.Affirmed(): panel...
openrobotics/openrobotics_thunderbot
pr3_teleop/talos_os/src/talos_smach/state_machines/follow_me_state_machine/no_user_detected_state.py
Python
mit
556
0.010791
## Author: Devon Ash ## Maitnainer: noobaca2@gmail.com import roslib import rospy import smach import smach_ros class NoUserDetectedState(smach.State): d
ef __init__(self): smach.State.__init__(self, outcomes=["UserDetected", "UserOffScreen", "UserOccluded", "TrackingWrongUser"]) self.counter = 0 def execute(self, userdata): rospy.loginfo("No user detected") user_detected = 1 if (user_detected): r...
ackingWrongUser"
JaDogg/__py_playground
reference/parsley/examples/trace_visualiser.py
Python
mit
2,033
0.000492
fr
om tkinter.scrolledtext import ScrolledText import tkinter as tk from trace_json import traceparse from parsley_json import jsonGrammar jsonData = open('337141-steamcube.json').read() class Tracer(object): def __init__(self, grammarWin, inputWin, logWin, trace): self.grammarWin = grammarWin sel...
self.logWin = logWin self.trace = trace self.position = 0 def advance(self): if self.position < len(self.trace): self.position += 1 self.display() def rewind(self): if self.position > 0: self.position -= 1 self.display() ...
ifduyue/sentry
src/sentry/south_migrations/0310_auto__add_field_savedsearch_owner.py
Python
bsd-3-clause
109,233
0.000861
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'SavedSearch.owner' db.add_column( 'sentry_save...
ue'
} ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' ...
izzygomez/cocoon
crypto/crypto.py
Python
mit
4,136
0.013781
from Crypto.Cipher import AES import base64 import hashlib import math BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s : s[0:-ord(s[-1])] # pseudo-random function def PRF(key, plaintext): keyHash = hashlib.sha256(key).hexdigest() ptxtHash = hashlib.sha256(plaintext).hexdi...
# Pad the index and inputSize to make sure they are a power of 2 bitLength = int(math.ceil(math.log(inputSize, 2))) paddedPermutedIndex = bin(permutedIndex)[2:].zfill(bitLength) # Next, split into left and right # If there are an even am
ount of bits if bitLength % 2 == 0: leftHalf = paddedPermutedIndex[:bitLength/2] rightHalf = paddedPermutedIndex[bitLength/2:] leftRandom = hashBinary(leftHalf, key, bitLength/2) rightHalf = int(rightHalf, 2) leftRandom = int(leftRandom, 2) leftXor = leftRandom ^ rightHalf leftXor = bin(le...
alexm92/sentry
src/sentry/rules/conditions/event_frequency.py
Python
bsd-3-clause
2,896
0
""" sentry.rules.conditions.event_frequency ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from datetime import timedelta from django import forms from django....
_sums( model=self.tsdb.models.group, keys=[event.group_id], start=start, end=end, )[event.group_id] class EventUniqueUserFrequencyCondition(BaseEventFrequencyCondition): label = 'An event is seen by more than {value} users in {interval}' def query(self,...
_by_group, keys=[event.group_id], start=start, end=end, )[event.group_id]
yosshy/nova
nova/tests/unit/scheduler/filters/test_affinity_filters.py
Python
apache-2.0
8,801
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...
ilter_properties = {'context': mock.sentinel.ctx,
'scheduler_hints': { 'different_host': ['same'], }} self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_affinity_different_filter_no_list_passes(self): host = fakes.FakeHostState('host1', 'node1', {}) host.instances =...
cgeoffroy/son-analyze
scripts/all.py
Python
apache-2.0
2,996
0
#! /usr/bin/env python3 # Copyright (c) 2015 SONATA-NFV, Thales Communications & Security # 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/...
a colorized string corresponding to the return code""" if return_code == 0: return '{} {}: commands succeeded{}'.format(Fore.GREEN, name, Style.RESET_ALL) return '{}ERROR, {}: commands failed{}'.format(Fore.RED, name, ...
print('\n{0} summary {0}'.format('_'*35)) for summary in summaries: print(text_summary(*summary)) def main() -> None: """Main entrypoint""" init() args = sys.argv[1:] summaries = [] # type: List[Tuple[str, int]] commands = [('flake8', 'scripts/flake8.sh'), ('pylint', '...
neoatlantis/MTSAT-2-plotter
converter.py
Python
gpl-3.0
468
0.004274
#!/u
sr/bin/python import os from subprocess import * import sys from PIL import Image def convert(table, dimension, dataString): tableStr = ''.join([chr(i) for i in tabl
e]) print "Calling C converter..." proc = Popen(['./converter'], stdin=PIPE, stdout=PIPE, shell=True, bufsize=0) strout, strerr = proc.communicate(tableStr + dataString) print "C converter called..." endstr = strout[-2:] strout = strout[:-2] return strout
thisismyrobot/dnstwister
tests/test_exports.py
Python
unlicense
14,760
0.000678
"""Test the csv/json export functionality.""" import binascii import textwrap import dnstwister.tools import patches from dnstwister.core.domain import Domain def test_csv_export(webapp, monkeypatch): """Test CSV export""" monkeypatch.setattr( 'dnstwister.tools.resolve', lambda domain: ('999.999.999....
port_a.com.json' assert response.json == { u'a.com': { u'fuzzy_domains': [ { u'domain-name': u'a.com', u'fuzzer': u'Original*', u'hex': u'612e636f6d', u'resolution': { u'error...
, monkeypatch): """Test JSON export looks nice :)""" monkeypatch.setattr( 'dnstwister.tools.dnstwist.DomainFuzzer', patches.SimpleFuzzer ) monkeypatch.setattr( 'dnstwister.tools.resolve', lambda domain: ('999.999.999.999', False) ) domain = 'a.com' path = Domain(domain).to_h...
hsoft/jobprogress
jobprogress/job.py
Python
bsd-3-clause
6,167
0.006162
# Created By: Virgil Dupras # Created On: 2004/12/20 # Copyright 2011 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses...
''' Iterate through sequence while automatically adding progress. ''' desc = '' if desc_format: desc = desc_format % (0, len(sequence)) self.start_job(len(sequence), desc) for i, element in enumerate(sequence, start=1): yield element if i % eve...
desc = desc_format % (len(sequence), len(sequence)) self.set_progress(100, desc) def start_job(self, max_progress=100, desc=''): """Begin work on the next job. You must not call start_job more than 'jobcount' (in __init__) times. 'max' is the job units you are to perfor...
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/terminal/iosxr.py
Python
bsd-3-clause
1,889
0.000529
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible is distributed in the hope that it will be useful, # but WITHO
UT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ ...
attojeon/learnsteam.node.js
gpio/dht11Run.py
Python
gpl-2.0
410
0.036585
import RPi.GPIO as GPIO import dht11 import time # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() instance = dht11.DHT
11(pin = 23) while( 1 ) : result = instance.read() if result.is_valid(): print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity)
else: continue # print("Error: %d" % result.error_code) time.sleep(0.5)
Positliver/Salmon
src/config.py
Python
bsd-3-clause
1,728
0.013657
''' Created on 2015-7-11 @author: livepc ''' #encoding=utf-8 import os DownloadDataDir = os.path.join(os.path.dirname(__file__), 'stockdata/') # os.path.pardir: 上级目录 DownloadCodeDir = os.path.join(os.path.dirname(__file__), 'stockcode/') HS300_CodePath =os.path.join(DownloadCodeDir, 'HS300S.csv') SZ50_Cod...
CALE_0 = 1.02 #没有补过仓的开盘卖价 KAIPAN_DELEGATESAIL_SCALE_1 = 1.01 #补过一次仓的卖价 KAIPAN_DELEGATESAIL_SCALE_2 = 1.00 #补过两次仓的卖价 PANZHONG_BUCANG_SCALE_0 = 0.92 # 盘中相对于今天开盘价的跌8个点 补仓。 WEIPAN_BUCANG_SCALE_0 = 1.02 # 尾盘时 计算是否可以补仓, 当跌幅超过2个点的时候,可以补仓 # KAIPAN_DELEGATEBUY_SCALE_1 = 0.92 #开盘没有卖出,基本判定需要补仓 # KAIPAN_DELEGATEBU...
进行开盘没有卖出的补仓 GEROU_SCALE_0 = 0.95 # 触发割肉条件,成本价跌5个点。 MOST_DAYS_CHIGU = 5 # 触发割肉 超过5天必须持股天数 INITIAL_MONEY= 100000 # 初始资金 CHICANG_BILIE_EXCEPT_BUCANG = 0.5 # 持仓比例, 新买入股票时使用, 补仓不使用 DATE_START = '2013-01-01' DATE_END = '2013-2-01'
leiyangyou/libvips
python/find_class_methods.py
Python
lgpl-2.1
1,412
0.002833
#!/usr/bin/python import sys import logging #logging.basicConfig(level = logging.DEBUG) from gi.repository import Vips, GObject # Search for all VipsOperation which don't have an input image object ... these # should be class methods and need to have their names pasted into Vips.py # This is slow :-( so we don't d...
gtype = Vips.type_find("VipsOperation", cls.name) nickname = Vips.nickname_find(gtype)
print ' "%s",' % nickname if len(cls.children) > 0: for child in cls.children: # not easy to get at the deprecated flag in an abtract type? if cls.name != 'VipsWrap7': find_class_methods(child) print 'found class methods:' find_class_methods(vips_type_o...
FinnStutzenstein/OpenSlides
server/openslides/motions/config_variables.py
Python
mit
13,984
0.001001
from django.conf import settings from django.core.validators import MinValueValidator from openslides.core.config import ConfigVariable from openslides.motions.models import MotionPoll from .models import Workflow def get_workflow_choices(): """ Returns a list of all workflows to be used as choices for the ...
lue="", label="Name of recommender for statute amendments", help_text="Will b
e displayed as label before selected recommendation in statute amendments.", weight=333, group="Motions", ) yield ConfigVariable( name="motions_recommendation_text_mode", default_value="diff", input_type="choice", label="Default text version for change recommenda...
UQ-UQx/edx-platform_lti
common/djangoapps/external_auth/views.py
Python
agpl-3.0
38,028
0.001499
import functools import json import logging import random import re import string # pylint: disable=deprecated-module import fnmatch import unicodedata import urllib from textwrap import dedent from external_auth.models import ExternalAuthMap from external_auth.djangostore import DjangoOpenIDStore from django.c...
counts # For Stanford shib, the email the idp returns is actually under the control of the user. # Since the id the idps return is not user-editable, and is of the from "username@stanford.edu", # use the id to link accounts instead. try: link_user = User.o...
(email=eamap.external_id) if not ExternalAuthMap.objects.filter(user=link_user).exists(): # if there's no pre-existing linked eamap, we link the user eamap.user = link_user eamap.save() internal_user = link_user ...
richardliaw/ray
python/ray/tune/examples/pbt_convnet_example.py
Python
apache-2.0
4,748
0
#!/usr/bin/env python # flake8: noqa # yapf: disable # __tutorial_imports_begin__ import argparse import os import numpy as np import torch import torch.optim as optim from torchvision import datasets from ray.tune.examples.mnist_pytorch import train, test, ConvNet,\ get_data_loaders import ray from ray import t...
export_formats=[ExportFormat.MODEL], checkpoint_score_attr="mean_accuracy", checkpoint_freq=5, keep_checkpoints_num=4, num_samples=4, config={ "lr": tune.uniform(0.001, 1), "momentum": tune.uniform(0.001, 1), }) # __tune_end__ best...
nalysis.best_trial best_checkpoint = analysis.best_checkpoint restored_trainable = PytorchTrainable() restored_trainable.restore(best_checkpoint) best_model = restored_trainable.model # Note that test only runs on a small random set of the test data, thus the # accuracy may be different from met...
DTUWindEnergy/FUSED-Wake
setup.py
Python
mit
2,875
0.005217
#!/usr/bin/env python # -*- coding: utf-8 -*- # # try: # from setuptools import setup # except ImportError: # from distutils.core import setup #from setuptools import setup #from setuptools import Extension from numpy.distutils.core import setup from numpy.distutils.extension import Extension import os impo...
ipy', 'pandas',
'matplotlib', 'PyYAML', 'utm' ] test_requirements = [ 'tox', 'pytest', 'coverall', ] setup( name='fusedwake', version='0.1.0', description="A collection of wind farm flow models for FUSED-Wind", long_description=readme + '\n\n' + history, author="Pierre-Elouan Rethore", a...
sacgup/django-rest-swagger
rest_framework_swagger/__init__.py
Python
bsd-2-clause
1,311
0.000763
VERSION = '0.3.4' DEFAULT_SWAGGER_SETTINGS = { 'exclude_namespaces': [], 'api_version': '', 'api_path': '/', 'api_key': '', 'token_type': 'Token', 'enabled_methods': ['get', 'post', 'put', 'patch', 'delete'], 'is_authenticated': False, 'is_superuser': False, 'unauthenticated_user': ...
SWAGGER_SETTINGS[key] = value def reload_settings(*args, **kwargs): setting, value = kwargs['setting'], kwargs['value'] if setting == 'SWAGGER_SETTINGS': load_settings(value) load_settings(getattr(settin
gs, 'SWAGGER_SETTINGS', DEFAULT_SWAGGER_SETTINGS)) setting_changed.connect(reload_settings) except: SWAGGER_SETTINGS = DEFAULT_SWAGGER_SETTINGS
AsgerPetersen/QGIS
python/plugins/GdalTools/tools/doExtractProj.py
Python
gpl-2.0
7,413
0.001079
# -*- coding: utf-8 -*- """ *************************************************************************** doExtractProj.py --------------------- Date : August 2011 Copyright : (C) 2011 by Alexander Bruy Email : alexander dot bruy at gmail dot com ************...
f run(self): self.mutex.lock() self.stopMe = 0 self.mutex.unlock() interrupted = False for f in self.inFiles: extractProjection(f, self.needPrj) self.fileProcessed.emit() self.mutex.lock() s = self.stopMe self.mutex.u...
() if s == 1: interrupted = True break if not interrupted: self.processFinished.emit() else: self.processIterrupted.emit() def stop(self): self.mutex.lock() self.stopMe = 1 self.mutex.unlock() QThr...
pudo/aleph
aleph/views/alerts_api.py
Python
mit
3,323
0
from flask import Blueprint, request from aleph.core import db from aleph.model import Alert from aleph.search import DatabaseQueryResult from aleph.views.serializers import AlertSerializer from aleph.views.util import require, obj_or_404 from aleph.views.util import parse_request from aleph.views.context import tag_r...
alert_id required: true schema: minimum: 1 type: integer example: 2 responses: '200': content: application/json: schema: $ref: '#/components/schemas/Alert' description: OK tags: - Alert ...
hz.logged_in) alert = obj_or_404(Alert.by_id(alert_id, role_id=request.authz.id)) return AlertSerializer.jsonify(alert) @blueprint.route("/api/2/alerts/<int:alert_id>", methods=["DELETE"]) def delete(alert_id): """Delete the alert with id `alert_id`. --- delete: summary: Delete an alert ...
googleads/google-ads-python
google/ads/googleads/v10/services/types/keyword_plan_campaign_service.py
Python
apache-2.0
5,624
0.000533
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
from google.protobuf import field_mask_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v10.services", marshal="google.ads.googleads.v10", manifest={ "M
utateKeywordPlanCampaignsRequest", "KeywordPlanCampaignOperation", "MutateKeywordPlanCampaignsResponse", "MutateKeywordPlanCampaignResult", }, ) class MutateKeywordPlanCampaignsRequest(proto.Message): r"""Request message for [KeywordPlanCampaignService.MutateKeywordPlanCampaigns][g...
vertexproject/synapse
synapse/cmds/hive.py
Python
apache-2.0
8,362
0.002153
import os import json import shlex import pprint import asyncio import tempfile import functools import subprocess import synapse.exc as s_exc import synapse.common as s_common import synapse.lib.cmd as s_cmd import synapse.lib.cli as s_cli ListHelp = ''' Lists all the keys underneath a particular key in the hive. ...
=functools.partial(s_cmd.Parser, outp=self)) parser_ls = subparsers.add_parser('list', aliases=['ls'], help="List entries in the hive", usage=ListHelp) parser_ls.add_argument('path', nargs='?', help='Hive path') parser_get = subparsers.add_parser('get', help="Get any entry in the hi
ve", usage=GetHelp) parser_get.add_argument('path', help='Hive path') parser_get.add_argument('-f', '--file', default=False, action='store', help='Save the data to a file.') parser_get.add_argument('--json', default=False, action='store_true', help='Emit output as...
rayrrr/luigi
test/range_test.py
Python
apache-2.0
65,208
0.001871
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
sC(luigi.Task): dm = luigi.DateMinuteParameter() def output(self): return MockTarget(self.dm.strftime('not/a/real/path/%Y-%m-%d/%H%M')) class CommonWrapperTaskMinutes(luigi.WrapperTask):
dm = luigi.DateMinuteParameter() def requires(self): yield TaskMinutesA(dm=self.dm) yield TaskMinutesB(dm=self.dm, complicator='no/worries') # str(self.dh) would complicate beyond working def mock_listdir(contents): def contents_listdir(_, glob): for path in fnmatch.filter(contents...
ecreall/nova-ideo
novaideo/views/comment_management/remove.py
Python
agpl-3.0
2,434
0.000411
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from pyramid.view import view_config from pyramid import renderers from dace.objectofcollaboration.principal.util import get_current from dace.processinsta...
lues, self.request) values = {'comment_body': comment_body} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]}
return result class RemoveForm(FormView): title = _('Remove comment') name = 'removecommentform' behaviors = [Remove, Cancel] viewid = 'removecommentform' validate_behaviors = False def before_update(self): self.action = self.request.resource_url( self.context, 'novai...
3cky/horus
src/horus/gui/wizard/scanningPage.py
Python
gpl-2.0
5,007
0.001398
# -*- coding: utf-8 -*- # This file is part of the Horus Project __author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>' __copyright__ = 'Copyright (C) 2014-2015 Mundo Reader S.L.' __license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html' import wx._core from horus.gui.wizard.wizardPage i...
it__(self, pare
nt, buttonPrevCallback=None, buttonNextCallback=None): WizardPage.__init__(self, parent, title=_("Scanning"), buttonPrevCallback=buttonPrevCallback, buttonNextCallback=buttonNextCallback) self.driver = Driver() ...
Flexlay/flexlay
netpanzer/netpanzer.py
Python
gpl-3.0
12,517
0.009907
## $Id$ ## ## Flexlay - A Generic 2D Game Editor ## Copyright (C) 2002 Ingo Ruhnke <grumbel@gmx.de> ## ## 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 Licen...
n(outposts)) for (name, x , y) in outpots: f.write("Name: %s\n" % "Foobar") f.write("Location: %d %d\n\n" % (int(x)/32, int(y)/32)) def save_spnfile(self, filename): spawnpoints = [] f = open(filename, "w") f.write("SpawnCount: %d\n\n" % len(spawnpoints)) ...
:] == ".npm": data.save(filename) save_optfile(filename[:-4] + ".opt") save_optfile(filename[:-4] + ".spn") else: raise "Fileextension not valid, must be .npm!" def activate(self, workspace): workspace.set_map(self.editormap) TilemapLayer.set_...
nmercier/linux-cross-gcc
win32/bin/Lib/distutils/file_util.py
Python
bsd-3-clause
8,370
0.000597
"""distutils.file_util Utility functions for operating on single files. """ __revision__ = "$Id$" import os from distutils.errors import DistutilsFileError from distutils import log # for generating verbose output in 'copy_file()' _copy_action = {None: 'copying', 'hard': 'hard linking',...
move_file (src, dst, verbose=1, dry_run=0): """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will be moved into it with the same name; otherwise, 'src' is just renamed to 'dst'. Return the new full name of the file. Handles c
ross-device moves on Unix using 'copy_file()'. What about other systems??? """ from os.path import exists, isfile, isdir, basename, dirname import errno if verbose >= 1: log.info("moving %s -> %s", src, dst) if dry_run: return dst if not isfile(src): ...
Ziqi-Li/bknqgis
bokeh/examples/howto/server_embed/standalone_embed.py
Python
gpl-2.0
1,771
0.002259
from tornado.ioloop import IOLoop import yaml from bokeh.application.handlers import FunctionHandler from bokeh.application import App
lication from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.plotting import figure from bokeh.server.server import Server from bokeh.themes import Theme from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature io_loop = IOLoop.current() def modify_doc(do...
ange=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean()...
bittner/django-media-tree
media_tree/contrib/cms_plugins/media_tree_image/views.py
Python
bsd-3-clause
1,854
0.002157
from media_tree.contrib.cms_plugins.media_tree_image.models import MediaTreeImage from media_tree.contrib.cms_plugins.helpers import PluginLink from media_tree.models import FileNode from media_tree.contrib.views.detail.image import ImageNodeDetailView from django.utils.translation import ugettext_lazy as _ from cms.ut...
# is a bit inefficient. page = get_page_from_path(plugin.page.get_path()) if page: allowed = True break if not allowed: raise Http404 return obj def get_context_data(self, *args, **kwargs): ...
if self.return_url: page = get_page_from_path(self.return_url.strip('/')) if page: context_data.update({ 'link': PluginLink(url=page.get_absolute_url(), text=_('Back to %s') % page.get_title()) }) retur...
PaddlePaddle/Paddle
python/paddle/incubate/__init__.py
Python
apache-2.0
1,529
0.000654
# Copyright (c) 2020 PaddlePaddle 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 applic...
r import DistributedFusedLamb # noqa: F401 from .checkpoint import auto
_checkpoint # noqa: F401 from ..fluid.layer_helper import LayerHelper # noqa: F401 from .operators import softmax_mask_fuse_upper_triangle # noqa: F401 from .operators import softmax_mask_fuse # noqa: F401 from .operators import graph_send_recv from .operators import graph_khop_sampler from .tensor import segment_s...
vahana/prf
prf/s3.py
Python
mit
954
0.004193
import logging import boto3 import io from slovar import slovar from prf import fs log = logging.getLogger(__name__) def includeme(config): Settings = slovar(config.registry.settings) S3.setup(Settings) class S3(fs.FS): def __init__(self, ds, create=False): path = ds.ns.split('/') bucke...
e(self.path) ) def drop_collection(self): for it in self.bucket.objects.filter(Prefix=self.path): it.delete() def get_file_or_bu
ff(self): obj = boto3.resource('s3').Object(self.bucket.name, self.path) return io.BytesIO(obj.get()['Body'].read())
eliquious/go-v8
v8-3.28/tools/testrunner/local/progress.py
Python
mit
10,716
0.008585
# Copyright 2012 the V8 project authors. 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 copyright # notice, this list of conditi...
T # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import json import os import sys import time from . import junit_output ABS_PATH_PREFIX = os.getcwd() + os.sep def EscapeCommand(command): parts = [] for part in command: if ' ' in part: # Escape spaces. We may need to esc...
mkuiack/tkp
tests/test_utility/test_sorting.py
Python
bsd-2-clause
1,609
0.001865
import unittest from collections import namedtuple from datetime import datetime, timedelta import random from tkp.steps.misc import group_per_timestep MockOrmImage = namedtuple('MockOrmImage', ['taustart_ts', 'freq_eff', 'stokes']) now = datetime.now() def create_input(): """ returns a list of mock orm imag...
= [] for hours in 1, 2, 3: taustart_ts = now - timedelta(hours=hours) for freq_ef
f in 100, 150, 200: for stokes in 1, 2, 3, 4: mockimages.append(MockOrmImage(taustart_ts=taustart_ts, freq_eff=freq_eff ** 6, stokes=stokes)) # when we seed the RNG with a constant the shuffle ...
MidAtlanticPortal/marco-portal2
marco/portal/base/migrations/0003_auto_20150122_2130.py
Python
isc
440
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('base', '0002_auto_20150122_2113'), ] operations = [ migrations.AlterField( model_n
ame='portalimage', name='creator_URL', field=models.URLField(blank=True),
preserve_default=True, ), ]
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_file_system/shutil_get_unpack_formats.py
Python
apache-2.0
163
0
import shutil for format, exts, description in
shutil.get_unpack_formats(): print('{:<5}: {}, names ending in {}'.format( format,
description, exts))
cmouse/buildbot
master/buildbot/test/integration/test_customservices.py
Python
gpl-2.0
3,838
0
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
build['steps'][0]['state_string'], 'num reconfig: 1') myService = self.master.service_manager.namedServices['myService'] self.assertEqual(myService.num_reconfig, 1) self.assertTrue(myService.running)
# We do several reconfig, and make sure the service # are reconfigured as expected yield self.master.reconfig() build = yield self.doForceBuild(wantSteps=True) self.assertEqual(myService.num_reconfig, 2) self.assertEqual(build['steps'][0]['state_string'], 'num reconfig: 2...
sv1jsb/pCMS
pCMS/urls.py
Python
bsd-3-clause
702
0.012821
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings admin.
autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root': settings.STATIC_ROOT}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root': settin
gs.MEDIA_ROOT}), url(r'fpg/',include('pCMS.fpg.urls')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}), url(r'^comments/', include('django.contrib.comments.urls')), )
azumimuo/family-xbmc-addon
plugin.video.bubbles/resources/lib/sources/russian/hoster/open/__init__.py
Python
gpl-2.0
910
0.002198
# -*- coding: utf-8 -*- """ Bubbles Addon Copyright (C) 2
016 Exodus 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 l
ater version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General...
AversivePlusPlus/AversivePlusPlus
tools/conan/conans/client/packager.py
Python
bsd-3-clause
2,736
0.001462
from conans.util.files import mkdir, save, rmdir import os from conans.util.log import logger from conans.paths import CONANINFO, CONAN_MANIFEST from conans.errors import ConanException, format_conanfile_exception from conans.model.build_info import DEFAULT_RES, DEFAULT_BIN, DEFAULT_LIB, DEFAULT_INCLUDE import shutil f...
raise ConanException(msg) _create_aux_files(build_folder, package_folder) output.success("Package '%s' created" %
os.path.basename(package_folder)) def generate_manifest(package_folder): # Create the digest for the package digest = FileTreeManifest.create(package_folder) save(os.path.join(package_folder, CONAN_MANIFEST), str(digest)) def _create_aux_files(build_folder, package_folder): """ auxiliary method tha...
F5Networks/f5-common-python
f5/bigip/tm/util/dig.py
Python
apache-2.0
1,322
0
# coding=utf-8 # # Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "Licen
se"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRA...
IP® utility module REST URI ``http://localhost/mgmt/tm/util/dig`` GUI Path N/A REST Kind ``tm:util:dig:*`` """ from f5.bigip.mixins import CommandExecutionMixin from f5.bigip.resource import UnnamedResource class Dig(UnnamedResource, CommandExecutionMixin): """BIG-IP® utility command .. note:...
596acres/django-livinglots-lots
livinglots_lots/urls.py
Python
agpl-3.0
3,373
0.000296
from django.conf.urls import url from livinglots import get_organizer_model, get_watcher_model from .views import (AddToGroupView, CheckLotWithParcelExistsView, CountParticipantsView, CreateLotByGeomView, EmailParticipantsView, HideLotView, HideLotSuccessView, ...
/email/', EmailParticipantsView.as_view( model=get_watcher_model(), participant_type='watcher', permission_required='organize.email_watcher', ), name='lot_em
ail_watchers'), url(r'^organize/watchers/count/', CountParticipantsView.as_view( model=get_watcher_model(), participant_type='watcher', permission_required='organize.email_watcher', ), name='lot_count_watchers'), url(r'^(?P<pk>\d+)/content/json/$', LotContent...
iut-ibk/DynaMind-UrbanSim
3rdparty/opus/src/sanfrancisco/business_relocation_probabilities.py
Python
gpl-2.0
218
0.009174
# Opus/UrbanSim urban simulat
ion software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from urbansim_parcel.business_relocation_probabilities import business_relocation_probabilitie
s
ztp-at/RKSV
librksv/depparser.py
Python
agpl-3.0
26,170
0.002981
########################################################################### # Copyright 2017 ZT Prentner IT GmbH (www.ztp.at) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either ver...
t in the DEP is redundant. """ def __init__(self, elem, groupidx=None): super(DuplicateDEPElementException, self).__init__( _("Duplicate element \
"{}\"").format(elem), groupidx) self._initargs = (elem, groupidx) class MalformedCertificateException(DEPParseException): """ Indicates that a certificate in the DEP is not properly formed. """ def __init__(self, cert): super(MalformedCertificateException, self).__init_...
heejongahn/flask-sqlalchemy
flask_sqlalchemy/__init__.py
Python
bsd-3-clause
35,980
0.000334
# -*- coding: utf-8 -*- """ flaskext.sqlalchemy ~~~~~~~~~~~~~~~~~~~ Adds basic SQLAlchemy support to your application. :copyright: (c) 2014 by Armin Ronacher, Daniel Neuhäuser. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement, absolute_import import os import ...
ools import warnings import sqlalchemy from math import ceil from functools import partial from flask import _request_ctx_stack, abort, has_request_context, request from flask.signals import Namespace from operator import itemgetter from threading import Lock from sqlalchemy import orm, event, inspect from sqlalchemy.o...
e import declarative_base, DeclarativeMeta from flask_sqlalchemy._compat import iteritems, itervalues, xrange, \ string_types # the best timer function for the platform if sys.platform == 'win32': _timer = time.clock else: _timer = time.time try: from flask import _app_ctx_stack except ImportError: ...
prusnak/bitcoin
test/functional/rpc_generateblock.py
Python
mit
5,595
0.006256
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. '''Test generateblock rpc. ''' from test_framework.test_framework import BitcoinTestFramework from test_f...
self.log.info('Fail to generate block with out of order txs') raw1 = node.createrawtransaction([{'txid':txid, 'vout':0}],[{address:0.9999}]) signed_raw1 = node.signrawtransactionwithwallet(raw1)['hex'] txid1 = node.sendrawtransaction(signed_raw1)
raw2 = node.createrawtransaction([{'txid':txid1, 'vout':0}],[{address:0.999}]) signed_raw2 = node.signrawtransactionwithwallet(raw2)['hex'] assert_raises_rpc_error(-25, 'TestBlockValidity failed: bad-txns-inputs-missingorspent', self.generateblock, node, address, [signed_raw2, txid1]) self.log....
prodromou87/gem5
tests/configs/realview-switcheroo-atomic.py
Python
bsd-3-clause
2,428
0
# Copyright (c) 2012 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 functionality ...
modified and in its entirety i
n all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 copyright # notice,...
sadad111/leetcodebox
Binary Tree Inorder Traversal.py
Python
gpl-3.0
1,336
0
# /** # * Definition for
a binary tree node. # * public class TreeNode { # * int val; # * TreeNode left; # * TreeNode right; # * TreeNode(int x) { val = x; } # * } # */ # public class Solution { # public List<Integer> inorderTraversal(TreeNode root) { # List<Integer> list = new ArrayList<Integer>(); # # ...
stack.add(cur); # cur = cur.left; # } # cur = stack.pop(); # list.add(cur.val); # cur = cur.right; # } # # return list; # } # } # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self...
rivasd/djPsych
djsend/migrations/0056_auto_20170614_1552.py
Python
gpl-3.0
588
0.001701
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-06-14 19:52 from __future__ import unicode_literals from django.db import migrations, models cla
ss Migration(migrations.Migration): dependencies = [ ('djsend', '0055_relationcategorizationblock_response_wait'), ] operations = [ migrations.AlterField( model_name='relationcategorizationblock', name='response_wait', field=models.BooleanField(default=F...
are gone before answering'), ), ]
glogiotatidis/bedrock
tests/functional/firefox/test_ios.py
Python
mpl-2.0
1,107
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from selenium.common.exceptions import TimeoutException from pages.firefox.ios import IOSPage @pytest.m...
.nondestructive def
test_send_to_device_sucessful_submission(base_url, selenium): page = IOSPage(selenium, base_url).open() send_to_device = page.send_to_device send_to_device.type_email('success@example.com') send_to_device.click_send() assert send_to_device.send_successful @pytest.mark.nondestructive def test_send_...
collingreen/djeroku
project/settings/prod.py
Python
mit
4,008
0
""" Production settings Debug OFF Djeroku Defaults: Mandrill Email -- Requires Mandrill addon dj_database_url and django-postgrespool for heroku postgres configuration memcachify for heroku memcache configuration Commented out by default - redisify for heroku redis cache configuration What you need t...
s to mandril, which is already set up when added to your app There is also a commented version that uses your gmail address. For more control, you can set any of the following keys in your environment: EMAIL_HOST, EMAIL_HOST_PASSWORD, EMAIL_HOST_USER, EMAIL_PORT """ from os
import environ import dj_database_url # automagically sets up whatever memcache heroku addon you have as the cache # https://github.com/rdegges/django-heroku-memcacheify from memcacheify import memcacheify # use redisify instead of memcacheify if you prefer # https://github.com/dirn/django-heroku-redisify # from red...
amonmoce/corba_examples
omniORBpy-4.2.1/build/python/COS/CosRelationships_idl.py
Python
mit
42,484
0.008191
# Python stubs generated by omniidl from /usr/local/share/idl/omniORB/COS/CosRelationships.idl # DO NOT EDIT THIS FILE! import omniORB, _omnipy from omniORB import CORBA, PortableServer _0_CORBA = CORBA _omnipy.checkVersion(4,2, __file__, 1) tr
y: property except NameError: def property(*args): return None # #include "corbaidl.idl" import corbaidl_idl _0_CORBA = omniORB.openModule("CORBA") _0_CORBA__POA = omniOR
B.openModule("CORBA__POA") # #include "boxes.idl" import boxes_idl _0_CORBA = omniORB.openModule("CORBA") _0_CORBA__POA = omniORB.openModule("CORBA__POA") # #include "ir.idl" import ir_idl _0_CORBA = omniORB.openModule("CORBA") _0_CORBA__POA = omniORB.openModule("CORBA__POA") # #include "CosObjectIdentity.idl" impor...
smartyrad/Python-scripts-for-web-scraping
shopclues_string.py
Python
gpl-3.0
2,978
0.004701
from lxml import html import csv, os, json import requests from exceptions import ValueError from time import sleep import urllib import lxml.html genList_shopclues = [] extracted_data_shopclues = [] data = [] papa = None site = None def ShopcluesParser(url): headers = { 'User-Agent': 'Mozilla/5.0 (X11; L...
join(''.join(RAW_NAME).split()) if RAW_NAME else None PRODUCTID = ' '.join(''.join(RAW_PRODUCTID).split()).strip() if RAW_PRODUCTID else None DISCOUNTED_PRICE = ' '.join(''.join(RAW_DISCOUNTED_PRICE).split()).strip() if RAW_DISCOUNTED_PRICE else None SALE_PRICE = ' '.join(''.join(RAW
_SALE_PRICE).split()).strip() if RAW_SALE_PRICE else None ORIGINAL_PRICE = ''.join(RAW_ORIGINAL_PRICE).strip() if RAW_ORIGINAL_PRICE else None DISCOUNT = ''.join(RAW_DISCOUNT).strip() if RAW_DISCOUNT else None if page.status_code != 200: raise ValueError('captcha') data = { 'NAME': NAME...
mitodl/micromasters
discussions/api.py
Python
bsd-3-clause
16,514
0.002241
"""API for open discussions integration""" import logging from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import transaction from open_discussions_api.client import OpenDiscussionsApi from open_discussions_api.constants import ROLE_STAFF from requests.exceptions ...
sion user to create Raises: DiscussionUserSyncException: if t
here was an error syncing the profile """ profile = discussion_user.user.profile api = get_staff_client() result = api.users.create( profile.user.username, email=profile.user.email, profile=dict( name=profile.full_name, image=profile.image.url if profile....
JamesLinus/OMMPS
ProcessMonitor.py
Python
lgpl-3.0
1,496
0.009358
#!/usr/bin/env python # -*- coding: utf-8 -*- #*/1 * * * * python /xxx/monitor.py >> /xxx/logs/monitor.log 2>&1 & import sys import subprocess import os.path as op import socket def this_abs_path(script_name): return op.abspath(op.join(op.dirname(__file__), script_name)) def monitor_process(key_word, cmd): ...
return sys.stderr.write('process[%s] is lost, run [%s]\n' % (key_word, cmd)) subprocess.call(cmd, shell=True)
def monitor_port(protocol, port, cmd): address = ('127.0.0.1', port) socket_type = socket.SOCK_STREAM if protocol == 'tcp' else socket.SOCK_DGRAM client = socket.socket(socket.AF_INET, socket_type) try: client.bind(address) except Exception, e: pass else: sys.stderr.writ...
phiros/nepi
src/nepi/resources/ns3/ns3server.py
Python
gpl-3.0
7,038
0.011367
# # NEPI, a framework to manage network experiments # Copyright (C) 2014 INRIA # # 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 ...
f not msg_type: # Ignore - connection lost close_socket(conn) continue if msg_type == NS3WrapperMessage.SHUTDOWN: stop = True try: reply = handle_message(ns3_wrapper, msg_type, args, kwargs) except: import traceback ...
gger.error(err) close_socket(conn) raise try: send_reply(conn, reply) except socket.error: import traceback err = traceback.format_exc() ns3_wrapper.logger.error(err) close_socket(conn) raise ...
tvalacarta/tvalacarta
python/main-classic/channels/xiptv.py
Python
gpl-3.0
11,785
0.018058
# -*- coding: utf-8 -*- #------------------------------------------------------------ # tvalacarta - XBMC Plugin # Canal para xip/tv # http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/ #------------------------------------------------------------ import urlparse,urllib,re from core import logger from core import sc...
alt="Frame_sex_toy_ficcions" src="/media/asset_publics/resources /000/106/321/program/FRAME_SEX_TOY_FICCIONS.JPG?1350386776" /></a> </div> <div class="archived"><em>Històric</em></div> <div class="content"> <h4><a href="/sex-toy-ficcions">Sex Toy Ficcions</a></h4> <h5> <a href="/programes/p...
gram%5Bprogram_categories%5D=Nous+formats" >Nous formats</a> </h5> <p>Sèrie en clau de comèdia, que gira al voltant de reunions cada cop més habituals conegudes com a "tupper sex", trobades a domicili per millorar la vida sexual de les persones que hi participen . La intenció de Sex Toy Ficcions és ...
ExploreEmbedded/Tit-Windows
tools/share/gdb/python/gdb/__init__.py
Python
bsd-3-clause
3,494
0.004007
# Copyright (C) 2010-2014 Free Software Foundation, Inc. # 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 progr...
ne # Ensure that sys.argv is set to something. # We do not use PySys_SetArgvEx because it di
d not appear until 2.6.6. sys.argv = [''] # Initial pretty printers. pretty_printers = [] # Initial type printers. type_printers = [] # Initial xmethod matchers. xmethods = [] # Initial frame filters. frame_filters = {} # Convenience variable to GDB's python directory PYTHONDIR = os.path.dirname(os.path.dirname(__fi...
viur-framework/server
db.py
Python
lgpl-3.0
43,494
0.040488
# -*- coding: utf-8 -*- from google.appengine.api import datastore, datastore_types, datastore_errors from google.appengine.datastore import datastore_query, datastore_rpc from google.appengine.api import memcache from google.appengine.api import search from server.config import conf import logging """ Tiny wrapper ...
gned by the data store. :param entities: Entity or list of entities to be stored. :type entities: :class:`server.db.Entity` | list of :class:`
server.db.Entity` :param config: Optional configuration to use for this request. This must be specified\ as a keyword argument. :type config: dict :returns: If the argument ``entities`` is a single :class:`server.db.Entity`, \ a single Key is returned. If the argument is a list of :class:`server.db.Entity`,...
joke2k/faker
faker/providers/person/en_NZ/__init__.py
Python
mit
40,961
0.000024
from collections import OrderedDict from typing import Dict from .. import Provider as PersonProvider class Provider(PersonProvider): formats = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{l...
"Hugo", 543), ("Hunter", 3044), ("Ian", 7592),
("Isaac", 4208), ("Isaiah", 349), ("Israel", 52), ("Ivan", 236), ("Jack", 9468), ("Jackson", 3088), ("Jacob", 8612), ("Jake", 2421), ("Jakob", 46), ("James", 27224), ("Jamie", 5064), ("...
ziirish/burp-ui
burpui/misc/backend/burp2.py
Python
bsd-3-clause
30,550
0.000556
# -*- coding: utf8 -*- """ .. module:: burpui.misc.backend.burp2 :platform: Unix :synopsis: Burp-UI burp2 backend module. .. moduleauthor:: Ziirish <hi+burpui@ziirish.me> """ import re import os import time import json from collections import OrderedDict from .burp1 import Burp as Burp1 from .interface impo...
og(number, client) ret.update(ret2) ret["encrypted"] = False if "files_enc" in ret and ret["files_enc"]["total"] > 0: ret["encrypted"] = True return ret @staticmethod def _do_parse_backup_log(data, client):
# tests ordered as the logs order ret = OrderedDict() ret["client_version"] = None ret["protocol"] = 1 ret["is_windows"] = False ret["server_version"] = None if not data: return ret try: log = data["clients"][0]["backups"][0]["logs...
Azure/azure-sdk-for-python
sdk/apimanagement/azure-mgmt-apimanagement/setup.py
Python
mit
2,672
0.001497
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
ng Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'License :: OSI Approved :: MIT License', ], zip_safe=False, packages=fi...
at will be covered by PEP420 or nspkg 'azure', 'azure.mgmt', ]), install_requires=[ 'msrest>=0.6.21', 'azure-common~=1.1', 'azure-mgmt-core>=1.3.0,<2.0.0', ], python_requires=">=3.6" )
xbmc/atv2
xbmc/lib/libPython/Python/Lib/plat-atheos/TYPES.py
Python
gpl-2.0
2,682
0.00783
# Generated by h2py from /include/sys/types.h _SYS_TYPES_H = 1 # Included from features.h _FEATURES_H = 1 __USE_ANSI = 1 __FAVOR_BSD = 1 _ISOC9X_SOURCE = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 199506L _XOPEN_SOURCE = 500 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 _BSD_SOURCE = 1 _SVID_SOURCE = 1 _BSD_SOURCE = 1...
FD_SETSIZE def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) # Included from sys/sysmacros.h _SYS_SYSMACROS_H = 1 def major(dev): return ( (( (dev) >> 8) & 0xff)) def minor(dev): retur
n ( ((dev) & 0xff))
pypa/warehouse
warehouse/packaging/search.py
Python
apache-2.0
2,723
0.000367
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lic
ense. # 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 or implied. # See the ...
import packaging.version from elasticsearch_dsl import Date, Document, Float, Keyword, Text, analyzer from warehouse.search.utils import doc_type EmailAnalyzer = analyzer( "email", tokenizer="uax_url_email", filter=["lowercase", "stop", "snowball"], ) NameAnalyzer = analyzer( "normalized_name", ...
ramineni/my_congress
congress/datasources/datasource_utils.py
Python
apache-2.0
6,907
0.000145
# Copyright (c) 2013,2014 VMware, 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 requi...
_prefix): """Inspect all callable methods from client for congress.""" # some methods are referred multiple times, we should # save them here to avoid infinite loop obj_checked = [] method_checked = [] # For depth-first search o
bj_stack = [] # save all inspected methods that will be returned allmethods = [] obj_checked.append(client) obj_stack.append(client) while len(obj_stack) > 0: cur_obj = obj_stack.pop() # everything starts with '_' are considered as internal only for f in [f for f in dir(cur_...
wprice/qpid-proton
tests/python/proton_tests/interop.py
Python
apache-2.0
5,318
0.004513
# # 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...
ert_next(Data.BINARY, str2bin("")) self.assert_next(Data.STRING, "") self.assert_next(Data.SYMBOL, "") assert self.data.next() is None def test_described(self): self.decode_data_file("described") self.assert_next(Data.DESCRIBED, Described("foo-descriptor", "foo-value")) ...
f.data.enter() self.assert_next(Data.INT, 12) self.assert_next(Data.INT, 13) self.data.exit() assert self.data.next() is None def test_described_array(self): self.decode_data_file("described_array") self.assert_next(Data.ARRAY, Array("int-array", Data.INT, *range(0,...
posix4e/electron
script/lib/config.py
Python
mit
2,118
0.01322
#!/usr/bin/env python import errno import os import platform import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/brave-laptop-binaries/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = os.getenv('LIBCHROMIUMCONTENT_COMMIT') or \ 'd715734c03b0c892ea66695ae63fc0db9c3fc027'...
$ATOM_SHELL_' + name return value def s3_config(): config = (get_env_var('S3_BUCKET'), get_env_var('S3_ACCESS_KEY'), get_env_var('S3_SECRET_KEY')) message = ('Error: Please set the $ELECTRON_S3_BUCKET, ' '$ELECTRON_S3_
ACCESS_KEY, and ' '$ELECTRON_S3_SECRET_KEY environment variables') assert all(len(c) for c in config), message return config def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode def get_zip_name(name,...
jsjohnst/tornado
tornado/locks.py
Python
apache-2.0
15,234
0.000197
# Copyright 2015 The Tornado Authors # # 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...
def notify_all(self): """Wake all waiters.""" self.notify(len(self._waiters)) class Event(object): """An event blocks coroutines until its internal flag is set to True. Similar to `threading.Event`. A coroutine can wait for an event to be set. On
ce it is set, calls to ``yield event.wait()`` will not block unless the event has been cleared: .. testcode:: from tornado import gen from tornado.ioloop import IOLoop from tornado.locks import Event event = Event() @gen.coroutine def waiter(): pri...
sensbio/sensbiotk
examples/scripts/fox_raw.py
Python
gpl-3.0
7,557
0.000265
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is a part of sensbiotk # Contact : sensbiotk@inria.fr # Copyright (C) 2015 INRIA # # 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 v...
ified filenames = [fnames] elif opt in ("-d", "--dir"): diroutput = arg elif opt in ("-b", "--basename"): newbasename = arg elif opt in ("-v", "--verif"): options.append("-v") elif opt in ("-t", "--time"): try: ...
od <= 0: usage() sys.exit(2) elif opt in ("-f", "--frequency"): try: period = float(arg) except ValueError: usage() sys.exit(2) if period <= 0: usage() sys.exit(2) ...
bcicen/fig
fig/__init__.py
Python
apache-2.0
107
0
from __future__ import unicode_literals from .service
import Service # noqa
:flake8 __version__ = '1.0.1'
kedz/cuttsum
trec2014/python/cuttsum/summarizer/filters.py
Python
apache-2.0
26,439
0.005371
from cuttsum.sentsim import SentenceLatentVectorsResource from cuttsum.summarizer.ap import APSummarizer, APSalienceSummarizer from cuttsum.summarizer.baseline import HACSummarizer import os import pandas as pd import numpy as np from datetime import datetime, timedelta from sklearn.metrics.pairwise import cosine_simil...
= lvec_df[Xsal_norm > sal_cutoff] str_df = str_df[Xsal_norm > sal_cutof
f] str_df = str_df.set_index(['stream id', 'sentence id']) lvec_df['salience'] = Xsal_norm[Xsal_norm > sal_cutoff] lvec_df.sort(['salience'], inplace=True, ascending=False) if Xcache is None: Xlvecs = lvec_df.as_matrix()[:, 2:-2].astype(np.float64) ...
dmahugh/gitdata
reposbymonth.py
Python
mit
629
0.00318
# reposbymonth.py # Convert temp.csv to temp2.csv (monthly totals) # temp.csv was created with this gitdata command: # gitdata repos -o* -amsftgi
ts -sa -ntemp.csv -fowner.login/name/private -v import csv with open('temp.csv', newline='') as csvfile1, open('temp2.csv', 'w', newline='') as csvfile2: reporeader = csv.reader(csvfile1, delimiter=' ', quotechar='|') repowriter = csv.writer(csvfile2, delimiter=' '
, quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in reporeader: values = row[0].split(',') values[3] = values[3][:7] print(values) repowriter.writerow([','.join(values)])
odoocn/pos-addons
pos_multi_session/__openerp__.py
Python
lgpl-3.0
424
0
{ 'na
me': "Sync POS orders across multiple sessions", 'version': '1.0.0', 'author':
'Ivan Yelizariev', 'category': 'Point Of Sale', 'website': 'https://yelizariev.github.io', 'depends': ['pos_disable_payment', 'bus'], 'data': [ 'security/ir.model.access.csv', 'views.xml', ], 'qweb': [ 'static/src/xml/pos_multi_session.xml', ], 'installable': ...
colour-science/colour
colour/io/tests/test_uprtek_sekonic.py
Python
bsd-3-clause
33,878
0
"""Defines unit tests for :mod:`colour.io.uprtek_sekonic` module.""" from __future__ import annotations import json import numpy as np import os import unittest from colour.colorimetry import SpectralDistribution from colour.hints import Any, Dict, Optional from colour.io import ( SpectralDistribution_UPRTek, ...
json.loads(sd.header.comments), value
) else: self.assertEqual( getattr(sd.header, specification.attribute), value ) class TestSpectralDistributionUprTek(AbstractSpectralDistributionTest): """ Define :class:`colour.SpectralDistribution_UPRTek` cl...
jtara1/tol-bot
tests_etc/PIL-test.py
Python
mit
340
0.017647
# -*- coding: utf-8 -*- """ Created on Wed Jul 22 14:49:04 2015 @author: James """ #import PIL from PIL import ImageOps, ImageFilter, ImageGrab, Image import os fp = os.getcwd() + '\\trees_ss 8.jpg\\' img = Image.open('
trees_ss 8.jpg', 'r') #labels = img.sp
lit #print labels pixel = img.getpixel((1,1)) r, g, b = img.split() print r
1065865483/0python_script
four/Webdriver/FindElement/By_xpath_p1.py
Python
mit
674
0.001684
from selenium import webdrive
r from time import sleep driver = webdriver.Firefox() driver.get("https://www.baidu.com/") #绝对路径定位 # driver.find_element_by_xpath("/html/body/div[1]/div[1]/div/div[1]/div/form/span[1]/input").send_keys("51zxw") # a.根据input标签中的id属性定位元素 driver.find_element_by_xpath("//input[@id='kw']").send_keys("51zxw") # b.根据input标...
']").send_keys("51zxw") driver.find_element_by_id("su").click() sleep(3) driver.quit()
thumbor-community/prometheus
tc_prometheus/metrics/prometheus_metrics.py
Python
mit
3,108
0.001287
#!/usr/bin/python # -*- coding: utf-8 -*- # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2017 Simon Effenberg <savar@schuldeigen.de> # Copyright (c) 2017 Thumbor Community Extensions from prometheus_client import Counter, start_http_server, Summary from thumbor.metr...
'original_image.status': ['statuscode'], 'original_image.fetch': ['statuscode', 'networklocation'], 'response.time': ['statuscode_extension'], } def incr(self, metricname, value=1): name, labels = self.__data(metricname) if name not in Metrics.counters: ...
if len(labels) != 0: counter = counter.labels(**labels) counter.inc(value) def timing(self, metricname, value): name, labels = self.__data(metricname) if name not in Metrics.summaries: Metrics.summaries[name] = Summary(name, name, labels.keys()) su...
ctgk/BayesianNetwork
test/image/test_util.py
Python
mit
1,753
0.00057
import unittest import numpy as np from bayesnet.image.util import img2patch, patch2img class TestImg2Patch(unittest.TestCase): def test_img2patch(self): img = np.arange(16).reshape(1, 4, 4, 1) patch = img2patch(img, size=3, step=1) expected = np.asarray([ [img[0, 0:3, 0:3, 0]...
(1, 4, 4, 1))).all()) if __name__
== '__main__': unittest.main()
CubicERP/geraldo
site/newsite/django_1_0/django/core/cache/__init__.py
Python
lgpl-3.0
2,288
0.003059
""" Caching framework. This package defines set of cache backends that all conform to a simple API. In a nutshell, a cache is a set of values -- which can be any object that may be pickled -- identified by string keys. For the complete API, see the abstract BaseCache class in django.core.cache.backends.base. Client ...
kend URI must start with scheme://" scheme, rest = backend_uri.split(':', 1) if not rest.startswith('//'): raise InvalidCacheBackendError, "Backend URI must start with scheme://" if scheme in DEPRECATED_BACKENDS: import warnings warnings.warn("'%s' backend is deprecated. Use '%s' ins...
rning) scheme = DEPRECATED_BACKENDS[scheme] host = rest[2:] qpos = rest.find('?') if qpos != -1: params = dict(parse_qsl(rest[qpos+1:])) host = rest[2:qpos] else: params = {} if host.endswith('/'): host = host[:-1] if scheme in BACKENDS: module =...
python-attrs/cattrs
src/cattr/preconf/tomlkit.py
Python
mit
1,561
0
"""Preconfigured converters for tomlkit.""" from base64 import b85decode, b85encode from datetime import datetime from typing import Any from .._compat import Set, is_mapping from ..converters import GenConverter from . import validate_datetime def configure_converter(converter: GenConverter): """ Configure ...
ver
ter.gen_unstructure_mapping( cl, unstructure_to=unstructure_to, key_handler=key_handler ) converter._unstructure_func.register_func_list( [(is_mapping, gen_unstructure_mapping, True)] ) converter.register_structure_hook(datetime, validate_datetime) def make_converter(*args, **...
tseaver/gcloud-python
speech/nox.py
Python
apache-2.0
3,927
0
# Copyright 2016 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
__future__ import absolute_import import os import nox LOCAL_DEPS = ( os.path.join('..', 'api_core'), ) @nox.session def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of
Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, then install this package in-place. session.install('mock', 'pytest', 'pytest-cov', *LOCAL_DEPS) session.install('-e', '.') # Run py.test against the unit tests. session.run( ...
IvanaXu/Test_Class_GOF
tPatterns/Behavioral_Patterns/test_Observer_Pattern.py
Python
gpl-3.0
1,644
0.001217
# -*-coding:utf-8-*- # @auth ivan # @time 2016-10-25 21:00:02 # @goal test for Observer Pattern class Subject(): def __init__(self): self.observers = [] self.state = 0 def getState(self): return self.state def setState(self, state): self.state = state def attach(self...
self): for observer in self.observers: observer.update() class Observer: def update(self):
return class BinaryObserver(Observer): def __init__(self, subject): self.subject = subject self.subject.attach(self) def update(self): print("Binary String: " + bin(self.subject.getState())) # BinaryObserver class OctalObserver(Observer): def __init__(self, subject): sel...
interlegis/sapl
sapl/sessao/urls.py
Python
gpl-3.0
11,025
0.001452
from django.conf.urls import include, url from sapl.sessao.views import (AdicionarVariasMateriasExpediente, AdicionarVariasMateriasOrdemDia, BancadaCrud, CargoBancadaCrud, ExpedienteMateriaCrud, ExpedienteView, JustificativaAu...
aria_ajax_view'), url(r'^sessao/(?P<pk>\d+)/(?P<spk>\d+)/abrir-votacao$', abrir_votacao, name="abrir_votacao"), url(
r'^sessao/(?P<pk>\d+)/reordena/(?P<tipo>[\w\-]+)/(?P<ordenacao>\d+)/$', reordena_materias, name="reordena_materias"), url(r'^sistema/sessao-plenaria/tipo/', include(TipoSessaoCrud.get_urls())), url(r'^sistema/sessao-plenaria/tipo-resultado-votacao/', include(TipoResultadoVotacaoCrud.get_urls())...
GoogleCloudPlatformTraining/cp100-appengine-memcache-python
guestbook.py
Python
apache-2.0
1,998
0.001001
#!/usr/bin/env python # # Copyright 2015 Google 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 applic...
cation = webapp2.WSGI
Application([ ('/', MainPage), ('/clear', Clear) ], debug=True)
ofreshy/vast
vast/errors.py
Python
gpl-3.0
298
0.006711
""" All err
or from this project can be found here """ class IllegalModelStateError(Exception): """ Raise when trying to create a Model which invalidates VAST specifications """ pass class ParseError(Exception): """ Raise when encountering a parsi
ng error """ pass
alexpearce/example-monitoring-app
monitoring_app/tasks.py
Python
mit
3,193
0
import os import ROOT def add_file_extension(filename): """Add `.root` extension to `filename`, if it's not already present.""" return (filename + '.root') if filename[-5:] != '.root' else filename def tfile_path(filename): """Return the path to the TFile with `filename`.""" here = os.path.dirname(_...
filename -- Name of file with full path, e.g. `/a/b/my_file.root` key_name -- Name of key object is stored as """ fil
ename = tfile_path(add_file_extension(filename)) f = ROOT.TFile(filename) if f.IsZombie(): return dict( success=False, message='Could not open file `{0}`'.format(filename) ) obj = None # This method, opposed to TFile.Get, is more robust against odd key names f...