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
Clinical-Genomics/scout
tests/commands/view/test_view_collections_cmd.py
Python
bsd-3-clause
491
0.002037
# -*- coding: utf-8 -*-
from scout.commands import cli from scout.server.extensions import store def test_view_diseases(mock_app): """Test CLI that shows all collections in the database""" runner = mock_app.test_cli_runner() assert runner # Test CLI result = runner.invoke(cli, ["view", "collections"]) assert result...
PetroDE/control
control/tests/test_builder.py
Python
mit
11,309
0.000265
"""test the cli_builder module""" import unittest from control.cli_builder import builder, Argument from control.exceptions import ControlException class BuilderFormattingTests(unittest.TestCase): """ Tests to make sure that the builders correctly create newlines when they should. Tests to make sure...
ing any other functionality """ def test_bool_arg_removal(self): """ Test that passing a False to a boolean setter removes the option from output """ result = builder('build', pretty=False).tty(False) self.assertEqual(str(result), "docker...
.") result = result.tty(False) self.assertEqual(str(result), "docker build .") def test_list_arg_invalid_type_raises(self): """ Make sure that if something that doesn't boil down to a string raises an exception """ result = builder('r...
fevangelista/pyWicked
external/pybind11/tests/test_inheritance.py
Python
mit
1,876
0.002132
import pytest def test_inheritance(msg): from pybind11_tests import Pet, Dog, Rabbit, Hamster, dog_bark, pet_name_species roger = Rabbit('Rabbit') assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot" assert pet_name_species(roger) == "Rabbit is a parrot" polly = Pet('Polly', ...
import return_class_1, return_class_2, return_class_n, return_none assert type(return_
class_1()).__name__ == "DerivedClass1" assert type(return_class_2()).__name__ == "DerivedClass2" assert type(return_none()).__name__ == "NoneType" # Repeat these a few times in a random order to ensure no invalid caching is applied assert type(return_class_n(1)).__name__ == "DerivedClass1" assert ty...
cloudify-cosmo/cloudify-system-tests
cosmo_tester/resources/blueprints/service_composition/scripts/app-commit.py
Python
apache-2.0
544
0
#!/usr/bin/env python from cloudify import ctx ctx.logger.info("Committing application") # We determ
ine whether the operation should fail or not, by inspecting # the value of a runtime property called "fail_commit". # If it is set to "True", then we fail the execution in a non-recoverable # manner (i.e. this operation won't be automatically retried). fail_commit = ctx.instance.runtime_pr
operties.get('fail_commit', False) if fail_commit: raise Exception("Asked to fail the commit operation") ctx.logger.info("Committed application")
neilhan/tensorflow
tensorflow/python/training/supervisor_test.py
Python
apache-2.0
30,964
0.01153
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
h.exists(test_dir): shutil.rmtree(test_dir) return test_dir class SupervisorTest(tf.test.TestCase): def _wait_for_glob(self, pattern, timeout_secs): """Wait for a checkpoint file to appear. Args: pattern: A string. timeout_secs: How long to wait for in seconds
. """ end_time = time.time() + timeout_secs while time.time() < end_time: if len(tf.gfile.Glob(pattern)) >= 1: return time.sleep(0.05) self.assertFalse(True, "Glob never matched any file: %s" % pattern) # This test does not test much. def testBasics(self): logdir = _test_dir...
hpcleuven/easybuild-framework
easybuild/framework/easyconfig/format/version.py
Python
gpl-2.0
30,531
0.004225
# # # Copyright 2013-2016 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (...
raise EasyBuildError("Types don't match in comparison: %s, expect
ed %s", type(versop), self.__class__) return self.version == versop.version and self.operator == versop.operator and self.suffix == versop.suffix def __ne__(self, versop): """Is self not equal to versop""" return not self.__eq__(versop) def versop_regex(self, begin_end=True): "...
pelson/cartopy
lib/cartopy/examples/un_flag.py
Python
lgpl-3.0
7,435
0
""" UN Flag ------- A demonstration of the power of Matplotlib combined with cartopy's Azimuthal Equidistant projection to reproduce the UN flag. """ import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt from matplotlib.patches import PathPatch import matplotlib.path import mat...
e figure. blue_background = PathPatch(matplotlib.path.Path.unit_rectangle(), transform=fig.transFigure, color=blue, zorder=-1) fig.patches.append(blue_background) # Set up the Azimuth
al Equidistant and Plate Carree projections # for later use. az_eq = ccrs.AzimuthalEquidistant(central_latitude=90) pc = ccrs.PlateCarree() # Pick a suitable location for the map (which is in an Azimuthal # Equidistant projection). ax = fig.add_axes([0.25, 0.24, 0.5, 0.54], projection=az_eq, fr...
desenho-sw-g5/service_control
Trabalho_1/api/tests/views_test/profile_detail_view_test.py
Python
mit
2,944
0.003397
import json from django.test import TestCase from rest_framework.test import APIRequestFactory from rest_framework.test import force_authenticate from rest_framework import status from rest_framework.authtoken.models import Token from core.models import Profile, User from api.views import ProfileDetail from api.se...
file/', data=data, content_type='application/json') force_authenticate(request, user=self.
admin_user, token=self.admin_user.auth_token) response = self.view(request, pk=self.test_profile.id) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('user' in response.data) self.assertEqual(response.data['user']['email'], new_email) def test_delete_profi...
rosenvladimirov/addons
purchase_landed_cost_bg/models/__init__.py
Python
agpl-3.0
247
0
# -*- coding: ut
f-8 -*- # License AGPL-3 - See http://www.gnu.org/licenses/ag
pl-3 from . import account_invoice from . import purchase_expense_type from . import purchase_cost_distribution from . import purchase_order from . import stock_picking
8cylinder/tv-overlord
tvoverlord/search_providers/onethreethreesevenx_to.py
Python
gpl-3.0
4,729
0.001692
import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import requests from pprint import pprint as pp import click import concurrent.futures import socket from tvoverlord.config import Config class Provider(): name = '1337X' shortname = '13' # can only be 2 characters long pr...
tds = tr.find_all('td') try:
detail_url = tds[0].find_all('a')[1]['href'] title = tds[0].get_text(strip=True) seeds = tds[1].get_text(strip=True) size = tds[4].contents[0] except IndexError: continue search_data.append([detai...
AdamWill/anaconda
pyanaconda/ui/tui/spokes/warnings_spoke.py
Python
gpl-2.0
2,511
0.001593
# Ask vnc text spoke # # Copyright (C) 2013 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the...
pyanaconda.i18n import N_, _ from pyanaconda.iutil import
is_unsupported_hw from pyanaconda.product import productName import logging log = logging.getLogger("anaconda") __all__ = ["WarningsSpoke"] class WarningsSpoke(StandaloneTUISpoke): """ .. inheritance-diagram:: WarningsSpoke :parts: 3 """ title = N_("Warnings") preForHub = SummaryHub...
jcchoiling/learningPython
books/learn-python-the-hard-way/ex6_Strings_and_Text.py
Python
gpl-3.0
668
0.013473
#!/usr/bin
/env python # -*- coding: utf-8 -*- # Author: Janice Cheng x = "There are %d types of people." %10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." %(binary,do_not) print(x) print(y) print("I said: %r." %x) print("I also said: '%s'." %y) hilarious = False joke_evaluation = "Isn't that jo...
) """ 1) What is the difference between %r and %d when you can just use %r We use %r for debugging ,since it displays the 'raw' data of the variable, but we use %s and others for displaying to users. """
HIPS/optofit
examples/cython_demo.py
Python
gpl-2.0
4,626
0.01297
import numpy as np # Set the random seed for reproducibility seed = np.random.randint(2**16) print "Seed: ", seed np.random.seed(seed) import matplotlib.pyplot as plt from matplotlib.patches import Polygon from optofit.cneuron.compartment import Compartment, SquidCompartment from optofit.cneuron.channels import LeakC...
dd_child(kdr) # Initialize the model # body.initialize_offsets() squid_body = SquidCompartment(name='body', hypers=hypers) # Initialize the model D, I = squid_body.initialize_offsets() # Set the recording duration t_start = 0 t_stop = 100. dt = 0.01 t = np.arange(t_start, t_st...
t from 500-600ms inpt = np.zeros((T, I)) inpt[50/dt:60/dt,:] = 7. inpt += np.random.randn(T, I) # Set the initial distribution to be Gaussian around the steady state z0 = np.zeros(D) squid_body.steady_state(z0) init = GaussianInitialDistribution(z0, 0.1**2 * np.eye(D)) # Set the propos...
ActiveState/code
recipes/Python/576415_ctype_Enumeration_class/recipe-576415.py
Python
mit
1,430
0.006294
from ctypes import * class EnumerationType(type(c_uint)):
def __new__(metacls, name, bases, dict): if not "_members_" in dict: _members_ = {} for key,value in dict.items(): if not key.startswith("_"): _members_[key] = value dict["_members_"] = _members_ cls = type(c_uint).__new__(m
etacls, name, bases, dict) for key,value in cls._members_.items(): globals()[key] = value return cls def __contains__(self, value): return value in self._members_.values() def __repr__(self): return "<Enumeration %s>" % self.__name__ class Enumeration(c_uint): ...
IuryAlves/pysnake
snake.py
Python
bsd-3-clause
2,438
0.00041
# coding: utf-8 import random import pygame from colors import * segment_width = 15 segment_height = 15 segment_margin = 0 class Snake(list): def __init__(self, group, *args, **kwargs): super(Snake, self).__init__(*args, **kwargs) self.group = group self.x = segment_width + segment_mar...
in range(15): x = 250 - (segment_width + segment_margin)
* i y = 30 self.add_segment(x, y, len(self) - 1) def collidesWithBlock(self, block): if self[0].rect.collidelist([block.rect]) != -1: self.add_segment(self[0].rect.x, self[0].rect.y) return True return False def outOfTheScreen(self): retu...
pombredanne/pymaven
tests/test_client.py
Python
apache-2.0
8,637
0.000232
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
ient.find_artifacts(%s)" % input @mock.patch("pyma
ven.client.LocalRepository") def test_get_artifact(self, _LocalRepository): _repo = mock.Mock(spec=LocalRepository) _repo.exists.side_effect = [True, False] _repo.open.return_value = StringIO("some data") _LocalRepository.return_value = _repo client = MavenClient("/maven"...
sumonchai/tough
toughradius/manage/system/index.py
Python
agpl-3.0
1,739
0.006325
#!/usr/bin/env python #coding:utf-8 import cyclone.auth import cyclone.escape import cyclone.web import datetime import time import os from beaker.cache import cache_managers from toughradius.manage.base import BaseHandler from toughlib.permit import permit from toughradius.manage import models from toughradius.manage....
s import psutil @permit.route(r"/admin") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): # cpuuse = psutil.cpu_percent(interval=None, percpu=True) # memuse = psutil.virtual_memory() # online_count = self.db.query(models.TrOnline.id).count() # user_total...
atus=1).count() # self.render("index.html",config=self.settings.config, # cpuuse=cpuuse,memuse=memuse,online_count=online_count,user_total=user_total) self.redirect("/admin/dashboard") @permit.route(r"/") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): ...
0x4C4A/SS-2014
LD3/ld3_script_unified.py
Python
cc0-1.0
7,931
0.00721
# -*- coding: utf-8 -*- # Signāli un sistēmas. 3. Laboratorijas darbs # == Taisnstūra loga ietekme uz signāla spektru == import sys import numpy as np import matplotlib.pyplot as plt from PyQt4 import QtGui, QtCore from scipy.fftpack import fft from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureC...
latuma'.decode('utf-8')) # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent #self.toolbar
= NavigationToolbar(self.canvas, self) # Make a slidebar sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) sld.setFocusPolicy(QtCore.Qt.StrongFocus) sld.setGeometry(30, 40, 200, 30) sld.setMaximum(T*10) sld.setMinimum(1) sld.setTickInterval(1) sld.setTickPos...
Alex2114/Deb-3df
redeem/gcodes/M106_M107.py
Python
gpl-3.0
2,425
0.005361
""" GCode M106 and M107 Control fans Author: Mathieu Monney email: zittix(at)xwaves(dot)net Website: http://www.xwaves.net License: CC BY-SA: http://creativecommons.org/licenses/by-sa/2.0/ """ from GCodeCommand import GCodeCommand class M106(GCodeCommand): def execute(self, gcode): fans = []
if gcode.has_letter("P"): fan_no = gcode.get_int_by_letter("P", 0) if fan_no < len(self.printer.fans): fans.append(self.printer.fans[fan_no]) elif len(self.printer.controlled_fans) > 0 : # No P in gcode, use fans from settings file fans = self.printer...
# Get the value, 255 if not present value = float(gcode.get_float_by_letter("S", 255)) / 255.0 for fan in fans: if gcode.has_letter("R"): # Ramp to value delay = gcode.get_float_by_letter("R", 0.01) fan.ramp_to(value, delay) else:...
aerickson/jenkinsapi
jenkinsapi_tests/unittests/test_artifact.py
Python
mit
7,356
0.004622
from mock import Mock, MagicMock, patch, call, mock_open # To run unittests on python 2.6 please use unittest2 library try: import unittest2 as unittest except ImportError: import unittest import re, jenkinsapi from jenkinsapi.artifact import Artifact from jenkinsapi.build import Build from jenkinsapi.custom_e...
'http://localhost', '097c42989a9e5d9dcced7b35ec4b0486', # MD5 of 'chunk1chunk2' self._build.job.jenkins) fp.validate_for_build.assert_called_once_with('artifact.zip', 'TestJob', 9999) @patch('jenkinsapi.artifact.os.path.exists', spec=True, return_value=True) def test_s...
k(return_value=True) self.assertEqual(artifact.save('/tmp/artifact.zip'), '/tmp/artifact.zip') mock_exists.assert_called_once_with('/tmp/artifact.zip') artifact._verify_download.assert_called_once_with('/tmp/artifact.zip', False) @patch('jenkinsapi.artifact.os.path.exists', spec=True, ret...
dob71/x2swn
skeinforge/fabmetheus_utilities/geometry/solids/difference.py
Python
gpl-3.0
1,517
0.013843
""" Boolean geometry difference of solids. """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work i
f the module is imported as a main module. import __init__ from fabmetheus_utilities.geometry.geometry_utilities import boolean_solid from fabmetheus_utilities.geometry.geometry_utilities import evaluate from fabmetheus_utilities.geometry.solids import group __auth
or__ = 'Enrique Perez (perez_enrique@yahoo.com)' __credits__ = 'Nophead <http://hydraraptor.blogspot.com/>\nArt of Illusion <http://www.artofillusion.org/>' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def convertElementNode(elementNode, geom...
akhambhati/Echobase
Echobase/Network/Partitioning/Module/modularity.py
Python
gpl-3.0
3,949
0
''' Construct and manipulate multilayer representations of configuration vectors Created by: Ankit Khambhati Change Log ---------- 2016/02/03 - Implement functions to construct multilayer networks ''' import numpy as np import scipy.sparse as sp from ....Common import errors from ...Transforms import configuration ...
l == 'connectional': rnd_node_ix = np.random.permutation(n_nodes) rnd_node_iy = np.random.permutation(n_nodes)
ix, iy = np.mgrid[0:n_nodes, 0:n_nodes] for ll, conn_vec in enumerate(conn_matr): A = configuration.convert_conn_vec_to_adj_matr(conn_vec) if null == 'connectional': A = A[rnd_node_ix[ix], rnd_node_iy[iy]] A = np.triu(A, k=1) A += A.T # Compute node de...
decvalts/landlab
landlab/grid/tests/test_raster_grid/test_faces.py
Python
mit
1,453
0.001376
import numpy as np from numpy.testing import assert_array_equal from nose.tools import (assert_equal, assert_raises, raises, assert_true, assert_false) try: from nose.tools import assert_is except ImportError: from landlab.testing.tools import assert_is from landlab import RasterModel...
def test_horizontally_adjacent_cells(self): assert_array_equal(self.rmg.get_face_connecting_cell_pair(0, 1), np.array([10])) def test_vertically_adjacent_cells(self): assert_array_equal(self.rmg.get_face_c
onnecting_cell_pair(0, 3), np.array([3])) def test_diagonally_adjacent_cells(self): assert_array_equal(self.rmg.get_face_connecting_cell_pair(1, 5), np.array([])) def test_non_adjacent_cells(self): assert_array_equal(self.rmg.get_face_conne...
Jumpscale/jumpscale_core8
lib/JumpScale/tools/cuisine/apps/CuisineHadoop.py
Python
apache-2.0
1,061
0.002828
from JumpScale import j base = j.tools.cuisine._getBaseClass() # TODO: *4 unfinished but ok for now class CuisineHadoop(base): def _install(self): if self._cuisine.core.isUbuntu: C = """\ apt-get install -y apt-get install openjdk-7-jre cd $tmpDir wget -...
sine.core.args_replace(C) self._cuisine.core.execute_bash(C, profile=True) self._cuisine.bash.addPath("/opt/hadoop-2.7.2/bin") self._cuisine.bash.addPath("/opt/hadoop-2.7.2/sbin") self._cuisine.bash.environSe
t("JAVA_HOME", "/usr/lib/jvm/java-7-openjdk-amd64") self._cuisine.bash.environSet("HADOOP_PREFIX", "/opt/hadoop-2.7.2/") else: raise NotImplementedError("unsupported platform") def install(self): self._install()
albertz/music-player
src/modules/Search.py
Python
bsd-2-clause
1,595
0.028876
# -*- coding: utf-8 -*- # MusicPlayer, https://github.com/albertz/music-player # Copyright (c) 2012, Albert Zeyer, www.az2000.de # All rights reserved. # This code is under the 2-clause BSD license, see License.txt in the root directory of this project. import utils from utils import formatTime import Traits import so...
Keys = ("artist", "title", "duration", "rating") def __init__(self):
self._searchText = "" self._searchResults = [] import threading self._lock = threading.RLock() def _startSearch(self, txt): def search(): with self._lock: if self._searchText != txt: return res = songdb.search(txt) with self._lock: if self._searchText == txt: self._searchResults = res...
compsoc-ssc/compsocssc
events/views.py
Python
mit
425
0
from django.shortcuts import redirect from django.shortcuts import render from django.views.decorators.gzip import gzip_page from events.mode
ls import Event @gzip_page def home(request): ''' View for the Events home page ''' template = 'events/home.html' events = Event.objects.all().order_by('start_time') context = { "events": events } return re
nder(request, template, context)
mktoni/anglerfish
tests/test_get_public_ip.py
Python
gpl-3.0
440
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Test for anglerfish.get_public_ip().""" import unittest from anglerfish import get_public_ip class TestName(unittest.TestCase): maxDiff, __slots__ =
None, () def test_get_public_ip(self): # Travis has an invalid certificate, and it fails because of that. assert get_public_ip() if __name__
.__contains__("__main__"): print(__doc__) unittest.main()
oukiar/netget
sitesolserver.py
Python
gpl-2.0
1,758
0.01934
#!/usr/bin/python # -*- coding: latin-1 -*- from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from network import Network import json, socket, urllib, os class SitesolServer(FloatLayout): def __init__(self, **kwargs): super(SitesolSe...
en el servidor esta IP r = urllib.urlopen('http://www.devsinc.com.mx/netget/solvers.php?set_server_ip=foo') def receiver(self, data, addr): #unpack data_dict = json.loads(data) self.txt_log.text += '\nMessage: ' + data_dict['msg'] + ' from '
+ addr[0] + ':' + str(addr[1]) data = data_dict['data'] #analize if data_dict['msg'] == 'ping': tosend = json.dumps({'msg':'ping_ack', 'data':socket.gethostname()}) self.net.send(addr, tosend) elif data_dict['msg'] == 'get_inet_addr': ...
vtemian/university_projects
data_structures/bitorrent/server/announce/api.py
Python
apache-2.0
984
0.006098
import json from flask import Blueprint, request
from utils.decorators import required from .torrent import Torrent endpoint = Blueprint('announce', __name__) @endpoint.route('/announce', methods=['GET']) @required('info_hash', 'peer_id', 'port', 'uploaded', 'downloaded', 'left', 'compact', 'no_peer_id', 'event') def announce(info_hash, peer_id, port, ...
no_peer_id, event): torrent = Torrent(info_hash) if not torrent.can_announce(peer_id): return json.dumps({ 'status': 'fail', 'message': 'You need to wait 5 minutes to reannounce yourself' }) torrent.peers = "%s:%s" % (request.remote_addr, port) torrent.set_announce(peer_id) respons...
gwpy/gwpy
gwpy/table/gravityspy.py
Python
gpl-3.0
8,173
0
# -*- coding: utf-8 -*- # Copyright (C) Scott Coughlin (2017-2021) # Cardiff University (2021) # # This file is part of GWpy. # # GWpy 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 versi...
target _download_target = _image_download_target( row, download_path, training_set=training_set, labelled_samples=labelled_samples, ) # and map the remote URL to a concrete target # for each duration request...
idx = int(col[3:]) # urlXXXX number duration = DURATIONS[idx-1] if duration in download_durs: # image requested urls[row[col]] = Path(_download_target.format(duration)) # create all of the directories needed up front for path in urls.val...
qgis/QGIS-Django
qgis-app/styles/migrations/0005_style_modified_date.py
Python
gpl-2.0
597
0.001675
# Generated by Django 2.2 on 2020-11-08 11:00 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('styles', '0004_auto_20201108_0742'), ] operations = [ migrations.AddField( mod
el_name='style', name='modified_date', field=models.DateTimeField(default=datetime.datetime(2020, 11, 8, 11, 0, 41, 965734), editable=False, help_text='The upload date. Automatically added on file upload.', verbose_name='Modified on'), preserve_default=Fals
e, ), ]
LeProjetDeLaSemaine/Projet_ISN
MoveToFront.py
Python
gpl-3.0
1,229
0.039637
#!/usr/bin/python #-*- coding: utf-8 -*- #Note : Cet algo semble (à ce que j'ai compris) avoir besoin qu'on lui précise #tous les caractères qu'il peut rencontrer #Ces
tNulOMG #Pour l'instant, on remarquera que je ne le fais fonctionner qu'avec les majuscules def moveToFront(texte, table): resultat = [] #on utilise une liste (hélas), puisque les éléments sont distincts for c in texte: #on boucle dans le texte index = table.index(c) #on récupère l'index de c dans la table resul...
dex)) #c'est mieux en str, mais il faut repasser en int pour décoder... Que faire ? table = [table.pop(index)] + table #on déplace le caractère à table[index] au début de table return resultat def moveToBack(liste, table): #moveToBack est l'inverse de moveToFront, logique :-P chaine = "" for i in liste: #on bouc...
popazerty/EG-2
lib/python/Components/Converter/CryptoInfo.py
Python
gpl-2.0
885
0.029379
from Components.Converter.Converter import Converter from Components.Element import cached from Components.config import config from Tools.GetEcmInfo import GetEcmInfo from Poll import Poll class CryptoInfo(Poll, Converter, object): def __init__(self, type): Converter.__init__(self, type) Poll.__init__(self) ...
onfig.usage.show_cryptoinfo.value) > 0: self.visible = True else: self.visible = False self.textvalue = "" self.poll_interval = 1000 self.poll_enabled = Tr
ue self.ecmdata = GetEcmInfo() @cached def getText(self): if int(config.usage.show_cryptoinfo.value) < 1: self.visible = False data = '' else: self.visible = True if self.type == "VerboseInfo": data = self.ecmdata.getEcmData()[0] else: data = self.ecmdata.getInfo(self.type) return data...
decarlin/indra
indra/bel/processor.py
Python
bsd-2-clause
27,816
0.00036
from indra.statements import * from rdflib import URIRef, Namespace from rdflib.namespace import RDF import collections import urllib import re import keyword BEL = Namespace("http://www.openbel.org/") prefixes = """ PREFIX belvoc: <http://www.openbel.org/vocabulary/> PREFIX belsc: <http://www.openbel.org/be...
asEvidence ?evidence . ?evidence belvoc:hasAnnotation ?annotation . } """ % statement.format() res_annotations = self.g.query(q_annotations) for stmt in res_annotations: annotations.append(stmt[0].format()) return (citation, evidence, annotations)...
odifications(self): q_phospho = prefixes + """ SELECT ?enzName ?actType ?substrateName ?mod ?pos ?stmt WHERE { ?stmt a belvoc:Statement . ?stmt belvoc:hasRelationship belvoc:DirectlyIncreases . ?stmt belvoc:hasSubject ?su...
youlanhai/ExcelToCode
xl2code/codegen/base_code_gen.py
Python
mit
1,056
0.038023
# -*- coding: utf-8 -*- import os INDENTS = [" " * (i * 4) for i in xrange(10)] class BaseCodeGen(object): def
__init__(self, module, module_name, generator_info): super(BaseCodeGen, self).__init__() self.content = [] self.module = module self.module_name = module_name self.generator_info = generator_info def run(self): pass def save_to_file(self, path): content = "".join(self.content) self.content = [] ...
n_content = f.read() if content == origin_content: return print "生成", path with open(path, "wb") as f: f.write(content) return def output(self, *args): self.content.extend(args) def write(self, indent, *args): assert(type(indent) == int) if indent > 0: self.content.append(INDENTS[indent]) sel...
wohnsinn2/Radicale
radicale/auth/__init__.py
Python
gpl-3.0
1,784
0
# -*- coding: utf-8 -*- # # This file is part of Radicale Server - Calendar Server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2013 Guillaume Ayoub # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as...
ig, log def load(): """Load list of available authentication managers.""" auth_type = config.get("auth", "type") log.LOGGER.debug("Authentication type is %s" % auth_type) if auth_type == "None": return None elif auth_type == 'custom': auth_module = confi
g.get("auth", "custom_handler") __import__(auth_module) module = sys.modules[auth_module] else: root_module = __import__( "auth.%s" % auth_type, globals=globals(), level=2) module = getattr(root_module, auth_type) # Override auth.is_authenticated sys.modules[__nam...
Juaanma/MultipleStocksPlotter
src/main.py
Python
bsd-2-clause
4,658
0.001932
import os import pandas as pd import sys import plotter from PyQt4 import QtGui, QtCore # The main window inherits from QWidget (an empty window). class MainLayout(QtGui.QWidget): def __init__(self): # Initialize the object as a QWidget QtGui.QWidget.__init__(self) self.setWindowTitle("M...
d, and create the
dataframe. stock_ids = self.stocks_input.text() stocks = pd.DataFrame() # If there's no text in the box, we shouldn't do anything. if not stock_ids: return QtGui.QMessageBox.information(self, "Loading", "The stocks are dow...
kabooom/plugin.video.xstream
sites/movie4k_to.py
Python
gpl-3.0
26,737
0.009202
# -*- coding: utf-8 -*- from resources.lib.util import cUtil from resources.lib.parser import cParser from resources.lib.handler.requestHandler import cRequestHandler from resources.lib.handler.ParameterHandler import ParameterHandler from resources.lib.gui.guiElement import cGuiElement from resources.lib.gui.gui impo...
(): oGui = cGui() __createMainMenuItem(oGui, 'Featured', URL_SERIES, 'showFeaturedSeries') __createMainMenuItem(oGui, 'Alle Serien', URL_SERIES_ALL, 'showCharacters') __createMainMenuItem(oGui, 'Genre', URL_SERIES_GENRE, 'showGenre') oGui.setEndOfDirectory() def showXXXMenu(): oGui = cGui()...
Genre', URL_XXX_GENRE, 'showGenre') oGui.setEndOfDirectory() def __getHtmlContent(sUrl = False, sSecurityValue = False): params = ParameterHandler() # Test if a url is available and set it if not sUrl: sUrl = params.getValue('siteUrl') if not sUrl: logger.info('no request ur...
H0neyBadger/cmdb
extra/create_rand_host.py
Python
mit
2,026
0.017769
import requests import json import random import uuid login="test" password="P@ssword" with open("dict", 'r', encoding="latin-1") as words : a = words.readlines() headers = { 'Content-type': 'application/json', 'Accept': 'application/json' } def gen_ip(): a = random.randint(1, 254) b = rando...
gen_ip()) mac = ':'.join(("%12x" % random.randint(0, 0xFFFFFFFFFFFF))[i:i+2] for i in range(0, 12, 2)) interfaces.append({ "ip_address": ips, "name": "{}{}".format(name,i), "mac_address": mac, #"host": null }) return interfaces while(1): ...
e = random.choice(a).replace('\n','' snow_id = random.randint(100000, 999999) machine_uuid = str(uuid.uuid4()) interfaces = gen_interface() data = { "interfaces": interfaces, "name": name, "snow_id": snow_id, "uuid": machine_uuid, "machine_id": machine_uuid, ...
vandorjw/django-traceability
traceability/managers/item.py
Python
bsd-3-clause
518
0.005792
from datetime import datetime, timedelta from django.db import models class InventoryMan
ager(model
s.Manager): def get_queryset(self): return super(InventoryManager, self).get_queryset().filter( shipment__isnull=True, ).distinct() def days_0_30(self): # Example method start_date = datetime.now() + timedelta(-30) return super(InventoryManager, self).get_queryset()....
kemaswill/keras
examples/babi_rnn.py
Python
mit
8,596
0.002792
'''Trains two recurrent neural networks based upon a story and a question. The resulting merged vector is then queried to answer a range of bAbI tasks. The results are comparable to those for an LSTM model provided in Weston et al.: "Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks" http://arxiv...
. ''' data = [] story = [] for line in lines: line = line.decode('utf-8').strip() nid, line = line.split(' ', 1) nid = int(nid) if nid == 1: story = [] if '\t' in line: q, a, supporting = line.split('\t') q = tokenize(q) ...
ing: # Only select the related substory supporting = map(int, supporting.split()) substory = [story[i - 1] for i in supporting] else: # Provide all the substories substory = [x for x in story if x] data.append((subst...
conejoninja/pelisalacarta
python/main-classic/channels/tubehentai.py
Python
gpl-3.0
3,912
0.01641
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para tubehentai # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os import sys from ...
" __language__ = "ES" DEBUG = config.get_setting("debu
g") def isGeneric(): return True def mainlist(item): logger.info("[tubehentai.py] mainlist") return novedades(Item(channel=__channel__, title="Novedades" , action="novedades" , url="http://tubehentai.com/" )) def novedades(item): logger.info("[tubehentai.py] getnovedades") # Descarga la página ...
guildai/guild
examples/debugging/submod.py
Python
apache-2.0
121
0.008264
"""Used a sub-module by test. Illustrates settin
g breakpoints in non-main
modules. """ def add(x, y): return x + y
knowmetools/km-api
km_api/km_auth/serializers.py
Python
apache-2.0
1,348
0
"""Serializers for authentication views. """ from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class TokenSerializer(serializers.Serializer): """ Serializer for obtaining an auth token. The actual generation of th...
llowed to obtain a token. Returns: dict: The validated data. Raises: ValidationError: If the provided credentials are invalid.
ValidationError: If the requesting user does not have a verified email address. """ user = authenticate(**data) if not user: raise serializers.ValidationError( _( "Invalid credentials. Check your email and passwor...
SophieBartmann/Faust-Bot
FaustBot/Modules/WhoObserver.py
Python
gpl-3.0
1,729
0.001157
from FaustBot.Communication import Connection from FaustBot.Model.RemoteUser import RemoteUser from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype from FaustBot.Modules.ModuleType import ModuleType from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype from FaustBot....
number'] == '315': # RPL_ENDOFWHO self.end_who() def input_who(self, data, connection: Connection): # target #channel user host server nick status :0 gecos target, channel, user, host, server, nick, *ign =
data['arguments'].split(' ') self.pending_whos.append(RemoteUser(nick, user, host)) def end_who(self): self.user_list.clear_list() for remuser in self.pending_whos: self.user_list.add_user(remuser) self.pending_whos = [] def update_on_ping(self, data, connection: C...
ROIV/ViorCoin-ElectrumWallet
lib/transaction.py
Python
gpl-3.0
27,739
0.007931
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # 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...
nse # along with this program. If not, see <http://www.gnu.org/licenses/>. # Note: The deserialization code originally comes from ABE. from bitcoin import * fro
m util import print_error import time import struct # # Workalike python implementation of Bitcoin's CDataStream class. # import struct import StringIO import mmap class SerializationError(Exception): """ Thrown when there's a problem deserializing or serializing """ class BCDataStream(object): def __init__(...
arenadata/ambari
ambari-server/src/main/resources/stacks/BigInsights/4.0/services/KAFKA/package/scripts/params.py
Python
apache-2.0
5,521
0.004347
#!/usr/bin/env python """ 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");...
uired by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from resource_manag...
ript from resource_management.libraries.functions import upgrade_summary from resource_management.libraries.functions.version import format_stack_version, compare_versions from resource_management.libraries.functions.default import default from resource_management.libraries.functions.stack_features import get_stack_fea...
kmacinnis/sympy
sympy/functions/combinatorial/tests/test_comb_factorials.py
Python
bsd-3-clause
5,343
0.000561
from sympy import (Symbol, symbols, factorial, factorial2, binomial, rf, ff, gamma, polygamma, EulerGamma, O, pi, nan, oo, simplify, expand_func) from sympy.functions.combinatorial.factorials import subfactorial from sympy.utilities.pytest import XFAIL, raises def test_rf_eval_ap...
mial(n, k).rewrite( factorial) == facto
rial(n)/(factorial(k)*factorial(n - k)) assert binomial( n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) @XFAIL def test_factorial_simplify_fail(): # simplify(factorial(x + 1).diff(x) - ((x + 1)*factorial(x)).diff(x))) == 0 from sympy.abc import x assert simplify(x*polygam...
kilon/sverchok
nodes/modifier_change/polygons_to_edges.py
Python
gpl-3.0
2,844
0.003516
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
out = [] for faces in obj: out_edges = [] #set() #[] for face in faces: for edge in zip(face, face[1:]+[face[
0]]): #out_edges.add(tuple(sorted(edge))) out_edges.append(list(edge)) out.append(out_edges) return out def polstoedgs(self, pols): out = [] for obj in pols: object = [] for pols in obj: edgs = [] ...
biolauncher/pycudalibs
test/test_linalg.py
Python
gpl-3.0
415
0
import unittest import test_dot import test_math import test_trans import test_lapack #
linear algebra group suite suite = unittest.TestSuite([test_dot.suite(), test_math.suite(), tes
t_trans.suite(), test_lapack.suite ]) if __name__ == "__main__": unittest.TextTestRunner(verbosity=2).run(suite)
spacecowboy/pyplotthemes
pyplotthemes/base.py
Python
gpl-2.0
14,283
0.00056
# -*- coding: utf-8 -*- import matplotlib as mpl from matplotlib import pyplot as plt import os class BaseTheme(object): ''' A theme wraps plotting methods and sets appropriate properties on the axis produced. Valid keyword arguments are anything that is accepted by matplotlib.rcParams. These va...
'path.simplify', True) cadd(kwargs, 'path.simplify_threshold', 0.1) cadd(kwargs, 'path.snap', True) cadd(kwargs, 'path.sketch', 'None') cadd(kwargs, 'savefig.dpi', 100) cadd(kwargs
, 'savefig.facecolor', 'white') cadd(kwargs, 'savefig.edgecolor', 'white') cadd(kwargs, 'savefig.format', 'png') cadd(kwargs, 'savefig.bbox', 'standard') cadd(kwargs, 'savefig.pad_inches', 0.1) cadd(kwargs, 'savefig.directory', '~') #cadd(kwargs, 'savefig.transparent', F...
scollis/Bork
awsome.py
Python
bsd-2-clause
60
0.016667
from future import print_function print ("Thi
s is awsome"
)
aryeelab/guideseq
setup.py
Python
agpl-3.0
1,263
0.001584
#!/usr/b
in/env python # -*-
coding: utf-8 -*- from distutils.core import setup requirements = [line.strip() for line in open('requirements.txt')] setup( name='guideseq', version='0.9.0', description="An easy to use bioinformatic pipeline for the GUIDE-seq assay.", author="Shengdar Q Tsai, Martin Aryee, Ved V Topkar", autho...
SSSD/sssd
src/tests/multihost/alltests/test_local_overrides.py
Python
gpl-3.0
2,290
0
""" Automation of localoverrides suite :requirement: local_overrides :casecomponent: sssd :subsystemteam: sst_idm_sssd :upstream: yes """ from __future__ import print_function import re import pytest from sssd.testlib.common.utils import sssdTools from constants import ds_instance_name import time @pytest.mark.usefi...
s = {'override_homedir': '/home/%u1'} client.sssd_conf(f'domain/{domain_name}', domain_params) multihost.client[0].service_sssd('restart') before = multihost.clie
nt[0].run_command("getent passwd " "foo5@example1") assert before.returncode == 0 multihost.client[0].run_command("sss_override " "user-add foo5@example1 -h " "/home/foo56") ...
cinepost/Copperfield_FX
copper/sop/sop_node.py
Python
unlicense
744
0.033602
import logging from copper.core.op.op_network import OP_Network from copper.core.parameter.parm_template import * from copper.core.data.geometry_data import GeometryData class SOPCookException(Exception): pass class SOP_Node(OP_Network): __base__ = True def __in
it__(self, engine, parent): super(SOP_Node, sel
f).__init__(engine, parent) self._geometry = GeometryData(sop_node=self) def cookMySop(self, lock, context): raise NotImplementedError def cookData(self, lock, context={}): try: self.cookMySop(lock, context) except Exception as e: logging.exception("Error cooking SOP data !!!") return False se...
aclowes/yawn-gke
yawn_settings.py
Python
mit
727
0.001376
import dj_database_url import pkg_resources from yawn.settings.base import * # this uses DATABASE_URL env variable: DATABASES['default'] = dj_database_url.config(conn_max_age=600) SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = [os.environ.get('ALLOWED_HOSTS')] # Allow anonymous read REST_FRAMEWORK['DEF...
PERMISSION_CLASSES'] = [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ] INSTALLED_APPS += ['raven.contrib.django'] try: yawn_version = pkg_resources.require("yawns")[0].version except: yawn_version = None RAVEN_CONFIG = { 'dsn': os.environ.get('SENTRY_DSN'), 'release': yawn_version, ...
'include_paths': ['yawn'], }
Alexander-M-Waldman/local_currency_site
lib/python2.7/site-packages/guardian/testapp/tests/conf.py
Python
gpl-3.0
2,998
0.002001
from __future__ import unicode_literals import os from guardian.compat import unittest from guardian.utils import abspath from django.conf import settings from django.conf import UserSettingsHolder from django.utils.functional import wraps THIS = abspath(os.path.dirname(__file__)) TEST_TEMPLATES_DIR = abspath(THIS, '...
or_create(pk=settings.ANONYMOUS_USER_ID) jack = User.objects.create(pk=1, username='jack', is_active=True, is_superuser=False, is_
staff=False) jack.groups.add(jack_group) class override_settings(object): """ Acts as either a decorator, or a context manager. If it's a decorator it takes a function and returns a wrapped function. If it's a contextmanager it's used with the ``with`` statement. In either event entering/exiti...
petrutlucian94/nova_dev
nova/virt/libvirt/volume.py
Python
apache-2.0
46,030
0.000369
# Copyright 2011 OpenStack Foundation # (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 # # ...
scover AoE target t
o find volume', deprecated_group='DEFAULT'), cfg.StrOpt('glusterfs_mount_point_base', default=paths.state_path_def('mnt'), help='Directory where the glusterfs volume is mounted on the ' 'compute node', deprecated_group='DEFAULT'), c...
mikitex70/pelican-plugins
gzip_cache/test_gzip_cache.py
Python
agpl-3.0
4,627
0.004971
# -*- coding: utf-8 -*- '''Core plugins unit tests''' import os import tempfile import unittest import time from contextlib import contextmanager from tempfile import mkdtemp from shutil import rmtree from hashlib import md5 import gzip_cache @contextmanager def temporary_folder(): """creates a temporary folder...
s not created. # The plugin walks over the output content af
ter the finalized signal # so it is safe to assume that the file exists (otherwise walk would # not report it). Therefore, create a dummy file to use. with temporary_folder() as tempdir: _, a_html_filename = tempfile.mkstemp(suffix='.html', dir=tempdir) gzip_cache.create_...
ieuan1630-cmis/ieuan1630-cmis-cs2
pep4.py
Python
cc0-1.0
2,405
0.009563
#Project Euler Problem 4 #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. #Find the largest palindrome made from the product of two 3-digit numbers. def palindrome(test): while len(test) > 2: if test[0] == test[-1]: ...
_palindrome_from_3digitproductsr() """ print 9*9 #highest square #digits involv
ed 1 print 9*8 #new number times highest #because old digits finished, add new digit print 8*8 #new squared #multiply involved digit by all involved hi to low print 9*7 #new digit times highest print 8*7#new times next highest print 9*6#new2 times highest print 7*7#new squared #new2 now new print 8*6#new times next hig...
zixan/django-crispy-forms
crispy_forms/tests/test_form_helper.py
Python
mit
23,197
0.001552
# -*- coding: utf-8 -*- import re import django, logging, warnings from django import forms from django.conf import settings from django.core.urlresolvers import reverse from django.forms.models import formset_factory from django.middleware.csrf import _get_new_csrf_key from django.template import ( loader, Templa...
er() form.helper.attrs = {'id': 'TestIdForm', 'autocomplete': "off"} html = render_crispy_form(form) self.assertTrue('autocomplete="off"' in html) self.assertTrue('id="TestIdForm"' in html) def test_template_context(self): helper = FormHelper() helper.attrs = { ...
autocomplete': 'off', } node = CrispyFormNode('form', 'helper') context = node.get_response_dict(helper, {}, False) self.assertEqual(context['form_id'], "test-form") self.assertEqual(context['form_attrs']['id'], "test-form") self.assertTrue("test-forms" in context['form_...
mad01/boilerplates
python/test_api_post.py
Python
mit
1,294
0.000773
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import json from lib.httpl import http_post from lib.testdata import random_data """ This is written to work with nosetest, the print statmetnts in the libs will be supressed when if a test passes when nosetest is running. When it fails the print statment...
p_post( shared.get('host'), api=shared.get('api'), payload={"hex": test_assert} ) data = json.loads(http_data) self.assertEqual(int(result_code), 200) self.assertEqual( unicode(test_assert), json.loads(data.get('data')).get('hex...
n dynamic_test_method testmap = random_data(10) for name, parms in testmap.iteritems(): data = dynamic_gen(parms["hex"]) data.__name__ = "test_{0}".format(name) data.__doc__ = "test_{0}".format(name) setattr(TestGenClass, data.__name__, data) del data if __name__ == "__main__": unittest.main()...
nacl-webkit/chrome_deps
tools/telemetry/telemetry/user_agent_unittest.py
Python
bsd-3-clause
539
0.003711
# Copyright (c) 2012 The Chromium Authors. All ri
ghts reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import tab_test_case from telemetry import user_agent class UserAgentTest(tab_test_case.TabTestCase): def CustomizeBrowserOptions(self, options): options.browser_user_agent_type =...
r.userAgent') self.assertEquals(ua, user_agent.UA_TYPE_MAPPING['tablet'])
bazingasheldon/tv
loader.py
Python
gpl-2.0
421
0.026128
# -*- coding: utf-8 -*- import xbmc,urllib all_modules = [ 'https://github.com/bazingasheldon/tv/blob/master/raspberry/addon.tar.gz?raw=true'] for parser in all_modules: xbmc.executebuiltin('XBMC.RunPlugin("plugin://plugin.video.p2p-streams/?mode=405
&name=p2p&url=' + urllib.quote(parser) + '")') xbmc.sleep(1000) xbmc.executebuiltin("Not
ification(%s,%s,%i,%s)" % ('P2P-Streams', "All parsers imported",1,''))
CroMarmot/MyOICode
ProjectEuler/p323.py
Python
gpl-3.0
1,577
0.016487
# x = last | random # expected step N => 32 bit full # 1 bit expected (step 1) = 1/2 # 1 bit expected (step 2) = 1/2^2 # 1 bit expected (step n) = 1/2^n # 1 bit expected step = 1/2+2(1/2^2)+3*1/2^3)+4*1/2^4 # ???? n step or step # 00 # 1.999999999 def bit1(): onebit = 0 for i in range(1000): onebi...
wobit[0]/4+twobit[1]/2+twobit[2]/2); twobit[1] = twobit[1]/2 + twobit[0]/4 twobit[2] = twobit[2]/2 + twobit[0]/4 twobit[0] = twobit[0]/4 print(i,twobit[3]) def bit2_2(): twobit = [1,0,0] for i in range(1,1000): twobit[2] += i*(twobit[0]/4+twobit[1]/2); twobit[1] ...
in range(n): r *= m-i for i in range(1,n+1): r /=i return r def bitn(n): bits = [0 for i in range(n+1)] bits[0] = 1 for i in range(1,1000): # expected in n for itr in range(n): bits[n] += i*(0.5**(n-itr))*bits[itr] for itr in range(n-1,-1,-1): ...
jwhitlock/kuma
kuma/wiki/tests/test_views.py
Python
mpl-2.0
116,810
0.000257
# -*- coding: utf-8 -*- import datetime import json import mock import pytest import requests_mock from constance.test import override_config from django.conf import settings from django.contrib.sites.models import Site from django.core import mail from django.template.loader import render_to_string from django.utils....
'%s?expand' % url resp = self.client.get(url) assert resp.status_code == 200 assert_share
d_cache_header(resp) assert resp['Access-Control-Allow-Origin'] == '*' json_obj = json.loads(resp.content) # Basic structure creation testing assert json_obj['slug'] == 'Root' if not expand: assert 'summary' not in json_obj else: ...
psiopic2/psicrawler
build-scripts/clean.py
Python
mit
977
0.010235
#!/usr/bin/env python import os import sys import shutil import glob import fnm
atch mydir = os.path.dirname(os.path.realpath(__file__)) projectdir = os.path.realpath(mydir + "/../") dirs = ['dist','deb_dist','build','.tox','.eggs','.cache','psicrawler.egg-info'] files = ['.coverage'] d
ef out(msg): sys.stdout.write(msg + "\n") sys.stdout.flush() for d in dirs: try: targetdir = projectdir + "/" + d shutil.rmtree(targetdir) out(targetdir) except OSError: pass for f in files: try: targetfile = projectdir + "/" + f os.remove(targetfile...
nosyndicate/pytorchrl
pytorchrl/config_personal.py
Python
mit
1,995
0.001003
import os.path as osp import os USE_GPU = False AWS_REGION_NAME = 'us-east-2' if USE_GPU: DOCKER_IMAGE = 'dementrock/rllab3-shared-gpu' else: # DOCKER_IMAGE = 'dwicke/jump:docker' DOCKER_IMAGE = 'dwicke/parameterized:latest' DOCKER_LOG_DIR = '/tmp/expt' AWS_S3_PATH = 's3://pytorchrl/pytorchrl/experimen...
': 'ami-b8b62bd8' } AWS_IMAGE_ID = ALL_REGION_AWS_IMAGE_IDS[AWS_REGION_NAME] if USE_GPU: AWS_INSTA
NCE_TYPE = 'g2.2xlarge' else: AWS_INSTANCE_TYPE = 'c4.2xlarge' ALL_REGION_AWS_KEY_NAMES = { "us-east-2": "pytorchrl-us-east-2", "us-east-1": "pytorchrl-us-east-1" } AWS_KEY_NAME = ALL_REGION_AWS_KEY_NAMES[AWS_REGION_NAME] AWS_SPOT = True AWS_SPOT_PRICE = '0.1' AWS_ACCESS_KEY = os.environ.get('AWS_ACCES...
yugangw-msft/azure-cli
src/azure-cli/azure/cli/command_modules/storage/tests/hybrid_2020_09_01/test_storage_account_scenarios.py
Python
mit
13,249
0.003849
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
e -n {} -g {} --sku
Standard_LRS --https-only '.format(name, resource_group) self.cmd(create_cmd, checks=[JMESPathCheck('identity', None)]) update_cmd = 'az storage account update -n {} -g {} --assign-identity'.format(name, resource_group) result = self.cmd(update_cmd).get_output_in_json() self.assertIn('...
kittiu/sale-workflow
sale_invoice_auto_deliver/tests/__init__.py
Python
agpl-3.0
70
0
# -*-
coding: utf-8 -
*- from . import test_sale_invoice_auto_deliver
tommy-u/chaco
chaco/tools/api.py
Python
bsd-3-clause
1,366
0.000732
from better_zoom import BetterZoom from better_selecting_zoom import BetterSelectingZoom from broadcaster import BroadcasterTool from dataprinter import DataPrinter from data_label_tool import DataLabelTool from enable.tools.drag_tool import DragTool from draw_points_tool import DrawPointsTool from drag_zoom import Dra...
Tool from pan_tool import Pan
Tool from point_marker import PointMarker from range_selection import RangeSelection from range_selection_2d import RangeSelection2D from range_selection_overlay import RangeSelectionOverlay from regression_lasso import RegressionLasso, RegressionOverlay from save_tool import SaveTool from scatter_inspector import Scat...
beetbox/beets
test/testall.py
Python
mit
1,255
0
#!/usr/bin/env python # This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The ab...
port os import re import sys import unittest pkgpath = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) or '..' sys.path.insert(0, pkgpath) def suite(): s = unittest.TestSuite() # Get the suite() of every module in this directory beginning with # "test_". for fname in os.listdir(os.path.j...
t-tran/libcloud
libcloud/test/storage/test_base.py
Python
apache-2.0
4,866
0
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
self.driver1.hash_type = 'invalid-hash-function' func = self.driver1._get_hash_function() except RuntimeError: pass else: self.fail('Invalid hash type but exception was not thrown') def test_upload_no_content_type_supplied_or_detected(self): iterator = St...
type should be used self.driver1.connection = Mock() self.driver1._upload_object(object_name='test', content_type=None, upload_func=upload_func, upload_func_kwargs={}, ...
jhaase1/zapdos
problems/Schottky_emission/transient/no_ballast/parametric/base/OldUnAveragedSystemData.py
Python
lgpl-2.1
5,514
0.013239
#### import the simple module from the paraview from paraview.simple import * import glob, re, os, numpy, csv def CreatePointSelection(ids): source = IDSelectionSource() source.FieldType = "POINT" sids = [] for i in ids: sids.append(0) #proc-id sids.append(i) #cell-id source.IDs = sids ...
ilable reader.ApplyDisplacements = 1 reader.DisplacementMagnitude = 1.0 ## Get cathode and anode coordinates calc = Calculator(Input=reader) calc.ResultArrayName = 'coords' calc.Function = 'coords' calc.UpdatePipeline() coordRange = calc.PointData['coords'].GetRange() minX = coordRange[0] maxX = coordRang...
VariablesofInterest = ['Time', 'Voltage', 'Current_Arp', 'Current_em', 'tot_gas_current', 'Emission_energy_flux'] ## Extract cathode data ## cathodeValues = ExtractLocation(Input=reader) cathodeValues.Location = [minX,0,0] cathodeValues.Mode = 'Interpolate At Location' electrodeData.append(selectElectrodeData...
gigitux/lollypop
src/widgets_radio.py
Python
gpl-3.0
4,766
0
# Copyright (c) 2014-2015 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # 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 vers...
def _on_eventbox_realize1(self, eventbox): """ Change cursor over cover eventbox @param eventbox as Gdk.Eventbox """ eventbox.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.HAND1)) def _on_eventbox_realize2(self, eventbox): """ Change cursor ...
set_cursor(Gdk.Cursor(Gdk.CursorType.PENCIL))
rht/zulip
zerver/tests/test_outgoing_http.py
Python
apache-2.0
4,946
0.002022
import os from typing import Any from unittest import mock import requests import responses from requests.packages.urllib3.util.retry import Retry from zerver.lib.outgoing_http import OutgoingSession from zerver.lib.test_classes import ZulipTestCase class RequestMockWithProxySupport(responses.RequestsMock): def...
reen-Role"], "testing") # We don't see the request-level headers in the prox
y # request. This isn't a _true_ test because we're # fiddling the headers above, instead of urllib3 actually # setting them. self.assertFalse("X-Foo" in headers) def test_timeouts(self) -> None: with RequestMockWithTimeoutAsHeader() as mock_requests: ...
chirilo/remo
remo/reports/__init__.py
Python
bsd-3-clause
844
0
ACTIVITY_EVENT_ATTEND = 'Attended an Event' ACTIVITY_EVENT
_CREATE = 'Organized an Event' ACTIVITY_CAMPAIGN = 'Participated in a campaign' ACTIVITY_MONTH_PLANNING = 'Month planning' ACTIVITY_MONTH_RECAP = 'Month recap' ACTIVITY_POST_EVENT_METRICS = 'Completed post-event
metrics' ACTIVITY_RECRUITMENT_EFFORT = 'Recruitment effort' RECRUIT_MOZILLIAN = 'Recruited a Mozillian' READONLY_ACTIVITIES = [ACTIVITY_CAMPAIGN, ACTIVITY_EVENT_ATTEND, ACTIVITY_EVENT_CREATE, RECRUIT_MOZILLIAN, ACTIVITY_POST_EVENT_METRICS] VERIFIABLE_ACTIVITIES = [RECRUIT...
realcr/docker_machinator
setup.py
Python
mit
1,193
0.015926
from setuptools import setup # Based on # https://python-packaging.readthedocs.io/en/latest/minimal.html def readme(): with open('README.md','r') as fr: return fr.read() setup(name='docker_machinator', version='0.1', description='A tool for managing docker machines from multiple' ...
entry_points={ 'console_scripts': [ 'dmachinator = docker_machinator.dmachinator:main', ], },
classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Topic :: Security', ], keywords='docker machine dmachinator secure on-disk', url='https://github.com/realcr/docker_...
auready/django
django/core/checks/messages.py
Python
bsd-3-clause
2,214
0.000903
from django.utils.encoding import force_text # Levels DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 class CheckMessage: def __init__(self, level, msg, hint=None, obj=None, id=None): assert isinstance(level, int), "The first argument should be level." self.level = level self....
Base): # We need to hardcode ModelBase and Field cases because its __str__ # method doesn't return "applabel.modellabel" and cannot be changed.
obj = self.obj._meta.label else: obj = force_text(self.obj) id = "(%s) " % self.id if self.id else "" hint = "\n\tHINT: %s" % self.hint if self.hint else '' return "%s: %s%s%s" % (obj, id, self.msg, hint) def __repr__(self): return "<%s: level=%r, msg=%r, ...
szymonlipinski/hackernews_dowloader
hnusers.py
Python
mit
5,013
0.001397
""" A simple script for downloading user data. """ import argparse import csv import json import os from dataclasses import dataclass from shutil import move import requests as r from common import convert, limit_rate, max_request_per_hour, pid_run users_file_name = "users" users_data_file_name = "users.data.csv" te...
uest_per_hour, 3600) def get_data(user_name: str) -> str: """ Makes request to the API and returns text reply. """ url = base_url
.format(user_name=user_name) return r.get(url).text def parse_response(response: str) -> dict: """ Parses the response from the API and returns dictionary with converted fields. """ res = json.loads(response) return dict( id=res["id"], username=res["username"], about=co...
ericmjl/bokeh
bokeh/client/session.py
Python
bsd-3-clause
18,677
0.003052
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
---------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import l
ogging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from urllib.parse import quote_plus # Bokeh imports from ..document ...
godaddy/cijtemplate
cijtemplate/settings/prod.py
Python
mit
36
0
DEB
UG = True TEMPLATE_DEBUG =
True
uber/pyro
tests/distributions/test_one_hot_categorical.py
Python
apache-2.0
3,921
0.00102
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 from unittest import TestCase import numpy as np import pytest import torch import pyro.distributions as dist from tests.common import assert_equal class TestOneHotCategorical(TestCase): """ Tests methods specific to th...
le = dist.OneHotCategorical(probs).sample() assert_correct_dimensions(sample, probs) def test_batch_log_dims(dim, probs): batch_pdf_shape = (
3,) + (1,) * (dim - 1) expected_log_prob_sum = np.array(wrap_nested(list(np.log(probs)), dim - 1)).reshape( *batch_pdf_shape ) probs = modify_params_using_dims(probs, dim) support = dist.OneHotCategorical(probs).enumerate_support() log_prob = dist.OneHotCategorical(probs).log_prob(support) ...
Jzarecta/pythonjr
codigo/funcion_con_parametros.py
Python
gpl-2.0
220
0.004545
#! /usr/bin/python # -*- coding: utf-8 -*- def multiplica(multiplo1, multiplo2=2): print multiplo1 *
multiplo2 multiplica(2) multiplica(5, 7.3) mul
tiplica("7", 6) numero = 12.5 multiplica(numero, 11) multiplica()
acarmisc/quickquest
quickquest/urls.py
Python
apache-2.0
301
0.013289
from django.conf.urls import patterns, include, url from
django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'quick
quest.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
JeffHoogland/qAndora
qAndora.py
Python
bsd-3-clause
24,713
0.010885
import sys import os import platform from PySide.QtGui import * from PySide.QtCore import * if not "arm" in platform.machine(): from ui_qAndora import Ui_MainWindow else: from ui_qAndora_mobile import Ui_MainWindow from ui_qPreferences import Ui_qPreferences from ui_qError import Ui_qError from playerVLC impor...
ces['password'] = userPassword self.savePreferences() self.radioPlayer.setVolume(self.preferences['volume']) self.volumeSlider.setValue(self.preferences['volume']) try: self.radioPlayer.auth(userName, userPassword) self.getLastStation() self....
self.tray.show() except: self.preferencesWin.show() def getLastStation(self): if self.preferences['station']: self.radioPlayer.setStation(self.radioPlayer.getStationFromName(self.preferences['station'])) else: self.radioPlayer.setStation(s...
kyasabu/Telethon
telethon/errors/rpc_errors_420.py
Python
mit
351
0.002849
from . import FloodError class FloodWaitError(FloodError): def __init__(self, **kwargs): self.seconds = kwargs['extra'] super(Exception, self).__init__( self, 'A wait of {} seconds is required.' .format(self.seconds) ) rpc_errors_420_all = { 'FLOOD...
WaitError }
brendanwhitfield/planetary
PlanetarySprites.py
Python
gpl-2.0
7,721
0.0294
''' Sprite object definitions. DisplayObject is the base class for displaying clickable images. It handles the drawing, moving, clicking, and hashing of a basic image. Subclasses of DisplayObject can and should override functions like blitTo(), animate() and hash() ''' import math import pygame from pygame.sprite imp...
Object): def __init__(self, pos, maxChars, font): self.lines = [] self.text = "" self.text_color = FONT_COLOR self.max_chars
= maxChars self.font = font self.alpha = 0 self.alpha_speed = FADE_SPEED self.setText("TextBox") super(TextBox, self).__init__(pos, False) self.active = False def animate(self): # opacity fader if self.active and self.alpha < 255: self.alpha += self.alpha_speed elif not self.active and self.alp...
htzy/bigfour
lms/startup.py
Python
agpl-3.0
4,878
0.002255
""" Module for code that should run during LMS startup """ # pylint: disable=unused-argument from django.conf import settings # Force settings to run so that the python path is modified settings.INSTALLED_APPS # pylint: disable=pointless-statement fr
om openedx.core.lib.django_startup import autostartup import edxmako import logging from monkey_patch import django_utils_translation import analytics log = logging.getLogger(_
_name__) def run(): """ Executed during django startup """ # Patch the xml libs. from safe_lxml import defuse_xml_libs defuse_xml_libs() django_utils_translation.patch() autostartup() add_mimetypes() if settings.FEATURES.get('USE_CUSTOM_THEME', False): enable_theme...
iemejia/incubator-beam
sdks/python/apache_beam/transforms/display_test.py
Python
apache-2.0
9,047
0.005085
# # 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 us...
e, shortValue='HasDisplayData'), DisplayDataItemMatcher( key='static_integer', value=120, namesp
ace=nspace), DisplayDataItemMatcher( key='static_string', value='static me!', namespace=nspace) ] hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items)) def test_drop_if_none(self): class MyDoFn(beam.DoFn): def display_data(self): return { 'some_v...
ivlukin/math_stat_python
problem1.py
Python
apache-2.0
1,341
0.006173
import numpy as np from scipy.stats import rv_continuous class customDist(rv_continuous): """" Distribution F(x)=1-exp(-exp(0.1x) """ #TODO поменять тут на своё распределение def _cdf(self, x, *args): return 1 - np.exp(-np.exp(x / 10.)) d = customDist() #Генерируем выборку из 100 случа...
") m.grid(True) #Генерируем выборку из 1000 случайных величин sample = d.rvs(size=1000) f = m.figure() m.hist(sample, bins=10) m.title("Dis
tribution F(x)=1-exp(-exp(0.1x)) 1000xValues") m.xlabel("Value") m.ylabel("Count of times") m.grid(True) #Генерируем выборку из 1000 случайных велечин #где каждая случайная величина является суммой 30 случайных велечин из исходной выборки sample = [sum(d.rvs(size=30)) for i in range(1000)] f = m.figure() m.hist(sampl...
parpg/parpg
parpg/components/container.py
Python
gpl-3.0
4,212
0.004748
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be...
dren") return fields class BulkLimitError(Exception): """Error that gets raised when the item would exceed the bulk limit of the container.""" def __init__(self, bulk, max_bulk): self.bulk = bulk self.max_bulk = max_bulk def __str__(self): return "Item would...
return "Container can't hold any more items." def get_free_slot(container): """Returns the first slot of the container that is not occupied.""" index = 0 for child in container.children: if not child: return index index += 1 raise NoFreeSlotError def get_total_bulk(co...
p2pu/mechanical-mooc
twitter/utils.py
Python
mit
3,949
0.004305
from django.conf import settings import hashlib import hmac import base64 import urllib import time import random import string import requests def _parse_response(text): return dict( [(k[0], k[1]) for k in [i.split('=') for i in text.split('&')]] ) def get_request_token(): url = 'https://api.twitter.com/o...
= authorize_request('GET', url, param_data=[('screen_name', screen_name)], oauth_token_pair=oauth_token_pair ) if resp.status_code != 200: raise Exception('Could not get user data') return resp.json() def authorize_request(method, url, param_data=None, extra_oauth_params=None, oaut...
.digits + string.letters) for i in range(32)]) parameter_values = [ ('oauth_consumer_key', settings.TWITTER_OAUTH_CONSUMER_KEY), ('oauth_nonce', nonce), ('oauth_signature_method', 'HMAC-SHA1'), ('oauth_timestamp', str(int(time.time()))), ('oauth_version', '1.0'), ] i...
w1ll1am23/home-assistant
homeassistant/components/device_tracker/legacy.py
Python
apache-2.0
27,443
0.000765
"""Legacy device tracker classes.""" from __future__ import annotations import asyncio from datetime import timedelta import hashlib from types import ModuleType from typing import Any, Callable, Sequence, final import attr import voluptuous as vol from homeassistant import util from homeassistant.components import ...
sistant.util import dt as dt_util from homeassistant.util.yaml im
port dump from .const import ( ATTR_ATTRIBUTES, ATTR_BATTERY, ATTR_CONSIDER_HOME, ATTR_DEV_ID, ATTR_GPS, ATTR_HOST_NAME, ATTR_LOCATION_NAME, ATTR_MAC, ATTR_SOURCE_TYPE, CONF_CONSIDER_HOME, CONF_NEW_DEVICE_DEFAULTS, CONF_SCAN_INTERVAL, CONF_TRACK_NEW, DEFAULT_CONS...
vincepandolfo/django
django/contrib/sessions/middleware.py
Python
bsd-3-clause
3,093
0.003233
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.shortcuts import redirect from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date class SessionMiddleware(object): def __i...
SESSION_COOKIE_DOMAIN) else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_E
VERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time()...
markmc/rhevm-api
python/lib/rhev/test/test_users.py
Python
lgpl-2.1
1,358
0
# # This file is part of pyth
on-rhev. python-rhev is free software that is # made available under the MIT license. Consult the file "LICENSE" that # is distributed together with this file for the exact licensing terms. # # python-rhev is copyright (c) 2010-2011 by the python-r
hev authors. See # the file "AUTHORS" for a complete overview. from rhev import * from rhev.test import util from rhev.test.base import BaseTest from rhev.test.loader import depends class TestUsers(BaseTest): def test_getall(self): users = self.api.getall(schema.User) assert isinstance(users, sc...
RPGOne/Skynet
xgboost-master/demo/yearpredMSD/csv2libsvm.py
Python
bsd-3-clause
333
0.003003
#!/usr/bin/python import sys if len(sys.argv) < 3: print 'Usage: <csv> <libsvm>' print 'convert a all numerical csv to libsvm' fo = open(sys.argv[2], 'w') for l in open(sys.argv[1]): arr = l.split(',') fo.write('%s' % arr[0]) for i in xrange(len(arr) - 1): fo.write(' %d:%
s' % (i, arr[i+1])) fo.clo
se()
boxu0001/practice
py3/dynamicProgramming/S5_LongestParlingdrom.py
Python
gpl-3.0
1,741
0.013211
# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. # Example: # Input: "babad" # Output: "bab" # Note: "aba" is also a valid answer. # Example: # Input: "cbbd" # Output: "bb" #Manacher's Algo class Solution: def longestPalindrome(self, s): ...
else 0 si, ei = (i+1)//2-1, i//2+1 while ls > ei and si >= 0: if s[si] == s[ei]: si-=1 ei+=1 else: break if ei - si
- 1 > maxl: maxStr = s[si+1:ei] maxl = ei - si - 1 return maxStr s=Solution() # print(s.longestPalindrome('babad')) # print(s.longestPalindrome('aa')) # print(s.longestPalindrome('ab')) # print(s.longestPalindrome('abadedab')) # print(s.longestPalingdromeWithDP('babad')) # pri...
belokop/indico_bare
indico_zodbimport/modules/event_timetable.py
Python
gpl-3.0
57,156
0.004077
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
nce, self.old_event)) self._migrate_event_persons() self._migrate_event_persons_links() self._migrate_contribution_types() self._migrate_contribution_fields() self._migrate_sessions() self._migrate_contributions()
self._migrate_abstracts() self._migrate_timetable() def _convert_principal(self, old_principal): principal = convert_principal(old_principal) if (principal is None and old_principal.__class__.__name__ in ('Avatar', 'AvatarUserWrapper') and 'email' in old_principal.__...
allmightyspiff/softlayer-python
SoftLayer/testing/xmlrpc.py
Python
mit
4,126
0
""" SoftLayer.testing.xmlrpc ~~~~~~~~~~~~~~~~~~~~~~~~ XMP-RPC server which can use a transport to proxy requests for testing. :license: MIT, see LICENSE for more details. """ import http.server import logging import threading import xmlrpc.client import SoftLayer from SoftLayer import transports from ...
server.HTTPServer): """Test HTTP server which holds a given transport.""" def __init__(self, transport, *args, **kw): http.server.HTTPServer.__init__(self, *args, **kw) self.transport = transport class TestHandler(http.server.BaseHTTPRequestHandler): """Test XML-RPC Handler which converts...
length = int(self.headers['Content-Length']) data = self.rfile.read(length).decode('utf-8') args, method = xmlrpc.client.loads(data) headers = args[0].get('headers', {}) # Form Request for the transport req = transports.Request() req.service = s...