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
websterkgd/PeasantMath
Roots/code/Roots.py
Python
cc0-1.0
3,247
0.009547
from __future__ import division import sys import os import matplotlib.pyplot as plt import scipy from scipy import special mydir = os.path.expanduser("~/") sys.path.append(mydir + "/GitHub/PeasantMath/Roots/code") import functions as fxn ks = [2, 3, 4, 5, 6, 7, 8, 9, 10, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5...
str(k)) plt.scatter(xs, WLs, color='c', alpha=0.9, label='WHL rule') #plt.yscale('log') #plt.xscale('log') plt.xlabel('x', fontsize=8) plt.ylabel('y', fontsize=8) plt.xlim(min(xs), max(xs)) plt.yl
im(min(WLs), max(rts)) plt.legend(bbox_to_anchor=(-0.04, 1.08, 2.59, .2), loc=10, ncol=2, mode="expand",prop={'size':16}) #leg = plt.legend(loc=4,prop={'size':12}) #leg.draw_frame(False) #plt.text(-50, 14, "How well does the WHL Rule approximate square roots?", fontsize=16) ax = ...
Mat-Frayne/HsBot
cogs/Admin.py
Python
mit
7,956
0.001131
#!/usr/bin/env python """.""" import asyncio import inspect import io import subprocess import textwrap import traceback from contextlib import redirect_stdout import discord from discord.ext import commands from sys import platform class Admin: """.""" def __init__(self, bot): """.""" self.b...
dule) out = "Reloaded {}".format(module) except Exception as exc: out = '{}: {}'.format(type(exc).__name__, exc) await ctx.send(out) @commands.is_owner() @commands.command(pass_context=True, hidden=True, name='eval') async def _eval(self, ctx, *, body: st...
env = { 'bot': self.bot, 'ctx': ctx, 'channel': ctx.channel, 'author': ctx.author, 'guild': ctx.guild, 'message': ctx.message, 'db': self.bot.models, '_': self._last_result } env.update(globals()) ...
Johnzero/erp
openerp/addons/auction/report/photo_shadow.py
Python
agpl-3.0
2,248
0.010231
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
draw = ImageDraw.Draw(newimg) draw.rectangle((6, im.size[1]-5, im.size[0], im.size[1]+5), fill=(90,90,90)) draw.rectangle((im.size[0]-5, 6, im.size[0]+5, im.size[1]), fill=(90,90,90)) del draw newimg = newimg.filter(ImageFilter.BLUR) newimg = newimg.filter(ImageFilt
er.BLUR) newimg = newimg.filter(ImageFilter.BLUR) newimg.paste(im, (0,0)) draw = ImageDraw.Draw(newimg) draw.rectangle((0, 0, im.size[0], im.size[1]), outline=(0,0,0)) del draw to_fp = file(to_file, 'wb') newimg.save(to_fp, "JPEG") to_fp.close() res = newimg.size del im del...
radiosilence/wire
wire/frontend/views.py
Python
mit
20,501
0.002975
import json import redis import uuid import subprocess from flask import Blueprint, request, session, g, redirect, url_for, abort, \ render_template, flash, current_app from flaskext.uploads import (UploadSet, configure_uploads, IMAGES, UploadNotAllowed) from wire.frontend import f...
ew_thread', thread_
id=thread_id)) else: return render_template('confirm.html', _message='Are you sure you want to delete this message?', _ok=url_for('frontend.delete_message', thread_id=thread_id, message_id=message_id), _cancel=url_for('frontend.view_thread', thread_id=thre...
chreman/isis-praktikum
sustainabilitylsa.py
Python
mit
20,232
0.007266
# import string import glob import time import xml.etree.ElementTree as ET from itertools import chain # Import reader import xlrd import csv import requests # Import data handlers import collections # Import Network Analysis Tools import networkx as nx import igraph as ig # Import language processing tools from g...
#test_for_topic_convergence(keyword, testdata, model, _model, num_topics, threshold, depth) export_matrix(keyword, dictionary, model, _model, show_topics, num_words, depth) export_topic_list(keyword, dictionary, model, _model, show_topics, num_words, depth) export_word_graph(keyword, dictionary, model...
, depth) def get_filelist(path, extension): """ Creates a list of files in a folder with a given extension. Navigate to this folder first. """ return [f for f in glob.glob("{0}/*.{1}".format(path, extension))] def preprocess_content(content, keyword, depth="document"): """ Takes a list o...
billlai95/bilimining
biligrab/SentenceSimilarityEvaluation.py
Python
apache-2.0
2,527
0.001187
# @see http://www.idayer.com/sentences-similarity.html # kindled by https://github.com/ineo6/chinese-segmentation import sys import math from pinyin.pinyin import Pinyin import biligrab.Functions from importlib import reload reload(sys) class Evaluator: d = {} @staticmethod def log(x): if not x:...
0.0 a_sq = 0.0 b_sq = 0.0 for a1, b1 in zip(a, b): part_up += a1 * b1 a_sq += a1 ** 2 b_sq += b1 ** 2 part_down = math.sqrt(a_sq * b_sq) if part_down == 0.0: return None else: return part_up / part_down @sta...
rst_run: Evaluator.init() Evaluator.first_run = False s1 = list(Evaluator.__solve(sentence1)) s2 = list(Evaluator.__solve(sentence2)) key = list(set(s1 + s2)) keylenth = len(key) keyvalue = 0 sk1 = [keyvalue] * keylenth sk2 = [keyvalue] ...
Transkribus/TranskribusDU
TranskribusDU/tasks/TablePrototypes/DU_ABPTableRCut1SIO.py
Python
bsd-3-clause
34,506
0.015218
# -*- coding: utf-8 -*- """ DU task for ABP Table: doing jointly row BIESO and horizontal cuts block2line edges do not cross another block. The cut are based on baselines of text blocks. - the labels of horizontal cuts are SIO (instead of SO in previous version) Copy
right Naver Labs Europe(C) 2018 JL Meunier Developed for the EU project READ. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant
agreement No 674943. """ import sys, os import math from lxml import etree import collections import numpy as np from sklearn.pipeline import Pipeline, FeatureUnion try: #to ease the use without proper Python installation import TranskribusDU_version except ImportError: sys.path.append( os.path.dirna...
kareemallen/beets
beetsplug/types.py
Python
mit
1,775
0
# -*- coding: utf-8 -*- # This file is
part of beets. # Copyright 2015, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge,...
ditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. from __future__ import (division, absolute_import, print_function, unicode_literals) from beets.plugins import BeetsPlugin from beets.dbcore import type...
nickchen-mitac/fork
src/ava/core/defines.py
Python
apache-2.0
1,103
0.001813
# -*- coding: utf-8 -*- """ Various definitions used across different packages. """ from __future__ import absolute_import, division, print_function, unicode_literals from .. import VERSION_STRING # return as the root resource. AG
ENT_INFO = { "EAvatar": "A versatile agent.", "version": VERSION_STRING, "vendor": { "name": "EAvatar Technology Ltd.", "version": VERSION_STRING }, } # activated engines INSTALLED_ENGINES = [ "ava.log.engine:LogEngine", "ava.data.engine:DataEngine", "ava.task.engine:TaskE...
frontEngine", ] ##### Environment variable #### AVA_POD_FOLDER = 'AVA_POD' # where the working directory. AVA_AGENT_SECRET = 'AVA_AGENT_SECRET' # the agent's own secret key. AVA_SWARM_SECRET = 'AVA_SWARM_SECRET' # the swarm's secret key. AVA_USER_XID = 'AVA_USER_XID' # the user's XID. # tries to import definiti...
CroceRossaItaliana/jorvik
autenticazione/viste.py
Python
gpl-3.0
986
0.002028
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import redirect from django.contrib.auth.views import logout as original_logout from loginas import settings as la_settings from loginas.utils impor...
lresolvers import reverse_lazy LOGOUT_URL = reverse_lazy('logout') """ original_session = request.session.get(la_settings.USER_SESSION_FLAG) if original_session: restore_original_login(request) return redirect(la_settings.LOGOUT_REDIRECT) else: return original_logout(request...
ame, redirect_field_name, extra_context)
kasper190/SPAforum
forum/api/permissions.py
Python
mit
441
0.006803
fr
om rest_framework.permissions import BasePermission, SAFE_METHODS class IsAdminOrModeratorOrReadOnly(BasePermission): def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True if request.user and request.user.is_staff: return True ...
leiyue/microblog
app/forms.py
Python
mit
1,399
0.00143
# -*- coding: utf-8 -*- # @Date : 2016-01-21 13:15 # @Author : le
iyue ([email protected]) # @Link : https://leiyue.wordpress.com/ from flask_wtf import Form from wtforms import StringField, BooleanField, TextAreaField from wtforms.validators import DataRequired, length from .models import User class LoginForm(Form): openid = StringField('openid', validators=[DataRequired...
me = BooleanField('remember_me', default=False) class EditForm(Form): nickname = StringField('nickname', validators=[DataRequired()]) about_me = TextAreaField('about_me', validators=[length(min=0, max=140)]) def __init__(self, original_nickname, *args, **kwargs): Form.__init__(self, *args, **kwar...
abertschi/postcards
postcards/plugin_pexels/postcards_pexels.py
Python
mit
618
0.001618
#!/usr/bin/env python # encoding: utf-8 from postcards.postcards import Postcards from postcards.plugin_pexels.util.pexels import get_random_image_url, read_from_url import sys class PostcardsPexel(Postcards): """ Send postcards with random images from pexels.com """ def get_img_and_text(self, plugi...
= get_random_image_url() self.logger.info('using pexels picture: ' + url) return { 'img': read_from_url(url), 'text': ''
} def main(): PostcardsPexel().main(sys.argv[1:]) if __name__ == '__main__': main()
qianwenming/mapnik
bindings/python/mapnik/__init__.py
Python
lgpl-2.1
35,583
0.005115
# # This file is part of Mapnik (C++/Python mapping toolkit) # Copyright (C) 2009 Artem Pavlenko # # Mapnik 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 any later versi...
is deprecated and will be removed in Mapnik 3.x, use 'Expression' instead", DeprecationWarning, 2) return Expression(*args, **kwargs) class Envelope(Box2d): def __init__(self, *args, **kwargs): warnings.warn("'Envelope' is deprecated and will be removed in Mapnik 3.x, use 'Box2d' instead", ...
oord(Coord,_injector): """ Represents a point with two coordinates (either lon/lat or x/y). Following operators are defined for Coord: Addition and subtraction of Coord objects: >>> Coord(10, 10) + Coord(20, 20) Coord(30.0, 30.0) >>> Coord(10, 10) - Coord(20, 20) Coord(-10.0, -10.0) ...
twpDone/SimpleAsIRC
Core.py
Python
mit
5,635
0.017746
#!/usr/bin/python # -*- coding: utf-8 -*- ## # Core of the application, implement a part of the RFC 1459: Internet Relay Chat ProtocolA (Client side). from Message import Message from Action import Action import socket import string import re import time #ssl support from ssl import SSLSocket ## # Core of the appl...
if data.upper().__contains__("PING"): self.m_socket.sendall('PONG\r\n') except Exception as ex: print("Erreur de reception"
) print(ex) ## # Ends the IRC protocol # @note Close the socket # @param self Self. def quit(self): self.m_socket.close(); ## # Overload the Core class to use a SSL Socket. class secureCore(Core): def __init__(self,channel="#dut.info",name="twp_bot",port=6697,host='irc.free...
beslave/auto-collector
auto/server/__init__.py
Python
mit
678
0.001475
import aiohttp_jinja2 import asyncio import jinja2 from aiohttp import web import setti
ngs from auto.server.middlewares import middlewares from auto.server.urls import url_patterns loop = asyncio.get_event_loop() app = web.Application(middlewares=middlewares) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(settings.TEMPLATE_DIR)) for url in url_patterns: app.router.add_route(url.method,...
=settings.SITE_PORT, # reuse_address=False, # reuse_port=False, ) tasks = [serve_task]
e2crawfo/dps
dps/tf/updater.py
Python
apache-2.0
21,553
0.002969
import abc import json from future.utils import with_metaclass from collections import defaultdict import numpy as np import tensorflow as tf from dps import cfg from dps.utils import Parameterized, Param from dps.utils.tf import build_gradient_train_op, trainable_variables, get_scheduled_values, ScopedFunction from ...
-- train op --- if cfg.do_train and not c
fg.get('no_gradient', False): tvars = self.trainable_variables(for_opt=True) self.train_op, self.train_records = build_gradient_train_op( self.loss, tvars, self.optimizer_spec, self.lr_schedule, self.max_grad_norm, self.noise_schedule, grad_n_record_groups=self.g...
soumide1102/pycbc
pycbc/transforms.py
Python
gpl-3.0
57,402
0.001115
# Copyright (C) 2017 Christopher M. Biwer # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 3 of the License, or (at your # option) any later version. # # This program is distribut...
ceived a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ This modules provides classes and functions for transforming parameters. """ import copy import logging import
numpy from six import string_types from pycbc import conversions from pycbc import coordinates from pycbc import cosmology from pycbc.io import record from pycbc.waveform import parameters from pycbc.boundaries import Bounds from pycbc import VARARGS_DELIM class BaseTransform(object): """A base class for transfor...
ppizarror/Hero-of-Antair
bin/simplejson/scanner.py
Python
gpl-2.0
4,693
0.000213
# coding=utf-8 """ JSON token scanner """ import re def _import_c_make_scanner(): try: from simplejson._speedups import make_scanner return make_scanner except ImportError: return None c_make_scanner = _import_c_make_scanner() __all__ = ['make_scanner', 'JSONDecodeError'] NUMBER_R...
ponding to pos colno: The column corresponding to pos endlineno: The line corresponding to end (may be None) endcolno: The column corresponding to end (may be None) """ # Note that this exception is used from _speedups def __init__(self, msg, doc, pos, end=None): ValueError.__init__(se...
inecol(doc, pos) if end is not None: self.endlineno, self.endcolno = linecol(doc, end) else: self.endlineno, self.endcolno = None, None def __reduce__(self): return self.__class__, (self.msg, self.doc, self.pos, self.end) def linecol(doc, pos): lineno = doc.cou...
Lyleo/OmniMarkupPreviewer
OmniMarkupLib/Renderers/base_renderer.py
Python
mit
4,974
0.000402
""" Copyright (c) 2013 Timon Wong Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub...
def executable_check(self, text, filename): tempfile_ = None result = '' try: args = [self.get_executable()] if self.input_method == InputMethod.STDIN: args.extend(self.get_args())
elif self.input_method == InputMethod.TEMPFILE: _, ext = os.path.splitext(filename) tempfile_ = tempfile.NamedTemporaryFile(suffix=ext) tempfile_.write(text) tempfile_.flush() args.extend(self.get_args(filename=tempfile_.name())) ...
Uli1/mapnik
scons/scons-local-2.4.0/SCons/Tool/__init__.py
Python
lgpl-2.1
34,247
0.008234
"""SCons.Tool SCons tool selection. This looks for modules that define a callable object that can modify a construction environment as appropriate for a given tool (or tool chain). Note that because this subsystem just *selects* a callable that can modify a construction environment, it's possible for people to defin...
src_suffix = '$OBJSUFFIX', src_builder = 'Object', target_scanner = ProgramScanner) env['BUILDERS']['Program'] = program retur
n program def createStaticLibBuilder(env): """This is a utility function that creates the StaticLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: static_lib = env['BUILDERS']['StaticLibrary'] except KeyError: ...
ctmil/bc_website_purchase
wizards/request_relevant_suppliers.py
Python
agpl-3.0
7,875
0.007238
__author__ = 'tbri' from openerp import fields, models, api, _ import logging _logger = logging.getLogger(__name__) class request_relevant_suppliers(models.TransientModel): _name = "requisition_suppliers" _description = "Purchase Requisition Suppliers" def _get_active_id(self): print "GETTING ACT...
tender = self.env['purchase.requisition'].browse(active_id) prods = self.env['relevant_supplierinfo'].search([('relevant_suppliers','=',self.id)]) _logger.info('create_order %s %s', self.id, prods) for si in prods: supplierinfo = si.read(['name', 'leadtime'])[0] ...
dtime = supplierinfo['leadtime'] rfq_id = tender.make_purchase_order(supplierinfo['name'][0]) _logger.info('create_order rfq %s', rfq_id) for rfq in rfq_id.values(): _logger.info('searching') # not great but po = self.env['purchase.orde...
cmyr/poetryutils2
tests/realness_tests.py
Python
mit
1,555
0.003215
# coding: utf-8 from __future__ import print_function from __future__ import unicode_literals import re import poetryutils2 # this is all for use within ipython def sample_words(): lines = poetryutils2.utils.debug_lines() words = list() for l in lines: words.extend(w.lower() for w in l.split()) ...
nt(len(sample)) fails = realness(sample) # for f in fails: # print(f) from collections import Counter counter = Counter(fails) for word, count in counter.most_common(): if count > 1: print(word, count) # import argparse # parser = argparse.ArgumentParser() ...
olean argument', action="store_true") # args = parser.parse_args() """ okay so what we're having trouble with: -est -ies -py """ if __name__ == "__main__": main()
PersonalGenomesOrg/open-humans
private_sharing/api_permissions.py
Python
mit
254
0
from rest_framework.per
missions import BasePermission class HasValidProjectToken(BasePermission): """ Return True if the request has a valid project token. """ def has_permission(self, request, view): return bo
ol(request.auth)
bennuttall/chef-hat
chef_hat/chef_hat.py
Python
bsd-3-clause
12,834
0.000156
from RPi import GPIO from w1thermsensor import W1ThermSensor import energenie from datetime import datetime, timedelta from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) class Chef(object): """ Provides an implementation of temperature moderation for use in sous vide cooking with the ...
back button to terminate the process. """ GPIO.setup(self.LED, GPIO.OUT) self.turn_led_off() for button in self.BUTTONS: GPIO.setup(button, GPIO.IN, self.PULL) self.remove_button_event(button) self.add_button_event(self.BUTTON_BACK, self.terminate) ...
"" self.remove_button_event(self.BUTTON_BACK) self.state = self.STATE_FINISHED def write(self, text, line=1): """ Prints `text` TODO: writes to the LCD """ print(text) def turn_led_on(self): """ Turns the status LED on """ ...
zhangtuoparis13/Vintageous
vi/variables.py
Python
mit
1,741
0.000574
import sublime import collections VAR_MAP_LEADER = 'mapleader' VAR_MAP_LOCAL_LEADER = 'maplocalleader' # well-known variables _SPECIAL_STRINGS = { '<leader>': VAR_MAP_LEADER, '<localleader>': VAR_MAP_LOCAL_LEADER, } _DEFAULTS = { VAR_MAP_LEADER: '\\', VAR_MAP_LOCAL_LEADER: '\\' } _VARIABLES = {...
ader + seq[len(var_na
me):] except TypeError: return seq def is_key_name(name): return name.lower() in _SPECIAL_STRINGS def get(name): name = name.lower() name = _SPECIAL_STRINGS.get(name, name) return _VARIABLES.get(name, _DEFAULTS.get(name)) def set_(name, value): # TODO(guillermooo): Set vars in sett...
Reading-eScience-Centre/pycovjson
pycovjson/writeNetCDF.py
Python
bsd-3-clause
524
0
from netCDF4 import Dataset from nump
y import arange, dtype nx = 4 ny = 4 nz = 4 ncfile = Dataset('test_xy.nc', 'w') # create the output data. data_out = arange(nx * ny) print(data_out) data_out.shape = (nx, ny) # reshape to 3d array # create the x and y dimensions. ncfile.createDimension('x', nx) ncfile.createDimension('y', ny)
# ncfile.createDimension('z', nz) data = ncfile.createVariable('data', dtype('float32').char, ('x', 'y')) data[:] = data_out # close the file. print(ncfile.variables) print("Wrote file!")
slank/awsmeta
awsmeta/metadata.py
Python
mit
1,422
0.000703
from urllib2 import ( urlopen, HTTPError,
URLError, ) BASEURL = 'http://169.254.169.254/' DEFAULT_TIMEOUT = 2 DEFAULT_API_VERSION = 'latest' class MetadataError(Exception): pass def path(path=None, api_version=DEFAULT_API_VERSION, timeout=DEFAULT_TIMEOUT): if not api_version: api_version = 'latest' md_path = api_version if pa...
imeout) except HTTPError as e: if e.code == 404: raise MetadataError("Path not found: /%s" % path) else: raise MetadataError(e) except URLError as e: raise MetadataError(e) if not path: return "\n".join(map(lambda p: p.strip() + "/", u.readlines())) ...
shanbay/sea
sea/config.py
Python
mit
1,363
0
from sea.datatypes import ConstantsObject class ConfigAttribute: """Makes an attribute forward to the config""" def __init__(self, name, get_converter=None): self.__name__ = name self.get_converter = get_converter def __get__(self, obj, type=None): if obj is None: ret...
r().__init__(defaults
or {}) self.root_path = root_path def from_object(self, obj): for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def get_namespace(self, namespace, lowercase=True, trim_namespace=True): rv = {} for k, v in self.items(): ...
turbokongen/home-assistant
tests/components/smartthings/conftest.py
Python
apache-2.0
10,388
0.00077
"""Test configuration and mocks for the SmartThings component.""" import secrets from unittest.mock import Mock, patch from uuid import uuid4 from pysmartthings import ( CLASSIFICATION_AUTOMATION, AppEntity, AppOAuthClient, AppSettings, DeviceEntity, DeviceStatus, InstalledApp, Installe...
DATA_BROKERS, DOMAIN, SETTINGS_INSTANCE_ID, STORAGE_KEY, STORAGE_VERSION, ) from homeassistant.config import async_process_ha_core_config from homeassistant.config_entries import CONN_CLASS_CLOUD_PUSH, SOURCE_USER, ConfigEntry from homeassistant.con
st import ( CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_WEBHOOK_ID, ) from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry from tests.components.light.conftest import mock_light_profiles # noqa COMPONENT_PREFIX = "homeassistant.components.smar...
beagles/neutron_hacking
neutron/api/rpc/agentnotifiers/metering_rpc_agent_api.py
Python
apache-2.0
4,002
0.00025
# Copyright (C) 2013 eNovance SAS <[email protected]> # # Author: Sylvain Afchain <[email protected]> # # 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.apach...
ebug(_('Notify metering agent at %(topic)s.%(host)s ' 'the message %(method)s'), {'topic': self.client.target.topic, 'host': l3_agent.host, 'method': method}) l3_router = l3_routers.get(l3
_agent.host, []) l3_router.append(router) l3_routers[l3_agent.host] = l3_router for host, routers in l3_routers.iteritems(): topic = '%s.%s' % (self.client.target.topic, host) cctxt = self.client.prepare(topic=topic) cctxt.cast(context, method...
meriembendris/ADNVideo
src/annotation/grammar/label-stats.py
Python
lgpl-3.0
2,190
0.005023
import json, sys from collections import defaultdict annotations = json.loads(sys.stdin.read()) stats = defaultdict(lambda: defaultdict(float)) fo
r annotation in annotations: show = '_'.join(annotation['name'].split('_')[:2]) stats['show'][show] += 1 stats['shots']['num'] += 1 stats['split'][annotation['split']] += 1 for subshot in annotation['subshots']: stats['subshots']['num'] += 1 stats['subshots'][subshot['type']] += 1 ...
!= None: stats['pose'][person['pose']] += 1 stats['pose']['all'] += 1 if person['location'] != None: stats['location'][person['location']] += 1 stats['location']['all'] += 1 for show in sorted(stats['show'], key=lambda x: -stats['show'][x]): ...
Kloenk/GarrysModserver
GModServer/StartServer.py
Python
apache-2.0
1,006
0.011928
#!/usr/bin/env python3 from GModServer import Variables import os def StartGarrysModServer(steanApiAuthKey=Variables.SteamApiAuthKey, steamWorkShopID=Variables.SteamWorkShopId, serverGamemode=Variables.ServerGamemode, serverDefaultMap=Variables.ServerDefaultMap, serve...
rt " \ "%s" % (serverRunFile, serverMaxPl
ayer, steanApiAuthKey, steamWorkShopID, serverDefaultMap, serverGamemode, serverPort) if(debug==True): print(Command) os.system(Command) #start gMod server if __name__ == '__main__': from PythonServerKernel.Exceptions import RunnedFromFalseFile rai...
dlcs/starsky
app/tests/test_metadata_width_height.py
Python
mit
1,410
0.002128
import unittest import starsky_ingest class TextMetadataWidthHeight(unittest.TestCase): def test_hocr(self): hocr = open('app/tests/fixtures/vet1.html').read() width, height, canvas_width, canvas_height = starsky_ingest.Starsky.get_width_height(hocr, 'hocr', "https://dlcs.io/iiif-img/50/1/000214...
sertEqual(2849, canvas_height) def test_hocr_nosize(self): hocr = open('app/tests/fixtures/ocropus_trained.html').read() width, height, canvas_width, canvas_height = starsky_ingest.Starsky.get_width_height(hocr, 'hocr', "https://dlcs.io/iiif-img/50/1/000214ef-74f3-4ec2-9a5f-3b79f50fc500") ...
29, canvas_width) self.assertEqual(2849, canvas_height) def test_alto(self): alto = open('app/tests/fixtures/b20402533_0010.xml').read() width, height, canvas_width, canvas_height = starsky_ingest.Starsky.get_width_height(alto, 'alto', "https://dlcs.io/iiif-img/50/1/000214ef-74f3-4ec2-9a5f...
ENCODE-DCC/snovault
src/snowflakes/audit/__init__.py
Python
mit
41
0
def includeme(config):
config.scan()
joefutrelle/pocean-core
pocean/__init__.py
Python
mit
164
0
#!python
# coding=utf-8 # Package level logger import logging logger = logging.getLogger("pocean") logger.addHandler(logging.NullHandler()) __version__
= "1.0.0"
CooperLuan/devops.notes
taobao/top/api/rest/ItempropsGetRequest.py
Python
mit
606
0.034653
''' Created by auto_sdk on 2014-12-17 17:22:51 ''' from top.api.bas
e import RestApi class ItempropsGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.attr_keys = None self.child_path = None self.cid = None self.fields = None self.is_color_prop = None self.is_enum_prop = None self.is_input_prop...
pid = None self.type = None def getapiname(self): return 'taobao.itemprops.get'
arviz-devs/arviz
doc/logo/generate_logo.py
Python
apache-2.0
1,282
0.00078
import matplotlib import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import PathPatch from matplotlib.path import Path from matplotlib.transforms import Bbox from scipy import stats x = np.linspace(0, 1, 200) pd
fx = stats.beta(2, 5).pdf(x) path = Path(np.array([x, pdfx]).transpose()) patch = PathPatch(path, facecolor="none", alpha=0) plt.gca().add_patch(patch) cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#00bfbf", "#00bfbf", "#126a8a"]) im = plt.imshow( np.array([[1, 0, 0], [1, 1, 0]]), cmap=cma...
interpolation="bicubic", origin="lower", extent=[0, 1, 0.0, 5], aspect="auto", clip_path=patch, clip_on=True, ) plt.axis("off") plt.ylim(0, 5.5) plt.xlim(0, 0.9) bbox = Bbox([[0.75, 0.5], [5.4, 2.2]]) # plt.savefig('logo_00.png', dpi=300, bbox_inches=bbox, transparent=True) plt.text( x=0.0...
yCanta/yCanta
windows-build.py
Python
unlicense
2,677
0.010086
#!/usr/env python import os import sys import shutil import tempfile if os.name != 'nt': print 'Windows only!' sys.exit(1) if not len(sys.argv) == 3: print 'USAGE: %s PortablePythonDir output-dir' % sys.argv[0] print ' Example: D:\yCanta>..\PortablePython\Python-Portable.exe windows-build.py d:\PortablePyth...
rns(*exclude)) shutil.copytree(ppy
dir, os.path.join(workdir, 'PortablePython')) print 'Creating launcher script' launcher = open(os.path.join(workdir, 'yCanta.bat'), 'w') launcher.write(r'''cd yCanta ..\PortablePython\Python-Portable.exe start-webapp.py --start-browser '''.rstrip()) launcher.close() print 'Installing packages into portable python env...
smutt/WRL
topThick.py
Python
gpl-3.0
2,656
0.016943
#!/usr/bin/python # The file is part of the WRL Project. # # The WRL Project 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. # # ...
n tld['domains']: dbg(d + "." + tld['name']) dbg(tld['name'] + ": " + str(tld['size'])) tlds.append(tld) tlds.sort(key=lambda tld: tld['size'], reverse=True) for ii in xrange(numTopTLDs): # Find FQDN of whois server
d = dns.resolver.Resolver() try: resp = d.query(tlds[ii]['name'] + serverZone, 'CNAME') if len(resp.rrset) < 1: whois = 'UNKNOWN' else: whois = str(resp.rrset[0]).strip('.') except: whois = 'UNKNOWN' s = whois + ',' for dom in tlds[ii]['domains']: s += dom + '.' + tlds[ii]['nam...
tinkererr/projecteulerpython
3.py
Python
unlicense
136
0.022059
factors = lambda x: [y for y in reversed(range(2,round(x/2)+1)) if x % y == 0 and len(factors(y)) == 0] print(factors(600851475143)[0]
)
Tong-Chen/scikit-learn
sklearn/metrics/scorer.py
Python
bsd-3-clause
10,407
0.000096
""" The :mod:`sklearn.metrics.scorer` submodule implements a flexible interface for model selection and evaluation using arbitrary score functions. A scorer object is a callable that can be passed to :class:`sklearn.grid_search.GridSearchCV` or :func:`sklearn.cross_validation.cross_val_score` as the ``scoring`` parame...
a and ``y`` is the ground truth labeling (or ``None`` in the case of unsupervised models). """ # Authors: Andreas Mueller <[email protected]> # Lars Buitinck <L.J.Buitinck
@uva.nl> # Arnaud Joly <[email protected]> # License: Simplified BSD from abc import ABCMeta, abstractmethod from warnings import warn import numpy as np from . import (r2_score, mean_squared_error, accuracy_score, f1_score, roc_auc_score, average_precision_score, precision_score, ...
hmvp/python-tdbus
lib/tdbus/gevent.py
Python
mit
4,066
0.000492
# # This file is part of python-tdbus. Python-tdbus is free software # available under the terms of the MIT license. See the file "LICENSE" that # was provided together with this source file for the licensing terms. # # Copyright (c) 2012 the python-tdbus authors. See the file "AUTHORS" for a # complete list. from __f...
tch.handle(flags) self._hub.loop.run_callback(self._handle_dispatch, self._connection) def add_timeout(self, timeout): interval = timeout.get_interval() event = get_hub().loop.timer(interval / 1000, interval / 1000) if timeout.get_enabled(): event.start(self._handle_time...
# Currently (June 2012) gevent does not support reading or changing # the interval of a timer. Libdbus however expects it an change the # interval, so we store it separately outside the event. timeout.set_data((interval, event)) def remove_timeout(self, timeout): interval, ...
openqt/algorithms
leetcode/python/lc414-third-maximum-number.py
Python
gpl-3.0
1,193
0.015926
# coding=utf-8 import unittest """414. Third Maximum Number https://leetcode.com/problems/third-maximum-number/description/
Given a **non-empty** array of integers, return the **third** maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). **Example 1:** **Input:** [3, 2, 1] **Output:** 1
**Explanation:** The third maximum is 1. **Example 2:** **Input:** [1, 2] **Output:** 2 **Explanation:** The third maximum does not exist, so the maximum (2) is returned instead. **Example 3:** **Input:** [2, 2, 3, 1] **Output:...
espressif/esp-idf
examples/system/esp_event/user_event_loops/example_test.py
Python
apache-2.0
1,311
0.003051
from __future__ import print_function import ttfw_idf TASK_ITERATION_LIMIT = 10 TASK_ITERATION_POSTING = 'posting TASK_EVENTS:TASK_ITERATION_EVENT to {}, iteration {} out of ' + str(TASK_ITERATION_LIMIT) TASK_ITERATION_HANDLING = 'handling TASK_EVENTS:TASK_ITERATION_EVENT from {}, iteration {}' @ttfw_idf.idf_examp...
on)) print('Posted iteration {} to {}'.format(iteratio
n, loop)) dut.expect(TASK_ITERATION_HANDLING.format(loop, iteration)) print('Handled iteration {} from {}'.format(iteration, loop)) dut.expect('deleting task event source') print('Deleted task event source') if __name__ == '__main__': test_user_event_loops_example()
Arkhash/arkhash
contrib/wallettools/walletchangepass.py
Python
mit
219
0.004566
from jsonrpc import ServiceProxy access = ServiceProxy("http://127.0.0.1:2979") pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassph
rasechan
ge(pwd, pwd2)
thammegowda/incubator-joshua
scripts/training/run_tuner.py
Python
apache-2.0
18,921
0.004334
#!/usr/bin/env python # -*- coding: utf-8 -*- # # 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,...
(not working) #-m Meteor en lowercase '0.5 1.0 0.5 0.5' 'exact stem synonym paraphrase' '1.0 0.5 0.5 0.5' #CMU meteor interface # maximum PRO iterations -maxIt <ITERATIONS> # file containing commands to run decoder -cmd <DECODER_COMMAN
D> # file prodcued by decoder -decOut <DECODER_OUTPUT> # decoder config file -dcfg <DECODER_CONFIG> # size of N-best list -N 300 # verbosity level (0-2; higher value => more verbose) -v 1 #use one of the classifiers(and the corresponding parameter setting) below: #1.perceptron paramters -classifierClass joshua...
phil-mansfield/gotetra
render/scripts/add_densities.py
Python
mit
206
0
import numpy as np import sys width = int(sys.argv[1]) out = sys.argv[2] inputs = sys.argv[3:] grid = np.zeros(width
* width * width) for fname in inputs: grid
+= np.fromfile(fname) grid.tofile(out)
evernym/zeno
plenum/test/node_request/test_propagate/helper.py
Python
apache-2.0
377
0.005305
from plenum.test.spy_helpers import get_coun
t def sum_of_request_propagates(node): return get_count(node.
replicas[0]._ordering_service, node.replicas[0]._ordering_service._request_propagates_if_needed) + \ get_count(node.replicas[1]._ordering_service, node.replicas[1]._ordering_service._request_propagates_if_needed)
metno/EVA
eva/rest/__init__.py
Python
gpl-2.0
5,891
0.003395
""" RESTful API for controlling and monitoring EVA. """ import eva import eva.globe import eva.gpg import eva.rest.resources import falcon import json import re import wsgiref.simple_server class RequireJSON(object): def process_request(self, req, resp): if not req.client_accepts_json: rais...
signature def _check_signature(self, payload, signature): checker = eva.gpg.GPGSignatureChecker(payload, signature) result = checker.verify() if result.exit_code != 0: self.logger.warning('GPG verification of request failed: %s', result.stderr[0]) for line in result...
raise falcon.HTTPUnauthorized('GPG verification of request failed.') if result.key_id is None: self.logger.warning('GPG key ID not parsed correctly from GPG output, dropping request.') raise falcon.HTTPUnauthorized('GPG verification of request failed.') self.logger...
billiob/papyon
papyon/msnp2p/session.py
Python
gpl-2.0
11,748
0.005958
# -*- coding: utf-8 -*- # # papyon - a python client library for Msn # # Copyright (C) 2007 Ali Sabil <[email protected]> # Copyright (C) 2008 Richard Spiers <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
self._id) self._respond_transreq(transreq, 603, body) self._dispose() def _close(self, context=None, reason=None): body = SLPSessionCloseBody(context=context, session_id=self._id, reason=reason, s_channel_state=0) self._cseq = 0 self._branch = "{%s}" % uuid.u...
, branch=self._branch, cseq=self._cseq, call_id=self._call_id) message.body = body self._send_slp_message(message) self._dispose() def _close_end_points(self, status): """Send BYE to other end points; this client already answered. ...
opennode/nodeconductor-assembly-waldur
src/waldur_geo_ip/views.py
Python
mit
706
0
fro
m rest_framework import status, views from rest_framework.response import Response from waldur_core.core.utils import get_lat_lon_from_address from . import serializers class GeocodeViewSet(views.APIView): def get(self, request):
serializer = serializers.GeoCodeSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) address = serializer.validated_data['address'] lat_lon = get_lat_lon_from_address(address) if lat_lon: return Response( {'latitude': lat_lo...
arielisidro/myprograms
python/practice/ExcelColumns.py
Python
gpl-2.0
2,439
0.02624
import string def fillChars(chars): for i in string.ascii_lowercase: chars.append(i) def getColumnNumber(): columnNumber=int(raw_input("Please input cell number: ")) return columnNumber def printColumns(chars): printBlank=True counter=1 for c0 in chars...
entColumn(computeColumn(getCo
lumnNumber())) printEquivalentColumn(computeColumn(getColumnNumber(),[]))
vmanoria/bluemix-hue-filebrowser
hue-3.8.1-bluemix/desktop/core/ext-py/configobj/validate.py
Python
gpl-2.0
46,768
0.003507
# validate.py # A Validator object # Copyright (C) 2005 Michael Foord, Mark Andrews, Nicola Larosa # E-mail: fuzzyman AT voidspace DOT org DOT uk # mark AT la-la DOT com # nico AT tekNico DOT net # This software is licensed under the terms of the BSD license. # http://www.voidspace.org.uk/python/licens...
presented by a dotted-quad string, i.e. '1.2.3.4'. * 'string': matches any string. Takes optional keyword args 'min' and 'max' to specify
min and max lengths of the string. * 'list': matches any list. Takes optional keyword args 'min', and 'max' to specify min and max sizes of the list. (Always returns a list.) * 'tuple': matches any tuple. Takes optional keyword args 'min', and 'max' to specify...
burakbayramli/classnotes
sk/2019/07/test_rocket1.py
Python
gpl-3.0
1,843
0.006511
from rocketlander import RocketLander from constants import LEFT_GROUND_CONTACT, RIGHT_GROUND_CONTACT import numpy as np import pyglet if __name__ == "__main__": # Settings holds all the settings for the rocket lander environment. settings = {'Side Engines': True, 'Clouds': True, ...
aw_marker(env.landing_coordinates[0], env.landing_coordinates[1])
# Refresh render env.refresh(render=False) # When should the barge move? Water movement, dynamics etc can be simulated here. if s[LEFT_GROUND_CONTACT] == 0 and s[RIGHT_GROUND_CONTACT] == 0: env.move_barge_randomly(0.05, left_or_right_barge_movement) ...
ATIX-AG/foreman-ansible-modules
plugins/modules/architecture.py
Python
gpl-3.0
3,245
0.000924
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2019 Manisha Singhal (ATIX AG) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
min" password: "changeme" state: present - name: "Delete an Architecture" theforeman.foreman.architecture: name: "i386" server_url: "https://foreman.example.com" username: "admin" password: "changeme" state: absent ''' RETURN = ''' entity: description: Final state of the affected entit...
tectures. type: list elements: dict contains: id: description: Database id of the architecture. type: int name: description: Name of the architecture. type: str operatinsystem_ids: description: Database ids of associated operati...
foreveremain/common-workflow-language
reference/cwltool/expression.py
Python
apache-2.0
2,977
0.004703
import docker import subprocess import json from aslist import aslist import logging import os from process import WorkflowException import process import yaml import avro_ld.validate as validate import avro_ld.ref_resolver _logger = logging.getLogger("cwltool") def exeval(ex, jobinput, requirements, outdir, tmpdir, ...
= ["docker", "run", "-i", "--rm", img_id] exdefs = [] for exdef in r.get("engineConfig", []): if isinstance(exdef, dict) and "ref" in exdef: with open(exdef["ref"][7:]) as f: exdefs.append(f.read()) elif isinstance(exde...
binput, "context": context, "outdir": outdir, "tmpdir": tmpdir, } _logger.debug("Invoking expression engine %s with %s", runtime + aslist(r["engineCommand"]), json.dumps(inp, ind...
jovanpacheco/todo-eureka
eureka/list/urls.py
Python
gpl-3.0
2,662
0.034936
from django.conf.urls import url,include from django.views.decorators.csrf import csrf_exempt from django.views.generic import TemplateView from .views import ( ListRetriveView,ListRegisterView,ListUpdateView,ListDetailView,ListDeleteView, ItemListView,ItemRegisterView,ItemUpdateView,ItemDeleteView,ItemCompleted ) f...
)/item/(?P<uuid>[-\w]+)/completed$',viewsets.CompletedItemViewSet.as_view(), name='completed_item'), url(r'^api/(?P<version>[v1.]+)/item/(?P<uuid>[-\w]+)/$',view
sets.ObjectItemViewSet.as_view(),name='uuid_item'), url(r'^api/(?P<version>[v1.]+)/item/list/(?P<uuid>[-\w]+)/$',viewsets.AllItemForListViewSet.as_view(), name='items_by_list'), # register a new user by api url(r'^api/(?P<version>[v1.]+)/user/$',viewsets.RegistrationView.as_view(),name='new_user'), ]
ngageoint/scale
scale/messaging/backends/backend.py
Python
apache-2.0
2,030
0.005419
from abc import ABCMeta, abstractmethod from django.conf import settings from util.broker import BrokerDetails class MessagingBackend(object): __metaclass__ = ABCMeta def __init__(self, backend_type): """Instantiates backend specific settings """ # Unique type of MessagingBackend, ...
at if a large number of messages are to be retrieved it be done directly in a single function call. Implementing function must yield messages from backend. Messages must be in dict form. It is also the responsibility of the function to handle a boolean response and appropriately acknowl...
Generator[dict] """ @abstractmethod def get_queue_size(self): """Gets the current length of the queue :return: number of messages in the queue :rtype: int """
alex/django-paging
paging/helpers.py
Python
bsd-3-clause
652
0.006135
from paging.paginators import * def paginate(request, queryset_or_list, per_page=25, endless=True): if endless: paginator_class = EndlessPaginator else: paginator_class = BetterPaginator paginator = paginator_class(queryset_or_list, per_page) query_dict = request.GET.copy() ...
r, TypeError): page = 1 if page < 1:
page = 1 context = { 'query_string': query_dict.urlencode(), 'paginator': paginator.get_context(page), } return context
jawilson/home-assistant
homeassistant/components/wled/models.py
Python
apache-2.0
875
0
"""Models for WLED.""" from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import WLEDDataUpdateCoordinator class WLEDEntity(CoordinatorEntity): """Defines a base WLED entity.""" coor
dinator: WLEDDataUpdateCoordinator @property def device_info(self) -> DeviceInfo: """Return device information about this WLED device.""" return DeviceInfo( identifiers={(DOMAIN, self.coordinator.data.info.mac_address)}, name=self.coordinator.data.info.name, ...
or.data.info.product, sw_version=str(self.coordinator.data.info.version), configuration_url=f"http://{self.coordinator.wled.host}", )
tiagocoutinho/bliss
bliss/controllers/motors/slitbox.py
Python
lgpl-3.0
1,530
0.000654
""" One calculation and two real motors. The calculation motor has the position of the motor tagged as first. The real motor tagged as second differs from the first by a fraction. orientation: label (horizontal | vertical) of the orientation of the motors. fraction: the difference [mm] between the first and the second...
alcController.__init__(self, *args, **kwargs) self.orientation = str(self.config.get("orientation")) def calc_from_real(self, positions_dict): return {self.orientation: positions_dict["first"]} def calc_to_real(self, positions_dict): fraction = float(self.config.get("fraction")) ...
return {"first": pos, "second": pos + fraction}
NirBenTalLab/proorigami-cde-package
cde-root/usr/local/apps/inkscape/share/inkscape/extensions/export_gimp_palette.py
Python
mit
1,346
0.021545
#!/usr/bin/env python ''' Author: Jos Hirth, kaioa.com License: GNU General Public License - http://www.gnu.or
g/licenses/gpl.html Warranty: see above ''' DOCNAME='sodipodi:docname' import sys, simplestyle try: from xml.dom.minidom import parse except: sys.exit('The export_gpl.py modu
le requires PyXML. Please download the latest version from <http://pyxml.sourceforge.net/>.') colortags=(u'fill',u'stroke',u'stop-color',u'flood-color',u'lighting-color') colors={} def walk(node): checkStyle(node) if node.hasChildNodes(): childs=node.childNodes for child in childs: ...
5StevenWu/Coursepy
L08/网络编程3.2粘包/client端.py
Python
apache-2.0
1,009
0.024277
#!/usr/bin/env python # -*- coding:utf-8 -*- '''''' ''' 此处接收分段 先接收大小 然后分段接收数据 ''' import socket,struct,json phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #等同于服务端 phone.connect(('
127.0.0.1',8080)) #拨通电话 注意此处是一个元组的形式 while True: cmd=input('>>:').strip() if not cmd:continue phone.send(cmd.encode('utf-8')) #转为二进制发出去 print('ready to recv message') '''先收报头的长度''' head_struct = phone.recv(4) head_len = struct.unpack('i',head_struct)[0] head_bytes = phone.recv(head...
total_size = head_dic['total_size'] recv_size=0 data=b'' while recv_size < total_size: recv_data=phone.recv(1024) data+=recv_data recv_size+=len(recv_data) print(data.decode('gbk')) phone.close()
pferreir/indico
indico/modules/admin/views.py
Python
mit
1,087
0.00092
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE fil
e for more details. from indico.util.i18n import _ from indico.web.breadcrumbs import render_breadcrumbs from indico.web.flask.util import url_for from indico.web.menu import get_menu_item from indico.web.views import WPDecorat
ed, WPJinjaMixin class WPAdmin(WPJinjaMixin, WPDecorated): """Base class for admin pages.""" def __init__(self, rh, active_menu_item=None, **kwargs): kwargs['active_menu_item'] = active_menu_item or self.sidemenu_option WPDecorated.__init__(self, rh, **kwargs) def _get_breadcrumbs(self):...
Infinidat/infi.pyutils
infi/pyutils/functors/pass_.py
Python
bsd-3-clause
198
0.015152
from .functor import Functor class _
PASS(Functor): def __call__(self, *_, **__): pass __enter__ = __exit__ = __call__ def __repr__(self):
return '<PASS>' PASS = _PASS()
Asparagirl/ArchiveBot
pipeline/archivebot/seesaw/wpullargs_test.py
Python
mit
2,884
0.003814
from os import environ as env import unittest from .wpull import WpullArgs from seesaw.item import Item # taken form pipeline/pipeline.py if 'WARC_MAX_SIZE' in env: WARC_MAX_SIZE = env['WARC_MAX_SIZE'] else: WARC_MAX_SIZE = '5368709120' def joined(args): return str.join(' ', args) class TestWpullArgs(un...
finished_warcs_dir='/lost+found/', warc_max_size=WARC_MAX_SIZE ) def test_user_agent_can_be_set(self): self.item['user_agent'] = 'Frobinator/20.1' self.assertIn('-U Frobinator/20.1', joined(self.args.realize(self.item))) def test_youtube_dl_activation(self): ...
ertIn('--youtube-dl', joined(self.args.realize(self.item))) def test_uses_default_user_agent(self): self.assertIn('-U Default/1', joined(self.args.realize(self.item))) def test_recursive_fetch_settings(self): self.item['recursive'] = True self.item['depth'] = 'inf' cmdline = j...
ClydeSpace-GroundStation/GroundStation
GNURadio/OOT_Modules/gr-ax25/python/__init__.py
Python
mit
1,133
0.002648
# # Copyright 2008,2009 Free Software Foundation, Inc. # # This application 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, or (at y
our option) # any later version. # # This application is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of
the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # The presence of this file turns this directory into a Python package ''' This is the GNU Radio AX25 module. Place your Python package descri...
pyrrho314/recipesystem
trunk/dontload-astrodata_Gemini/ADCONFIG_Gemini/lookups/NIRI/NIRISpecDict.py
Python
mpl-2.0
1,538
0.028609
niriSpecDict = { # Database for nprepare.cl # Date: 2004 July 6 # Author: Joe Jensen, Gemini Observatory # The long 6-pix and 4-pix centered slits are currently installed # # Array characteristics "readnoise" : 70, # electrons (1 read pair, 1 digital av...
hallowbias" : -0.6, # detector bias (V) "deepbias" : -0.87, # detector bias (V) "linearlimit" : 0.7, # non-linear regime (fraction of saturation) # # Camera+FPmask SPECSEC1 SPECSEC2 SPECSEC3 # "f6f6-2pix_G5211" : ( "[1:1...
3" : ( "[1:1024,1:1024]" , "none", "none" ), "f6f6-2pixBl_G5214" : ( "[1:1024,276:700]" , "none", "none" ), "f6f6-4pixBl_G5215" : ( "[1:1024,276:700]" , "none", "none" ), "f6f6-6pixBl_G5216" : ( "[1:1024,276:700]" , "none", "none" ), "f6f6-4pix_G5222" : ( "[1:1024...
samuelmaudo/yepes
yepes/test/plugins/base.py
Python
bsd-3-clause
8,371
0.000717
# -*- coding:utf-8 -*- from __future__ import unicode_literals from argparse import ArgumentError import textwrap from warnings import warn class Plugin(object): """ Base class for test plugins. It's recommended but not *necessary* to subclass this class to create a plugin, but all plugins *must* implem...
self): """ Return help for this plugin. This will be output as the help section of the --with-$name option that enables the plugin. """ docs = self.__class__.__doc__ if docs: # doc sections are often indented; compress the spaces return textwrap.de...
able)' class PluginInterface(object): """ PluginInterface describes the plugin API. Do not subclass or use this class directly. """ def __new__(cls, *arg, **kw): raise TypeError('PluginInterface class is for documentation only') def addArguments(self, parser): """ Call...
0xSteve/detection_learning
distest/helpers.py
Python
apache-2.0
1,230
0
'''Some helper functions.''' def make_p(count): '''A helper function that generates a probaiblity vector, p, based on the number of actions.''' a = [] for i in range(count): a.append(1.0 / count) return a def subtract_nonzero(array, amount): for i in range(len(array)): if(...
(p_ve
ctor)): sigma += p_vector[i] cdf.append(sigma) return cdf def get_index(desired_action, cdf_array): '''Given a desired action get the action that corresponds to it from the cdf of the action probability vector.''' index = 0 # Return the first action as default. for i in range(l...
aboyett/blockdiag
src/blockdiag/tests/test_builder_node.py
Python
apache-2.0
6,607
0
# -*- coding: utf-8 -*- from collections import defaultdict from blockdiag.tests.utils import BuilderTestCase class TestBuilderNode(BuilderTestCase): def test_single_node_diagram(self): diagram = self.build('single_node.diag') self.assertEqual(1, len(diagram.nodes)) self.assertEqual(0, l...
'box'}) def test_node_has_multilined_label_diagram(self): diagram = self.build('node_has_multilined_label.diag') self.assertNodeXY(diagram, {'A
': (0, 0), 'Z': (0, 1)}) self.assertNodeLabel(diagram, {'A': "foo\nbar", 'Z': 'Z'}) def test_quoted_node_id_diagram(self): diagram = self.build('quoted_node_id.diag') self.assertNodeXY(diagram, {'A': (0, 0), "'A'": (1, 0), 'B': (2, 0), 'Z': (0, 1)}) ...
tonyduckles/svn2svn
svnreplay.py
Python
gpl-3.0
95
0
#!/usr/bin/env python impo
rt sys from svn2svn.run.svnreplay import main sys.exit(main
() or 0)
dmitriyminer/webgpio
webgpio/auth/views.py
Python
mit
2,048
0
import logging import aiohttp_jinja2 from aiohttp import web from aiohttp_session import get_session from .sa import check_password, user_exist, create_user auth_logger = logging.getLogger('auth.logger') @aiohttp_jinja2.template('auth/login.html') async def login(request): session = await get_session(request) ...
context['errors'] = ['Wrong email or password'] return context @aiohttp_jinja2.template('auth/register.
html') async def register(request): data = await request.post() context = dict() if all([data, data.get('email'), data.get('passwd'), data.get('passwd') == data.get('passwd1')]): already_exist = await user_exist(request.app['db'], **data) if already_exist: context['er...
dyrock/trafficserver
tests/gold_tests/headers/hsts.test.py
Python
apache-2.0
2,907
0.002408
''' Test the hsts response header. ''' # 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, ...
e=server.key' ) # Test 1 - 200 Response tr = Test.AddTestRun() tr.Processes.Default.St
artBefore(server) tr.Processes.Default.StartBefore(Test.Processes.ts) tr.Processes.Default.Command = ( 'curl -s -D - --verbose --ipv4 --http1.1 --insecure --header "Host: {0}" https://localhost:{1}' .format('www.example.com', ts.Variables.ssl_port) ) tr.Processes.Default.ReturnCode = 0 tr.Processes.Default.Stre...
cloudmesh/management
tests/test_02_user_list.py
Python
apache-2.0
967
0.003102
from cloudmesh_database.dbconn import get_mongo_db, get_mongo_dbname_from_collection, DBConnFactory from cloudmesh_base.util import HEADING from cloudmesh_management.user import Users from cloudmesh_management.mongo import Mongo class TestListUsers: yaml_dir = "~/.cloudmesh_yaml"
def setup(self): # HEADING() db_name = get_mongo_dbname_from_collection("manage") if db_name: meta = {'db_alias': db_name} obj = Mongo() obj.check_mongo() get_mongo_db("manage", DBConnFactory.TYPE_MONGOENGINE) pass def teardown(self):
# HEADING() pass def test_listusers(self): HEADING() """ Test to list users in default format followed by JSON format """ user = Users() print "Listing users in default format" user.list_users() print "Listing users in JSON format" ...
nylas/sync-engine
migrations/versions/018_message_contact_association.py
Python
agpl-3.0
1,215
0.001646
"""message contact association Revision ID: 223041bb858b Revises: 2c9f3a06de09 Create Date: 2014-04-28 23:52:05.449401 """ # revision identifiers, used by Alembic. revision = '223041bb858b' down_revision = '2c9f3a06de09' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( '...
.ForeignKeyConstraint(['contact_id'], ['contact.id'], ), sa.ForeignKeyConstraint(['message_id'], ['message.id'], ), sa.PrimaryKeyConstraint('id', 'contact_id', 'message_id') ) # Yes, this is a terrible hack. But tools/rer
ank_contacts.py already # contains a script to process contacts from messages, so it's very # expedient. import sys sys.path.append('./tools') from rerank_contacts import rerank_contacts rerank_contacts() def downgrade(): op.drop_table('messagecontactassociation')
micromagnetics/magnum.fe
tests/cache_test.py
Python
lgpl-3.0
1,521
0.015779
import unittest from magnumfe import * set_log_active(False) class CacheTest(unittest.TestCase): def test_initial_update(self): mesh = UnitCubeMesh(1,1,1) state = State(mesh) cache = Cache() self.assertTrue(cache.requires_update(state)) def test_change_state(self): mesh = UnitCubeMesh(1,1,1...
.0, 0.0, 0.0)), j = Constant((0.0, 0.0, 0.0))) cache = Cache("m", "t") count = 0 if cache.requires_update(state): count += 1 self.assertEqual(1, count) if cache.requires_update(state): count += 1 self.assertEqual(1, count) state.t = 1.0 if cache.requires_update(state): count += 1 ...
l(2, count) state.m = Constant((0.0, 1.0, 0.0)) if cache.requires_update(state): count += 1 self.assertEqual(3, count) if cache.requires_update(state): count += 1 self.assertEqual(3, count) state.j = Constant((1.0, 0.0, 0.0)) if cache.requires_update(state): count += 1 self.assertEqu...
KaranToor/MA450
google-cloud-sdk/lib/surface/container/node_pools/describe.py
Python
apache-2.0
1,997
0.003005
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
ject. It is mocked out in order to capture some information, but behaves like an ArgumentParser. """ flags.AddNodePoolNameArg(parser, 'The name of the node pool.') flags.AddNodePoolClusterFlag(parser, 'The name of the cluster.') def Run(self, args): """This is what gets called when the user...
amespace. All the arguments that were provided to this command invocation. Returns: Some value that we want to have printed later. """ adapter = self.context['api_adapter'] try: return adapter.GetNodePool(adapter.ParseNodePool(args.name)) except apitools_exceptions.HttpError as...
easmetz/inasafe
safe/impact_functions/ash/ash_raster_population/impact_function.py
Python
gpl-3.0
7,502
0
# coding=utf-8 """InaSAFE Disaster risk tool by Australian Aid - Ash Raster on Population Impact Function Contact : [email protected] .. note:: 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 Softwa...
interval_classes[i], tr('High Population [%i people/cell]' % classes[i])) else: label = c
reate_label(interval_classes[i]) style_class['label'] = label style_class['quantity'] = classes[i] style_class['transparency'] = 0 style_class['colour'] = colours[i] style_classes.append(style_class) style_info = dict( target_field=None, ...
abhijithanilkumar/CollegeSeatAllocation
src/CollegeSeatAllocation/settings/base.py
Python
mit
4,017
0.001494
""" Django settings for CollegeSeatAllocation project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from django.core.urlresolvers import reverse_lazy from os.pat...
_), 'local.env') if exists(env_file): environ.Env.read_env(str(env_file)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Raises ImproperlyConfigured exceptio...
RET_KEY') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.auth', 'django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authtools', 'cr...
googleapis/python-compute
google/cloud/compute_v1/services/service_attachments/client.py
Python
apache-2.0
59,785
0.001321
# -*- coding: utf-8 -*- # Copyright 2022 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...
st"] = ServiceAttachmentsRestTransport def get_transport_class( cls, label: str = None, ) -> Type[ServiceAttachmentsTransport]: """Returns an appropriate transport class. Args: labe
l: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry...
kakunbsc/enigma2.4
lib/python/Components/Network.py
Python
gpl-2.0
20,526
0.034883
from os import system, popen, path as os_path, listdir from re import compile as re_compile, search as re_search from socket import * from enigma import eConsoleAppContainer from Components.Console import Console from Components.PluginComponent import plugins from Plugins.Plugin import PluginDescriptor class Network: ...
lf.deactivateConsole = Console() self.deactivateInterfaceConsole = Console() self.activateConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.config_ready = None self.getInterfaces() def onRemoteRootFS(self): fp = file('/proc/mounts', 'r') mounts = fp.readlines() ...
1] == '/' and (parts[2] == 'nfs' or parts[2] == 'smbfs'): return True return False def getInterfaces(self, callback = None): devicesPattern = re_compile('[a-z]+[0-9]+') self.configuredInterfaces = [] fp = file('/proc/net/dev', 'r') result = fp.readlines() fp.close() for line in result: try: d...
n054/qBittorrent
src/searchengine/nova/engines/torrentz.py
Python
gpl-2.0
5,201
0.003076
#VERSION: 2.12 #AUTHORS: Diego de las Heras ([email protected]) # Redistribution and us
e 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 conditions and the following disclaimer. # * Redistributions in binary form must reproduce th...
documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOL...
ChantyTaguan/zds-site
zds/forum/admin.py
Python
gpl-3.0
1,098
0
from django.contrib import admin from zds.forum.models import ForumCategory, Forum, Post, Topic, TopicRead class TopicAdmin(admin.ModelAdmin): list_display = ("title", "author", "forum", "pubdate") list_filter = ("is_locked", "is_sticky") raw_id_fields = ("forum", "author", "last_message", "tags", "solve...
display = ("topic", "user") raw_id_fields = ("topic", "post", "user") search_fields = ("topic__title", "user__username") class PostAdmin(admin.ModelAdmin): list_display = ("topic", "author", "ip_address", "pubdate", "is_visible") list_filter = ("is_visible",) raw_id_fields = ("author", "editor") ...
ister(Forum) admin.site.register(Post, PostAdmin) admin.site.register(Topic, TopicAdmin) admin.site.register(TopicRead, TopicReadAdmin)
wogsland/QSTK
Homework/hw3.py
Python
bsd-3-clause
3,364
0.0217
''' Example call: python marketsim.py 1000000 orders.csv values.csv python hw3.py 1000000 orders.csv values.csv Example orders.csv: 2008, 12, 3, AAPL, BUY, 130 2008, 12, 8, AAPL, SELL, 130 2008, 12, 5, IBM, BUY, 50 Example values.csv: 2008, 12, 3, 1000000 2008, 12, 4, 1000010 2008, 12, 5, 1000250 ''' # QSTK Imports ...
import QSTK.qstkutil.DataAccess as da # Third Party Imports import datetime as dt import matplotlib.pyplot as plt import pandas as pd import numpy as np import math import csv import sys import copy import string if __name__ == '__main__': # 1. Read the dates and symbols startcash = int(sys.argv[1]) filename =...
symb_array.append(row[3].strip()) the_date = dt.datetime(int(row[0]), int(row[1]), int(row[2]), 16) dt_array.append(the_date) #the_date = row[0]+"-"+row[1]+"-"+row[2]+" 16:00:00" trade_array.append([row[3].strip(), row[4].strip(), row[5].strip(), the_date]) print dt_array dt_array = sorted(list(se...
SINGROUP/pycp2k
pycp2k/classes/_bse1.py
Python
lgpl-3.0
682
0.002933
from pycp2k.inputsection import InputSection class _bse1(InputSection): def __init__(self): InputSection.__init__(self) self.Num_z_vectors = None self.Threshold_min_trans = None self.Max_iter = None self._name = "BSE" self._keywords = {'Num_z_vectors':
'NUM_Z_VECTORS', 'Threshold_min_trans': '
THRESHOLD_MIN_TRANS', 'Max_iter': 'MAX_ITER'} self._aliases = {'Eps': 'Threshold_min_trans'} @property def Eps(self): """ See documentation for Threshold_min_trans """ return self.Threshold_min_trans @Eps.setter def Eps(self, value): self.Threshold_min_...
Akagi201/learning-python
json/json_mixed_data.py
Python
mit
762
0.001312
#!/usr/bin/env python # encoding: utf-8 import json decoder = json.JSONDecoder() def get_decoded_and_remainder(input_data): obj, end = decoder.raw_decode(input_data) remaining = input_data[end:] return (obj, end, remaining) encoded_object = '[{"a": "A", "c": 3.0, "b": [2, 4]}]' extra_text = 'This text...
encoded_object, extra_text])) print 'Object :', obj print 'End of parsed input :', end print 'Remaining text :', repr(remaining) print print 'JSON embedded:' try:
obj, end, remaining = get_decoded_and_remainder( ' '.join([extra_text, encoded_object, extra_text]) ) except ValueError, err: print 'ERROR:', err
C-o-r-E/OctoPrint
src/octoprint/server/api/printer.py
Python
agpl-3.0
9,354
0.027053
# coding=utf-8 __author__ = "Gina Häußge <[email protected]>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' from flask import request, jsonify, make_response import re from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, restricted_a...
initSdCard() elif command == "refresh": printer.refreshSdFiles() elif command == "release": printer.releaseSdCard() return NO_CONTENT @api.route("/printer/sd", methods=["GET"]
) def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) return jsonify(ready=printer.isSdReady()) ##~~ Commands @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): # TODO: document me if not prin...
DavidCain/mitoc-trips
ws/templatetags/medical_tags.py
Python
gpl-3.0
1,991
0.001005
from datetime import timedelta from django import template import ws.utils.dates as date_utils import ws.utils.perms as perm_utils from ws import forms from ws.utils.itinerary import get_cars register = template.Library() @register.inclusion_tag('for_templatetags/show_wimp.html') def show_wimp(wimp): return { ...
gned_up_participants.filter(signup__on_trip=True).select_related( 'emergency_info__emergency_contact' ) ), 'trip_leaders': ( trip.leaders.select_related('emergency_info__emergency_contact') ), 'cars': get_cars(trip), 'show_participants_if_n...
_utils.leader_on_trip(participant, trip), }
4shadoww/stabilizerbot
core/rules/ores.py
Python
mit
2,595
0.003083
from core.rule_core import * from core import yapi from core.config_loader import cur_conf class YunoModule: name = "ores" cfg_ver = None ores_api = yapi.ORES config = [ { "models": { "damaging": {"max_false": 0.15, "min_true": 0.8}, "goodfaith": ...
reversed(range(tries)): scores = self.ores_api.getScore([rev["revision"]["new"]])[cur_conf["core"]["lang"]+"wiki"]["scores"] revid_data = scores[str(rev["revision"]["new"])] for i
tem in revid_data: if "error" in revid_data[item] and "scores" not in revid_data[item]: if i <= 0: logger.error("failed to fetch ores revision data: %s" % str(revid_data)) return False else: break ...
ZeitOnline/zeit.content.dynamicfolder
src/zeit/content/dynamicfolder/browser/tests/test_folder.py
Python
bsd-3-clause
873
0
import zeit.cms.interfaces import zeit.cms.testing import zeit.content.dynamicfolder.testing class EditDynamicFolder(zeit.cms.testing.BrowserTestCase): layer = zeit.content.dynamicfolder.testing.DYNAMIC_LAYER def test_check_out_and_edit_folder(self): b = self.browser b.open('http://localhost...
vivi/repository/dynamicfolder') b.getLink('Checkout').click() b.getControl( 'Configuration file').value = 'http://xml.zeit.de/testcontent' b.getControl('Apply').click() self.assertEllipsis('...Updated on...', b.contents) b.getLink('Checkin').click() self.asser...
t.de/testcontent', folder.config_file.uniqueId)
texta-tk/texta
account/migrations/0001_initial.py
Python
gpl-3.0
909
0.0033
# Generated by Django 2.0.4 on 2019-01-10 11:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
grations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('auth_token', models.CharField(blank=True, default='', max_length=14)), ('email_confirmation_token', models.CharField(blank=True, default='...
to=settings.AUTH_USER_MODEL)), ], ), ]
onysos/django-nginx-config
django_nginx/management/commands/create_nginx_config.py
Python
mit
8,249
0.002669
# -*- coding: utf-8 -*- """ Created on 18 juil. 2013 """ from __future__ import unicode_literals import logging from django.core.management.base import BaseCommand, CommandError from django.conf import settings import sys import os from django.template import loader from django.template.context import Context import sh...
main.ext.d/switch_maintenance.sh" ], init=["django_sub.domain.ext"], systemd=[ "sub.domain.ext.service", "sub.domain.ext.socket"
], ) def handle(self, *args, **options): if len(args) > 0: dest = args[0] else: dest = "nginx_conf" socket = options["socket"] buildout = not options["buildout"] workon_home = options["workon_home"] if workon_home is None and not bu...
etamponi/emetrics
emetrics/evaluation/test_random_subsets_experiment.py
Python
gpl-2.0
2,356
0.002971
import pickle import unittest import numpy from sklearn.tree.tree import D
ecisionTreeClassifier from emetrics.correlation_s
core import CorrelationScore from emetrics.evaluation.random_subsets_experiment import RandomSubsetsExperiment __author__ = 'Emanuele Tamponi' class RandomSubsetsExperimentTest(unittest.TestCase): def test_results_in_shape(self): experiment = RandomSubsetsExperiment( dataset="aggregatio...
yannrouillard/weboob
modules/imdb/browser.py
Python
agpl-3.0
8,535
0.001054
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
. If not, see <http://www.gnu.org/licenses/>. from HTMLParser import HTMLParser from weboob.tools.browser import BaseBrowser, BrowserHTTPNotFound from weboob.capabilities.base import NotAvailable, NotLoaded from weboob.capabilities.cinema import Movie, Person from weboob.tools.json import json from .pages import Per...
r'] class ImdbBrowser(BaseBrowser): DOMAIN = 'www.imdb.com' PROTOCOL = 'http' ENCODING = 'utf-8' USER_AGENT = BaseBrowser.USER_AGENTS['wget'] PAGES = { 'http://www.imdb.com/title/tt[0-9]*/fullcredits.*': MovieCrewPage, 'http://www.imdb.com/title/tt[0-9]*/releaseinfo.*': ReleasePage...
lvdongbing/python-bileanclient
bileanclient/tests/unit/test_http.py
Python
apache-2.0
16,420
0.000914
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
n(self.endpoint, comm_err.message) def test_connection_refused(self): """ Should receive a CommunicationError if connection refused. And the error should list the host and port that refused the connection """ def cb(request, context): raise requests.exce...
tions.ConnectionError() path = '/events?limit=20' self.mock.get(self.endpoint + path, text=cb) comm_err = self.assertRaises(bileanclient.exc.CommunicationError, self.client.get, '/events?limit=20') self.assertIn...
edeposit/edeposit.amqp.rest
bin/edeposit_rest_runzeo.py
Python
mit
785
0.001274
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== import sys import os.path import subprocess sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../src/edeposit/amqp")) try: from rest import ...
from edeposit.amqp.rest import settings # Variables =================================================
================== assert settings.ZEO_SERVER_CONF_FILE, settings._format_error( "ZEO_SERVER_CONF_FILE", settings.ZEO_SERVER_CONF_FILE ) # Main program ================================================================ if __name__ == '__main__': subprocess.check_call(["runzeo", "-C", settings.ZEO_SERVER_CON...
endlessm/chromium-browser
third_party/catapult/systrace/profile_chrome/chrome_startup_tracing_agent_unittest.py
Python
bsd-3-clause
1,066
0.010319
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import j
son from profile_chrome import chrome_startup_tracing_agent from systrace import decorators from systrace.tracing_agents import agents_unittest class ChromeAgentTest(agents_unittest.BaseAgentTest): # TODO(washingtonp): This test seems to fail on the version of Android # currently on the Trybot servers (KTU84P), ...
agent on Android KTU84P. @decorators.Disabled def testTracing(self): agent = chrome_startup_tracing_agent.ChromeStartupTracingAgent( self.device, self.package_info, '', # webapk_package False, # cold 'https://www.google.com' # url ) try: agent.StartAgentTracing(No...
harshilasu/GraphicMelon
y/google-cloud-sdk/platform/gsutil/third_party/boto/tests/integration/swf/test_cert_verification.py
Python
gpl-3.0
1,553
0
# Copyright (c) 2012 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its affiliates. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software withou...
nittest from tests.integration import ServiceCertVerificationTe
st import boto.swf class SWFCertVerificationTest(unittest.TestCase, ServiceCertVerificationTest): swf = True regions = boto.swf.regions() def sample_service_call(self, conn): conn.list_domains('REGISTERED')