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
ronekko/deep_metric_learning
main_n_pair_mc.py
Python
mit
2,501
0.001999
# -*- coding: utf-8 -*- """ Created on Mon Jan 09 20:49:04 2017 @author: sakurai """ import colorama import chainer.functions as F from sklearn.model_selection import ParameterSampler from lib.functions.n_pair_mc_loss import n_pair_mc_loss from lib.common.utils import LogUniformDistribution, load_params from lib.co...
c_data = batch x_data = model.xp.asarray(x_data) y = model(x_data) y_a, y_p = F.split_axis(y, 2, axis=0) return n_pair_mc_loss(y_a, y_p, params.loss_l2_reg) if __name__ == '__main__': param_filename = 'n_pair_mc_cars196.yaml' random_search_mode = True random_state = None num_runs = 1...
save_distance_matrix = False if random_search_mode: param_distributions = dict( learning_rate=LogUniformDistribution(low=6e-5, high=8e-5), # loss_l2_reg=LogUniformDistribution(low=1e-6, high=5e-3), # l2_weight_decay=LogUniformDistribution(low=1e-5, high=1e-2), # ...
andrucuna/python
interactivepython-coursera/interactivepython/week4/Motion.py
Python
gpl-2.0
796
0.005025
__author__ = 'andrucuna' # Ball motion with an explicit timer import simplegui # Initialize globals
WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 init_pos = [WIDTH / 2, HEIGHT / 2] vel = [0, 3] # pixels per tick time = 0 # define event handlers def tick(): global time time = time + 1 def draw(canvas): # create a list to hold ball position ball_pos = [0, 0] # calculate ball position ball_pos[0...
+ time * vel[0] ball_pos[1] = init_pos[1] + time * vel[1] # draw ball canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") # create frame frame = simplegui.create_frame("Motion", WIDTH, HEIGHT) # register event handlers frame.set_draw_handler(draw) timer = simplegui.create_timer(100, tick) # st...
zmallen/flock
twitter_app.py
Python
mit
1,763
0.024957
from flask import Flask,redirect from flask import render_template from flask import request from twython import Twython from redis import Redis import settings app = Flask(__name__) r = Redis() API_KEY = settings.API_KEY API_SECRET = settings.API_SECRET @app.route("/twitter", methods=["GET"
]) def display(): #Create Twitter API instance twitter = Twython(app_key=API_KEY, app_secret=API_SECRET) #Get auth url auth = twitter.get_authentication_tokens(callback_url='http://138.197.113.54:8080/twitterfinish') #Save off token and secret for later use. Could be saved in cookies. r.set("twitter:token", auth[...
) r.set("twitter:secret", auth['oauth_token_secret']) #redirect user to auth link return redirect(auth['auth_url']) @app.route("/twitterfinish", methods=["GET"]) def finish(): #Get verifier from GET request from Twitter verifier = request.args['oauth_verifier'] #Get token and secret that was saved earlier token...
caasiu/xbmc-addons-chinese
plugin.video.dnvodPlayer/js2py/constructors/jsuint16array.py
Python
gpl-2.0
3,043
0.011502
# this is based on jsarray.py from ..base import * try: import numpy except: pass @Js def Uint16Array(): TypedArray = (PyJsInt8Array,PyJsUint8Array,PyJsUint8ClampedArray,PyJsInt16Array,PyJsUint16Array,PyJsInt32Array,PyJsUint32Array,PyJsFloat32Array,PyJsFloat64Array) a = arguments[0] if isinstance(...
y, 'enumerable': False, 'writable': True, 'config
urable': True}) Uint16ArrayPrototype.define_own_property('BYTES_PER_ELEMENT', {'value': Js(2), 'enumerable': False, 'writable': False, 'configurable': False})
business-factory/gold-digger
gold_digger/data_providers/_provider.py
Python
apache-2.0
5,065
0.000987
from abc import ABCMeta, abstractmethod from datetime import date from decimal import Decimal, InvalidOperation from functools import wraps from http import HTTPStatus from inspect import getcallargs from cachetools import Cache from requests import RequestException, Session class Provider(metaclass=ABCMeta): DE...
f): """ :rtype: str """ return self.name @staticmethod def is_first_day_of_month(): """ :rtype: bool """ return date.today().day == 1 @staticmethod def check_request_limit(return_value=None): """ Check request limit and pr...
ent API call if the limit was exceeded. :type return_value: dict | set | None :rtype: function """ def decorator(func): """ :type func: function :rtype: function """ @wraps(func) def wrapper(*args, **kwargs): ...
pychess/pychess
lib/pychess/Database/JvR.py
Python
gpl-3.0
6,560
0.005488
# Chess Analyses by Jan van Reek # http://www.endgame.nl/index.html JvR_links = ( ("http://www.endgame.nl/match.htm", "http://www.endgame.nl/MATCHPGN.ZIP"), ("http://www.endgame.nl/bad1870.htm", "http://www.endgame.nl/bad1870.pgn"), ("http://www.endgame.nl/wfairs.htm", "http://www.endgame.nl/wfairs.pgn"), ...
ame.nl/wbm.htm", "http://www.endgame.nl/wbm.pgn"), ("http://www.endgame.nl/AVRO1938.htm", "http:/
/www.endgame.nl/avro1938.pgn"), ("http://www.endgame.nl/salz1942.htm", "http://www.endgame.nl/salz1942.pgn"), ("http://www.endgame.nl/itct.html", "http://www.endgame.nl/itct.pgn"), ("http://www.endgame.nl/zurich1953.htm", "http://www.endgame.nl/zurich.pgn"), ("http://www.endgame.nl/spassky.htm", "http:/...
joksnet/youtube-dl
youtube_dl/extractor/gamespot.py
Python
unlicense
2,196
0.006831
import re import xml.etree.ElementTree from .common import InfoExtractor from ..utils import ( unified_strdate, compat_urllib_parse, ) class GameSpotIE(InfoExtractor): _VALID_URL = r'(?:http://)?(?:www\.)?gamespot\.com/.*-(?P<page_id>\d+)/?' _TEST = { u"url": u"http://www.gamespot.com/arma-iii...
text view_count = int(clip_el.find('./views').text) upload_date = unified_strdate(clip_el.find('./postDate').text) return [{ 'id' : video_id, 'url' : video
_url, 'ext' : ext, 'title' : title, 'thumbnail' : thumbnail_url, 'upload_date' : upload_date, 'view_count' : view_count, }]
Masood-M/yalih
malwebsites.py
Python
apache-2.0
2,519
0.037316
#! /usr/bin/env python import subprocess import sys, threading, Qu
eue import os import string from time import gmtime, strftime import urllib2 import urllib import re, time import urlparse import os.path import logging #from google import search import scan import executemechanize import extraction import mechanize from BeautifulSoup import BeautifulSoup def domaindownload():# this...
ebsite database from https://spyeyetracker.abuse.ch exists!\n" print "Continuing with the next list." else: print "Fetching list from: https://spyeyetracker.abuse.ch" command1="wget https://zeustracker.abuse.ch/blocklist.php?download=domainblocklist -O list/list1.txt" os.system(command1) #--proxy-user=username...
hastexo/edx-platform
common/djangoapps/third_party_auth/tests/specs/test_lti.py
Python
agpl-3.0
7,528
0.002125
""" Integration tests for third_party_auth LTI auth providers """ import unittest import django from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from oauthlib.oauth1.rfc5849 import Client, SIGNATURE_TYPE_BODY from openedx.tests.util import expecte...
I_TPA_COMPLETE_URL = '/auth/complete/lti/' OTHER_LTI_CONSUMER_KEY = 'settings-consumer' OTHER_LTI_CONSUMER_SECRET = 'secret2' LTI_USER_ID = 'lti_user_id' EDX_USER_ID = 'test_user' EMAIL = '[email protected]' @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class IntegrationTestLT...
s for third_party_auth LTI auth providers """ def setUp(self): super(IntegrationTestLTI, self).setUp() self.hostname = 'testserver' self.client.defaults['SERVER_NAME'] = self.hostname self.url_prefix = 'http://{}'.format(self.hostname) self.configure_lti_provider( ...
ildoc/homeboard
faqs/admin.py
Python
mit
900
0
from django.contrib import admin from django.db import models from pagedown.widgets import AdminPagedownWidget from .models import Faq, Category class FaqAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': AdminPagedownWidget}, } fieldsets = [ ('Faq', {'fields'...
e', 'slug') search_fields = ['ti
tle'] admin.site.register(Faq, FaqAdmin) admin.site.register(Category, CategoryAdmin)
spreaker/android-publish-cli
setup.py
Python
mit
975
0.042051
from __future__ import print_function from setuptools import setup import sys if sys.version_info < (2, 6): print('google-api-python-client requires python version >= 2.6.', file = sys.stderr) sys.exit(1) install_requires = ['google-api-python-client==1.3.1'] if sys.version_info < (2, 7): install_requi...
gle Play Publish API', author = 'Spreaker', author_email = '[email protected]', url = 'https://github.com/spreaker/android-publish-cli', download_url = 'https://github.com/spreaker/android-publish-cli/tarball/0.1.2', keywords = ['android', 'automa...
['bin/android-publish'] )
Cisco-Talos/pyrebox
volatility/volatility/plugins/linux/check_fops.py
Python
gpl-2.0
10,529
0.009023
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 as # published by the Free Software Foundation. You may not use, modify or # distribu...
seen_pids[pidns.v()] = 1 proc_mnts.append(pidns.proc_mnt) for proc_mnt in proc_mnts: root = proc_mnt.mnt_root for (hooked_member, hook_address) in self.verify_ops(root.d_inode.i_fop, f_op_members, module
s): yield ("proc_mnt: root: %x" % root.v(), hooked_member, hook_address) # only check the root directory if self.addr_space.profile.obj_has_member("dentry", "d_child"): walk_member = "d_child" else: walk_member = "d_u" for...
sgiavasis/nipype
nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py
Python
bsd-3-clause
1,067
0.01687
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..postproc import TrackMerge def test_TrackMerge_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=...
0, ), ) inputs = TrackMerge.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_TrackMerge_outputs(): output_map = dict(track_file=dict(), ) ...
): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
datafiniti/Diamond
src/diamond/collector.py
Python
mit
13,380
0.000299
# coding=utf-8 """ The Collector class is a base class for all metric collectors. """ import os import socket import platform import logging import configobj import traceback import time from diamond.metric import Metric # Detect the architecture of the system and set the counters for MAX_VALUES # appropriately. Ot...
, # Path Prefix 'path_prefix': 'servers', # Path Prefix for Virtual Machine metrics 'instance_prefix': 'instances', # Path Suffix 'path_suffix': '', # Default splay time (seconds) 'splay': 1,
# Default Poll Interval (seconds) 'interval': 300, # Default collector threading model 'method': 'Sequential', # Default numeric output 'byte_unit': 'byte', # Collect the collector run time in ms 'measure_collector_time': False,...
jhermann/rituals
src/rituals/util/__init__.py
Python
gpl-2.0
1,671
0
# -*- coding: utf-8 -*- """ rituals.util – Helper modules. """ # Copyright ⓒ 2015 Jürgen Hermann # # Thi
s program is free software; you can redistribute it and/or modify # it under the terms of the GNU General
Public License version 2 as # published by the Free Software Foundation. # # 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. # ...
jacenkow/beard-server
beard_server/celery.py
Python
gpl-2.0
1,257
0
# -*- coding: utf-8 -*- # # This file is part of Inspire. # Copyright (C) 2016 CERN. # # Inspire is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
it itself to any jurisdiction. """Celery service instance.""" from __future__ import absolute_import, division, print_function, \ unicode_literals from beard_server import config from celery import Celery app = Celery('beard_server') app.config_from_object(
config) if __name__ == '__main__': app.start()
gomjellie/SoongSiri
legacy_codes/app/managers.py
Python
mit
10,044
0.000426
from .message import * from functools import wraps import datetime import pymongo import re from app import session class Singleton(type): instance = None def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return...
{ '식단 리뷰': ReviewInitMessage, }, { '리뷰 보기': Revie
wBrowseMessage, '리뷰 남기기': ReviewPostMessage, '리뷰 삭제하기': OnGoingMessage, }, { # 리뷰 남기기 하면 3단계까지 옴 키보드로 입력받은 문자열이 오기때문에 가능성이 다양함 '*': OnGoingMessage, } ], } def handle_process(self, process, user_key, cont...
MaximeGLegault/StrategyIA
RULEngine/Communication/receiver/vision_receiver.py
Python
mit
843
0.00358
# Under MIT License, see LICENSE.txt """ Implémente la logique et les services nécessaires pour communiquer avec le serveur de vision. """ from RULEngine.Communication.protobuf import messages_robocup_ssl_wrapper_pb2 a
s ssl_wrapper from RULEngine.Communication.util.protobuf_packet_receiver import ProtobufPacketReceiver from config.config_service import ConfigService class VisionReceiver(ProtobufPacketReceiver): """ Initie le serveur de vision, semble superflue. """ # FIXME: est-c
e réellement utile? la classe ne semble aucunement générique def __init__(self): cfg = ConfigService() host = cfg.config_dict["COMMUNICATION"]["udp_address"] port = int(cfg.config_dict["COMMUNICATION"]["vision_port"]) super(VisionReceiver, self).__init__(host, port, ssl_wrapper.SSL_...
kstilwell/tcex
tcex/stix/observables/domain_name.py
Python
apache-2.0
1,634
0.00306
"""Parser for STIX Domain Name Object. see: https://docs.oa
sis-open.org/cti/stix/v2.1/csprd01/stix-v2.1-csprd01.html#_Toc16070687 """ # standard library from typing import Iterable, Union # third-party from stix2 import DomainName # first-party from tcex.stix.model import StixModel class StixDomainNameObject(StixModel): """Parser for STIX Domain Name Object. see: ...
rd01.html#_Toc16070687 """ # pylint: disable=arguments-differ def produce(self, tc_data: Union[list, dict], **kwargs) -> Iterable[DomainName]: """Produce STIX 2.0 JSON object from TC API response.""" if isinstance(tc_data, list) and len(tc_data) > 0 and 'summary' in tc_data[0]: ...
jocave/snapcraft
snapcraft/plugins/nodejs.py
Python
gpl-3.0
4,091
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2015-2016 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in ...
self.options.node_engine), self._npm_dir) def pull(self): super().pull() os.makedirs(self._npm_dir, exist_ok=True) self._nodejs_tar.download() def clean_pull(self): super().clean_pull() # Remove the npm directory (if any) if os.path.exists(self._npm_dir): ...
per().build() self._nodejs_tar.provision( self.installdir, clean_target=False, keep_tarball=True) for pkg in self.options.node_packages: self.run(['npm', 'install', '-g', pkg]) if os.path.exists(os.path.join(self.builddir, 'package.json')): self.run(['npm', 'i...
ioannistsanaktsidis/inspire-next
inspire/base/format_elements/bfe_inspire_conferences_date.py
Python
gpl-2.0
2,924
0.00513
# -*- coding: utf-8 -*- ## ## This file is part of INSPIRE. ## Copyright (C) 2015 CERN. ## ## INSPIRE is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
details. ## ## You should have received a copy of the GNU General Public License ## along with INSPIRE; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # """BibFormat element - Prints INSPIRE jobs contact name HEPNAMES search """ from datetime import dat...
earch in the HepNames database. @param style: CSS class of the link @param separator: the separator between names. """ out = [] fulladdress = bfo.fields("111__") sday = '' smonth = '' syear = '' fday = '' fmonth = '' fyear = '' printaddress = '' for printaddress in ...
vinaypost/multiuploader
multiuploader/context_processors.py
Python
mit
93
0
# -*- coding:utf-8 -*- def booleans
(request):
return {'True': True, 'False': False}
georgesk/webvtt-editor
video/models.py
Python
gpl-3.0
2,689
0.009745
from django.db import models from django.core.exceptions import ValidationError # Create your models here. class Etudiant(models.Model): """ Représente un étudiant qui peut "sous-titrer". Les champs "uidNumber" et "uid" identifient l'étudiant dans l'annuaire LDAP de l'établissement. """ uidNu...
ef __str__(self): return "{} -> {}".format(self.enseignant.nom, self.classe) class Atelier(models.Model): """ associe une vidéo et peut-être des sous-t
itres à une classe et un prof """ ec = models.ForeignKey(EnseignantClasse) video = models.FileField(upload_to='video') tt = models.TextField(default="WEBTT\n\n") def __str__(self): return "{} {} {}".format(self.ec, self.video, self.tt[:20]+"...") class Travail(models.Model): """ ...
ezequielpereira/Time-Line
timelinelib/wxgui/dialogs/setcategory/controller.py
Python
gpl-3.0
2,583
0.000774
# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline 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 th...
hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warran
ty 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 Timeline. If not, see <http://www.gnu.org/licenses/>. from timelinelib.wxgui.framework import Controller class SetC...
gdsglgf/tutorials
python/pillow/image_converter.py
Python
mit
896
0.03288
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from PIL import Image def gray2rgb(data): return np.array(Image.fromarray(data, 'L').convert('RGB')) # ITU-R 601-2 luma transform: # L
= R * 299/1000 + G * 587/1000 + B * 114/1000 def rgb2gray(data): return np.array(Image.fromarray(data, 'RGB').convert('L')) def toGray(rgb): row, column, pipe = rg
b.shape for i in range(row): for j in range(column): pix = rgb[i, j] r = pix[0] g = pix[1] b = pix[2] gray = (r * 299 + g * 587 + b * 114) / 1000 print '%4d' %(gray), print def main(): rgb = np.array(np.arange(8 * 8 * 3).reshape((8, 8, 3)), dtype='uint8') print rgb print rgb2gray(rgb) toGr...
mtagle/airflow
tests/utils/test_weight_rule.py
Python
apache-2.0
1,201
0
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
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 distribu
ted on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import unittest from airflow.utils.weight_rule import WeightRule class TestWeightRule(unittest.TestCase): ...
finder/mako_base
auth/urls.py
Python
mit
232
0.008621
from django.conf.u
rls.defaults import * import views urlpatterns = patterns('', (r'^login/$', views.login), (r'^logout/$', views.lo
gout), (r'^register/$', views.register), (r'^forgot_pass/$', views.forgot_pass), )
xuchao1213/AliyunDdnsPython
config.py
Python
gpl-3.0
1,746
0.002291
#!/usr/bin/python # -*- coding: utf-8 -*- import sys if sys.version_info < (3,): import ConfigParser else: import configparser as ConfigParser class Config: def __init__(self): self.interval = 30 self.access_key_id = None self.access_key_secret = None self.domain_name = N...
type = "A" if not self.region_id: self.region_id = "cn-hangzhou" except Exception, e: print "invalid config: {0}".format(e.message) return False if not self.access_key_id or not self.access_key_secret or not self.domain_name or not self.sub_domain_nam...
turn True
delectable/DIGITS
digits/config/test_prompt.py
Python
bsd-3-clause
3,424
0.004089
# Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved. import sys from contextlib import contextmanager from StringIO import StringIO import mock from nose.tools import raises from . import prompt as _ class TestValueToStr(): def test_none(self): # pass none to value_to_str assert ...
if not self.flag: self.flag = True return '' else: return 'a' with mockInput(Temp()): asser
t _.get_input('Test', lambda x: x, self.suggestions) == 'alpha', 'get_input should return "alpha" for input "a"' def test_get_input_empty_default(self): # empty input should choose the default self.suggestions[0].default = True with mockInput(lambda _: ''): assert _.get_input('...
pythonkr/pyconapac-2016
registration/admin.py
Python
mit
3,854
0.001728
# -*- coding: utf-8 -*- from django.contrib import admin from django.core.mail import send_mass_mail from django.shortcuts import render from constance import config from datetime import datetime from iamporter import get_access_token, Iamporter, IamporterError from .models import Registration, Option def send_bankp...
Option, OptionAdmin) class RegistrationAdmin(admin.ModelAdmin): list_display = ('user', 'option', 'name', 'email', 'payment_method', 'payment_status', 'created', 'confirmed', 'canceled') list_editable = ('payment_status',) list_filter = ('option', 'payment_method',
'payment_status') csv_fields = ['name', 'email', 'company', 'option', ] search_fields = ('name', 'email') readonly_fields = ('created', ) ordering = ('id',) actions = (send_bankpayment_alert_email, cancel_registration) admin.site.register(Registration, RegistrationAdmin)
adwiputra/LUMENS-repo
processing/molusce/algorithms/models/crosstabs/manager.py
Python
gpl-2.0
3,527
0.005671
#!/usr/bin/env python # -*- coding: utf-8 -*- from PyQt4.QtCore import * import numpy as np from processing.molusce.algorithms.models.crosstabs.model import CrossTable class CrossTabManagerError(Exception): '''Base class for exceptions in this module.''' def __init__(self, msg): self.msg = msg cla...
elf.crosstable.errorReport.connect(self.__crosstableError) def __crosstableFinished(sel
f): self.crosstable.rangeChanged.disconnect(self.__crosstableProgressRangeChanged) self.crosstable.updateProgress.disconnect(self.__crosstableProgressChanged) self.crosstable.crossTableFinished.disconnect(self.__crosstableFinished) self.crossTableFinished.emit() def __crosstableProgr...
nontas/menpowidgets
docs/sphinxext/ref_prettify.py
Python
bsd-3-clause
763
0
from sphinx.domains.python import PyXRefRole def setup(app): """ Any time a python class is referenced, make it a prett
y link that doesn't include the full package path. This makes the base cla
sses much prettier. """ app.add_role_to_domain('py', 'class', truncate_class_role) return {'parallel_read_safe': True} def truncate_class_role(name, rawtext, text, lineno, inliner, options={}, content=[]): if '<' not in rawtext: text = '{} <{}>'.format(text.split('.')[-...
vijayendrabvs/hap
neutron/tests/unit/test_iptables_manager.py
Python
apache-2.0
28,031
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Locaweb. # 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/license...
.root_helper)) self.exe
cute = mock.patch.object(self.iptables, "execute").start() def test_binary_name(self): self.assertEqual(iptables_manager.binary_name, os.path.basename(inspect.stack()[-1][1])[:16]) def test_get_chain_name(self): name = '0123456789' * 5 # 28 chars is the maximum...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractBibliophilesociety888305596WordpressCom.py
Python
bsd-3-clause
594
0.031987
def extractBibliophilesociety888305596WordpressCom(item): ''' Parser for 'bibliophilesociety888305596.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (
chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp...
, postfix=postfix, tl_type=tl_type) return False
saltstack/salt
tests/pytests/unit/modules/test_salt_version.py
Python
apache-2.0
8,304
0.002288
""" Unit tests for salt/modules/salt_version.py """ import salt.modules.salt_version as salt_version import salt.version from tests.support.mock import MagicMock, patch def test_mocked_objects(): """ Test that the mocked objects actually have what we expect. For example, earlier tests incorrectly mocked...
"" with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")): with patch( "salt.version.SaltStackVersion.LNAMES", {"oxygen": (2018, 3), "nitrogen": (2017, 7)}, )
: assert salt_version.equal("Nitrogen") is False def test_equal_older_codename_new_version(): """ Test that when an older codename is passed in, the function returns False. while also testing with the new versioning. """ with patch("salt.version.SaltStackVersion", MagicMock(return_valu...
Goyatuzo/Challenges
CodeEval/Easy/Fizz Buzz/fizz_buzz.py
Python
mit
460
0.002174
def fizz_buzz(fizz, buzz, highest): result = [] for i in range(1, highest + 1): letter = '' # If divisible by fizz or buzz, add F or B appropriately. if i % fizz == 0: letter += 'F' if i % buzz == 0: letter += 'B' # If neither F or B has been la...
ter == '': letter = str(i
) result.append(letter) return " ".join(result)
jonparrott/google-cloud-python
asset/google/cloud/asset_v1beta1/gapic/asset_service_client_config.py
Python
apache-2.0
1,173
0
config = { "interfaces": { "google.cloud.asset.v1beta1.AssetService": { "retry_codes": { "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], "non_idempotent": []
}, "retry_params": { "default": { "initial_retry_delay_millis": 100, "retry_delay_mult
iplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 20000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 20000, "total_timeout_millis": 600000 } }, ...
schroeder-dewitt/polyomino-self-assembly
test/SearchSpaceAdv/alpha-working/main.py
Python
apache-2.0
7,493
0.029227
import pycuda.autoinit import pycuda.driver as drv import numpy from pycuda.compiler import SourceModule from jinja2 import Environment, PackageLoader def main(): #FourPermutations set-up FourPermutations = numpy.array([ [1,2,3,4], [1,2,4,3], ...
"fit_dim_thread_x":3
2*BankSize, "fit_dim_thread_y":1, "fit_dim_block_x":BlockDimX, "fit_dim_grid_x":19, "fit_dim_grid_y":19, "fit_nr_four_permutations":24, "fit_length_movelist":244, "fit_nr_redundancy_grid_depth":2, ...
ratschlab/rQuant
tools/ParseGFF.py
Python
gpl-3.0
19,046
0.012969
#!/usr/bin/env python # # 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. # # Written (W) 2010 Vipin T Sreedharan # Copyri...
return gene_details def FeatureValueFormat(singlegene): """Make feature value compactable to write in a .mat format""" ## based on the feature set including for rQuant process each genes selected feature values. import numpy as np comp_exon = np.zeros((len(singlegene['exons']),), dty
pe=np.object) for i in range(len(singlegene['exons'])): comp_exon[i]= np.array(singlegene['exons'][i]) singlegene['exons'] = comp_exon comp_transcripts = np.zeros((len(singlegene['transcripts']),), dtype=np.object) for i in range(len(singlegene['transcripts'])): comp_transcripts[i] = np....
parroyo/Zappa
zappa/cli.py
Python
mit
87,982
0.004065
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Zappa CLI Deploy arbitrary Python programs as serverless Zappa applications. """ from __future__ import unicode_literals from __future__ import division import argcomplete import argparse import base64 import pkgutil import botocore import click import collections...
e = None use_apigateway = None lambda_handler = None django_settings = None manage_roles = True exception_handler = None environment_variables = None authorizer = None stage_name_env_pattern = re.compile('^[a-zA-Z0-9_]+$') def __init__(self): self._stage_config_overrides = ...
property for settings of a stage. """ def get_stage_setting(stage, extended_stages=None): if extended_stages is None: extended_stages = [] if stage in extended_stages: raise RuntimeError(stage + " has already been extended to these settings. " ...
GitOnUp/environs
vimenv.py
Python
mit
2,178
0.003673
""" vimenv.py Vim-specific environment helpers. This module uses git and pathogen to manage vim plugins. """ from collections import namedtuple from os import path, makedirs, walk, chdir, getcwd from urllib import urlretrieve from subprocess import check_call VimPlugin = namedtuple('VimPlugin', ['find_file', 'frien...
/pathogen.vim', path.join(_autoload, 'pathogen.vim')) d
ef install_plugins(): ensure_pathogen() def find_vim_file(dv): for root, dirs, files in walk(_dotvim): for file in files: if file == vp.find_file: return True return False origwd = getcwd() chdir(_bundle) ex = None for vp in plug...
virtacoin/VirtaCoinProject
contrib/pyminer/pyminer.py
Python
mit
6,441
0.034777
#!/usr/bin/python # # Copyright (c) 2011 The VirtaCoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib impo...
.py CONFIG-FILE" sys.exit(1) f =
open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' ...
evgeniy-shorgin/python_training
fixture/db.py
Python
apache-2.0
2,681
0.006341
import pymysql.cursors from model.group import Group from model.contact import Contact class DbFixture: def __init__(self, host, name, user, password): self.host = host self.name = name self.user = user self.password = password self.connection = pymysql.connect(host=host, ...
= row list.append(Contact(ident=str(ident), firstname=firstname, middlename=middlename, lastname=lastname, nickname=nickname, title=title, company=company, company_address=company_address, homephone=homephone, mobilephone=mobilepho...
il2, email3=email3, homepage=homepage, birthday_year=birthday_year, anniversary=anniversary, secondary_address=secondary_address, secondaryphone=secondaryphone, secondary_notes=secondary_notes, ...
opesci/devito
devito/ir/support/vector.py
Python
mit
14,039
0.001353
from collections import OrderedDict from sympy import true from devito.tools import as_tuple, is_integer, memoized_meth from devito.types import Dimension __all__ = ['Vector', 'LabeledVector', 'vmin', 'vmax'] class Vector(tuple): """ An object in an N-dimensional space. The elements of a vector can b...
# definitely `i > 0` is generally False, so __gt__ must # return False return False elif (i <= 0) == true: return False raise TypeError("Non-comparable index functions") return False def __le__...
== v1 --> False # But # * v0 <= v1 --> True # # For example, take `v0 = (a + 2)` and `v1 = (2)`; if `a` is attached # the property that definitely `a >= 0`, then surely `v1 <= v0`, even # though it can't be assumed anything about `v1 < 0` and `v1 == v0` for i in ...
gregbdunn/aws-ec2rescue-linux
lib/boto3/dynamodb/types.py
Python
apache-2.0
9,677
0
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
string {
'S': string} Binary/bytearray/bytes (py3 only) {'B': bytes} set([int/Decimal]) {'NS': [str(value)]} set([string]) {'SS': [string]) set([Binary/bytearray/bytes]) {'BS': [bytes]} list ...
DavidParkin/pomodoro-indicator
app/twcurrent.py
Python
gpl-3.0
986
0.001014
from taskw import TaskWarriorShellout class TwCurrent(object): def __init__(self, file=None): self.tw = TaskWarriorShellout() self.tw.config_filename = file def get_current(self): tw = TaskWarriorShellout() tw.config_filename = self.tw.config_filename tasks = tw.filte...
({'status': 'pending'}) return tasks if __name__
== '__main__': tw = TwCurrent() tw.get_current()
EmadMokhtar/halaqat
halaqat/settings/shaha.py
Python
mit
1,432
0.000698
import os import dj_database_url from .base_settings import * ALLOWED_HOSTS = ['shaha-halaqat.herokuapp.com', '0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATI...
static') STATIC_URL = '/static/' STATICFILES_DIRS = () # STATICFILES_STORAGE = 'whi
tenoise.django.GzipManifestStaticFilesStorage' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': False, 'OPTIONS': { 'loaders': [ ( 'django.template.loaders.cached.Loader'...
quake0day/oj
Sparse Matrix Multiplication.py
Python
mit
535
0.005607
class Solution(object): def
multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ p = len(B[0]) C = [[0 for _ in xrange(p)] for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(len(B)): if A[i]...
kawasaki2013/getting-started-python
7-gce/config.py
Python
apache-2.0
4,302
0
# 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 applicable law or agreed to in writing, ...
your-connection-name=tcp:3306 # # Alternatively, you could use a local MySQL instance for testing. LOCAL_SQLALCHEMY_DATABASE_URI = ( 'mysql+pymysql://{user}:{password}@localhost/{database}').format( user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD, database=CLOUDSQL_DATABASE) # When running on App En...
URI = ( 'mysql+pymysql://{user}:{password}@localhost/{database}' '?unix_socket=/cloudsql/{connection_name}').format( user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD, database=CLOUDSQL_DATABASE, connection_name=CLOUDSQL_CONNECTION_NAME) if os.environ.get('GAE_APPENGINE_HOSTNAME'): SQLALCHEMY_...
mihaimaruseac/dphcar
tools/stats_scripts/parse_icde.py
Python
bsd-3-clause
6,386
0.008613
import os import sys import matplotlib.pyplot as plt class Experiment: def __init__(self, db, eps, eps_share, c0, rmax, nits, bf, seed): self.db = db self.eps = eps self.eps_share = eps_share self.c0 = c0 self.rmax = rmax self.nits = nits self.bf = bf ...
.3f}".format(self, s) s = "{1}\t{0.rules}\t{0.rules50}\t{0.prec:5.2f}".format(self, s) s = "{1}\t{0.realrules}\t{0.recall}".format(self, s) return s @staticm
ethod def legend(): s = "db\t\teps\tepsh\tc0\trmax\tnits\tbf\tseed\tleaves\ttime" s += "\ttpl\trules\trules50\tprec50\trealrls\trecall" return s experiments = [] for r, _, files in os.walk(sys.argv[1]): for fname in files: with open(os.path.join(r, fname), "r") as f: ...
IncidentNormal/TestApps
pyTest/meshgrid.py
Python
gpl-2.0
546
0.016484
import numpy as np def get_test_data(delta=0.05): ''' Return a tuple X, Y, Z with a test data set. ''' from matplotlib.mlab import bivariate_normal x = y = np.arange(-3.0, 3.0, delta) prin
t x X, Y = np.meshgrid(x, y) Z = np.sin(X) print Z ## Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) ## ## Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) ## ## Z = Z2 - Z1 ## #print 'Z' ## #print Z[0] ## #print Z[0][
0] X = X * 10 Y = Y * 10 Z = Z * 500 return X, Y, Z get_test_data()
Acidburn0zzz/readthedocs.org
readthedocs/rtd_tests/tests/test_doc_building.py
Python
mit
818
0.001222
import shutil from django.contrib.admin.models import User from projects.models import Project from rtd_tests.ut
ils import make_test_git from rtd_tests.base import RTDTestCase class TestBuilding(RTDTestCase): """These tests run the build functions directly. They don't use celery""" fixture
s = ['eric.json'] def setUp(self): repo = make_test_git() self.repo = repo super(TestBuilding, self).setUp() self.eric = User.objects.get(username='eric') self.project = Project.objects.create( name="Test Project", repo_type="git", #Our to...
anuragbanerjee/HandyTools
csv-to-json.py
Python
mit
1,300
0.016923
#!/usr/bin/env python ''' CSV to JSON Converter Created by Anurag Banerjee. Copyright 2016. All rights reserved. USAGE `python csv-to-json.py <CSV FILE>` Use I/O Redirection for creating resulting files. `python csv-to-json.py sample.csv > sample.json` ''' from codecs import open import json import sys def showIn...
try: entry = result_json[entryId] except IndexError: result_json.append({}) entry = result_json[-1] for id, val in enumerate(l.split(",")): result_json[entryId][fields[id]] = val.rstrip() else: entryId+=1 print json.dumps( result_json, encoding="ut...
s=(',', ': '), ensure_ascii=False ).encode("utf-8") if __name__ == '__main__': main()
mikf/gallery-dl
gallery_dl/extractor/kohlchan.py
Python
gpl-2.0
2,737
0
# -*- coding: utf-8 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. """Extractors for https://kohlchan.net/""" from .common import Extractor, Message from .. import text import ...
Extractor for Kohlchan threads""" category = "kohlch
an" subcategory = "thread" directory_fmt = ("{category}", "{boardUri}", "{threadId} {subject|message[:50]}") filename_fmt = "{postId}{num:?-//} {filename}.{extension}" archive_fmt = "{boardUri}_{postId}_{num}" pattern = r"(?:https?://)?kohlchan\.net/([^/?#]+)/res/(\d+)" test...
evernym/zeno
plenum/test/txn_author_agreement/acceptance/helper.py
Python
apache-2.0
2,183
0.000458
import json from indy.ledger import ( append_txn_author_agreement_acceptance_to_request, sign_request )
from plenum.common.util import randomString from plenum.test.pool_transactions.helper import ( prepare_nym_request, prepare_new_node_data, prepare_node_request )
# TODO makes sense to make more generic and move to upper level helper def build_nym_request(looper, sdk_wallet): return looper.loop.run_until_complete( prepare_nym_request( sdk_wallet, named_seed=randomString(32), alias=randomString(5), role=None ) ...
t11e/django
django/db/models/sql/subqueries.py
Python
bsd-3-clause
7,675
0.002606
""" Query subclasses which provide extra functionality beyond simple data retrieval. """ from django.core.exceptions import FieldError from django.db import connections from django.db.models.sql.constants import * from django.db.models.sql.datastructures import Date from django.db.models.sql.expressions import SQLEval...
one(klass, related_updates=self.related_updates.copy(), **kwargs) def clear_related(self, related_field, pk_list, using): """ Set up
and execute an update query that clears related entries for the keys in pk_list. This is used by the QuerySet.delete_objects() method. """ for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): self.where = self.where_class() f = self.model._meta.pk ...
mahak/cinder
cinder/tests/unit/backup/drivers/test_backup_nfs.py
Python
apache-2.0
40,941
0
# Copyright (C) 2015 Tom Barron <[email protected]> # 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 # # ...
KE_EGID, 0), (FAKE_EGID, stat.S_IWGRP), (6666, 0), (6666, stat.S_IWGRP)) @ddt.unpack def test_init_backup_repo_path(self, file_gid, file_mode, mock_get_file_mode, ...
mock_getegid): self.override_config('backup_share', FAKE_BACKUP_SHARE) self.override_config('backup_mount_point_base', FAKE_BACKUP_MOUNT_POINT_BASE) mock_remotefsclient = mock.Mock() mock_remotefsclient.get_mount_point = mock.Mock( return_v...
jolyonb/edx-platform
lms/djangoapps/verify_student/tests/test_signals.py
Python
agpl-3.0
4,171
0.003836
""" Unit tests for the VerificationDeadline signals """ from datetime import timedelta from django.utils.timezone import now from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification, VerificationDeadline from lms.djangoapps.verify_student.signals import _listen_for_course_publish, _listen_for...
tries(self): user = UserFactory() _listen_for_lms_retire(sender=self.__class__, user=user) def test_idempotent(self): verification = self._create_entry() #
Run this twice to make sure there are no errors raised 2nd time through _listen_for_lms_retire(sender=self.__class__, user=verification.user) fake_completed_retirement(verification.user) _listen_for_lms_retire(sender=self.__class__, user=verification.user) ver_obj = SoftwareSecurePhoto...
mverzett/rootpy
rootpy/plotting/contrib/plot_corrcoef_matrix.py
Python
gpl-3.0
12,192
0.000082
# Copyright 2012 the rootpy developers # distributed under the terms of the GNU General Public License from __future__ import absolute_import from ...extern.six.moves import range from ...extern.six import string_types __all__ = [ 'plot_corrcoef_matrix', 'corrcoef', 'cov', ] def plot_corrcoef_matrix(mat...
the upper triangular matrix matrix[np.triu_indices(matrix.shape[0])] = np.nan if isinstance(cmap_text, string_types): cmap_text = cm.get_cmap(cmap_text, 201) if cmap is None: cmap = cm.get_cmap('jet', 201) elif isinstance(cmap, string_types): cmap = cm.get_cmap(cmap, 201) # ...
er', vmin=-1, vmax=1) axes.set_frame_on(False) plt.setp(axes.get_yticklabels(), visible=False) plt.setp(axes.get_yticklines(), visible=False) plt.setp(axes.get_xticklabels(), visible=False) plt.setp(axes.get_xticklines(), visible=False) if grid: # draw grid lines ...
404d/Temporals-Web
temporals_web/gmod/views.py
Python
mit
7,019
0.001425
# -*- encoding: utf-8 -*- import hashlib import json import os import re import magic from perpetualfailure.db import session from pyramid.authentication import ( Authenticated, Everyone, ) from pyramid.httpexceptions import ( HTTPException, HTTPBadRequest, HTTPFound, HTTPNotFound, HTTPForb...
acp_background_edit(request): background = session.query(m.LS_Background).filter(m.LS_Background.id==request.matchdict["id"]).first() if not request.permits("edit", background): return HTTPForbidden() r = background_update(request, ba
ckground) if isinstance(r, HTTPException): return r return {"background": background, "upload": False} @view_config( route_name='servers.gmod.acp.gamemode.add', renderer="gmod/acp/gamemode.mako", permission=Authenticated, ) def acp_gamemode_add(request): mode = m.LS_Gamemode() if n...
synicalsyntax/zulip
zerver/tests/test_message_edit_notifications.py
Python
apache-2.0
21,406
0.001261
from typing import Any, Dict, Mapping, Union from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import get_client from zerver.lib.push_notifications import get_apns_badge_count from zerver.lib.test_classes import ZulipTestCase from zerver.models import Subscription...
ata = self._send_and_update_message(original_content, updated_content) message_id = notification_message_data['message_id'] info = notification_message_data['info'] cordelia = self.example_user('cordelia') expected_enqueue_kwargs = dict( user_profile_id=cordelia.id, ...
ention_notify=False, stream_push_notify=False, stream_email_notify=False, stream_name='Scotland', always_push_notify=False, idle=True, already_notified={}, ) self.assertEqual(info['enqueue_kwargs'], expected_enqueue_kwargs) ...
mfraezz/osf.io
tests/test_views.py
Python
apache-2.0
220,173
0.001894
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Views tests for the OSF.""" from __future__ import absolute_import import datetime as dt from rest_framework import status as http_status import json import time import unittest from future.moves.urllib.parse import quote from flask import request import mock import ...
.views.node import _should_show_wiki_widget, _view_project, abbrev_authors from website.util import api_url_for, web_url_for from website.util import rubeus from website.util.metrics import OsfSourceTags, OsfClaimedTags, provider_source_tag, provider_claimed_tag from osf.utils import permissions from osf.models import ...
t from osf.models import OSFUser, Tag from osf.models import Email from osf.models.spam import SpamStatus from tests.base import ( assert_is_redirect, capture_signals, fake, get_default_metaschema, OsfTestCase, assert_datetime_equal, ) from tests.base import test_app as mock_app from tests.utils...
LuyaoHuang/patchwatcher
patchwatcher2/patchwatcher2/wsgi.py
Python
lgpl-3.0
403
0
"""
WSGI config for patchwatcher2 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi impo
rt get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "patchwatcher2.settings") application = get_wsgi_application()
quarckster/cfme_tests
cfme/utils/virtual_machines.py
Python
gpl-2.0
3,708
0.004315
"""Helper functions related to the creation and destruction of virtual machines and instances """ import pytest from cfme.utils.providers import get_crud from fixtures.pytest_store import store from novaclient.exceptions import OverLimit as OSOverLimit from ovirtsdk.infrastructure.errors import RequestError as RHEVReq...
= get_crud(provider_key) deploy_args.update(vm_name=vm_name) if template_name is None: try: deploy_args.update(template=provider_crud.data['templat
es']['small_template']['name']) except KeyError: raise KeyError('small_template not defined for Provider {} in cfme_data.yaml' .format(provider_key)) else: deploy_args.update(template=template_name) deploy_args.update(provider_crud.deployment_helper(deploy_args)) ...
google/neural-light-transport
data_gen/util.py
Python
apache-2.0
2,045
0.000489
# 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 agreed to in writing, ...
eft-top corner (where background takes colors from) to black src_[0, 0, ...] = 0 dst = cv2.remap(src_, mapping_x, mapping_y, cv2.INTER_LINEAR) return dst def add_b_ch(img_rg): assert img_rg.ndim == 3 and img_rg.shape[2] == 2, "Input should be HxWx2" img_rgb = np.dstack((img_rg, np.zeros_like(...
)) def name_from_json_path(json_path): return basename(json_path)[:-len('.json')]
henryfjordan/incident-commander
templates/responses.py
Python
mit
3,231
0.001243
#!/usr/bin/env python # -*- coding: utf-8 -*- from jinja2 import Template CREATE_INCIDENT = Template(""" *INCIDENT CREATED!* Thi
s incident is now being tracked and documented, but we still need your help! When you have a moment, please use these commands to provide more information: ``` @commander set title <title> @commander set reporter <@reporter> @commander set severity <1-3> @commander set description <description>
``` """) CREATE_INCIDENT_FAILED = Template("Hey, did you forget to include an application name?") # noqa NAG = Template("Be a dear and run `@commander set {{key}} <value>`") SET = Template("Set *{{field}}* to `{{value}}`") GET = Template("*{{field}}*: {{value}}") GET_LIST = Template(""" *{{field}}:* >>> {% for val...
Hellrungj/CSC-412-Networking
rpc-project/venv/lib/python2.7/site-packages/plumbum/colors.py
Python
gpl-3.0
646
0.003096
""" This module imitates a real module, providing standard syntax like from `plumbum.colors` and from `plumbum.colors.bg` to work alongside all the standard syntax for colors. """ from __future__ import print_function import sys import os import atexit from plumbum.colorlib import ansicolors, main _reset = ansicolors...
2, but not Python3 sys.modules[__name__ + '.fg'] = ansicolors.fg sys.modules[__name__ +
'.bg'] = ansicolors.bg sys.modules[__name__] = ansicolors
google-research/robel
robel/components/tracking/virtual_reality/client.py
Python
apache-2.0
3,972
0
# Copyright 2019 The ROBEL 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 wr...
_lookup.clear() self._device_serial_lookup.clear() devices = [] for device_index in range(openvr.k_unMaxTrackedDeviceCount): device = VrDevice(self._vr_system, device_index)
if not device.is_connected(): continue devices.append(device) self._device_index_lookup[str(device.index)] = device self._device_serial_lookup[device.get_serial()] = device self._devices = devices return devices def get_poses(self, time...
marklocklear/Online-Student-Profile
deploy/osp_settings.py
Python
lgpl-3.0
5,374
0.000186
from osp.conf.settings import * # Unique key used for salting passwords SECRET_KEY = 'Chac-8#haCa_Ra-e?-e+ucrur=gEFRasejayasaC?meMe!AC-a' # DEBUG should be False in production, True in development DEBUG = False # List of administrators who should receive error reports ADMINS = ( ('John Smith', 'john.smith@exampl...
heduled Appointment with Career Services', 'No Show for Appointment', 'Took Career Assessment(s)', 'Met with Career Counselor', 'Career Decision in Process', 'Career and Program Decision Completed', 'Referred for Program Update', 'Program Updated', ] # List of intervention reasons INTERVENT...
l or Social Counseling', 'Needs Career Exploration', 'Needs Tutoring', ] # Re-structure the choices lists for Django's sake CAMPUS_CHOICES = [(x, x) for x in CAMPUS_CHOICES] VISIT_CONTACT_TYPE_CHOICES = [(x, x) for x in VISIT_CONTACT_TYPE_CHOICES] VISIT_REASON_CHOICES = [(x, x) for x in VISIT_REASON_CHOICES] V...
showerst/openstates
openstates/ma/actions.py
Python
gpl-3.0
4,155
0.002407
import re from billy.scrape.actions import Rule, BaseCategorizer # These are regex patterns that map to action categories. _categorizer_rules = ( Rule([u'Amendment #\\S+ \\((?P<legislator>.+?)\\) bundle YES adopted'], [u'amendment:passed']), Rule([u'(?i)Signed by (the )Governor(.*)'], [u'governor:sign...
\S+ \\((?P<legislator>.+?)\\)\\s+-\\s+rejected', u'(?i)Amendment \\d+ rejected', u'Amendment #?\\S+ \\((?P<legislator>.+
?)\\) rejected'], [u'amendment:failed']), Rule([u'Amended \\((?P<legislator>.+?)\\) ', u'Amendment #?\\S+ \\((?P<legislator>.+?)\\) adopted'], [u'amendment:passed']), Rule([u'(?i)read.{,10}second'], [u'bill:reading:2']), Rule([u'Amendment #\\d+ \\((?P<legislator>.+?)\\) pending'], ...
seem-sky/FrameworkBenchmarks
pyramid/setup_benchmark.py
Python
bsd-3-clause
708
0.001412
import subprocess import setup_ut
il import multiprocessing import os home = os.path.expanduser('~') bin_dir = os.path.expanduser('~/FrameworkBenchmarks/installs/py3/bin') NCPU = multiprocessing.cpu_count() proc = None def start(args): global proc setup_util.replace_text( "frameworkbenchmarks/models.py", "DBHOSTNAME = 'local...
bin_dir + '/gunicorn', 'wsgi:app', '-b', "0.0.0.0:6543", '-w', str(NCPU*3)], cwd='pyramid' ) return 0 def stop(): global proc if proc is not None: proc.terminate() proc.wait() return 0
lucacasagrande/qgis2web
olLayerScripts.py
Python
gpl-2.0
21,275
0.000141
import re import traceback import os import codecs from urlparse import parse_qs from PyQt4.QtCore import QCoreApplication from qgis.core import (QgsRenderContext, QgsSingleSymbolRendererV2, QgsCategorizedSymbolRendererV2, QgsGraduatedSymbolRendererV...
for range in ranges: if
(attrValue >= range.lowerValue() and attrValue <= range.upperValue()): symbol = range.symbol().clone() else: symbol = renderer.symbolForFeature2(feat, ...
sean797/tracer
tests/test_processes.py
Python
gpl-2.0
1,199
0.021685
from .__meta__ import * from tracer.resources.processes import Processes, Process from tracer.resources.collections import ProcessesCollection import os import subprocess @unittest.skipIf(True, "@TODO Create Mock for Processes class") class TestProcesses(unittest.TestCase): def test_children(self): process = Proce...
ocess.children() self.assertIsInstance(children, ProcessesCollection) for child in children: self.assertIsInstance(child, Process) def test_unique_process(self): process = Proc
ess(os.getpid()) parent = Process(os.getppid()) self.assertIs(process, Process(os.getpid())) self.assertIs(parent, process.parent()) self.assertIn(process, parent.children()) Process.reset_cache() process2 = Process(os.getpid()) self.assertEqual(process, process2) self.assertIsNot(process, process2) ...
rbjorklin/lift-meet-manager
lift_meet_manager/urls.py
Python
bsd-2-clause
342
0.011696
from django
.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'lift_meet_manager.views.home', name='home'), # url(r'^blog/'
, include('blog.urls')), url(r'^lift_tables/', include('lift_tables.urls')), url(r'^admin/', include(admin.site.urls)), )
pk-sam/crosswalk-test-suite
wrt/wrt-security-android-tests/security/permissiontest.py
Python
bsd-3-clause
3,330
0.003604
#!/usr/bin/env python # # Copyright (c) 2015 Intel Corporation. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of works must retain the original copyright notice, this # list of conditions and t...
= "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s" % \ (comm.Pck_Tools, comm.ARCH, comm.MODE, manifestPath) packInfo = commands.getstatusoutput(cmd) self.assertNotEquals(0, packInfo[0]) if __name__ == '__main__': unittest.main()
isaced/ComSay
views/index.py
Python
mit
3,226
0.027588
from flask import Blueprint, render_template,request,Response,make_response,session,flash,redirect,url_for index = Blueprint('index', __name__) from models.User import User from models.Company import Company from models.Comments import Comments import time,serials @index.route('/') def index_list(): list=Company...
omments/submit",methods=["POST"
]) def commentsSub(): user_id=request.form["user_id"] company_id=request.form["company_id"] contents=request.form["contents"] if user_id==None or company_id==None or contents==None: abort(404) user=User.query.filter_by(id=user_id).first() company=Company.query.filter_by(id=company_id).fi...
hnb2/flask-customers
tests/test_customers.py
Python
mit
8,076
0.002105
''' To run these tests you need to create a test database, instructions are inside the README.md ''' import customers from customers.utils import db import unittest import json import base64 class CustomersTestCase(unittest.TestCase): ''' Test the customers application ''' EMAIL = '[email protected]' ...
) resp = self._open( 'register', 'POST', data=json.dumps(dat
a), ) json_data = json.loads(resp.get_data()) self.assertIsNotNone(json_data.get('errors')) self.assertIsNotNone(json_data['errors'].get('email')) #Correct parameters => success data = dict(email='[email protected]', password='test2') resp = self._open( ...
slyphon/pants
tests/python/pants_test/backend/jvm/tasks/test_jvm_dependency_usage.py
Python
apache-2.0
4,527
0.003755
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from colle...
ost(t2), 3) self.assertEqual(graph._trans_cost(t3), 4) self._cover_output(graph) def test_dep_usage_graph_with_synthetic_targets(self): t1 = self.make_java_target(spec=':t1', sources=['t1.thrift']) t1_x = self.make_java_target(spec=':t1.x', derived_from=t1) t1_y = self.make_java_target(spec=':t1...
e_java_target(spec=':t1.z', derived_from=t1) t2 = self.make_java_target(spec=':t2', sources=['a.java', 'b.java'], dependencies=[t1, t1_x, t1_y, t1_z]) self.set_options(size_estimator='nosize') dep_usage, product_deps_by_src = self._setup({ ...
NovaXeros/OpelSqueeze
lib/smartshuffle.py
Python
gpl-2.0
859
0.044237
#!/usr/bin/env python import os.path import time import transmission as send import shelving as db def first_check(): if os.path.isfile('check.db') == False: db.prime() else: if send.passthru(['mode','?']) == 'play': db.update_shelf() else: perform_start_tasks() def perform_start_tasks(): last_known_c...
g') last_known_prog = db.query('prog') ti
me_without = time.time() - int(last_known_check) if last_known_song == 'PRIMED': send.passthru(['randomplay','tracks']) else: if (time_without < 600): send.passthru(['playlist','add',last_known_song]) send.passthru(['play','5']) send.passthru(['time',last_known_prog]) send.rp_add() db.update_shel...
OlgaKuratkina/python_training_qa
conftest.py
Python
apache-2.0
2,798
0.004289
import pytest import json import os.path import importlib import jsonpickle from fixture.application import Application from fixture.db import DBfixture from fixture.orm import ORMfixture fixture = None target = None def load_config(file): global target if target is None: config_file = os.path.join(o...
["user"], password=db_config["password"]) return orm_fixture @pytest.fixture(scope="session", autouse=True) def stop(request): def fin(): fixture.session.ensure_logout() fixture.destroy() request.addfinalizer(fin) return fixture @pytest.fixture() def check
_ui(request): return request.config.getoption("--check_ui") def pytest_addoption(parser): parser.addoption("--browser", action="store", default="firefox") parser.addoption("--target", action="store", default="target.json") parser.addoption("--check_ui", action="store_true") def pytest_generate_tests(...
PyRsw/PyRsw
src/Fluxes/SADOURNY_SW.py
Python
mit
4,319
0.015513
import Differentiation as Diff import numpy as np import sys # Geometry: periodic in x and y # Arakawa C-grid # # | | | | # h -- u -- h -- u -- h -- u -- h -- # | | | | # | | | | # v q v q...
: need q*V^x # v-eqn: need q*U_y # h-eqn: need U left
and V down def sadourny_sw_flux(sim): Nx, Ny, Nz = sim.Nx, sim.Ny, sim.Nz dx, dy = sim.dx[0], sim.dx[1] # Loop through each layer and compute the flux for ii in range(Nz): # Assign nice names to primary variables h = sim.soln.h[:,:,ii] u = sim.soln.u[:,:,ii] v...
madvas/gae-angular-material-starter
main/api/v1/feedback_api.py
Python
mit
1,108
0.00361
# coding: utf-8 # pylint: disable=too-few-public-methods, no-self-use, missing-docstring, unused-argument from flask_restful import reqparse, Resource from flask import abort from main import API import task import config from api.helpers import ArgumentValidator, make_empty_ok_response from api.decorators import verif...
s.email} i
f args.email else {} task.send_mail_notification('%s...' % body[:48].strip(), body, **kwargs) return make_empty_ok_response()
leonth/private-configs
sublime-text-3/Packages/Jedi - Python autocompletion/jedi/parser/__init__.py
Python
mit
28,035
0.000214
""" The ``Parser`` tries to convert the available Python code in an easy to read format, something like an abstract syntax tree. The classes who represent this tree, are sitting in the :mod:`parsing_representation` module. The Python module ``tokenize`` is a very important part in the ``Parser``, because it splits the...
:rtype: tuple(Name, int, str) """ def append(el): names.append(el) self.module.temp_used_names.append(el[0]) names = [] if pre_used_token is None: token_type, tok = self.next() if t
oken_type != tokenize.NAME and tok != '*': return [], token_type, tok else: token_type, tok = pre_used_token if token_type != tokenize.NAME and tok != '*': # token maybe a name or star return None, token_type, tok append((tok, self.start_pos)...
anselmobd/fo2
src/contabil/forms.py
Python
mit
4,534
0
from pprint import pprint from django import forms from base.forms.custom import O2BaseForm from base.forms.fields import ( O2FieldCorForm, O2FieldModeloForm, O2FieldRefForm, ) class InfAdProdForm(forms.Form): pedido = forms.CharField( label='Pedido', widget=forms.TextInput(attrs={'t...
DateField( label='NF Remessa - Data inicial', required=False, widget=forms.DateInput(attrs={'type': 'date'})) da
ta_ate = forms.DateField( label='NF Remessa - Data final', required=False, widget=forms.DateInput(attrs={'type': 'date'})) faccao = forms.CharField( label='Facção', required=False, help_text='Busca no nome e no CNPJ da facção', widget=forms.TextInput(attrs={'type': 'string'}...
openprocurement/openprocurement.tender.competitivedialogue
setup.py
Python
apache-2.0
1,767
0.001132
from setuptools import setup, find_packages import os version = '2.4.3' requires = [ 'setupto
ols' ] api_requires = requires + [ 'openprocurement.api>=2.4', 'openprocurement.tender.openua>=2.4.2', 'openprocurement.tender.openeu>=2.4.2', 'openp
rocurement.tender.core>=2.4' ] test_requires = api_requires + requires + [ 'webtest', 'python-coveralls', ] docs_requires = requires + [ 'sphinxcontrib-httpdomain', ] entry_points = { 'openprocurement.tender.core.plugins': [ 'competitivedialogue = openprocurement.tender.competitivedialogue.in...
quantumlib/Cirq
cirq-web/cirq_web/circuits/symbols.py
Python
apache-2.0
5,383
0.000557
# Copyright 2021 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
nent = info._wire_symbols_including_formatted_exponent( CircuitDiagramInfoArgs.UNINFORMED_DEFAULT ) symbol_info = SymbolInfo(list(symbol_exponent), []) for symbol in wire_symbols: symbol_info.colors.append(DefaultResolver._SYMBOL_COLORS.get(symbol, 'gray')) retur...
) -> SymbolInfo: """Builds a SymbolInfo object based off of a designated operation and list of resolvers. The latest resolver takes precendent. Args: operation: the cirq.Operation object to resolve resolvers: a list of SymbolResolvers which provides instructions on how to build Symb...
comicxmz001/LeetCode
Python/28 Implement strStr.py
Python
mit
792
0.059343
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 if len(haystack) < len(needle): return -1 for i in xrange(len(haystack)): if
i + len(needle) > len(haystack): return -1 if haystack[i] != needle[0] or haystack[i+len(needle)-1] != needle[-1]: continue else: j=0 while j < len(needle) and i+j < len(haystack): if haystack[i+j] != needle[j]: break j +=
1 if j == len(needle): return i return -1 if __name__ == '__main__': s1 = "" s2 = "" s3 = "" print Solution().strStr(s1,s2)
thaim/ansible
lib/ansible/modules/cloud/cloudstack/cs_vpn_gateway.py
Python
mit
5,470
0.000732
#!/usr/bin/pytho
n # -*- coding: utf-8 -*- # # (c) 2017, René Moser <[email protected]> # GNU General Public License v3.0+ (see COPY
ING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cs_vpn_gateway short_description: Manages site-to-site VPN gateways on Apache CloudStack based cl...
ewandor/git-french-law
LegifranceClient/__init__.py
Python
gpl-2.0
2,270
0.002203
from datetime import datetime from mechanize import Browser from FrenchLawModel import Text, Article, Version, Law from page import ConstitutionPage, ArticlePage class LegifranceClient(object): host = 'http://www.legifrance.gouv.fr/' def __init__(self): self.user_agent = 'Mozilla/4.0 (compatible; M...
fying_law_page) law = law_page.set_law(Law()) version.set_modifying_law(law) else: version.set_modifying_law(self.initial_law) article.add_version(version) constitution.add_article(article) return co
nstitution
95subodh/Leetcode
129. Sum Root to Leaf Numbers.py
Python
mit
960
0.035417
#Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. # #An example is the root-to-leaf path 1->2->3 which represents the number 123. # #Find the total sum of all root-to-leaf numbers. # #For example, # # 1 # / \ # 2 3 #The root-to-leaf path 1->2 represents the n...
f __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ stk=[] ans=0 if root: stk=[[root,root.val]] while stk: z=stk.pop() if z[0].left: stk.append([z[0]...
urn ans
ErnieAllen/qpid-dispatch
tests/friendship_server.py
Python
apache-2.0
3,531
0.00085
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOT
ICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in 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 WARRANTIES OR CONDITIONS OF ANY # KIND, either express or i...
thebigmunch/gmusicapi-wrapper
tests/test_filter_google_songs.py
Python
mit
6,138
0.021505
# coding=utf-8 """Module for testing gmusciapi_wrapper.utils.filter_google_songs utility function.""" from gmusicapi_wrapper.utils import filter_google_songs from fixtures import TEST_SONGS_1 def test_filter_google_songs_no_filters(): """Test gmusicapi_wrapper.utils.filter_google_songs with no filters.""" match...
= TEST_SONGS_1 expected_f
iltered = [] assert matched == expected_matched assert filtered == expected_filtered
snahelou/awx
awx/main/south_migrations/0055_v210_changes.py
Python
apache-2.0
53,135
0.00717
# -*- 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 model 'CustomInventoryScript' db.create_table(u'main_custominven...
o.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [],...
gth': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), ...
achanda/flocker
flocker/node/agents/_logging.py
Python
apache-2.0
5,427
0
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Helper module to provide macros for logging support for storage drivers (AWS, Cinder). See https://clusterhq.atlassian.net/browse/FLOC-2053 for consolidation opportunities. """ from eliot import Field, ActionType, MessageType # Begin: Common structures us...
:agents:blockdevice:openstack' # ActionType used by OpenStack storage driver. OPENSTACK_ACTION = ActionType( CINDER_LOG_HEADER, [OPERATION], [], u"An IBlockDeviceAPI operation is executing using OpenStack" u"sto
rage driver.") CINDER_CREATE = u'flocker:node:agents:blockdevice:openstack:create_volume' # End: Helper datastructures used by OpenStack storage driver.
bungoume/django-template
project_name/manage.py
Python
mit
550
0.001818
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError(
"Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
rackerlabs/pitchfork
pitchfork/config/config.example.py
Python
apache-2.0
1,097
0
# Copyright 2014 Dave Kludt # # 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...
BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ If you are running the application within docker using the provided Dockerfile and docker-compose then you will need
to change the MONGO_HOST option to use the correct container. import os MONGO_HOST = os.environ['PITCHFORK_DB_1_PORT_27017_TCP_ADDR'] """ MONGO_HOST = 'localhost' MONGO_PORT = 27017 MONGO_KWARGS = {'tz_aware': True} MONGO_DATABASE = 'pitchfork' ADMIN_USERNAME = 'cloud_username' ADMIN_NAME = 'Admin Ful...
sippy/rtpproxy
misc/includepolice.py
Python
bsd-2-clause
6,459
0.006038
#!/usr/bin/env python from random import random from subprocess import call import sys, os def get_ip_flags(iname, includedirs): includedirs = ['.',] + includedirs for dname in includedirs: try: f = open('%s/%s' % (dname, iname)) break except IOError:
continue else: raise Exception('%s is not found in %s' % (iname, includedirs)) for line in f.readlines(): line = line.strip() if not line.startswith('/*') and line.endswith('*/'): continue line = line[2:-2].strip() if not line.startswith('IP
OLICE_FLAGS:'): continue ip_pars = line.split(':', 1) ip_flags = ip_pars[1].strip().split(',') return ip_flags return None class header_file(object): ifname = None ip_flags = None def __init__(self, ifname, includedirs): self.ifname = ifname if not i...
cwolferh/heat-scratch
heat/engine/resources/openstack/neutron/lbaas/pool.py
Python
apache-2.0
9,455
0
# # Copyright 2015 IBM Corp. # # 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 require...
_PERSISTENCE_TYPES = ( SOURCE_IP, HTTP_COOKIE, APP_COOKIE ) = ( 'SOURCE_IP', 'HTTP_COOKIE', 'APP_COOKIE' ) ATTRIBUTES = ( HEALTHMONITOR_ID_ATTR, LISTENERS_ATTR, MEMBERS_ATTR ) = ( 'healthmonito
r_id', 'listeners', 'members' ) properties_schema = { ADMIN_STATE_UP: properties.Schema( properties.Schema.BOOLEAN, _('The administrative state of this pool.'), default=True, update_allowed=True ), DESCRIPTION: properties.Schema( ...
2deviant/Mathematica-Trees
trees.py
Python
mit
2,017
0.003966
import converters import math import random import sys def random_real(a, b): """ Random real between a and b inclusively. """ return a + random.random() * (b - a) def branch_length(depth): """ Somewhat random length of the branch. Play around with this to achieve a desired tree structure...
an, max_lean)
length = branch_length(depth) # branch is the line segment (x0, y0) - (x1, y0) x1 = x0 + length*math.sin(angle) y1 = y0 + length*math.cos(angle) # construct the branch # the depth -- or inverse height -- is stored so that the # rendering code can use it to vary the thickness of the # br...
wdbm/media_editing
setup.py
Python
gpl-3.0
1,765
0.022663
#!/usr/bin/python # -*- coding: utf-8 -*- import os import setuptools def main(): setuptools.setup( name = "media_editing", version = "2018.03.26.0007", description = "media editing", long_description = long_description(), url = "htt...
md" ): if os.path.isfile(os.path.expandvars(filena
me)): try: import pypandoc long_description = pypandoc.convert_file(filename, "rst") except ImportError: long_description = open(filename).read() else: long_description = "" return long_description if __name__ == "__main__": main()